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