1 /*
   2  * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "ci/bcEscapeAnalyzer.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "libadt/vectset.hpp"
  29 #include "memory/allocation.hpp"
  30 #include "opto/c2compiler.hpp"
  31 #include "opto/callnode.hpp"
  32 #include "opto/cfgnode.hpp"
  33 #include "opto/compile.hpp"
  34 #include "opto/escape.hpp"
  35 #include "opto/phaseX.hpp"
  36 #include "opto/movenode.hpp"
  37 #include "opto/rootnode.hpp"
  38 
  39 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn) :
  40   _nodes(C->comp_arena(), C->unique(), C->unique(), NULL),
  41   _collecting(true),
  42   _verify(false),
  43   _compile(C),
  44   _igvn(igvn),
  45   _node_map(C->comp_arena()) {
  46   // Add unknown java object.
  47   add_java_object(C->top(), PointsToNode::GlobalEscape);
  48   phantom_obj = ptnode_adr(C->top()->_idx)->as_JavaObject();
  49   // Add ConP(#NULL) and ConN(#NULL) nodes.
  50   Node* oop_null = igvn->zerocon(T_OBJECT);
  51   assert(oop_null->_idx < nodes_size(), "should be created already");
  52   add_java_object(oop_null, PointsToNode::NoEscape);
  53   null_obj = ptnode_adr(oop_null->_idx)->as_JavaObject();
  54   if (UseCompressedOops) {
  55     Node* noop_null = igvn->zerocon(T_NARROWOOP);
  56     assert(noop_null->_idx < nodes_size(), "should be created already");
  57     map_ideal_node(noop_null, null_obj);
  58   }
  59   _pcmp_neq = NULL; // Should be initialized
  60   _pcmp_eq  = NULL;
  61 }
  62 
  63 bool ConnectionGraph::has_candidates(Compile *C) {
  64   // EA brings benefits only when the code has allocations and/or locks which
  65   // are represented by ideal Macro nodes.
  66   int cnt = C->macro_count();
  67   for (int i = 0; i < cnt; i++) {
  68     Node *n = C->macro_node(i);
  69     if (n->is_Allocate())
  70       return true;
  71     if (n->is_Lock()) {
  72       Node* obj = n->as_Lock()->obj_node()->uncast();
  73       if (!(obj->is_Parm() || obj->is_Con()))
  74         return true;
  75     }
  76     if (n->is_CallStaticJava() &&
  77         n->as_CallStaticJava()->is_boxing_method()) {
  78       return true;
  79     }
  80   }
  81   return false;
  82 }
  83 
  84 void ConnectionGraph::do_analysis(Compile *C, PhaseIterGVN *igvn) {
  85   Compile::TracePhase tp("escapeAnalysis", &Phase::timers[Phase::_t_escapeAnalysis]);
  86   ResourceMark rm;
  87 
  88   // Add ConP#NULL and ConN#NULL nodes before ConnectionGraph construction
  89   // to create space for them in ConnectionGraph::_nodes[].
  90   Node* oop_null = igvn->zerocon(T_OBJECT);
  91   Node* noop_null = igvn->zerocon(T_NARROWOOP);
  92   ConnectionGraph* congraph = new(C->comp_arena()) ConnectionGraph(C, igvn);
  93   // Perform escape analysis
  94   if (congraph->compute_escape()) {
  95     // There are non escaping objects.
  96     C->set_congraph(congraph);
  97   }
  98   // Cleanup.
  99   if (oop_null->outcnt() == 0)
 100     igvn->hash_delete(oop_null);
 101   if (noop_null->outcnt() == 0)
 102     igvn->hash_delete(noop_null);
 103 }
 104 
 105 bool ConnectionGraph::compute_escape() {
 106   Compile* C = _compile;
 107   PhaseGVN* igvn = _igvn;
 108 
 109   // Worklists used by EA.
 110   Unique_Node_List delayed_worklist;
 111   GrowableArray<Node*> alloc_worklist;
 112   GrowableArray<Node*> ptr_cmp_worklist;
 113   GrowableArray<Node*> storestore_worklist;
 114   GrowableArray<PointsToNode*>   ptnodes_worklist;
 115   GrowableArray<JavaObjectNode*> java_objects_worklist;
 116   GrowableArray<JavaObjectNode*> non_escaped_worklist;
 117   GrowableArray<FieldNode*>      oop_fields_worklist;
 118   DEBUG_ONLY( GrowableArray<Node*> addp_worklist; )
 119 
 120   { Compile::TracePhase tp("connectionGraph", &Phase::timers[Phase::_t_connectionGraph]);
 121 
 122   // 1. Populate Connection Graph (CG) with PointsTo nodes.
 123   ideal_nodes.map(C->live_nodes(), NULL);  // preallocate space
 124   // Initialize worklist
 125   if (C->root() != NULL) {
 126     ideal_nodes.push(C->root());
 127   }
 128   for( uint next = 0; next < ideal_nodes.size(); ++next ) {
 129     Node* n = ideal_nodes.at(next);
 130     // Create PointsTo nodes and add them to Connection Graph. Called
 131     // only once per ideal node since ideal_nodes is Unique_Node list.
 132     add_node_to_connection_graph(n, &delayed_worklist);
 133     PointsToNode* ptn = ptnode_adr(n->_idx);
 134     if (ptn != NULL) {
 135       ptnodes_worklist.append(ptn);
 136       if (ptn->is_JavaObject()) {
 137         java_objects_worklist.append(ptn->as_JavaObject());
 138         if ((n->is_Allocate() || n->is_CallStaticJava()) &&
 139             (ptn->escape_state() < PointsToNode::GlobalEscape)) {
 140           // Only allocations and java static calls results are interesting.
 141           non_escaped_worklist.append(ptn->as_JavaObject());
 142         }
 143       } else if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
 144         oop_fields_worklist.append(ptn->as_Field());
 145       }
 146     }
 147     if (n->is_MergeMem()) {
 148       // Collect all MergeMem nodes to add memory slices for
 149       // scalar replaceable objects in split_unique_types().
 150       _mergemem_worklist.append(n->as_MergeMem());
 151     } else if (OptimizePtrCompare && n->is_Cmp() &&
 152                (n->Opcode() == Op_CmpP || n->Opcode() == Op_CmpN)) {
 153       // Collect compare pointers nodes.
 154       ptr_cmp_worklist.append(n);
 155     } else if (n->is_MemBarStoreStore()) {
 156       // Collect all MemBarStoreStore nodes so that depending on the
 157       // escape status of the associated Allocate node some of them
 158       // may be eliminated.
 159       storestore_worklist.append(n);
 160     } else if (n->is_MemBar() && (n->Opcode() == Op_MemBarRelease) &&
 161                (n->req() > MemBarNode::Precedent)) {
 162       record_for_optimizer(n);
 163 #ifdef ASSERT
 164     } else if (n->is_AddP()) {
 165       // Collect address nodes for graph verification.
 166       addp_worklist.append(n);
 167 #endif
 168     }
 169     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 170       Node* m = n->fast_out(i);   // Get user
 171       ideal_nodes.push(m);
 172     }
 173   }
 174   if (non_escaped_worklist.length() == 0) {
 175     _collecting = false;
 176     return false; // Nothing to do.
 177   }
 178   // Add final simple edges to graph.
 179   while(delayed_worklist.size() > 0) {
 180     Node* n = delayed_worklist.pop();
 181     add_final_edges(n);
 182   }
 183   int ptnodes_length = ptnodes_worklist.length();
 184 
 185 #ifdef ASSERT
 186   if (VerifyConnectionGraph) {
 187     // Verify that no new simple edges could be created and all
 188     // local vars has edges.
 189     _verify = true;
 190     for (int next = 0; next < ptnodes_length; ++next) {
 191       PointsToNode* ptn = ptnodes_worklist.at(next);
 192       add_final_edges(ptn->ideal_node());
 193       if (ptn->is_LocalVar() && ptn->edge_count() == 0) {
 194         ptn->dump();
 195         assert(ptn->as_LocalVar()->edge_count() > 0, "sanity");
 196       }
 197     }
 198     _verify = false;
 199   }
 200 #endif
 201 
 202   // 2. Finish Graph construction by propagating references to all
 203   //    java objects through graph.
 204   if (!complete_connection_graph(ptnodes_worklist, non_escaped_worklist,
 205                                  java_objects_worklist, oop_fields_worklist)) {
 206     // All objects escaped or hit time or iterations limits.
 207     _collecting = false;
 208     return false;
 209   }
 210 
 211   // 3. Adjust scalar_replaceable state of nonescaping objects and push
 212   //    scalar replaceable allocations on alloc_worklist for processing
 213   //    in split_unique_types().
 214   int non_escaped_length = non_escaped_worklist.length();
 215   for (int next = 0; next < non_escaped_length; next++) {
 216     JavaObjectNode* ptn = non_escaped_worklist.at(next);
 217     bool noescape = (ptn->escape_state() == PointsToNode::NoEscape);
 218     Node* n = ptn->ideal_node();
 219     if (n->is_Allocate()) {
 220       n->as_Allocate()->_is_non_escaping = noescape;
 221     }
 222     if (n->is_CallStaticJava()) {
 223       n->as_CallStaticJava()->_is_non_escaping = noescape;
 224     }
 225     if (noescape && ptn->scalar_replaceable()) {
 226       adjust_scalar_replaceable_state(ptn);
 227       if (ptn->scalar_replaceable()) {
 228         alloc_worklist.append(ptn->ideal_node());
 229       }
 230     }
 231   }
 232 
 233 #ifdef ASSERT
 234   if (VerifyConnectionGraph) {
 235     // Verify that graph is complete - no new edges could be added or needed.
 236     verify_connection_graph(ptnodes_worklist, non_escaped_worklist,
 237                             java_objects_worklist, addp_worklist);
 238   }
 239   assert(C->unique() == nodes_size(), "no new ideal nodes should be added during ConnectionGraph build");
 240   assert(null_obj->escape_state() == PointsToNode::NoEscape &&
 241          null_obj->edge_count() == 0 &&
 242          !null_obj->arraycopy_src() &&
 243          !null_obj->arraycopy_dst(), "sanity");
 244 #endif
 245 
 246   _collecting = false;
 247 
 248   } // TracePhase t3("connectionGraph")
 249 
 250   // 4. Optimize ideal graph based on EA information.
 251   bool has_non_escaping_obj = (non_escaped_worklist.length() > 0);
 252   if (has_non_escaping_obj) {
 253     optimize_ideal_graph(ptr_cmp_worklist, storestore_worklist);
 254   }
 255 
 256 #ifndef PRODUCT
 257   if (PrintEscapeAnalysis) {
 258     dump(ptnodes_worklist); // Dump ConnectionGraph
 259   }
 260 #endif
 261 
 262   bool has_scalar_replaceable_candidates = (alloc_worklist.length() > 0);
 263 #ifdef ASSERT
 264   if (VerifyConnectionGraph) {
 265     int alloc_length = alloc_worklist.length();
 266     for (int next = 0; next < alloc_length; ++next) {
 267       Node* n = alloc_worklist.at(next);
 268       PointsToNode* ptn = ptnode_adr(n->_idx);
 269       assert(ptn->escape_state() == PointsToNode::NoEscape && ptn->scalar_replaceable(), "sanity");
 270     }
 271   }
 272 #endif
 273 
 274   // 5. Separate memory graph for scalar replaceable allcations.
 275   if (has_scalar_replaceable_candidates &&
 276       C->AliasLevel() >= 3 && EliminateAllocations) {
 277     // Now use the escape information to create unique types for
 278     // scalar replaceable objects.
 279     split_unique_types(alloc_worklist);
 280     if (C->failing())  return false;
 281     C->print_method(PHASE_AFTER_EA, 2);
 282 
 283 #ifdef ASSERT
 284   } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
 285     tty->print("=== No allocations eliminated for ");
 286     C->method()->print_short_name();
 287     if(!EliminateAllocations) {
 288       tty->print(" since EliminateAllocations is off ===");
 289     } else if(!has_scalar_replaceable_candidates) {
 290       tty->print(" since there are no scalar replaceable candidates ===");
 291     } else if(C->AliasLevel() < 3) {
 292       tty->print(" since AliasLevel < 3 ===");
 293     }
 294     tty->cr();
 295 #endif
 296   }
 297   return has_non_escaping_obj;
 298 }
 299 
 300 // Utility function for nodes that load an object
 301 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
 302   // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
 303   // ThreadLocal has RawPtr type.
 304   const Type* t = _igvn->type(n);
 305   if (t->make_ptr() != NULL) {
 306     Node* adr = n->in(MemNode::Address);
 307 #ifdef ASSERT
 308     if (!adr->is_AddP()) {
 309       assert(_igvn->type(adr)->isa_rawptr(), "sanity");
 310     } else {
 311       assert((ptnode_adr(adr->_idx) == NULL ||
 312               ptnode_adr(adr->_idx)->as_Field()->is_oop()), "sanity");
 313     }
 314 #endif
 315     add_local_var_and_edge(n, PointsToNode::NoEscape,
 316                            adr, delayed_worklist);
 317   }
 318 }
 319 
 320 // Populate Connection Graph with PointsTo nodes and create simple
 321 // connection graph edges.
 322 void ConnectionGraph::add_node_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
 323   assert(!_verify, "this method sould not be called for verification");
 324   PhaseGVN* igvn = _igvn;
 325   uint n_idx = n->_idx;
 326   PointsToNode* n_ptn = ptnode_adr(n_idx);
 327   if (n_ptn != NULL)
 328     return; // No need to redefine PointsTo node during first iteration.
 329 
 330   if (n->is_Call()) {
 331     // Arguments to allocation and locking don't escape.
 332     if (n->is_AbstractLock()) {
 333       // Put Lock and Unlock nodes on IGVN worklist to process them during
 334       // first IGVN optimization when escape information is still available.
 335       record_for_optimizer(n);
 336     } else if (n->is_Allocate()) {
 337       add_call_node(n->as_Call());
 338       record_for_optimizer(n);
 339     } else {
 340       if (n->is_CallStaticJava()) {
 341         const char* name = n->as_CallStaticJava()->_name;
 342         if (name != NULL && strcmp(name, "uncommon_trap") == 0)
 343           return; // Skip uncommon traps
 344       }
 345       // Don't mark as processed since call's arguments have to be processed.
 346       delayed_worklist->push(n);
 347       // Check if a call returns an object.
 348       if ((n->as_Call()->returns_pointer() &&
 349            n->as_Call()->proj_out(TypeFunc::Parms) != NULL) ||
 350           (n->is_CallStaticJava() &&
 351            n->as_CallStaticJava()->is_boxing_method())) {
 352         add_call_node(n->as_Call());
 353       }
 354     }
 355     return;
 356   }
 357   // Put this check here to process call arguments since some call nodes
 358   // point to phantom_obj.
 359   if (n_ptn == phantom_obj || n_ptn == null_obj)
 360     return; // Skip predefined nodes.
 361 
 362   int opcode = n->Opcode();
 363   switch (opcode) {
 364     case Op_AddP: {
 365       Node* base = get_addp_base(n);
 366       PointsToNode* ptn_base = ptnode_adr(base->_idx);
 367       // Field nodes are created for all field types. They are used in
 368       // adjust_scalar_replaceable_state() and split_unique_types().
 369       // Note, non-oop fields will have only base edges in Connection
 370       // Graph because such fields are not used for oop loads and stores.
 371       int offset = address_offset(n, igvn);
 372       add_field(n, PointsToNode::NoEscape, offset);
 373       if (ptn_base == NULL) {
 374         delayed_worklist->push(n); // Process it later.
 375       } else {
 376         n_ptn = ptnode_adr(n_idx);
 377         add_base(n_ptn->as_Field(), ptn_base);
 378       }
 379       break;
 380     }
 381     case Op_CastX2P: {
 382       map_ideal_node(n, phantom_obj);
 383       break;
 384     }
 385     case Op_CastPP:
 386     case Op_CheckCastPP:
 387     case Op_EncodeP:
 388     case Op_DecodeN:
 389     case Op_EncodePKlass:
 390     case Op_DecodeNKlass: {
 391       add_local_var_and_edge(n, PointsToNode::NoEscape,
 392                              n->in(1), delayed_worklist);
 393       break;
 394     }
 395     case Op_CMoveP: {
 396       add_local_var(n, PointsToNode::NoEscape);
 397       // Do not add edges during first iteration because some could be
 398       // not defined yet.
 399       delayed_worklist->push(n);
 400       break;
 401     }
 402     case Op_ConP:
 403     case Op_ConN:
 404     case Op_ConNKlass: {
 405       // assume all oop constants globally escape except for null
 406       PointsToNode::EscapeState es;
 407       const Type* t = igvn->type(n);
 408       if (t == TypePtr::NULL_PTR || t == TypeNarrowOop::NULL_PTR) {
 409         es = PointsToNode::NoEscape;
 410       } else {
 411         es = PointsToNode::GlobalEscape;
 412       }
 413       add_java_object(n, es);
 414       break;
 415     }
 416     case Op_CreateEx: {
 417       // assume that all exception objects globally escape
 418       add_java_object(n, PointsToNode::GlobalEscape);
 419       break;
 420     }
 421     case Op_LoadKlass:
 422     case Op_LoadNKlass: {
 423       // Unknown class is loaded
 424       map_ideal_node(n, phantom_obj);
 425       break;
 426     }
 427     case Op_LoadP:
 428     case Op_LoadN:
 429     case Op_LoadPLocked: {
 430       add_objload_to_connection_graph(n, delayed_worklist);
 431       break;
 432     }
 433     case Op_Parm: {
 434       map_ideal_node(n, phantom_obj);
 435       break;
 436     }
 437     case Op_PartialSubtypeCheck: {
 438       // Produces Null or notNull and is used in only in CmpP so
 439       // phantom_obj could be used.
 440       map_ideal_node(n, phantom_obj); // Result is unknown
 441       break;
 442     }
 443     case Op_Phi: {
 444       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
 445       // ThreadLocal has RawPtr type.
 446       const Type* t = n->as_Phi()->type();
 447       if (t->make_ptr() != NULL) {
 448         add_local_var(n, PointsToNode::NoEscape);
 449         // Do not add edges during first iteration because some could be
 450         // not defined yet.
 451         delayed_worklist->push(n);
 452       }
 453       break;
 454     }
 455     case Op_Proj: {
 456       // we are only interested in the oop result projection from a call
 457       if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
 458           n->in(0)->as_Call()->returns_pointer()) {
 459         add_local_var_and_edge(n, PointsToNode::NoEscape,
 460                                n->in(0), delayed_worklist);
 461       }
 462       break;
 463     }
 464     case Op_Rethrow: // Exception object escapes
 465     case Op_Return: {
 466       if (n->req() > TypeFunc::Parms &&
 467           igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
 468         // Treat Return value as LocalVar with GlobalEscape escape state.
 469         add_local_var_and_edge(n, PointsToNode::GlobalEscape,
 470                                n->in(TypeFunc::Parms), delayed_worklist);
 471       }
 472       break;
 473     }
 474     case Op_GetAndSetP:
 475     case Op_GetAndSetN: {
 476       add_objload_to_connection_graph(n, delayed_worklist);
 477       // fallthrough
 478     }
 479     case Op_StoreP:
 480     case Op_StoreN:
 481     case Op_StoreNKlass:
 482     case Op_StorePConditional:
 483     case Op_CompareAndSwapP:
 484     case Op_CompareAndSwapN: {
 485       Node* adr = n->in(MemNode::Address);
 486       const Type *adr_type = igvn->type(adr);
 487       adr_type = adr_type->make_ptr();
 488       if (adr_type == NULL) {
 489         break; // skip dead nodes
 490       }
 491       if (adr_type->isa_oopptr() ||
 492           (opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass) &&
 493                         (adr_type == TypeRawPtr::NOTNULL &&
 494                          adr->in(AddPNode::Address)->is_Proj() &&
 495                          adr->in(AddPNode::Address)->in(0)->is_Allocate())) {
 496         delayed_worklist->push(n); // Process it later.
 497 #ifdef ASSERT
 498         assert(adr->is_AddP(), "expecting an AddP");
 499         if (adr_type == TypeRawPtr::NOTNULL) {
 500           // Verify a raw address for a store captured by Initialize node.
 501           int offs = (int)igvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
 502           assert(offs != Type::OffsetBot, "offset must be a constant");
 503         }
 504 #endif
 505       } else {
 506         // Ignore copy the displaced header to the BoxNode (OSR compilation).
 507         if (adr->is_BoxLock())
 508           break;
 509         // Stored value escapes in unsafe access.
 510         if ((opcode == Op_StoreP) && (adr_type == TypeRawPtr::BOTTOM)) {
 511           // Pointer stores in G1 barriers looks like unsafe access.
 512           // Ignore such stores to be able scalar replace non-escaping
 513           // allocations.
 514           if (UseG1GC && adr->is_AddP()) {
 515             Node* base = get_addp_base(adr);
 516             if (base->Opcode() == Op_LoadP &&
 517                 base->in(MemNode::Address)->is_AddP()) {
 518               adr = base->in(MemNode::Address);
 519               Node* tls = get_addp_base(adr);
 520               if (tls->Opcode() == Op_ThreadLocal) {
 521                 int offs = (int)igvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
 522                 if (offs == in_bytes(JavaThread::satb_mark_queue_offset() +
 523                                      PtrQueue::byte_offset_of_buf())) {
 524                   break; // G1 pre barier previous oop value store.
 525                 }
 526                 if (offs == in_bytes(JavaThread::dirty_card_queue_offset() +
 527                                      PtrQueue::byte_offset_of_buf())) {
 528                   break; // G1 post barier card address store.
 529                 }
 530               }
 531             }
 532           }
 533           delayed_worklist->push(n); // Process unsafe access later.
 534           break;
 535         }
 536 #ifdef ASSERT
 537         n->dump(1);
 538         assert(false, "not unsafe or G1 barrier raw StoreP");
 539 #endif
 540       }
 541       break;
 542     }
 543     case Op_AryEq:
 544     case Op_StrComp:
 545     case Op_StrEquals:
 546     case Op_StrIndexOf:
 547     case Op_EncodeISOArray: {
 548       add_local_var(n, PointsToNode::ArgEscape);
 549       delayed_worklist->push(n); // Process it later.
 550       break;
 551     }
 552     case Op_ThreadLocal: {
 553       add_java_object(n, PointsToNode::ArgEscape);
 554       break;
 555     }
 556     default:
 557       ; // Do nothing for nodes not related to EA.
 558   }
 559   return;
 560 }
 561 
 562 #ifdef ASSERT
 563 #define ELSE_FAIL(name)                               \
 564       /* Should not be called for not pointer type. */  \
 565       n->dump(1);                                       \
 566       assert(false, name);                              \
 567       break;
 568 #else
 569 #define ELSE_FAIL(name) \
 570       break;
 571 #endif
 572 
 573 // Add final simple edges to graph.
 574 void ConnectionGraph::add_final_edges(Node *n) {
 575   PointsToNode* n_ptn = ptnode_adr(n->_idx);
 576 #ifdef ASSERT
 577   if (_verify && n_ptn->is_JavaObject())
 578     return; // This method does not change graph for JavaObject.
 579 #endif
 580 
 581   if (n->is_Call()) {
 582     process_call_arguments(n->as_Call());
 583     return;
 584   }
 585   assert(n->is_Store() || n->is_LoadStore() ||
 586          (n_ptn != NULL) && (n_ptn->ideal_node() != NULL),
 587          "node should be registered already");
 588   int opcode = n->Opcode();
 589   switch (opcode) {
 590     case Op_AddP: {
 591       Node* base = get_addp_base(n);
 592       PointsToNode* ptn_base = ptnode_adr(base->_idx);
 593       assert(ptn_base != NULL, "field's base should be registered");
 594       add_base(n_ptn->as_Field(), ptn_base);
 595       break;
 596     }
 597     case Op_CastPP:
 598     case Op_CheckCastPP:
 599     case Op_EncodeP:
 600     case Op_DecodeN:
 601     case Op_EncodePKlass:
 602     case Op_DecodeNKlass: {
 603       add_local_var_and_edge(n, PointsToNode::NoEscape,
 604                              n->in(1), NULL);
 605       break;
 606     }
 607     case Op_CMoveP: {
 608       for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
 609         Node* in = n->in(i);
 610         if (in == NULL)
 611           continue;  // ignore NULL
 612         Node* uncast_in = in->uncast();
 613         if (uncast_in->is_top() || uncast_in == n)
 614           continue;  // ignore top or inputs which go back this node
 615         PointsToNode* ptn = ptnode_adr(in->_idx);
 616         assert(ptn != NULL, "node should be registered");
 617         add_edge(n_ptn, ptn);
 618       }
 619       break;
 620     }
 621     case Op_LoadP:
 622     case Op_LoadN:
 623     case Op_LoadPLocked: {
 624       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
 625       // ThreadLocal has RawPtr type.
 626       const Type* t = _igvn->type(n);
 627       if (t->make_ptr() != NULL) {
 628         Node* adr = n->in(MemNode::Address);
 629         add_local_var_and_edge(n, PointsToNode::NoEscape, adr, NULL);
 630         break;
 631       }
 632       ELSE_FAIL("Op_LoadP");
 633     }
 634     case Op_Phi: {
 635       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
 636       // ThreadLocal has RawPtr type.
 637       const Type* t = n->as_Phi()->type();
 638       if (t->make_ptr() != NULL) {
 639         for (uint i = 1; i < n->req(); i++) {
 640           Node* in = n->in(i);
 641           if (in == NULL)
 642             continue;  // ignore NULL
 643           Node* uncast_in = in->uncast();
 644           if (uncast_in->is_top() || uncast_in == n)
 645             continue;  // ignore top or inputs which go back this node
 646           PointsToNode* ptn = ptnode_adr(in->_idx);
 647           assert(ptn != NULL, "node should be registered");
 648           add_edge(n_ptn, ptn);
 649         }
 650         break;
 651       }
 652       ELSE_FAIL("Op_Phi");
 653     }
 654     case Op_Proj: {
 655       // we are only interested in the oop result projection from a call
 656       if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
 657           n->in(0)->as_Call()->returns_pointer()) {
 658         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), NULL);
 659         break;
 660       }
 661       ELSE_FAIL("Op_Proj");
 662     }
 663     case Op_Rethrow: // Exception object escapes
 664     case Op_Return: {
 665       if (n->req() > TypeFunc::Parms &&
 666           _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
 667         // Treat Return value as LocalVar with GlobalEscape escape state.
 668         add_local_var_and_edge(n, PointsToNode::GlobalEscape,
 669                                n->in(TypeFunc::Parms), NULL);
 670         break;
 671       }
 672       ELSE_FAIL("Op_Return");
 673     }
 674     case Op_StoreP:
 675     case Op_StoreN:
 676     case Op_StoreNKlass:
 677     case Op_StorePConditional:
 678     case Op_CompareAndSwapP:
 679     case Op_CompareAndSwapN:
 680     case Op_GetAndSetP:
 681     case Op_GetAndSetN: {
 682       Node* adr = n->in(MemNode::Address);
 683       const Type *adr_type = _igvn->type(adr);
 684       adr_type = adr_type->make_ptr();
 685 #ifdef ASSERT
 686       if (adr_type == NULL) {
 687         n->dump(1);
 688         assert(adr_type != NULL, "dead node should not be on list");
 689         break;
 690       }
 691 #endif
 692       if (opcode == Op_GetAndSetP || opcode == Op_GetAndSetN) {
 693         add_local_var_and_edge(n, PointsToNode::NoEscape, adr, NULL);
 694       }
 695       if (adr_type->isa_oopptr() ||
 696           (opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass) &&
 697                         (adr_type == TypeRawPtr::NOTNULL &&
 698                          adr->in(AddPNode::Address)->is_Proj() &&
 699                          adr->in(AddPNode::Address)->in(0)->is_Allocate())) {
 700         // Point Address to Value
 701         PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
 702         assert(adr_ptn != NULL &&
 703                adr_ptn->as_Field()->is_oop(), "node should be registered");
 704         Node *val = n->in(MemNode::ValueIn);
 705         PointsToNode* ptn = ptnode_adr(val->_idx);
 706         assert(ptn != NULL, "node should be registered");
 707         add_edge(adr_ptn, ptn);
 708         break;
 709       } else if ((opcode == Op_StoreP) && (adr_type == TypeRawPtr::BOTTOM)) {
 710         // Stored value escapes in unsafe access.
 711         Node *val = n->in(MemNode::ValueIn);
 712         PointsToNode* ptn = ptnode_adr(val->_idx);
 713         assert(ptn != NULL, "node should be registered");
 714         set_escape_state(ptn, PointsToNode::GlobalEscape);
 715         // Add edge to object for unsafe access with offset.
 716         PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
 717         assert(adr_ptn != NULL, "node should be registered");
 718         if (adr_ptn->is_Field()) {
 719           assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
 720           add_edge(adr_ptn, ptn);
 721         }
 722         break;
 723       }
 724       ELSE_FAIL("Op_StoreP");
 725     }
 726     case Op_AryEq:
 727     case Op_StrComp:
 728     case Op_StrEquals:
 729     case Op_StrIndexOf:
 730     case Op_EncodeISOArray: {
 731       // char[] arrays passed to string intrinsic do not escape but
 732       // they are not scalar replaceable. Adjust escape state for them.
 733       // Start from in(2) edge since in(1) is memory edge.
 734       for (uint i = 2; i < n->req(); i++) {
 735         Node* adr = n->in(i);
 736         const Type* at = _igvn->type(adr);
 737         if (!adr->is_top() && at->isa_ptr()) {
 738           assert(at == Type::TOP || at == TypePtr::NULL_PTR ||
 739                  at->isa_ptr() != NULL, "expecting a pointer");
 740           if (adr->is_AddP()) {
 741             adr = get_addp_base(adr);
 742           }
 743           PointsToNode* ptn = ptnode_adr(adr->_idx);
 744           assert(ptn != NULL, "node should be registered");
 745           add_edge(n_ptn, ptn);
 746         }
 747       }
 748       break;
 749     }
 750     default: {
 751       // This method should be called only for EA specific nodes which may
 752       // miss some edges when they were created.
 753 #ifdef ASSERT
 754       n->dump(1);
 755 #endif
 756       guarantee(false, "unknown node");
 757     }
 758   }
 759   return;
 760 }
 761 
 762 void ConnectionGraph::add_call_node(CallNode* call) {
 763   assert(call->returns_pointer(), "only for call which returns pointer");
 764   uint call_idx = call->_idx;
 765   if (call->is_Allocate()) {
 766     Node* k = call->in(AllocateNode::KlassNode);
 767     const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
 768     assert(kt != NULL, "TypeKlassPtr  required.");
 769     ciKlass* cik = kt->klass();
 770     PointsToNode::EscapeState es = PointsToNode::NoEscape;
 771     bool scalar_replaceable = true;
 772     if (call->is_AllocateArray()) {
 773       if (!cik->is_array_klass()) { // StressReflectiveCode
 774         es = PointsToNode::GlobalEscape;
 775       } else {
 776         int length = call->in(AllocateNode::ALength)->find_int_con(-1);
 777         if (length < 0 || length > EliminateAllocationArraySizeLimit) {
 778           // Not scalar replaceable if the length is not constant or too big.
 779           scalar_replaceable = false;
 780         }
 781       }
 782     } else {  // Allocate instance
 783       if (cik->is_subclass_of(_compile->env()->Thread_klass()) ||
 784           cik->is_subclass_of(_compile->env()->Reference_klass()) ||
 785          !cik->is_instance_klass() || // StressReflectiveCode
 786           cik->as_instance_klass()->has_finalizer()) {
 787         es = PointsToNode::GlobalEscape;
 788       }
 789     }
 790     add_java_object(call, es);
 791     PointsToNode* ptn = ptnode_adr(call_idx);
 792     if (!scalar_replaceable && ptn->scalar_replaceable()) {
 793       ptn->set_scalar_replaceable(false);
 794     }
 795   } else if (call->is_CallStaticJava()) {
 796     // Call nodes could be different types:
 797     //
 798     // 1. CallDynamicJavaNode (what happened during call is unknown):
 799     //
 800     //    - mapped to GlobalEscape JavaObject node if oop is returned;
 801     //
 802     //    - all oop arguments are escaping globally;
 803     //
 804     // 2. CallStaticJavaNode (execute bytecode analysis if possible):
 805     //
 806     //    - the same as CallDynamicJavaNode if can't do bytecode analysis;
 807     //
 808     //    - mapped to GlobalEscape JavaObject node if unknown oop is returned;
 809     //    - mapped to NoEscape JavaObject node if non-escaping object allocated
 810     //      during call is returned;
 811     //    - mapped to ArgEscape LocalVar node pointed to object arguments
 812     //      which are returned and does not escape during call;
 813     //
 814     //    - oop arguments escaping status is defined by bytecode analysis;
 815     //
 816     // For a static call, we know exactly what method is being called.
 817     // Use bytecode estimator to record whether the call's return value escapes.
 818     ciMethod* meth = call->as_CallJava()->method();
 819     if (meth == NULL) {
 820       const char* name = call->as_CallStaticJava()->_name;
 821       assert(strncmp(name, "_multianewarray", 15) == 0, "TODO: add failed case check");
 822       // Returns a newly allocated unescaped object.
 823       add_java_object(call, PointsToNode::NoEscape);
 824       ptnode_adr(call_idx)->set_scalar_replaceable(false);
 825     } else if (meth->is_boxing_method()) {
 826       // Returns boxing object
 827       PointsToNode::EscapeState es;
 828       vmIntrinsics::ID intr = meth->intrinsic_id();
 829       if (intr == vmIntrinsics::_floatValue || intr == vmIntrinsics::_doubleValue) {
 830         // It does not escape if object is always allocated.
 831         es = PointsToNode::NoEscape;
 832       } else {
 833         // It escapes globally if object could be loaded from cache.
 834         es = PointsToNode::GlobalEscape;
 835       }
 836       add_java_object(call, es);
 837     } else {
 838       BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
 839       call_analyzer->copy_dependencies(_compile->dependencies());
 840       if (call_analyzer->is_return_allocated()) {
 841         // Returns a newly allocated unescaped object, simply
 842         // update dependency information.
 843         // Mark it as NoEscape so that objects referenced by
 844         // it's fields will be marked as NoEscape at least.
 845         add_java_object(call, PointsToNode::NoEscape);
 846         ptnode_adr(call_idx)->set_scalar_replaceable(false);
 847       } else {
 848         // Determine whether any arguments are returned.
 849         const TypeTuple* d = call->tf()->domain();
 850         bool ret_arg = false;
 851         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
 852           if (d->field_at(i)->isa_ptr() != NULL &&
 853               call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
 854             ret_arg = true;
 855             break;
 856           }
 857         }
 858         if (ret_arg) {
 859           add_local_var(call, PointsToNode::ArgEscape);
 860         } else {
 861           // Returns unknown object.
 862           map_ideal_node(call, phantom_obj);
 863         }
 864       }
 865     }
 866   } else {
 867     // An other type of call, assume the worst case:
 868     // returned value is unknown and globally escapes.
 869     assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
 870     map_ideal_node(call, phantom_obj);
 871   }
 872 }
 873 
 874 void ConnectionGraph::process_call_arguments(CallNode *call) {
 875     bool is_arraycopy = false;
 876     switch (call->Opcode()) {
 877 #ifdef ASSERT
 878     case Op_Allocate:
 879     case Op_AllocateArray:
 880     case Op_Lock:
 881     case Op_Unlock:
 882       assert(false, "should be done already");
 883       break;
 884 #endif
 885     case Op_ArrayCopy:
 886     case Op_CallLeafNoFP:
 887       // Most array copies are ArrayCopy nodes at this point but there
 888       // are still a few direct calls to the copy subroutines (See
 889       // PhaseStringOpts::copy_string())
 890       is_arraycopy = (call->Opcode() == Op_ArrayCopy) ||
 891         (call->as_CallLeaf()->_name != NULL &&
 892          strstr(call->as_CallLeaf()->_name, "arraycopy") != 0);
 893       // fall through
 894     case Op_CallLeaf: {
 895       // Stub calls, objects do not escape but they are not scale replaceable.
 896       // Adjust escape state for outgoing arguments.
 897       const TypeTuple * d = call->tf()->domain();
 898       bool src_has_oops = false;
 899       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
 900         const Type* at = d->field_at(i);
 901         Node *arg = call->in(i);
 902         if (arg == NULL) {
 903           continue;
 904         }
 905         const Type *aat = _igvn->type(arg);
 906         if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr())
 907           continue;
 908         if (arg->is_AddP()) {
 909           //
 910           // The inline_native_clone() case when the arraycopy stub is called
 911           // after the allocation before Initialize and CheckCastPP nodes.
 912           // Or normal arraycopy for object arrays case.
 913           //
 914           // Set AddP's base (Allocate) as not scalar replaceable since
 915           // pointer to the base (with offset) is passed as argument.
 916           //
 917           arg = get_addp_base(arg);
 918         }
 919         PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
 920         assert(arg_ptn != NULL, "should be registered");
 921         PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
 922         if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
 923           assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
 924                  aat->isa_ptr() != NULL, "expecting an Ptr");
 925           bool arg_has_oops = aat->isa_oopptr() &&
 926                               (aat->isa_oopptr()->klass() == NULL || aat->isa_instptr() ||
 927                                (aat->isa_aryptr() && aat->isa_aryptr()->klass()->is_obj_array_klass()));
 928           if (i == TypeFunc::Parms) {
 929             src_has_oops = arg_has_oops;
 930           }
 931           //
 932           // src or dst could be j.l.Object when other is basic type array:
 933           //
 934           //   arraycopy(char[],0,Object*,0,size);
 935           //   arraycopy(Object*,0,char[],0,size);
 936           //
 937           // Don't add edges in such cases.
 938           //
 939           bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
 940                                        arg_has_oops && (i > TypeFunc::Parms);
 941 #ifdef ASSERT
 942           if (!(is_arraycopy ||
 943                 (call->as_CallLeaf()->_name != NULL &&
 944                  (strcmp(call->as_CallLeaf()->_name, "g1_wb_pre")  == 0 ||
 945                   strcmp(call->as_CallLeaf()->_name, "g1_wb_post") == 0 ||
 946                   strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 ||
 947                   strcmp(call->as_CallLeaf()->_name, "aescrypt_encryptBlock") == 0 ||
 948                   strcmp(call->as_CallLeaf()->_name, "aescrypt_decryptBlock") == 0 ||
 949                   strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_encryptAESCrypt") == 0 ||
 950                   strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_decryptAESCrypt") == 0 ||
 951                   strcmp(call->as_CallLeaf()->_name, "sha1_implCompress") == 0 ||
 952                   strcmp(call->as_CallLeaf()->_name, "sha1_implCompressMB") == 0 ||
 953                   strcmp(call->as_CallLeaf()->_name, "sha256_implCompress") == 0 ||
 954                   strcmp(call->as_CallLeaf()->_name, "sha256_implCompressMB") == 0 ||
 955                   strcmp(call->as_CallLeaf()->_name, "sha512_implCompress") == 0 ||
 956                   strcmp(call->as_CallLeaf()->_name, "sha512_implCompressMB") == 0 ||
 957                   strcmp(call->as_CallLeaf()->_name, "multiplyToLen") == 0)
 958                   ))) {
 959             call->dump();
 960             fatal(err_msg_res("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name));
 961           }
 962 #endif
 963           // Always process arraycopy's destination object since
 964           // we need to add all possible edges to references in
 965           // source object.
 966           if (arg_esc >= PointsToNode::ArgEscape &&
 967               !arg_is_arraycopy_dest) {
 968             continue;
 969           }
 970           set_escape_state(arg_ptn, PointsToNode::ArgEscape);
 971           if (arg_is_arraycopy_dest) {
 972             Node* src = call->in(TypeFunc::Parms);
 973             if (src->is_AddP()) {
 974               src = get_addp_base(src);
 975             }
 976             PointsToNode* src_ptn = ptnode_adr(src->_idx);
 977             assert(src_ptn != NULL, "should be registered");
 978             if (arg_ptn != src_ptn) {
 979               // Special arraycopy edge:
 980               // A destination object's field can't have the source object
 981               // as base since objects escape states are not related.
 982               // Only escape state of destination object's fields affects
 983               // escape state of fields in source object.
 984               add_arraycopy(call, PointsToNode::ArgEscape, src_ptn, arg_ptn);
 985             }
 986           }
 987         }
 988       }
 989       break;
 990     }
 991     case Op_CallStaticJava: {
 992       // For a static call, we know exactly what method is being called.
 993       // Use bytecode estimator to record the call's escape affects
 994 #ifdef ASSERT
 995       const char* name = call->as_CallStaticJava()->_name;
 996       assert((name == NULL || strcmp(name, "uncommon_trap") != 0), "normal calls only");
 997 #endif
 998       ciMethod* meth = call->as_CallJava()->method();
 999       if ((meth != NULL) && meth->is_boxing_method()) {
1000         break; // Boxing methods do not modify any oops.
1001       }
1002       BCEscapeAnalyzer* call_analyzer = (meth !=NULL) ? meth->get_bcea() : NULL;
1003       // fall-through if not a Java method or no analyzer information
1004       if (call_analyzer != NULL) {
1005         PointsToNode* call_ptn = ptnode_adr(call->_idx);
1006         const TypeTuple* d = call->tf()->domain();
1007         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1008           const Type* at = d->field_at(i);
1009           int k = i - TypeFunc::Parms;
1010           Node* arg = call->in(i);
1011           PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
1012           if (at->isa_ptr() != NULL &&
1013               call_analyzer->is_arg_returned(k)) {
1014             // The call returns arguments.
1015             if (call_ptn != NULL) { // Is call's result used?
1016               assert(call_ptn->is_LocalVar(), "node should be registered");
1017               assert(arg_ptn != NULL, "node should be registered");
1018               add_edge(call_ptn, arg_ptn);
1019             }
1020           }
1021           if (at->isa_oopptr() != NULL &&
1022               arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
1023             if (!call_analyzer->is_arg_stack(k)) {
1024               // The argument global escapes
1025               set_escape_state(arg_ptn, PointsToNode::GlobalEscape);
1026             } else {
1027               set_escape_state(arg_ptn, PointsToNode::ArgEscape);
1028               if (!call_analyzer->is_arg_local(k)) {
1029                 // The argument itself doesn't escape, but any fields might
1030                 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape);
1031               }
1032             }
1033           }
1034         }
1035         if (call_ptn != NULL && call_ptn->is_LocalVar()) {
1036           // The call returns arguments.
1037           assert(call_ptn->edge_count() > 0, "sanity");
1038           if (!call_analyzer->is_return_local()) {
1039             // Returns also unknown object.
1040             add_edge(call_ptn, phantom_obj);
1041           }
1042         }
1043         break;
1044       }
1045     }
1046     default: {
1047       // Fall-through here if not a Java method or no analyzer information
1048       // or some other type of call, assume the worst case: all arguments
1049       // globally escape.
1050       const TypeTuple* d = call->tf()->domain();
1051       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1052         const Type* at = d->field_at(i);
1053         if (at->isa_oopptr() != NULL) {
1054           Node* arg = call->in(i);
1055           if (arg->is_AddP()) {
1056             arg = get_addp_base(arg);
1057           }
1058           assert(ptnode_adr(arg->_idx) != NULL, "should be defined already");
1059           set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape);
1060         }
1061       }
1062     }
1063   }
1064 }
1065 
1066 
1067 // Finish Graph construction.
1068 bool ConnectionGraph::complete_connection_graph(
1069                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
1070                          GrowableArray<JavaObjectNode*>& non_escaped_worklist,
1071                          GrowableArray<JavaObjectNode*>& java_objects_worklist,
1072                          GrowableArray<FieldNode*>&      oop_fields_worklist) {
1073   // Normally only 1-3 passes needed to build Connection Graph depending
1074   // on graph complexity. Observed 8 passes in jvm2008 compiler.compiler.
1075   // Set limit to 20 to catch situation when something did go wrong and
1076   // bailout Escape Analysis.
1077   // Also limit build time to 30 sec (60 in debug VM).
1078 #define CG_BUILD_ITER_LIMIT 20
1079 #ifdef ASSERT
1080 #define CG_BUILD_TIME_LIMIT 60.0
1081 #else
1082 #define CG_BUILD_TIME_LIMIT 30.0
1083 #endif
1084 
1085   // Propagate GlobalEscape and ArgEscape escape states and check that
1086   // we still have non-escaping objects. The method pushs on _worklist
1087   // Field nodes which reference phantom_object.
1088   if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist)) {
1089     return false; // Nothing to do.
1090   }
1091   // Now propagate references to all JavaObject nodes.
1092   int java_objects_length = java_objects_worklist.length();
1093   elapsedTimer time;
1094   int new_edges = 1;
1095   int iterations = 0;
1096   do {
1097     while ((new_edges > 0) &&
1098           (iterations++   < CG_BUILD_ITER_LIMIT) &&
1099           (time.seconds() < CG_BUILD_TIME_LIMIT)) {
1100       time.start();
1101       new_edges = 0;
1102       // Propagate references to phantom_object for nodes pushed on _worklist
1103       // by find_non_escaped_objects() and find_field_value().
1104       new_edges += add_java_object_edges(phantom_obj, false);
1105       for (int next = 0; next < java_objects_length; ++next) {
1106         JavaObjectNode* ptn = java_objects_worklist.at(next);
1107         new_edges += add_java_object_edges(ptn, true);
1108       }
1109       if (new_edges > 0) {
1110         // Update escape states on each iteration if graph was updated.
1111         if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist)) {
1112           return false; // Nothing to do.
1113         }
1114       }
1115       time.stop();
1116     }
1117     if ((iterations     < CG_BUILD_ITER_LIMIT) &&
1118         (time.seconds() < CG_BUILD_TIME_LIMIT)) {
1119       time.start();
1120       // Find fields which have unknown value.
1121       int fields_length = oop_fields_worklist.length();
1122       for (int next = 0; next < fields_length; next++) {
1123         FieldNode* field = oop_fields_worklist.at(next);
1124         if (field->edge_count() == 0) {
1125           new_edges += find_field_value(field);
1126           // This code may added new edges to phantom_object.
1127           // Need an other cycle to propagate references to phantom_object.
1128         }
1129       }
1130       time.stop();
1131     } else {
1132       new_edges = 0; // Bailout
1133     }
1134   } while (new_edges > 0);
1135 
1136   // Bailout if passed limits.
1137   if ((iterations     >= CG_BUILD_ITER_LIMIT) ||
1138       (time.seconds() >= CG_BUILD_TIME_LIMIT)) {
1139     Compile* C = _compile;
1140     if (C->log() != NULL) {
1141       C->log()->begin_elem("connectionGraph_bailout reason='reached ");
1142       C->log()->text("%s", (iterations >= CG_BUILD_ITER_LIMIT) ? "iterations" : "time");
1143       C->log()->end_elem(" limit'");
1144     }
1145     assert(ExitEscapeAnalysisOnTimeout, err_msg_res("infinite EA connection graph build (%f sec, %d iterations) with %d nodes and worklist size %d",
1146            time.seconds(), iterations, nodes_size(), ptnodes_worklist.length()));
1147     // Possible infinite build_connection_graph loop,
1148     // bailout (no changes to ideal graph were made).
1149     return false;
1150   }
1151 #ifdef ASSERT
1152   if (Verbose && PrintEscapeAnalysis) {
1153     tty->print_cr("EA: %d iterations to build connection graph with %d nodes and worklist size %d",
1154                   iterations, nodes_size(), ptnodes_worklist.length());
1155   }
1156 #endif
1157 
1158 #undef CG_BUILD_ITER_LIMIT
1159 #undef CG_BUILD_TIME_LIMIT
1160 
1161   // Find fields initialized by NULL for non-escaping Allocations.
1162   int non_escaped_length = non_escaped_worklist.length();
1163   for (int next = 0; next < non_escaped_length; next++) {
1164     JavaObjectNode* ptn = non_escaped_worklist.at(next);
1165     PointsToNode::EscapeState es = ptn->escape_state();
1166     assert(es <= PointsToNode::ArgEscape, "sanity");
1167     if (es == PointsToNode::NoEscape) {
1168       if (find_init_values(ptn, null_obj, _igvn) > 0) {
1169         // Adding references to NULL object does not change escape states
1170         // since it does not escape. Also no fields are added to NULL object.
1171         add_java_object_edges(null_obj, false);
1172       }
1173     }
1174     Node* n = ptn->ideal_node();
1175     if (n->is_Allocate()) {
1176       // The object allocated by this Allocate node will never be
1177       // seen by an other thread. Mark it so that when it is
1178       // expanded no MemBarStoreStore is added.
1179       InitializeNode* ini = n->as_Allocate()->initialization();
1180       if (ini != NULL)
1181         ini->set_does_not_escape();
1182     }
1183   }
1184   return true; // Finished graph construction.
1185 }
1186 
1187 // Propagate GlobalEscape and ArgEscape escape states to all nodes
1188 // and check that we still have non-escaping java objects.
1189 bool ConnectionGraph::find_non_escaped_objects(GrowableArray<PointsToNode*>& ptnodes_worklist,
1190                                                GrowableArray<JavaObjectNode*>& non_escaped_worklist) {
1191   GrowableArray<PointsToNode*> escape_worklist;
1192   // First, put all nodes with GlobalEscape and ArgEscape states on worklist.
1193   int ptnodes_length = ptnodes_worklist.length();
1194   for (int next = 0; next < ptnodes_length; ++next) {
1195     PointsToNode* ptn = ptnodes_worklist.at(next);
1196     if (ptn->escape_state() >= PointsToNode::ArgEscape ||
1197         ptn->fields_escape_state() >= PointsToNode::ArgEscape) {
1198       escape_worklist.push(ptn);
1199     }
1200   }
1201   // Set escape states to referenced nodes (edges list).
1202   while (escape_worklist.length() > 0) {
1203     PointsToNode* ptn = escape_worklist.pop();
1204     PointsToNode::EscapeState es  = ptn->escape_state();
1205     PointsToNode::EscapeState field_es = ptn->fields_escape_state();
1206     if (ptn->is_Field() && ptn->as_Field()->is_oop() &&
1207         es >= PointsToNode::ArgEscape) {
1208       // GlobalEscape or ArgEscape state of field means it has unknown value.
1209       if (add_edge(ptn, phantom_obj)) {
1210         // New edge was added
1211         add_field_uses_to_worklist(ptn->as_Field());
1212       }
1213     }
1214     for (EdgeIterator i(ptn); i.has_next(); i.next()) {
1215       PointsToNode* e = i.get();
1216       if (e->is_Arraycopy()) {
1217         assert(ptn->arraycopy_dst(), "sanity");
1218         // Propagate only fields escape state through arraycopy edge.
1219         if (e->fields_escape_state() < field_es) {
1220           set_fields_escape_state(e, field_es);
1221           escape_worklist.push(e);
1222         }
1223       } else if (es >= field_es) {
1224         // fields_escape_state is also set to 'es' if it is less than 'es'.
1225         if (e->escape_state() < es) {
1226           set_escape_state(e, es);
1227           escape_worklist.push(e);
1228         }
1229       } else {
1230         // Propagate field escape state.
1231         bool es_changed = false;
1232         if (e->fields_escape_state() < field_es) {
1233           set_fields_escape_state(e, field_es);
1234           es_changed = true;
1235         }
1236         if ((e->escape_state() < field_es) &&
1237             e->is_Field() && ptn->is_JavaObject() &&
1238             e->as_Field()->is_oop()) {
1239           // Change escape state of referenced fileds.
1240           set_escape_state(e, field_es);
1241           es_changed = true;;
1242         } else if (e->escape_state() < es) {
1243           set_escape_state(e, es);
1244           es_changed = true;;
1245         }
1246         if (es_changed) {
1247           escape_worklist.push(e);
1248         }
1249       }
1250     }
1251   }
1252   // Remove escaped objects from non_escaped list.
1253   for (int next = non_escaped_worklist.length()-1; next >= 0 ; --next) {
1254     JavaObjectNode* ptn = non_escaped_worklist.at(next);
1255     if (ptn->escape_state() >= PointsToNode::GlobalEscape) {
1256       non_escaped_worklist.delete_at(next);
1257     }
1258     if (ptn->escape_state() == PointsToNode::NoEscape) {
1259       // Find fields in non-escaped allocations which have unknown value.
1260       find_init_values(ptn, phantom_obj, NULL);
1261     }
1262   }
1263   return (non_escaped_worklist.length() > 0);
1264 }
1265 
1266 // Add all references to JavaObject node by walking over all uses.
1267 int ConnectionGraph::add_java_object_edges(JavaObjectNode* jobj, bool populate_worklist) {
1268   int new_edges = 0;
1269   if (populate_worklist) {
1270     // Populate _worklist by uses of jobj's uses.
1271     for (UseIterator i(jobj); i.has_next(); i.next()) {
1272       PointsToNode* use = i.get();
1273       if (use->is_Arraycopy())
1274         continue;
1275       add_uses_to_worklist(use);
1276       if (use->is_Field() && use->as_Field()->is_oop()) {
1277         // Put on worklist all field's uses (loads) and
1278         // related field nodes (same base and offset).
1279         add_field_uses_to_worklist(use->as_Field());
1280       }
1281     }
1282   }
1283   while(_worklist.length() > 0) {
1284     PointsToNode* use = _worklist.pop();
1285     if (PointsToNode::is_base_use(use)) {
1286       // Add reference from jobj to field and from field to jobj (field's base).
1287       use = PointsToNode::get_use_node(use)->as_Field();
1288       if (add_base(use->as_Field(), jobj)) {
1289         new_edges++;
1290       }
1291       continue;
1292     }
1293     assert(!use->is_JavaObject(), "sanity");
1294     if (use->is_Arraycopy()) {
1295       if (jobj == null_obj) // NULL object does not have field edges
1296         continue;
1297       // Added edge from Arraycopy node to arraycopy's source java object
1298       if (add_edge(use, jobj)) {
1299         jobj->set_arraycopy_src();
1300         new_edges++;
1301       }
1302       // and stop here.
1303       continue;
1304     }
1305     if (!add_edge(use, jobj))
1306       continue; // No new edge added, there was such edge already.
1307     new_edges++;
1308     if (use->is_LocalVar()) {
1309       add_uses_to_worklist(use);
1310       if (use->arraycopy_dst()) {
1311         for (EdgeIterator i(use); i.has_next(); i.next()) {
1312           PointsToNode* e = i.get();
1313           if (e->is_Arraycopy()) {
1314             if (jobj == null_obj) // NULL object does not have field edges
1315               continue;
1316             // Add edge from arraycopy's destination java object to Arraycopy node.
1317             if (add_edge(jobj, e)) {
1318               new_edges++;
1319               jobj->set_arraycopy_dst();
1320             }
1321           }
1322         }
1323       }
1324     } else {
1325       // Added new edge to stored in field values.
1326       // Put on worklist all field's uses (loads) and
1327       // related field nodes (same base and offset).
1328       add_field_uses_to_worklist(use->as_Field());
1329     }
1330   }
1331   return new_edges;
1332 }
1333 
1334 // Put on worklist all related field nodes.
1335 void ConnectionGraph::add_field_uses_to_worklist(FieldNode* field) {
1336   assert(field->is_oop(), "sanity");
1337   int offset = field->offset();
1338   add_uses_to_worklist(field);
1339   // Loop over all bases of this field and push on worklist Field nodes
1340   // with the same offset and base (since they may reference the same field).
1341   for (BaseIterator i(field); i.has_next(); i.next()) {
1342     PointsToNode* base = i.get();
1343     add_fields_to_worklist(field, base);
1344     // Check if the base was source object of arraycopy and go over arraycopy's
1345     // destination objects since values stored to a field of source object are
1346     // accessable by uses (loads) of fields of destination objects.
1347     if (base->arraycopy_src()) {
1348       for (UseIterator j(base); j.has_next(); j.next()) {
1349         PointsToNode* arycp = j.get();
1350         if (arycp->is_Arraycopy()) {
1351           for (UseIterator k(arycp); k.has_next(); k.next()) {
1352             PointsToNode* abase = k.get();
1353             if (abase->arraycopy_dst() && abase != base) {
1354               // Look for the same arracopy reference.
1355               add_fields_to_worklist(field, abase);
1356             }
1357           }
1358         }
1359       }
1360     }
1361   }
1362 }
1363 
1364 // Put on worklist all related field nodes.
1365 void ConnectionGraph::add_fields_to_worklist(FieldNode* field, PointsToNode* base) {
1366   int offset = field->offset();
1367   if (base->is_LocalVar()) {
1368     for (UseIterator j(base); j.has_next(); j.next()) {
1369       PointsToNode* f = j.get();
1370       if (PointsToNode::is_base_use(f)) { // Field
1371         f = PointsToNode::get_use_node(f);
1372         if (f == field || !f->as_Field()->is_oop())
1373           continue;
1374         int offs = f->as_Field()->offset();
1375         if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
1376           add_to_worklist(f);
1377         }
1378       }
1379     }
1380   } else {
1381     assert(base->is_JavaObject(), "sanity");
1382     if (// Skip phantom_object since it is only used to indicate that
1383         // this field's content globally escapes.
1384         (base != phantom_obj) &&
1385         // NULL object node does not have fields.
1386         (base != null_obj)) {
1387       for (EdgeIterator i(base); i.has_next(); i.next()) {
1388         PointsToNode* f = i.get();
1389         // Skip arraycopy edge since store to destination object field
1390         // does not update value in source object field.
1391         if (f->is_Arraycopy()) {
1392           assert(base->arraycopy_dst(), "sanity");
1393           continue;
1394         }
1395         if (f == field || !f->as_Field()->is_oop())
1396           continue;
1397         int offs = f->as_Field()->offset();
1398         if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
1399           add_to_worklist(f);
1400         }
1401       }
1402     }
1403   }
1404 }
1405 
1406 // Find fields which have unknown value.
1407 int ConnectionGraph::find_field_value(FieldNode* field) {
1408   // Escaped fields should have init value already.
1409   assert(field->escape_state() == PointsToNode::NoEscape, "sanity");
1410   int new_edges = 0;
1411   for (BaseIterator i(field); i.has_next(); i.next()) {
1412     PointsToNode* base = i.get();
1413     if (base->is_JavaObject()) {
1414       // Skip Allocate's fields which will be processed later.
1415       if (base->ideal_node()->is_Allocate())
1416         return 0;
1417       assert(base == null_obj, "only NULL ptr base expected here");
1418     }
1419   }
1420   if (add_edge(field, phantom_obj)) {
1421     // New edge was added
1422     new_edges++;
1423     add_field_uses_to_worklist(field);
1424   }
1425   return new_edges;
1426 }
1427 
1428 // Find fields initializing values for allocations.
1429 int ConnectionGraph::find_init_values(JavaObjectNode* pta, PointsToNode* init_val, PhaseTransform* phase) {
1430   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
1431   int new_edges = 0;
1432   Node* alloc = pta->ideal_node();
1433   if (init_val == phantom_obj) {
1434     // Do nothing for Allocate nodes since its fields values are "known".
1435     if (alloc->is_Allocate())
1436       return 0;
1437     assert(alloc->as_CallStaticJava(), "sanity");
1438 #ifdef ASSERT
1439     if (alloc->as_CallStaticJava()->method() == NULL) {
1440       const char* name = alloc->as_CallStaticJava()->_name;
1441       assert(strncmp(name, "_multianewarray", 15) == 0, "sanity");
1442     }
1443 #endif
1444     // Non-escaped allocation returned from Java or runtime call have
1445     // unknown values in fields.
1446     for (EdgeIterator i(pta); i.has_next(); i.next()) {
1447       PointsToNode* field = i.get();
1448       if (field->is_Field() && field->as_Field()->is_oop()) {
1449         if (add_edge(field, phantom_obj)) {
1450           // New edge was added
1451           new_edges++;
1452           add_field_uses_to_worklist(field->as_Field());
1453         }
1454       }
1455     }
1456     return new_edges;
1457   }
1458   assert(init_val == null_obj, "sanity");
1459   // Do nothing for Call nodes since its fields values are unknown.
1460   if (!alloc->is_Allocate())
1461     return 0;
1462 
1463   InitializeNode* ini = alloc->as_Allocate()->initialization();
1464   bool visited_bottom_offset = false;
1465   GrowableArray<int> offsets_worklist;
1466 
1467   // Check if an oop field's initializing value is recorded and add
1468   // a corresponding NULL if field's value if it is not recorded.
1469   // Connection Graph does not record a default initialization by NULL
1470   // captured by Initialize node.
1471   //
1472   for (EdgeIterator i(pta); i.has_next(); i.next()) {
1473     PointsToNode* field = i.get(); // Field (AddP)
1474     if (!field->is_Field() || !field->as_Field()->is_oop())
1475       continue; // Not oop field
1476     int offset = field->as_Field()->offset();
1477     if (offset == Type::OffsetBot) {
1478       if (!visited_bottom_offset) {
1479         // OffsetBot is used to reference array's element,
1480         // always add reference to NULL to all Field nodes since we don't
1481         // known which element is referenced.
1482         if (add_edge(field, null_obj)) {
1483           // New edge was added
1484           new_edges++;
1485           add_field_uses_to_worklist(field->as_Field());
1486           visited_bottom_offset = true;
1487         }
1488       }
1489     } else {
1490       // Check only oop fields.
1491       const Type* adr_type = field->ideal_node()->as_AddP()->bottom_type();
1492       if (adr_type->isa_rawptr()) {
1493 #ifdef ASSERT
1494         // Raw pointers are used for initializing stores so skip it
1495         // since it should be recorded already
1496         Node* base = get_addp_base(field->ideal_node());
1497         assert(adr_type->isa_rawptr() && base->is_Proj() &&
1498                (base->in(0) == alloc),"unexpected pointer type");
1499 #endif
1500         continue;
1501       }
1502       if (!offsets_worklist.contains(offset)) {
1503         offsets_worklist.append(offset);
1504         Node* value = NULL;
1505         if (ini != NULL) {
1506           // StoreP::memory_type() == T_ADDRESS
1507           BasicType ft = UseCompressedOops ? T_NARROWOOP : T_ADDRESS;
1508           Node* store = ini->find_captured_store(offset, type2aelembytes(ft, true), phase);
1509           // Make sure initializing store has the same type as this AddP.
1510           // This AddP may reference non existing field because it is on a
1511           // dead branch of bimorphic call which is not eliminated yet.
1512           if (store != NULL && store->is_Store() &&
1513               store->as_Store()->memory_type() == ft) {
1514             value = store->in(MemNode::ValueIn);
1515 #ifdef ASSERT
1516             if (VerifyConnectionGraph) {
1517               // Verify that AddP already points to all objects the value points to.
1518               PointsToNode* val = ptnode_adr(value->_idx);
1519               assert((val != NULL), "should be processed already");
1520               PointsToNode* missed_obj = NULL;
1521               if (val->is_JavaObject()) {
1522                 if (!field->points_to(val->as_JavaObject())) {
1523                   missed_obj = val;
1524                 }
1525               } else {
1526                 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
1527                   tty->print_cr("----------init store has invalid value -----");
1528                   store->dump();
1529                   val->dump();
1530                   assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
1531                 }
1532                 for (EdgeIterator j(val); j.has_next(); j.next()) {
1533                   PointsToNode* obj = j.get();
1534                   if (obj->is_JavaObject()) {
1535                     if (!field->points_to(obj->as_JavaObject())) {
1536                       missed_obj = obj;
1537                       break;
1538                     }
1539                   }
1540                 }
1541               }
1542               if (missed_obj != NULL) {
1543                 tty->print_cr("----------field---------------------------------");
1544                 field->dump();
1545                 tty->print_cr("----------missed referernce to object-----------");
1546                 missed_obj->dump();
1547                 tty->print_cr("----------object referernced by init store -----");
1548                 store->dump();
1549                 val->dump();
1550                 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
1551               }
1552             }
1553 #endif
1554           } else {
1555             // There could be initializing stores which follow allocation.
1556             // For example, a volatile field store is not collected
1557             // by Initialize node.
1558             //
1559             // Need to check for dependent loads to separate such stores from
1560             // stores which follow loads. For now, add initial value NULL so
1561             // that compare pointers optimization works correctly.
1562           }
1563         }
1564         if (value == NULL) {
1565           // A field's initializing value was not recorded. Add NULL.
1566           if (add_edge(field, null_obj)) {
1567             // New edge was added
1568             new_edges++;
1569             add_field_uses_to_worklist(field->as_Field());
1570           }
1571         }
1572       }
1573     }
1574   }
1575   return new_edges;
1576 }
1577 
1578 // Adjust scalar_replaceable state after Connection Graph is built.
1579 void ConnectionGraph::adjust_scalar_replaceable_state(JavaObjectNode* jobj) {
1580   // Search for non-escaping objects which are not scalar replaceable
1581   // and mark them to propagate the state to referenced objects.
1582 
1583   // 1. An object is not scalar replaceable if the field into which it is
1584   // stored has unknown offset (stored into unknown element of an array).
1585   //
1586   for (UseIterator i(jobj); i.has_next(); i.next()) {
1587     PointsToNode* use = i.get();
1588     assert(!use->is_Arraycopy(), "sanity");
1589     if (use->is_Field()) {
1590       FieldNode* field = use->as_Field();
1591       assert(field->is_oop() && field->scalar_replaceable() &&
1592              field->fields_escape_state() == PointsToNode::NoEscape, "sanity");
1593       if (field->offset() == Type::OffsetBot) {
1594         jobj->set_scalar_replaceable(false);
1595         return;
1596       }
1597       // 2. An object is not scalar replaceable if the field into which it is
1598       // stored has multiple bases one of which is null.
1599       if (field->base_count() > 1) {
1600         for (BaseIterator i(field); i.has_next(); i.next()) {
1601           PointsToNode* base = i.get();
1602           if (base == null_obj) {
1603             jobj->set_scalar_replaceable(false);
1604             return;
1605           }
1606         }
1607       }
1608     }
1609     assert(use->is_Field() || use->is_LocalVar(), "sanity");
1610     // 3. An object is not scalar replaceable if it is merged with other objects.
1611     for (EdgeIterator j(use); j.has_next(); j.next()) {
1612       PointsToNode* ptn = j.get();
1613       if (ptn->is_JavaObject() && ptn != jobj) {
1614         // Mark all objects.
1615         jobj->set_scalar_replaceable(false);
1616          ptn->set_scalar_replaceable(false);
1617       }
1618     }
1619     if (!jobj->scalar_replaceable()) {
1620       return;
1621     }
1622   }
1623 
1624   for (EdgeIterator j(jobj); j.has_next(); j.next()) {
1625     // Non-escaping object node should point only to field nodes.
1626     FieldNode* field = j.get()->as_Field();
1627     int offset = field->as_Field()->offset();
1628 
1629     // 4. An object is not scalar replaceable if it has a field with unknown
1630     // offset (array's element is accessed in loop).
1631     if (offset == Type::OffsetBot) {
1632       jobj->set_scalar_replaceable(false);
1633       return;
1634     }
1635     // 5. Currently an object is not scalar replaceable if a LoadStore node
1636     // access its field since the field value is unknown after it.
1637     //
1638     Node* n = field->ideal_node();
1639     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1640       if (n->fast_out(i)->is_LoadStore()) {
1641         jobj->set_scalar_replaceable(false);
1642         return;
1643       }
1644     }
1645 
1646     // 6. Or the address may point to more then one object. This may produce
1647     // the false positive result (set not scalar replaceable)
1648     // since the flow-insensitive escape analysis can't separate
1649     // the case when stores overwrite the field's value from the case
1650     // when stores happened on different control branches.
1651     //
1652     // Note: it will disable scalar replacement in some cases:
1653     //
1654     //    Point p[] = new Point[1];
1655     //    p[0] = new Point(); // Will be not scalar replaced
1656     //
1657     // but it will save us from incorrect optimizations in next cases:
1658     //
1659     //    Point p[] = new Point[1];
1660     //    if ( x ) p[0] = new Point(); // Will be not scalar replaced
1661     //
1662     if (field->base_count() > 1) {
1663       for (BaseIterator i(field); i.has_next(); i.next()) {
1664         PointsToNode* base = i.get();
1665         // Don't take into account LocalVar nodes which
1666         // may point to only one object which should be also
1667         // this field's base by now.
1668         if (base->is_JavaObject() && base != jobj) {
1669           // Mark all bases.
1670           jobj->set_scalar_replaceable(false);
1671           base->set_scalar_replaceable(false);
1672         }
1673       }
1674     }
1675   }
1676 }
1677 
1678 #ifdef ASSERT
1679 void ConnectionGraph::verify_connection_graph(
1680                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
1681                          GrowableArray<JavaObjectNode*>& non_escaped_worklist,
1682                          GrowableArray<JavaObjectNode*>& java_objects_worklist,
1683                          GrowableArray<Node*>& addp_worklist) {
1684   // Verify that graph is complete - no new edges could be added.
1685   int java_objects_length = java_objects_worklist.length();
1686   int non_escaped_length  = non_escaped_worklist.length();
1687   int new_edges = 0;
1688   for (int next = 0; next < java_objects_length; ++next) {
1689     JavaObjectNode* ptn = java_objects_worklist.at(next);
1690     new_edges += add_java_object_edges(ptn, true);
1691   }
1692   assert(new_edges == 0, "graph was not complete");
1693   // Verify that escape state is final.
1694   int length = non_escaped_worklist.length();
1695   find_non_escaped_objects(ptnodes_worklist, non_escaped_worklist);
1696   assert((non_escaped_length == non_escaped_worklist.length()) &&
1697          (non_escaped_length == length) &&
1698          (_worklist.length() == 0), "escape state was not final");
1699 
1700   // Verify fields information.
1701   int addp_length = addp_worklist.length();
1702   for (int next = 0; next < addp_length; ++next ) {
1703     Node* n = addp_worklist.at(next);
1704     FieldNode* field = ptnode_adr(n->_idx)->as_Field();
1705     if (field->is_oop()) {
1706       // Verify that field has all bases
1707       Node* base = get_addp_base(n);
1708       PointsToNode* ptn = ptnode_adr(base->_idx);
1709       if (ptn->is_JavaObject()) {
1710         assert(field->has_base(ptn->as_JavaObject()), "sanity");
1711       } else {
1712         assert(ptn->is_LocalVar(), "sanity");
1713         for (EdgeIterator i(ptn); i.has_next(); i.next()) {
1714           PointsToNode* e = i.get();
1715           if (e->is_JavaObject()) {
1716             assert(field->has_base(e->as_JavaObject()), "sanity");
1717           }
1718         }
1719       }
1720       // Verify that all fields have initializing values.
1721       if (field->edge_count() == 0) {
1722         tty->print_cr("----------field does not have references----------");
1723         field->dump();
1724         for (BaseIterator i(field); i.has_next(); i.next()) {
1725           PointsToNode* base = i.get();
1726           tty->print_cr("----------field has next base---------------------");
1727           base->dump();
1728           if (base->is_JavaObject() && (base != phantom_obj) && (base != null_obj)) {
1729             tty->print_cr("----------base has fields-------------------------");
1730             for (EdgeIterator j(base); j.has_next(); j.next()) {
1731               j.get()->dump();
1732             }
1733             tty->print_cr("----------base has references---------------------");
1734             for (UseIterator j(base); j.has_next(); j.next()) {
1735               j.get()->dump();
1736             }
1737           }
1738         }
1739         for (UseIterator i(field); i.has_next(); i.next()) {
1740           i.get()->dump();
1741         }
1742         assert(field->edge_count() > 0, "sanity");
1743       }
1744     }
1745   }
1746 }
1747 #endif
1748 
1749 // Optimize ideal graph.
1750 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
1751                                            GrowableArray<Node*>& storestore_worklist) {
1752   Compile* C = _compile;
1753   PhaseIterGVN* igvn = _igvn;
1754   if (EliminateLocks) {
1755     // Mark locks before changing ideal graph.
1756     int cnt = C->macro_count();
1757     for( int i=0; i < cnt; i++ ) {
1758       Node *n = C->macro_node(i);
1759       if (n->is_AbstractLock()) { // Lock and Unlock nodes
1760         AbstractLockNode* alock = n->as_AbstractLock();
1761         if (!alock->is_non_esc_obj()) {
1762           if (not_global_escape(alock->obj_node())) {
1763             assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
1764             // The lock could be marked eliminated by lock coarsening
1765             // code during first IGVN before EA. Replace coarsened flag
1766             // to eliminate all associated locks/unlocks.
1767             alock->set_non_esc_obj();
1768           }
1769         }
1770       }
1771     }
1772   }
1773 
1774   if (OptimizePtrCompare) {
1775     // Add ConI(#CC_GT) and ConI(#CC_EQ).
1776     _pcmp_neq = igvn->makecon(TypeInt::CC_GT);
1777     _pcmp_eq = igvn->makecon(TypeInt::CC_EQ);
1778     // Optimize objects compare.
1779     while (ptr_cmp_worklist.length() != 0) {
1780       Node *n = ptr_cmp_worklist.pop();
1781       Node *res = optimize_ptr_compare(n);
1782       if (res != NULL) {
1783 #ifndef PRODUCT
1784         if (PrintOptimizePtrCompare) {
1785           tty->print_cr("++++ Replaced: %d %s(%d,%d) --> %s", n->_idx, (n->Opcode() == Op_CmpP ? "CmpP" : "CmpN"), n->in(1)->_idx, n->in(2)->_idx, (res == _pcmp_eq ? "EQ" : "NotEQ"));
1786           if (Verbose) {
1787             n->dump(1);
1788           }
1789         }
1790 #endif
1791         igvn->replace_node(n, res);
1792       }
1793     }
1794     // cleanup
1795     if (_pcmp_neq->outcnt() == 0)
1796       igvn->hash_delete(_pcmp_neq);
1797     if (_pcmp_eq->outcnt()  == 0)
1798       igvn->hash_delete(_pcmp_eq);
1799   }
1800 
1801   // For MemBarStoreStore nodes added in library_call.cpp, check
1802   // escape status of associated AllocateNode and optimize out
1803   // MemBarStoreStore node if the allocated object never escapes.
1804   while (storestore_worklist.length() != 0) {
1805     Node *n = storestore_worklist.pop();
1806     MemBarStoreStoreNode *storestore = n ->as_MemBarStoreStore();
1807     Node *alloc = storestore->in(MemBarNode::Precedent)->in(0);
1808     assert (alloc->is_Allocate(), "storestore should point to AllocateNode");
1809     if (not_global_escape(alloc)) {
1810       MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
1811       mb->init_req(TypeFunc::Memory, storestore->in(TypeFunc::Memory));
1812       mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
1813       igvn->register_new_node_with_optimizer(mb);
1814       igvn->replace_node(storestore, mb);
1815     }
1816   }
1817 }
1818 
1819 // Optimize objects compare.
1820 Node* ConnectionGraph::optimize_ptr_compare(Node* n) {
1821   assert(OptimizePtrCompare, "sanity");
1822   PointsToNode* ptn1 = ptnode_adr(n->in(1)->_idx);
1823   PointsToNode* ptn2 = ptnode_adr(n->in(2)->_idx);
1824   JavaObjectNode* jobj1 = unique_java_object(n->in(1));
1825   JavaObjectNode* jobj2 = unique_java_object(n->in(2));
1826   assert(ptn1->is_JavaObject() || ptn1->is_LocalVar(), "sanity");
1827   assert(ptn2->is_JavaObject() || ptn2->is_LocalVar(), "sanity");
1828 
1829   // Check simple cases first.
1830   if (jobj1 != NULL) {
1831     if (jobj1->escape_state() == PointsToNode::NoEscape) {
1832       if (jobj1 == jobj2) {
1833         // Comparing the same not escaping object.
1834         return _pcmp_eq;
1835       }
1836       Node* obj = jobj1->ideal_node();
1837       // Comparing not escaping allocation.
1838       if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
1839           !ptn2->points_to(jobj1)) {
1840         return _pcmp_neq; // This includes nullness check.
1841       }
1842     }
1843   }
1844   if (jobj2 != NULL) {
1845     if (jobj2->escape_state() == PointsToNode::NoEscape) {
1846       Node* obj = jobj2->ideal_node();
1847       // Comparing not escaping allocation.
1848       if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
1849           !ptn1->points_to(jobj2)) {
1850         return _pcmp_neq; // This includes nullness check.
1851       }
1852     }
1853   }
1854   if (jobj1 != NULL && jobj1 != phantom_obj &&
1855       jobj2 != NULL && jobj2 != phantom_obj &&
1856       jobj1->ideal_node()->is_Con() &&
1857       jobj2->ideal_node()->is_Con()) {
1858     // Klass or String constants compare. Need to be careful with
1859     // compressed pointers - compare types of ConN and ConP instead of nodes.
1860     const Type* t1 = jobj1->ideal_node()->get_ptr_type();
1861     const Type* t2 = jobj2->ideal_node()->get_ptr_type();
1862     if (t1->make_ptr() == t2->make_ptr()) {
1863       return _pcmp_eq;
1864     } else {
1865       return _pcmp_neq;
1866     }
1867   }
1868   if (ptn1->meet(ptn2)) {
1869     return NULL; // Sets are not disjoint
1870   }
1871 
1872   // Sets are disjoint.
1873   bool set1_has_unknown_ptr = ptn1->points_to(phantom_obj);
1874   bool set2_has_unknown_ptr = ptn2->points_to(phantom_obj);
1875   bool set1_has_null_ptr    = ptn1->points_to(null_obj);
1876   bool set2_has_null_ptr    = ptn2->points_to(null_obj);
1877   if (set1_has_unknown_ptr && set2_has_null_ptr ||
1878       set2_has_unknown_ptr && set1_has_null_ptr) {
1879     // Check nullness of unknown object.
1880     return NULL;
1881   }
1882 
1883   // Disjointness by itself is not sufficient since
1884   // alias analysis is not complete for escaped objects.
1885   // Disjoint sets are definitely unrelated only when
1886   // at least one set has only not escaping allocations.
1887   if (!set1_has_unknown_ptr && !set1_has_null_ptr) {
1888     if (ptn1->non_escaping_allocation()) {
1889       return _pcmp_neq;
1890     }
1891   }
1892   if (!set2_has_unknown_ptr && !set2_has_null_ptr) {
1893     if (ptn2->non_escaping_allocation()) {
1894       return _pcmp_neq;
1895     }
1896   }
1897   return NULL;
1898 }
1899 
1900 // Connection Graph constuction functions.
1901 
1902 void ConnectionGraph::add_local_var(Node *n, PointsToNode::EscapeState es) {
1903   PointsToNode* ptadr = _nodes.at(n->_idx);
1904   if (ptadr != NULL) {
1905     assert(ptadr->is_LocalVar() && ptadr->ideal_node() == n, "sanity");
1906     return;
1907   }
1908   Compile* C = _compile;
1909   ptadr = new (C->comp_arena()) LocalVarNode(C, n, es);
1910   _nodes.at_put(n->_idx, ptadr);
1911 }
1912 
1913 void ConnectionGraph::add_java_object(Node *n, PointsToNode::EscapeState es) {
1914   PointsToNode* ptadr = _nodes.at(n->_idx);
1915   if (ptadr != NULL) {
1916     assert(ptadr->is_JavaObject() && ptadr->ideal_node() == n, "sanity");
1917     return;
1918   }
1919   Compile* C = _compile;
1920   ptadr = new (C->comp_arena()) JavaObjectNode(C, n, es);
1921   _nodes.at_put(n->_idx, ptadr);
1922 }
1923 
1924 void ConnectionGraph::add_field(Node *n, PointsToNode::EscapeState es, int offset) {
1925   PointsToNode* ptadr = _nodes.at(n->_idx);
1926   if (ptadr != NULL) {
1927     assert(ptadr->is_Field() && ptadr->ideal_node() == n, "sanity");
1928     return;
1929   }
1930   bool unsafe = false;
1931   bool is_oop = is_oop_field(n, offset, &unsafe);
1932   if (unsafe) {
1933     es = PointsToNode::GlobalEscape;
1934   }
1935   Compile* C = _compile;
1936   FieldNode* field = new (C->comp_arena()) FieldNode(C, n, es, offset, is_oop);
1937   _nodes.at_put(n->_idx, field);
1938 }
1939 
1940 void ConnectionGraph::add_arraycopy(Node *n, PointsToNode::EscapeState es,
1941                                     PointsToNode* src, PointsToNode* dst) {
1942   assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
1943   assert((src != null_obj) && (dst != null_obj), "not for ConP NULL");
1944   PointsToNode* ptadr = _nodes.at(n->_idx);
1945   if (ptadr != NULL) {
1946     assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
1947     return;
1948   }
1949   Compile* C = _compile;
1950   ptadr = new (C->comp_arena()) ArraycopyNode(C, n, es);
1951   _nodes.at_put(n->_idx, ptadr);
1952   // Add edge from arraycopy node to source object.
1953   (void)add_edge(ptadr, src);
1954   src->set_arraycopy_src();
1955   // Add edge from destination object to arraycopy node.
1956   (void)add_edge(dst, ptadr);
1957   dst->set_arraycopy_dst();
1958 }
1959 
1960 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
1961   const Type* adr_type = n->as_AddP()->bottom_type();
1962   BasicType bt = T_INT;
1963   if (offset == Type::OffsetBot) {
1964     // Check only oop fields.
1965     if (!adr_type->isa_aryptr() ||
1966         (adr_type->isa_aryptr()->klass() == NULL) ||
1967          adr_type->isa_aryptr()->klass()->is_obj_array_klass()) {
1968       // OffsetBot is used to reference array's element. Ignore first AddP.
1969       if (find_second_addp(n, n->in(AddPNode::Base)) == NULL) {
1970         bt = T_OBJECT;
1971       }
1972     }
1973   } else if (offset != oopDesc::klass_offset_in_bytes()) {
1974     if (adr_type->isa_instptr()) {
1975       ciField* field = _compile->alias_type(adr_type->isa_instptr())->field();
1976       if (field != NULL) {
1977         bt = field->layout_type();
1978       } else {
1979         // Check for unsafe oop field access
1980         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1981           int opcode = n->fast_out(i)->Opcode();
1982           if (opcode == Op_StoreP || opcode == Op_LoadP ||
1983               opcode == Op_StoreN || opcode == Op_LoadN) {
1984             bt = T_OBJECT;
1985             (*unsafe) = true;
1986             break;
1987           }
1988         }
1989       }
1990     } else if (adr_type->isa_aryptr()) {
1991       if (offset == arrayOopDesc::length_offset_in_bytes()) {
1992         // Ignore array length load.
1993       } else if (find_second_addp(n, n->in(AddPNode::Base)) != NULL) {
1994         // Ignore first AddP.
1995       } else {
1996         const Type* elemtype = adr_type->isa_aryptr()->elem();
1997         bt = elemtype->array_element_basic_type();
1998       }
1999     } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
2000       // Allocation initialization, ThreadLocal field access, unsafe access
2001       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2002         int opcode = n->fast_out(i)->Opcode();
2003         if (opcode == Op_StoreP || opcode == Op_LoadP ||
2004             opcode == Op_StoreN || opcode == Op_LoadN) {
2005           bt = T_OBJECT;
2006           break;
2007         }
2008       }
2009     }
2010   }
2011   return (bt == T_OBJECT || bt == T_NARROWOOP || bt == T_ARRAY);
2012 }
2013 
2014 // Returns unique pointed java object or NULL.
2015 JavaObjectNode* ConnectionGraph::unique_java_object(Node *n) {
2016   assert(!_collecting, "should not call when contructed graph");
2017   // If the node was created after the escape computation we can't answer.
2018   uint idx = n->_idx;
2019   if (idx >= nodes_size()) {
2020     return NULL;
2021   }
2022   PointsToNode* ptn = ptnode_adr(idx);
2023   if (ptn->is_JavaObject()) {
2024     return ptn->as_JavaObject();
2025   }
2026   assert(ptn->is_LocalVar(), "sanity");
2027   // Check all java objects it points to.
2028   JavaObjectNode* jobj = NULL;
2029   for (EdgeIterator i(ptn); i.has_next(); i.next()) {
2030     PointsToNode* e = i.get();
2031     if (e->is_JavaObject()) {
2032       if (jobj == NULL) {
2033         jobj = e->as_JavaObject();
2034       } else if (jobj != e) {
2035         return NULL;
2036       }
2037     }
2038   }
2039   return jobj;
2040 }
2041 
2042 // Return true if this node points only to non-escaping allocations.
2043 bool PointsToNode::non_escaping_allocation() {
2044   if (is_JavaObject()) {
2045     Node* n = ideal_node();
2046     if (n->is_Allocate() || n->is_CallStaticJava()) {
2047       return (escape_state() == PointsToNode::NoEscape);
2048     } else {
2049       return false;
2050     }
2051   }
2052   assert(is_LocalVar(), "sanity");
2053   // Check all java objects it points to.
2054   for (EdgeIterator i(this); i.has_next(); i.next()) {
2055     PointsToNode* e = i.get();
2056     if (e->is_JavaObject()) {
2057       Node* n = e->ideal_node();
2058       if ((e->escape_state() != PointsToNode::NoEscape) ||
2059           !(n->is_Allocate() || n->is_CallStaticJava())) {
2060         return false;
2061       }
2062     }
2063   }
2064   return true;
2065 }
2066 
2067 // Return true if we know the node does not escape globally.
2068 bool ConnectionGraph::not_global_escape(Node *n) {
2069   assert(!_collecting, "should not call during graph construction");
2070   // If the node was created after the escape computation we can't answer.
2071   uint idx = n->_idx;
2072   if (idx >= nodes_size()) {
2073     return false;
2074   }
2075   PointsToNode* ptn = ptnode_adr(idx);
2076   PointsToNode::EscapeState es = ptn->escape_state();
2077   // If we have already computed a value, return it.
2078   if (es >= PointsToNode::GlobalEscape)
2079     return false;
2080   if (ptn->is_JavaObject()) {
2081     return true; // (es < PointsToNode::GlobalEscape);
2082   }
2083   assert(ptn->is_LocalVar(), "sanity");
2084   // Check all java objects it points to.
2085   for (EdgeIterator i(ptn); i.has_next(); i.next()) {
2086     if (i.get()->escape_state() >= PointsToNode::GlobalEscape)
2087       return false;
2088   }
2089   return true;
2090 }
2091 
2092 
2093 // Helper functions
2094 
2095 // Return true if this node points to specified node or nodes it points to.
2096 bool PointsToNode::points_to(JavaObjectNode* ptn) const {
2097   if (is_JavaObject()) {
2098     return (this == ptn);
2099   }
2100   assert(is_LocalVar() || is_Field(), "sanity");
2101   for (EdgeIterator i(this); i.has_next(); i.next()) {
2102     if (i.get() == ptn)
2103       return true;
2104   }
2105   return false;
2106 }
2107 
2108 // Return true if one node points to an other.
2109 bool PointsToNode::meet(PointsToNode* ptn) {
2110   if (this == ptn) {
2111     return true;
2112   } else if (ptn->is_JavaObject()) {
2113     return this->points_to(ptn->as_JavaObject());
2114   } else if (this->is_JavaObject()) {
2115     return ptn->points_to(this->as_JavaObject());
2116   }
2117   assert(this->is_LocalVar() && ptn->is_LocalVar(), "sanity");
2118   int ptn_count =  ptn->edge_count();
2119   for (EdgeIterator i(this); i.has_next(); i.next()) {
2120     PointsToNode* this_e = i.get();
2121     for (int j = 0; j < ptn_count; j++) {
2122       if (this_e == ptn->edge(j))
2123         return true;
2124     }
2125   }
2126   return false;
2127 }
2128 
2129 #ifdef ASSERT
2130 // Return true if bases point to this java object.
2131 bool FieldNode::has_base(JavaObjectNode* jobj) const {
2132   for (BaseIterator i(this); i.has_next(); i.next()) {
2133     if (i.get() == jobj)
2134       return true;
2135   }
2136   return false;
2137 }
2138 #endif
2139 
2140 int ConnectionGraph::address_offset(Node* adr, PhaseTransform *phase) {
2141   const Type *adr_type = phase->type(adr);
2142   if (adr->is_AddP() && adr_type->isa_oopptr() == NULL &&
2143       adr->in(AddPNode::Address)->is_Proj() &&
2144       adr->in(AddPNode::Address)->in(0)->is_Allocate()) {
2145     // We are computing a raw address for a store captured by an Initialize
2146     // compute an appropriate address type. AddP cases #3 and #5 (see below).
2147     int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
2148     assert(offs != Type::OffsetBot ||
2149            adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
2150            "offset must be a constant or it is initialization of array");
2151     return offs;
2152   }
2153   const TypePtr *t_ptr = adr_type->isa_ptr();
2154   assert(t_ptr != NULL, "must be a pointer type");
2155   return t_ptr->offset();
2156 }
2157 
2158 Node* ConnectionGraph::get_addp_base(Node *addp) {
2159   assert(addp->is_AddP(), "must be AddP");
2160   //
2161   // AddP cases for Base and Address inputs:
2162   // case #1. Direct object's field reference:
2163   //     Allocate
2164   //       |
2165   //     Proj #5 ( oop result )
2166   //       |
2167   //     CheckCastPP (cast to instance type)
2168   //      | |
2169   //     AddP  ( base == address )
2170   //
2171   // case #2. Indirect object's field reference:
2172   //      Phi
2173   //       |
2174   //     CastPP (cast to instance type)
2175   //      | |
2176   //     AddP  ( base == address )
2177   //
2178   // case #3. Raw object's field reference for Initialize node:
2179   //      Allocate
2180   //        |
2181   //      Proj #5 ( oop result )
2182   //  top   |
2183   //     \  |
2184   //     AddP  ( base == top )
2185   //
2186   // case #4. Array's element reference:
2187   //   {CheckCastPP | CastPP}
2188   //     |  | |
2189   //     |  AddP ( array's element offset )
2190   //     |  |
2191   //     AddP ( array's offset )
2192   //
2193   // case #5. Raw object's field reference for arraycopy stub call:
2194   //          The inline_native_clone() case when the arraycopy stub is called
2195   //          after the allocation before Initialize and CheckCastPP nodes.
2196   //      Allocate
2197   //        |
2198   //      Proj #5 ( oop result )
2199   //       | |
2200   //       AddP  ( base == address )
2201   //
2202   // case #6. Constant Pool, ThreadLocal, CastX2P or
2203   //          Raw object's field reference:
2204   //      {ConP, ThreadLocal, CastX2P, raw Load}
2205   //  top   |
2206   //     \  |
2207   //     AddP  ( base == top )
2208   //
2209   // case #7. Klass's field reference.
2210   //      LoadKlass
2211   //       | |
2212   //       AddP  ( base == address )
2213   //
2214   // case #8. narrow Klass's field reference.
2215   //      LoadNKlass
2216   //       |
2217   //      DecodeN
2218   //       | |
2219   //       AddP  ( base == address )
2220   //
2221   Node *base = addp->in(AddPNode::Base);
2222   if (base->uncast()->is_top()) { // The AddP case #3 and #6.
2223     base = addp->in(AddPNode::Address);
2224     while (base->is_AddP()) {
2225       // Case #6 (unsafe access) may have several chained AddP nodes.
2226       assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
2227       base = base->in(AddPNode::Address);
2228     }
2229     Node* uncast_base = base->uncast();
2230     int opcode = uncast_base->Opcode();
2231     assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
2232            opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() ||
2233            (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_rawptr() != NULL)) ||
2234            (uncast_base->is_Proj() && uncast_base->in(0)->is_Allocate()), "sanity");
2235   }
2236   return base;
2237 }
2238 
2239 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
2240   assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
2241   Node* addp2 = addp->raw_out(0);
2242   if (addp->outcnt() == 1 && addp2->is_AddP() &&
2243       addp2->in(AddPNode::Base) == n &&
2244       addp2->in(AddPNode::Address) == addp) {
2245     assert(addp->in(AddPNode::Base) == n, "expecting the same base");
2246     //
2247     // Find array's offset to push it on worklist first and
2248     // as result process an array's element offset first (pushed second)
2249     // to avoid CastPP for the array's offset.
2250     // Otherwise the inserted CastPP (LocalVar) will point to what
2251     // the AddP (Field) points to. Which would be wrong since
2252     // the algorithm expects the CastPP has the same point as
2253     // as AddP's base CheckCastPP (LocalVar).
2254     //
2255     //    ArrayAllocation
2256     //     |
2257     //    CheckCastPP
2258     //     |
2259     //    memProj (from ArrayAllocation CheckCastPP)
2260     //     |  ||
2261     //     |  ||   Int (element index)
2262     //     |  ||    |   ConI (log(element size))
2263     //     |  ||    |   /
2264     //     |  ||   LShift
2265     //     |  ||  /
2266     //     |  AddP (array's element offset)
2267     //     |  |
2268     //     |  | ConI (array's offset: #12(32-bits) or #24(64-bits))
2269     //     | / /
2270     //     AddP (array's offset)
2271     //      |
2272     //     Load/Store (memory operation on array's element)
2273     //
2274     return addp2;
2275   }
2276   return NULL;
2277 }
2278 
2279 //
2280 // Adjust the type and inputs of an AddP which computes the
2281 // address of a field of an instance
2282 //
2283 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
2284   PhaseGVN* igvn = _igvn;
2285   const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
2286   assert(base_t != NULL && base_t->is_known_instance(), "expecting instance oopptr");
2287   const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
2288   if (t == NULL) {
2289     // We are computing a raw address for a store captured by an Initialize
2290     // compute an appropriate address type (cases #3 and #5).
2291     assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
2292     assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
2293     intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
2294     assert(offs != Type::OffsetBot, "offset must be a constant");
2295     t = base_t->add_offset(offs)->is_oopptr();
2296   }
2297   int inst_id =  base_t->instance_id();
2298   assert(!t->is_known_instance() || t->instance_id() == inst_id,
2299                              "old type must be non-instance or match new type");
2300 
2301   // The type 't' could be subclass of 'base_t'.
2302   // As result t->offset() could be large then base_t's size and it will
2303   // cause the failure in add_offset() with narrow oops since TypeOopPtr()
2304   // constructor verifies correctness of the offset.
2305   //
2306   // It could happened on subclass's branch (from the type profiling
2307   // inlining) which was not eliminated during parsing since the exactness
2308   // of the allocation type was not propagated to the subclass type check.
2309   //
2310   // Or the type 't' could be not related to 'base_t' at all.
2311   // It could happened when CHA type is different from MDO type on a dead path
2312   // (for example, from instanceof check) which is not collapsed during parsing.
2313   //
2314   // Do nothing for such AddP node and don't process its users since
2315   // this code branch will go away.
2316   //
2317   if (!t->is_known_instance() &&
2318       !base_t->klass()->is_subtype_of(t->klass())) {
2319      return false; // bail out
2320   }
2321   const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();
2322   // Do NOT remove the next line: ensure a new alias index is allocated
2323   // for the instance type. Note: C++ will not remove it since the call
2324   // has side effect.
2325   int alias_idx = _compile->get_alias_index(tinst);
2326   igvn->set_type(addp, tinst);
2327   // record the allocation in the node map
2328   set_map(addp, get_map(base->_idx));
2329   // Set addp's Base and Address to 'base'.
2330   Node *abase = addp->in(AddPNode::Base);
2331   Node *adr   = addp->in(AddPNode::Address);
2332   if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
2333       adr->in(0)->_idx == (uint)inst_id) {
2334     // Skip AddP cases #3 and #5.
2335   } else {
2336     assert(!abase->is_top(), "sanity"); // AddP case #3
2337     if (abase != base) {
2338       igvn->hash_delete(addp);
2339       addp->set_req(AddPNode::Base, base);
2340       if (abase == adr) {
2341         addp->set_req(AddPNode::Address, base);
2342       } else {
2343         // AddP case #4 (adr is array's element offset AddP node)
2344 #ifdef ASSERT
2345         const TypeOopPtr *atype = igvn->type(adr)->isa_oopptr();
2346         assert(adr->is_AddP() && atype != NULL &&
2347                atype->instance_id() == inst_id, "array's element offset should be processed first");
2348 #endif
2349       }
2350       igvn->hash_insert(addp);
2351     }
2352   }
2353   // Put on IGVN worklist since at least addp's type was changed above.
2354   record_for_optimizer(addp);
2355   return true;
2356 }
2357 
2358 //
2359 // Create a new version of orig_phi if necessary. Returns either the newly
2360 // created phi or an existing phi.  Sets create_new to indicate whether a new
2361 // phi was created.  Cache the last newly created phi in the node map.
2362 //
2363 PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, bool &new_created) {
2364   Compile *C = _compile;
2365   PhaseGVN* igvn = _igvn;
2366   new_created = false;
2367   int phi_alias_idx = C->get_alias_index(orig_phi->adr_type());
2368   // nothing to do if orig_phi is bottom memory or matches alias_idx
2369   if (phi_alias_idx == alias_idx) {
2370     return orig_phi;
2371   }
2372   // Have we recently created a Phi for this alias index?
2373   PhiNode *result = get_map_phi(orig_phi->_idx);
2374   if (result != NULL && C->get_alias_index(result->adr_type()) == alias_idx) {
2375     return result;
2376   }
2377   // Previous check may fail when the same wide memory Phi was split into Phis
2378   // for different memory slices. Search all Phis for this region.
2379   if (result != NULL) {
2380     Node* region = orig_phi->in(0);
2381     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
2382       Node* phi = region->fast_out(i);
2383       if (phi->is_Phi() &&
2384           C->get_alias_index(phi->as_Phi()->adr_type()) == alias_idx) {
2385         assert(phi->_idx >= nodes_size(), "only new Phi per instance memory slice");
2386         return phi->as_Phi();
2387       }
2388     }
2389   }
2390   if ((int) (C->live_nodes() + 2*NodeLimitFudgeFactor) > MaxNodeLimit) {
2391     if (C->do_escape_analysis() == true && !C->failing()) {
2392       // Retry compilation without escape analysis.
2393       // If this is the first failure, the sentinel string will "stick"
2394       // to the Compile object, and the C2Compiler will see it and retry.
2395       C->record_failure(C2Compiler::retry_no_escape_analysis());
2396     }
2397     return NULL;
2398   }
2399   orig_phi_worklist.append_if_missing(orig_phi);
2400   const TypePtr *atype = C->get_adr_type(alias_idx);
2401   result = PhiNode::make(orig_phi->in(0), NULL, Type::MEMORY, atype);
2402   C->copy_node_notes_to(result, orig_phi);
2403   igvn->set_type(result, result->bottom_type());
2404   record_for_optimizer(result);
2405   set_map(orig_phi, result);
2406   new_created = true;
2407   return result;
2408 }
2409 
2410 //
2411 // Return a new version of Memory Phi "orig_phi" with the inputs having the
2412 // specified alias index.
2413 //
2414 PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist) {
2415   assert(alias_idx != Compile::AliasIdxBot, "can't split out bottom memory");
2416   Compile *C = _compile;
2417   PhaseGVN* igvn = _igvn;
2418   bool new_phi_created;
2419   PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, new_phi_created);
2420   if (!new_phi_created) {
2421     return result;
2422   }
2423   GrowableArray<PhiNode *>  phi_list;
2424   GrowableArray<uint>  cur_input;
2425   PhiNode *phi = orig_phi;
2426   uint idx = 1;
2427   bool finished = false;
2428   while(!finished) {
2429     while (idx < phi->req()) {
2430       Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist);
2431       if (mem != NULL && mem->is_Phi()) {
2432         PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, new_phi_created);
2433         if (new_phi_created) {
2434           // found an phi for which we created a new split, push current one on worklist and begin
2435           // processing new one
2436           phi_list.push(phi);
2437           cur_input.push(idx);
2438           phi = mem->as_Phi();
2439           result = newphi;
2440           idx = 1;
2441           continue;
2442         } else {
2443           mem = newphi;
2444         }
2445       }
2446       if (C->failing()) {
2447         return NULL;
2448       }
2449       result->set_req(idx++, mem);
2450     }
2451 #ifdef ASSERT
2452     // verify that the new Phi has an input for each input of the original
2453     assert( phi->req() == result->req(), "must have same number of inputs.");
2454     assert( result->in(0) != NULL && result->in(0) == phi->in(0), "regions must match");
2455 #endif
2456     // Check if all new phi's inputs have specified alias index.
2457     // Otherwise use old phi.
2458     for (uint i = 1; i < phi->req(); i++) {
2459       Node* in = result->in(i);
2460       assert((phi->in(i) == NULL) == (in == NULL), "inputs must correspond.");
2461     }
2462     // we have finished processing a Phi, see if there are any more to do
2463     finished = (phi_list.length() == 0 );
2464     if (!finished) {
2465       phi = phi_list.pop();
2466       idx = cur_input.pop();
2467       PhiNode *prev_result = get_map_phi(phi->_idx);
2468       prev_result->set_req(idx++, result);
2469       result = prev_result;
2470     }
2471   }
2472   return result;
2473 }
2474 
2475 //
2476 // The next methods are derived from methods in MemNode.
2477 //
2478 Node* ConnectionGraph::step_through_mergemem(MergeMemNode *mmem, int alias_idx, const TypeOopPtr *toop) {
2479   Node *mem = mmem;
2480   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
2481   // means an array I have not precisely typed yet.  Do not do any
2482   // alias stuff with it any time soon.
2483   if (toop->base() != Type::AnyPtr &&
2484       !(toop->klass() != NULL &&
2485         toop->klass()->is_java_lang_Object() &&
2486         toop->offset() == Type::OffsetBot)) {
2487     mem = mmem->memory_at(alias_idx);
2488     // Update input if it is progress over what we have now
2489   }
2490   return mem;
2491 }
2492 
2493 //
2494 // Move memory users to their memory slices.
2495 //
2496 void ConnectionGraph::move_inst_mem(Node* n, GrowableArray<PhiNode *>  &orig_phis) {
2497   Compile* C = _compile;
2498   PhaseGVN* igvn = _igvn;
2499   const TypePtr* tp = igvn->type(n->in(MemNode::Address))->isa_ptr();
2500   assert(tp != NULL, "ptr type");
2501   int alias_idx = C->get_alias_index(tp);
2502   int general_idx = C->get_general_index(alias_idx);
2503 
2504   // Move users first
2505   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2506     Node* use = n->fast_out(i);
2507     if (use->is_MergeMem()) {
2508       MergeMemNode* mmem = use->as_MergeMem();
2509       assert(n == mmem->memory_at(alias_idx), "should be on instance memory slice");
2510       if (n != mmem->memory_at(general_idx) || alias_idx == general_idx) {
2511         continue; // Nothing to do
2512       }
2513       // Replace previous general reference to mem node.
2514       uint orig_uniq = C->unique();
2515       Node* m = find_inst_mem(n, general_idx, orig_phis);
2516       assert(orig_uniq == C->unique(), "no new nodes");
2517       mmem->set_memory_at(general_idx, m);
2518       --imax;
2519       --i;
2520     } else if (use->is_MemBar()) {
2521       assert(!use->is_Initialize(), "initializing stores should not be moved");
2522       if (use->req() > MemBarNode::Precedent &&
2523           use->in(MemBarNode::Precedent) == n) {
2524         // Don't move related membars.
2525         record_for_optimizer(use);
2526         continue;
2527       }
2528       tp = use->as_MemBar()->adr_type()->isa_ptr();
2529       if (tp != NULL && C->get_alias_index(tp) == alias_idx ||
2530           alias_idx == general_idx) {
2531         continue; // Nothing to do
2532       }
2533       // Move to general memory slice.
2534       uint orig_uniq = C->unique();
2535       Node* m = find_inst_mem(n, general_idx, orig_phis);
2536       assert(orig_uniq == C->unique(), "no new nodes");
2537       igvn->hash_delete(use);
2538       imax -= use->replace_edge(n, m);
2539       igvn->hash_insert(use);
2540       record_for_optimizer(use);
2541       --i;
2542 #ifdef ASSERT
2543     } else if (use->is_Mem()) {
2544       if (use->Opcode() == Op_StoreCM && use->in(MemNode::OopStore) == n) {
2545         // Don't move related cardmark.
2546         continue;
2547       }
2548       // Memory nodes should have new memory input.
2549       tp = igvn->type(use->in(MemNode::Address))->isa_ptr();
2550       assert(tp != NULL, "ptr type");
2551       int idx = C->get_alias_index(tp);
2552       assert(get_map(use->_idx) != NULL || idx == alias_idx,
2553              "Following memory nodes should have new memory input or be on the same memory slice");
2554     } else if (use->is_Phi()) {
2555       // Phi nodes should be split and moved already.
2556       tp = use->as_Phi()->adr_type()->isa_ptr();
2557       assert(tp != NULL, "ptr type");
2558       int idx = C->get_alias_index(tp);
2559       assert(idx == alias_idx, "Following Phi nodes should be on the same memory slice");
2560     } else {
2561       use->dump();
2562       assert(false, "should not be here");
2563 #endif
2564     }
2565   }
2566 }
2567 
2568 //
2569 // Search memory chain of "mem" to find a MemNode whose address
2570 // is the specified alias index.
2571 //
2572 Node* ConnectionGraph::find_inst_mem(Node *orig_mem, int alias_idx, GrowableArray<PhiNode *>  &orig_phis) {
2573   if (orig_mem == NULL)
2574     return orig_mem;
2575   Compile* C = _compile;
2576   PhaseGVN* igvn = _igvn;
2577   const TypeOopPtr *toop = C->get_adr_type(alias_idx)->isa_oopptr();
2578   bool is_instance = (toop != NULL) && toop->is_known_instance();
2579   Node *start_mem = C->start()->proj_out(TypeFunc::Memory);
2580   Node *prev = NULL;
2581   Node *result = orig_mem;
2582   while (prev != result) {
2583     prev = result;
2584     if (result == start_mem)
2585       break;  // hit one of our sentinels
2586     if (result->is_Mem()) {
2587       const Type *at = igvn->type(result->in(MemNode::Address));
2588       if (at == Type::TOP)
2589         break; // Dead
2590       assert (at->isa_ptr() != NULL, "pointer type required.");
2591       int idx = C->get_alias_index(at->is_ptr());
2592       if (idx == alias_idx)
2593         break; // Found
2594       if (!is_instance && (at->isa_oopptr() == NULL ||
2595                            !at->is_oopptr()->is_known_instance())) {
2596         break; // Do not skip store to general memory slice.
2597       }
2598       result = result->in(MemNode::Memory);
2599     }
2600     if (!is_instance)
2601       continue;  // don't search further for non-instance types
2602     // skip over a call which does not affect this memory slice
2603     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
2604       Node *proj_in = result->in(0);
2605       if (proj_in->is_Allocate() && proj_in->_idx == (uint)toop->instance_id()) {
2606         break;  // hit one of our sentinels
2607       } else if (proj_in->is_Call()) {
2608         CallNode *call = proj_in->as_Call();
2609         if (!call->may_modify(toop, igvn)) {
2610           result = call->in(TypeFunc::Memory);
2611         }
2612       } else if (proj_in->is_Initialize()) {
2613         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
2614         // Stop if this is the initialization for the object instance which
2615         // which contains this memory slice, otherwise skip over it.
2616         if (alloc == NULL || alloc->_idx != (uint)toop->instance_id()) {
2617           result = proj_in->in(TypeFunc::Memory);
2618         }
2619       } else if (proj_in->is_MemBar()) {
2620         result = proj_in->in(TypeFunc::Memory);
2621       }
2622     } else if (result->is_MergeMem()) {
2623       MergeMemNode *mmem = result->as_MergeMem();
2624       result = step_through_mergemem(mmem, alias_idx, toop);
2625       if (result == mmem->base_memory()) {
2626         // Didn't find instance memory, search through general slice recursively.
2627         result = mmem->memory_at(C->get_general_index(alias_idx));
2628         result = find_inst_mem(result, alias_idx, orig_phis);
2629         if (C->failing()) {
2630           return NULL;
2631         }
2632         mmem->set_memory_at(alias_idx, result);
2633       }
2634     } else if (result->is_Phi() &&
2635                C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
2636       Node *un = result->as_Phi()->unique_input(igvn);
2637       if (un != NULL) {
2638         orig_phis.append_if_missing(result->as_Phi());
2639         result = un;
2640       } else {
2641         break;
2642       }
2643     } else if (result->is_ClearArray()) {
2644       if (!ClearArrayNode::step_through(&result, (uint)toop->instance_id(), igvn)) {
2645         // Can not bypass initialization of the instance
2646         // we are looking for.
2647         break;
2648       }
2649       // Otherwise skip it (the call updated 'result' value).
2650     } else if (result->Opcode() == Op_SCMemProj) {
2651       Node* mem = result->in(0);
2652       Node* adr = NULL;
2653       if (mem->is_LoadStore()) {
2654         adr = mem->in(MemNode::Address);
2655       } else {
2656         assert(mem->Opcode() == Op_EncodeISOArray, "sanity");
2657         adr = mem->in(3); // Memory edge corresponds to destination array
2658       }
2659       const Type *at = igvn->type(adr);
2660       if (at != Type::TOP) {
2661         assert (at->isa_ptr() != NULL, "pointer type required.");
2662         int idx = C->get_alias_index(at->is_ptr());
2663         assert(idx != alias_idx, "Object is not scalar replaceable if a LoadStore node access its field");
2664         break;
2665       }
2666       result = mem->in(MemNode::Memory);
2667     }
2668   }
2669   if (result->is_Phi()) {
2670     PhiNode *mphi = result->as_Phi();
2671     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
2672     const TypePtr *t = mphi->adr_type();
2673     if (!is_instance) {
2674       // Push all non-instance Phis on the orig_phis worklist to update inputs
2675       // during Phase 4 if needed.
2676       orig_phis.append_if_missing(mphi);
2677     } else if (C->get_alias_index(t) != alias_idx) {
2678       // Create a new Phi with the specified alias index type.
2679       result = split_memory_phi(mphi, alias_idx, orig_phis);
2680     }
2681   }
2682   // the result is either MemNode, PhiNode, InitializeNode.
2683   return result;
2684 }
2685 
2686 //
2687 //  Convert the types of unescaped object to instance types where possible,
2688 //  propagate the new type information through the graph, and update memory
2689 //  edges and MergeMem inputs to reflect the new type.
2690 //
2691 //  We start with allocations (and calls which may be allocations)  on alloc_worklist.
2692 //  The processing is done in 4 phases:
2693 //
2694 //  Phase 1:  Process possible allocations from alloc_worklist.  Create instance
2695 //            types for the CheckCastPP for allocations where possible.
2696 //            Propagate the the new types through users as follows:
2697 //               casts and Phi:  push users on alloc_worklist
2698 //               AddP:  cast Base and Address inputs to the instance type
2699 //                      push any AddP users on alloc_worklist and push any memnode
2700 //                      users onto memnode_worklist.
2701 //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
2702 //            search the Memory chain for a store with the appropriate type
2703 //            address type.  If a Phi is found, create a new version with
2704 //            the appropriate memory slices from each of the Phi inputs.
2705 //            For stores, process the users as follows:
2706 //               MemNode:  push on memnode_worklist
2707 //               MergeMem: push on mergemem_worklist
2708 //  Phase 3:  Process MergeMem nodes from mergemem_worklist.  Walk each memory slice
2709 //            moving the first node encountered of each  instance type to the
2710 //            the input corresponding to its alias index.
2711 //            appropriate memory slice.
2712 //  Phase 4:  Update the inputs of non-instance memory Phis and the Memory input of memnodes.
2713 //
2714 // In the following example, the CheckCastPP nodes are the cast of allocation
2715 // results and the allocation of node 29 is unescaped and eligible to be an
2716 // instance type.
2717 //
2718 // We start with:
2719 //
2720 //     7 Parm #memory
2721 //    10  ConI  "12"
2722 //    19  CheckCastPP   "Foo"
2723 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
2724 //    29  CheckCastPP   "Foo"
2725 //    30  AddP  _ 29 29 10  Foo+12  alias_index=4
2726 //
2727 //    40  StoreP  25   7  20   ... alias_index=4
2728 //    50  StoreP  35  40  30   ... alias_index=4
2729 //    60  StoreP  45  50  20   ... alias_index=4
2730 //    70  LoadP    _  60  30   ... alias_index=4
2731 //    80  Phi     75  50  60   Memory alias_index=4
2732 //    90  LoadP    _  80  30   ... alias_index=4
2733 //   100  LoadP    _  80  20   ... alias_index=4
2734 //
2735 //
2736 // Phase 1 creates an instance type for node 29 assigning it an instance id of 24
2737 // and creating a new alias index for node 30.  This gives:
2738 //
2739 //     7 Parm #memory
2740 //    10  ConI  "12"
2741 //    19  CheckCastPP   "Foo"
2742 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
2743 //    29  CheckCastPP   "Foo"  iid=24
2744 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
2745 //
2746 //    40  StoreP  25   7  20   ... alias_index=4
2747 //    50  StoreP  35  40  30   ... alias_index=6
2748 //    60  StoreP  45  50  20   ... alias_index=4
2749 //    70  LoadP    _  60  30   ... alias_index=6
2750 //    80  Phi     75  50  60   Memory alias_index=4
2751 //    90  LoadP    _  80  30   ... alias_index=6
2752 //   100  LoadP    _  80  20   ... alias_index=4
2753 //
2754 // In phase 2, new memory inputs are computed for the loads and stores,
2755 // And a new version of the phi is created.  In phase 4, the inputs to
2756 // node 80 are updated and then the memory nodes are updated with the
2757 // values computed in phase 2.  This results in:
2758 //
2759 //     7 Parm #memory
2760 //    10  ConI  "12"
2761 //    19  CheckCastPP   "Foo"
2762 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
2763 //    29  CheckCastPP   "Foo"  iid=24
2764 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
2765 //
2766 //    40  StoreP  25  7   20   ... alias_index=4
2767 //    50  StoreP  35  7   30   ... alias_index=6
2768 //    60  StoreP  45  40  20   ... alias_index=4
2769 //    70  LoadP    _  50  30   ... alias_index=6
2770 //    80  Phi     75  40  60   Memory alias_index=4
2771 //   120  Phi     75  50  50   Memory alias_index=6
2772 //    90  LoadP    _ 120  30   ... alias_index=6
2773 //   100  LoadP    _  80  20   ... alias_index=4
2774 //
2775 void ConnectionGraph::split_unique_types(GrowableArray<Node *>  &alloc_worklist) {
2776   GrowableArray<Node *>  memnode_worklist;
2777   GrowableArray<PhiNode *>  orig_phis;
2778   PhaseIterGVN  *igvn = _igvn;
2779   uint new_index_start = (uint) _compile->num_alias_types();
2780   Arena* arena = Thread::current()->resource_area();
2781   VectorSet visited(arena);
2782   ideal_nodes.clear(); // Reset for use with set_map/get_map.
2783   uint unique_old = _compile->unique();
2784 
2785   //  Phase 1:  Process possible allocations from alloc_worklist.
2786   //  Create instance types for the CheckCastPP for allocations where possible.
2787   //
2788   // (Note: don't forget to change the order of the second AddP node on
2789   //  the alloc_worklist if the order of the worklist processing is changed,
2790   //  see the comment in find_second_addp().)
2791   //
2792   while (alloc_worklist.length() != 0) {
2793     Node *n = alloc_worklist.pop();
2794     uint ni = n->_idx;
2795     if (n->is_Call()) {
2796       CallNode *alloc = n->as_Call();
2797       // copy escape information to call node
2798       PointsToNode* ptn = ptnode_adr(alloc->_idx);
2799       PointsToNode::EscapeState es = ptn->escape_state();
2800       // We have an allocation or call which returns a Java object,
2801       // see if it is unescaped.
2802       if (es != PointsToNode::NoEscape || !ptn->scalar_replaceable())
2803         continue;
2804       // Find CheckCastPP for the allocate or for the return value of a call
2805       n = alloc->result_cast();
2806       if (n == NULL) {            // No uses except Initialize node
2807         if (alloc->is_Allocate()) {
2808           // Set the scalar_replaceable flag for allocation
2809           // so it could be eliminated if it has no uses.
2810           alloc->as_Allocate()->_is_scalar_replaceable = true;
2811         }
2812         if (alloc->is_CallStaticJava()) {
2813           // Set the scalar_replaceable flag for boxing method
2814           // so it could be eliminated if it has no uses.
2815           alloc->as_CallStaticJava()->_is_scalar_replaceable = true;
2816         }
2817         continue;
2818       }
2819       if (!n->is_CheckCastPP()) { // not unique CheckCastPP.
2820         assert(!alloc->is_Allocate(), "allocation should have unique type");
2821         continue;
2822       }
2823 
2824       // The inline code for Object.clone() casts the allocation result to
2825       // java.lang.Object and then to the actual type of the allocated
2826       // object. Detect this case and use the second cast.
2827       // Also detect j.l.reflect.Array.newInstance(jobject, jint) case when
2828       // the allocation result is cast to java.lang.Object and then
2829       // to the actual Array type.
2830       if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL
2831           && (alloc->is_AllocateArray() ||
2832               igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeKlassPtr::OBJECT)) {
2833         Node *cast2 = NULL;
2834         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2835           Node *use = n->fast_out(i);
2836           if (use->is_CheckCastPP()) {
2837             cast2 = use;
2838             break;
2839           }
2840         }
2841         if (cast2 != NULL) {
2842           n = cast2;
2843         } else {
2844           // Non-scalar replaceable if the allocation type is unknown statically
2845           // (reflection allocation), the object can't be restored during
2846           // deoptimization without precise type.
2847           continue;
2848         }
2849       }
2850 
2851       const TypeOopPtr *t = igvn->type(n)->isa_oopptr();
2852       if (t == NULL)
2853         continue;  // not a TypeOopPtr
2854       if (!t->klass_is_exact())
2855         continue; // not an unique type
2856 
2857       if (alloc->is_Allocate()) {
2858         // Set the scalar_replaceable flag for allocation
2859         // so it could be eliminated.
2860         alloc->as_Allocate()->_is_scalar_replaceable = true;
2861       }
2862       if (alloc->is_CallStaticJava()) {
2863         // Set the scalar_replaceable flag for boxing method
2864         // so it could be eliminated.
2865         alloc->as_CallStaticJava()->_is_scalar_replaceable = true;
2866       }
2867       set_escape_state(ptnode_adr(n->_idx), es); // CheckCastPP escape state
2868       // in order for an object to be scalar-replaceable, it must be:
2869       //   - a direct allocation (not a call returning an object)
2870       //   - non-escaping
2871       //   - eligible to be a unique type
2872       //   - not determined to be ineligible by escape analysis
2873       set_map(alloc, n);
2874       set_map(n, alloc);
2875       const TypeOopPtr* tinst = t->cast_to_instance_id(ni);
2876       igvn->hash_delete(n);
2877       igvn->set_type(n,  tinst);
2878       n->raise_bottom_type(tinst);
2879       igvn->hash_insert(n);
2880       record_for_optimizer(n);
2881       if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
2882 
2883         // First, put on the worklist all Field edges from Connection Graph
2884         // which is more accurate then putting immediate users from Ideal Graph.
2885         for (EdgeIterator e(ptn); e.has_next(); e.next()) {
2886           PointsToNode* tgt = e.get();
2887           Node* use = tgt->ideal_node();
2888           assert(tgt->is_Field() && use->is_AddP(),
2889                  "only AddP nodes are Field edges in CG");
2890           if (use->outcnt() > 0) { // Don't process dead nodes
2891             Node* addp2 = find_second_addp(use, use->in(AddPNode::Base));
2892             if (addp2 != NULL) {
2893               assert(alloc->is_AllocateArray(),"array allocation was expected");
2894               alloc_worklist.append_if_missing(addp2);
2895             }
2896             alloc_worklist.append_if_missing(use);
2897           }
2898         }
2899 
2900         // An allocation may have an Initialize which has raw stores. Scan
2901         // the users of the raw allocation result and push AddP users
2902         // on alloc_worklist.
2903         Node *raw_result = alloc->proj_out(TypeFunc::Parms);
2904         assert (raw_result != NULL, "must have an allocation result");
2905         for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) {
2906           Node *use = raw_result->fast_out(i);
2907           if (use->is_AddP() && use->outcnt() > 0) { // Don't process dead nodes
2908             Node* addp2 = find_second_addp(use, raw_result);
2909             if (addp2 != NULL) {
2910               assert(alloc->is_AllocateArray(),"array allocation was expected");
2911               alloc_worklist.append_if_missing(addp2);
2912             }
2913             alloc_worklist.append_if_missing(use);
2914           } else if (use->is_MemBar()) {
2915             memnode_worklist.append_if_missing(use);
2916           }
2917         }
2918       }
2919     } else if (n->is_AddP()) {
2920       JavaObjectNode* jobj = unique_java_object(get_addp_base(n));
2921       if (jobj == NULL || jobj == phantom_obj) {
2922 #ifdef ASSERT
2923         ptnode_adr(get_addp_base(n)->_idx)->dump();
2924         ptnode_adr(n->_idx)->dump();
2925         assert(jobj != NULL && jobj != phantom_obj, "escaped allocation");
2926 #endif
2927         _compile->record_failure(C2Compiler::retry_no_escape_analysis());
2928         return;
2929       }
2930       Node *base = get_map(jobj->idx());  // CheckCastPP node
2931       if (!split_AddP(n, base)) continue; // wrong type from dead path
2932     } else if (n->is_Phi() ||
2933                n->is_CheckCastPP() ||
2934                n->is_EncodeP() ||
2935                n->is_DecodeN() ||
2936                (n->is_ConstraintCast() && n->Opcode() == Op_CastPP)) {
2937       if (visited.test_set(n->_idx)) {
2938         assert(n->is_Phi(), "loops only through Phi's");
2939         continue;  // already processed
2940       }
2941       JavaObjectNode* jobj = unique_java_object(n);
2942       if (jobj == NULL || jobj == phantom_obj) {
2943 #ifdef ASSERT
2944         ptnode_adr(n->_idx)->dump();
2945         assert(jobj != NULL && jobj != phantom_obj, "escaped allocation");
2946 #endif
2947         _compile->record_failure(C2Compiler::retry_no_escape_analysis());
2948         return;
2949       } else {
2950         Node *val = get_map(jobj->idx());   // CheckCastPP node
2951         TypeNode *tn = n->as_Type();
2952         const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
2953         assert(tinst != NULL && tinst->is_known_instance() &&
2954                tinst->instance_id() == jobj->idx() , "instance type expected.");
2955 
2956         const Type *tn_type = igvn->type(tn);
2957         const TypeOopPtr *tn_t;
2958         if (tn_type->isa_narrowoop()) {
2959           tn_t = tn_type->make_ptr()->isa_oopptr();
2960         } else {
2961           tn_t = tn_type->isa_oopptr();
2962         }
2963         if (tn_t != NULL && tinst->klass()->is_subtype_of(tn_t->klass())) {
2964           if (tn_type->isa_narrowoop()) {
2965             tn_type = tinst->make_narrowoop();
2966           } else {
2967             tn_type = tinst;
2968           }
2969           igvn->hash_delete(tn);
2970           igvn->set_type(tn, tn_type);
2971           tn->set_type(tn_type);
2972           igvn->hash_insert(tn);
2973           record_for_optimizer(n);
2974         } else {
2975           assert(tn_type == TypePtr::NULL_PTR ||
2976                  tn_t != NULL && !tinst->klass()->is_subtype_of(tn_t->klass()),
2977                  "unexpected type");
2978           continue; // Skip dead path with different type
2979         }
2980       }
2981     } else {
2982       debug_only(n->dump();)
2983       assert(false, "EA: unexpected node");
2984       continue;
2985     }
2986     // push allocation's users on appropriate worklist
2987     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
2988       Node *use = n->fast_out(i);
2989       if(use->is_Mem() && use->in(MemNode::Address) == n) {
2990         // Load/store to instance's field
2991         memnode_worklist.append_if_missing(use);
2992       } else if (use->is_MemBar()) {
2993         if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
2994           memnode_worklist.append_if_missing(use);
2995         }
2996       } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
2997         Node* addp2 = find_second_addp(use, n);
2998         if (addp2 != NULL) {
2999           alloc_worklist.append_if_missing(addp2);
3000         }
3001         alloc_worklist.append_if_missing(use);
3002       } else if (use->is_Phi() ||
3003                  use->is_CheckCastPP() ||
3004                  use->is_EncodeNarrowPtr() ||
3005                  use->is_DecodeNarrowPtr() ||
3006                  (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
3007         alloc_worklist.append_if_missing(use);
3008 #ifdef ASSERT
3009       } else if (use->is_Mem()) {
3010         assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
3011       } else if (use->is_MergeMem()) {
3012         assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
3013       } else if (use->is_SafePoint()) {
3014         // Look for MergeMem nodes for calls which reference unique allocation
3015         // (through CheckCastPP nodes) even for debug info.
3016         Node* m = use->in(TypeFunc::Memory);
3017         if (m->is_MergeMem()) {
3018           assert(_mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
3019         }
3020       } else if (use->Opcode() == Op_EncodeISOArray) {
3021         if (use->in(MemNode::Memory) == n || use->in(3) == n) {
3022           // EncodeISOArray overwrites destination array
3023           memnode_worklist.append_if_missing(use);
3024         }
3025       } else {
3026         uint op = use->Opcode();
3027         if (!(op == Op_CmpP || op == Op_Conv2B ||
3028               op == Op_CastP2X || op == Op_StoreCM ||
3029               op == Op_FastLock || op == Op_AryEq || op == Op_StrComp ||
3030               op == Op_StrEquals || op == Op_StrIndexOf)) {
3031           n->dump();
3032           use->dump();
3033           assert(false, "EA: missing allocation reference path");
3034         }
3035 #endif
3036       }
3037     }
3038 
3039   }
3040   // New alias types were created in split_AddP().
3041   uint new_index_end = (uint) _compile->num_alias_types();
3042   assert(unique_old == _compile->unique(), "there should be no new ideal nodes after Phase 1");
3043 
3044   //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
3045   //            compute new values for Memory inputs  (the Memory inputs are not
3046   //            actually updated until phase 4.)
3047   if (memnode_worklist.length() == 0)
3048     return;  // nothing to do
3049   while (memnode_worklist.length() != 0) {
3050     Node *n = memnode_worklist.pop();
3051     if (visited.test_set(n->_idx))
3052       continue;
3053     if (n->is_Phi() || n->is_ClearArray()) {
3054       // we don't need to do anything, but the users must be pushed
3055     } else if (n->is_MemBar()) { // Initialize, MemBar nodes
3056       // we don't need to do anything, but the users must be pushed
3057       n = n->as_MemBar()->proj_out(TypeFunc::Memory);
3058       if (n == NULL)
3059         continue;
3060     } else if (n->Opcode() == Op_EncodeISOArray) {
3061       // get the memory projection
3062       for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3063         Node *use = n->fast_out(i);
3064         if (use->Opcode() == Op_SCMemProj) {
3065           n = use;
3066           break;
3067         }
3068       }
3069       assert(n->Opcode() == Op_SCMemProj, "memory projection required");
3070     } else {
3071       assert(n->is_Mem(), "memory node required.");
3072       Node *addr = n->in(MemNode::Address);
3073       const Type *addr_t = igvn->type(addr);
3074       if (addr_t == Type::TOP)
3075         continue;
3076       assert (addr_t->isa_ptr() != NULL, "pointer type required.");
3077       int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
3078       assert ((uint)alias_idx < new_index_end, "wrong alias index");
3079       Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
3080       if (_compile->failing()) {
3081         return;
3082       }
3083       if (mem != n->in(MemNode::Memory)) {
3084         // We delay the memory edge update since we need old one in
3085         // MergeMem code below when instances memory slices are separated.
3086         set_map(n, mem);
3087       }
3088       if (n->is_Load()) {
3089         continue;  // don't push users
3090       } else if (n->is_LoadStore()) {
3091         // get the memory projection
3092         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3093           Node *use = n->fast_out(i);
3094           if (use->Opcode() == Op_SCMemProj) {
3095             n = use;
3096             break;
3097           }
3098         }
3099         assert(n->Opcode() == Op_SCMemProj, "memory projection required");
3100       }
3101     }
3102     // push user on appropriate worklist
3103     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3104       Node *use = n->fast_out(i);
3105       if (use->is_Phi() || use->is_ClearArray()) {
3106         memnode_worklist.append_if_missing(use);
3107       } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
3108         if (use->Opcode() == Op_StoreCM) // Ignore cardmark stores
3109           continue;
3110         memnode_worklist.append_if_missing(use);
3111       } else if (use->is_MemBar()) {
3112         if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
3113           memnode_worklist.append_if_missing(use);
3114         }
3115 #ifdef ASSERT
3116       } else if(use->is_Mem()) {
3117         assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
3118       } else if (use->is_MergeMem()) {
3119         assert(_mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
3120       } else if (use->Opcode() == Op_EncodeISOArray) {
3121         if (use->in(MemNode::Memory) == n || use->in(3) == n) {
3122           // EncodeISOArray overwrites destination array
3123           memnode_worklist.append_if_missing(use);
3124         }
3125       } else {
3126         uint op = use->Opcode();
3127         if (!(op == Op_StoreCM ||
3128               (op == Op_CallLeaf && use->as_CallLeaf()->_name != NULL &&
3129                strcmp(use->as_CallLeaf()->_name, "g1_wb_pre") == 0) ||
3130               op == Op_AryEq || op == Op_StrComp ||
3131               op == Op_StrEquals || op == Op_StrIndexOf)) {
3132           n->dump();
3133           use->dump();
3134           assert(false, "EA: missing memory path");
3135         }
3136 #endif
3137       }
3138     }
3139   }
3140 
3141   //  Phase 3:  Process MergeMem nodes from mergemem_worklist.
3142   //            Walk each memory slice moving the first node encountered of each
3143   //            instance type to the the input corresponding to its alias index.
3144   uint length = _mergemem_worklist.length();
3145   for( uint next = 0; next < length; ++next ) {
3146     MergeMemNode* nmm = _mergemem_worklist.at(next);
3147     assert(!visited.test_set(nmm->_idx), "should not be visited before");
3148     // Note: we don't want to use MergeMemStream here because we only want to
3149     // scan inputs which exist at the start, not ones we add during processing.
3150     // Note 2: MergeMem may already contains instance memory slices added
3151     // during find_inst_mem() call when memory nodes were processed above.
3152     igvn->hash_delete(nmm);
3153     uint nslices = nmm->req();
3154     for (uint i = Compile::AliasIdxRaw+1; i < nslices; i++) {
3155       Node* mem = nmm->in(i);
3156       Node* cur = NULL;
3157       if (mem == NULL || mem->is_top())
3158         continue;
3159       // First, update mergemem by moving memory nodes to corresponding slices
3160       // if their type became more precise since this mergemem was created.
3161       while (mem->is_Mem()) {
3162         const Type *at = igvn->type(mem->in(MemNode::Address));
3163         if (at != Type::TOP) {
3164           assert (at->isa_ptr() != NULL, "pointer type required.");
3165           uint idx = (uint)_compile->get_alias_index(at->is_ptr());
3166           if (idx == i) {
3167             if (cur == NULL)
3168               cur = mem;
3169           } else {
3170             if (idx >= nmm->req() || nmm->is_empty_memory(nmm->in(idx))) {
3171               nmm->set_memory_at(idx, mem);
3172             }
3173           }
3174         }
3175         mem = mem->in(MemNode::Memory);
3176       }
3177       nmm->set_memory_at(i, (cur != NULL) ? cur : mem);
3178       // Find any instance of the current type if we haven't encountered
3179       // already a memory slice of the instance along the memory chain.
3180       for (uint ni = new_index_start; ni < new_index_end; ni++) {
3181         if((uint)_compile->get_general_index(ni) == i) {
3182           Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni);
3183           if (nmm->is_empty_memory(m)) {
3184             Node* result = find_inst_mem(mem, ni, orig_phis);
3185             if (_compile->failing()) {
3186               return;
3187             }
3188             nmm->set_memory_at(ni, result);
3189           }
3190         }
3191       }
3192     }
3193     // Find the rest of instances values
3194     for (uint ni = new_index_start; ni < new_index_end; ni++) {
3195       const TypeOopPtr *tinst = _compile->get_adr_type(ni)->isa_oopptr();
3196       Node* result = step_through_mergemem(nmm, ni, tinst);
3197       if (result == nmm->base_memory()) {
3198         // Didn't find instance memory, search through general slice recursively.
3199         result = nmm->memory_at(_compile->get_general_index(ni));
3200         result = find_inst_mem(result, ni, orig_phis);
3201         if (_compile->failing()) {
3202           return;
3203         }
3204         nmm->set_memory_at(ni, result);
3205       }
3206     }
3207     igvn->hash_insert(nmm);
3208     record_for_optimizer(nmm);
3209   }
3210 
3211   //  Phase 4:  Update the inputs of non-instance memory Phis and
3212   //            the Memory input of memnodes
3213   // First update the inputs of any non-instance Phi's from
3214   // which we split out an instance Phi.  Note we don't have
3215   // to recursively process Phi's encounted on the input memory
3216   // chains as is done in split_memory_phi() since they  will
3217   // also be processed here.
3218   for (int j = 0; j < orig_phis.length(); j++) {
3219     PhiNode *phi = orig_phis.at(j);
3220     int alias_idx = _compile->get_alias_index(phi->adr_type());
3221     igvn->hash_delete(phi);
3222     for (uint i = 1; i < phi->req(); i++) {
3223       Node *mem = phi->in(i);
3224       Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
3225       if (_compile->failing()) {
3226         return;
3227       }
3228       if (mem != new_mem) {
3229         phi->set_req(i, new_mem);
3230       }
3231     }
3232     igvn->hash_insert(phi);
3233     record_for_optimizer(phi);
3234   }
3235 
3236   // Update the memory inputs of MemNodes with the value we computed
3237   // in Phase 2 and move stores memory users to corresponding memory slices.
3238   // Disable memory split verification code until the fix for 6984348.
3239   // Currently it produces false negative results since it does not cover all cases.
3240 #if 0 // ifdef ASSERT
3241   visited.Reset();
3242   Node_Stack old_mems(arena, _compile->unique() >> 2);
3243 #endif
3244   for (uint i = 0; i < ideal_nodes.size(); i++) {
3245     Node*    n = ideal_nodes.at(i);
3246     Node* nmem = get_map(n->_idx);
3247     assert(nmem != NULL, "sanity");
3248     if (n->is_Mem()) {
3249 #if 0 // ifdef ASSERT
3250       Node* old_mem = n->in(MemNode::Memory);
3251       if (!visited.test_set(old_mem->_idx)) {
3252         old_mems.push(old_mem, old_mem->outcnt());
3253       }
3254 #endif
3255       assert(n->in(MemNode::Memory) != nmem, "sanity");
3256       if (!n->is_Load()) {
3257         // Move memory users of a store first.
3258         move_inst_mem(n, orig_phis);
3259       }
3260       // Now update memory input
3261       igvn->hash_delete(n);
3262       n->set_req(MemNode::Memory, nmem);
3263       igvn->hash_insert(n);
3264       record_for_optimizer(n);
3265     } else {
3266       assert(n->is_Allocate() || n->is_CheckCastPP() ||
3267              n->is_AddP() || n->is_Phi(), "unknown node used for set_map()");
3268     }
3269   }
3270 #if 0 // ifdef ASSERT
3271   // Verify that memory was split correctly
3272   while (old_mems.is_nonempty()) {
3273     Node* old_mem = old_mems.node();
3274     uint  old_cnt = old_mems.index();
3275     old_mems.pop();
3276     assert(old_cnt == old_mem->outcnt(), "old mem could be lost");
3277   }
3278 #endif
3279 }
3280 
3281 #ifndef PRODUCT
3282 static const char *node_type_names[] = {
3283   "UnknownType",
3284   "JavaObject",
3285   "LocalVar",
3286   "Field",
3287   "Arraycopy"
3288 };
3289 
3290 static const char *esc_names[] = {
3291   "UnknownEscape",
3292   "NoEscape",
3293   "ArgEscape",
3294   "GlobalEscape"
3295 };
3296 
3297 void PointsToNode::dump(bool print_state) const {
3298   NodeType nt = node_type();
3299   tty->print("%s ", node_type_names[(int) nt]);
3300   if (print_state) {
3301     EscapeState es = escape_state();
3302     EscapeState fields_es = fields_escape_state();
3303     tty->print("%s(%s) ", esc_names[(int)es], esc_names[(int)fields_es]);
3304     if (nt == PointsToNode::JavaObject && !this->scalar_replaceable())
3305       tty->print("NSR ");
3306   }
3307   if (is_Field()) {
3308     FieldNode* f = (FieldNode*)this;
3309     if (f->is_oop())
3310       tty->print("oop ");
3311     if (f->offset() > 0)
3312       tty->print("+%d ", f->offset());
3313     tty->print("(");
3314     for (BaseIterator i(f); i.has_next(); i.next()) {
3315       PointsToNode* b = i.get();
3316       tty->print(" %d%s", b->idx(),(b->is_JavaObject() ? "P" : ""));
3317     }
3318     tty->print(" )");
3319   }
3320   tty->print("[");
3321   for (EdgeIterator i(this); i.has_next(); i.next()) {
3322     PointsToNode* e = i.get();
3323     tty->print(" %d%s%s", e->idx(),(e->is_JavaObject() ? "P" : (e->is_Field() ? "F" : "")), e->is_Arraycopy() ? "cp" : "");
3324   }
3325   tty->print(" [");
3326   for (UseIterator i(this); i.has_next(); i.next()) {
3327     PointsToNode* u = i.get();
3328     bool is_base = false;
3329     if (PointsToNode::is_base_use(u)) {
3330       is_base = true;
3331       u = PointsToNode::get_use_node(u)->as_Field();
3332     }
3333     tty->print(" %d%s%s", u->idx(), is_base ? "b" : "", u->is_Arraycopy() ? "cp" : "");
3334   }
3335   tty->print(" ]]  ");
3336   if (_node == NULL)
3337     tty->print_cr("<null>");
3338   else
3339     _node->dump();
3340 }
3341 
3342 void ConnectionGraph::dump(GrowableArray<PointsToNode*>& ptnodes_worklist) {
3343   bool first = true;
3344   int ptnodes_length = ptnodes_worklist.length();
3345   for (int i = 0; i < ptnodes_length; i++) {
3346     PointsToNode *ptn = ptnodes_worklist.at(i);
3347     if (ptn == NULL || !ptn->is_JavaObject())
3348       continue;
3349     PointsToNode::EscapeState es = ptn->escape_state();
3350     if ((es != PointsToNode::NoEscape) && !Verbose) {
3351       continue;
3352     }
3353     Node* n = ptn->ideal_node();
3354     if (n->is_Allocate() || (n->is_CallStaticJava() &&
3355                              n->as_CallStaticJava()->is_boxing_method())) {
3356       if (first) {
3357         tty->cr();
3358         tty->print("======== Connection graph for ");
3359         _compile->method()->print_short_name();
3360         tty->cr();
3361         first = false;
3362       }
3363       ptn->dump();
3364       // Print all locals and fields which reference this allocation
3365       for (UseIterator j(ptn); j.has_next(); j.next()) {
3366         PointsToNode* use = j.get();
3367         if (use->is_LocalVar()) {
3368           use->dump(Verbose);
3369         } else if (Verbose) {
3370           use->dump();
3371         }
3372       }
3373       tty->cr();
3374     }
3375   }
3376 }
3377 #endif