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