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