1 /*
   2  * Copyright (c) 2005, 2025, 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 "ci/bcEscapeAnalyzer.hpp"
  26 #include "compiler/compileLog.hpp"
  27 #include "gc/shared/barrierSet.hpp"
  28 #include "gc/shared/c2/barrierSetC2.hpp"
  29 #include "libadt/vectset.hpp"
  30 #include "memory/allocation.hpp"
  31 #include "memory/metaspace.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "opto/arraycopynode.hpp"
  34 #include "opto/c2compiler.hpp"
  35 #include "opto/callnode.hpp"
  36 #include "opto/castnode.hpp"
  37 #include "opto/cfgnode.hpp"
  38 #include "opto/compile.hpp"
  39 #include "opto/escape.hpp"
  40 #include "opto/inlinetypenode.hpp"
  41 #include "opto/locknode.hpp"
  42 #include "opto/macro.hpp"
  43 #include "opto/movenode.hpp"
  44 #include "opto/narrowptrnode.hpp"
  45 #include "opto/phaseX.hpp"
  46 #include "opto/rootnode.hpp"
  47 #include "utilities/macros.hpp"
  48 
  49 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn, int invocation) :
  50   // If ReduceAllocationMerges is enabled we might call split_through_phi during
  51   // split_unique_types and that will create additional nodes that need to be
  52   // pushed to the ConnectionGraph. The code below bumps the initial capacity of
  53   // _nodes by 10% to account for these additional nodes. If capacity is exceeded
  54   // the array will be reallocated.
  55   _nodes(C->comp_arena(), C->do_reduce_allocation_merges() ? C->unique()*1.10 : C->unique(), C->unique(), nullptr),
  56   _in_worklist(C->comp_arena()),
  57   _next_pidx(0),
  58   _collecting(true),
  59   _verify(false),
  60   _compile(C),
  61   _igvn(igvn),
  62   _invocation(invocation),
  63   _build_iterations(0),
  64   _build_time(0.),
  65   _node_map(C->comp_arena()) {
  66   // Add unknown java object.
  67   add_java_object(C->top(), PointsToNode::GlobalEscape);
  68   phantom_obj = ptnode_adr(C->top()->_idx)->as_JavaObject();
  69   set_not_scalar_replaceable(phantom_obj NOT_PRODUCT(COMMA "Phantom object"));
  70   // Add ConP and ConN null oop nodes
  71   Node* oop_null = igvn->zerocon(T_OBJECT);
  72   assert(oop_null->_idx < nodes_size(), "should be created already");
  73   add_java_object(oop_null, PointsToNode::NoEscape);
  74   null_obj = ptnode_adr(oop_null->_idx)->as_JavaObject();
  75   set_not_scalar_replaceable(null_obj NOT_PRODUCT(COMMA "Null object"));
  76   if (UseCompressedOops) {
  77     Node* noop_null = igvn->zerocon(T_NARROWOOP);
  78     assert(noop_null->_idx < nodes_size(), "should be created already");
  79     map_ideal_node(noop_null, null_obj);
  80   }
  81 }
  82 
  83 bool ConnectionGraph::has_candidates(Compile *C) {
  84   // EA brings benefits only when the code has allocations and/or locks which
  85   // are represented by ideal Macro nodes.
  86   int cnt = C->macro_count();
  87   for (int i = 0; i < cnt; i++) {
  88     Node *n = C->macro_node(i);
  89     if (n->is_Allocate()) {
  90       return true;
  91     }
  92     if (n->is_Lock()) {
  93       Node* obj = n->as_Lock()->obj_node()->uncast();
  94       if (!(obj->is_Parm() || obj->is_Con())) {
  95         return true;
  96       }
  97     }
  98     if (n->is_CallStaticJava() &&
  99         n->as_CallStaticJava()->is_boxing_method()) {
 100       return true;
 101     }
 102   }
 103   return false;
 104 }
 105 
 106 void ConnectionGraph::do_analysis(Compile *C, PhaseIterGVN *igvn) {
 107   Compile::TracePhase tp(Phase::_t_escapeAnalysis);
 108   ResourceMark rm;
 109 
 110   // Add ConP and ConN null oop nodes before ConnectionGraph construction
 111   // to create space for them in ConnectionGraph::_nodes[].
 112   Node* oop_null = igvn->zerocon(T_OBJECT);
 113   Node* noop_null = igvn->zerocon(T_NARROWOOP);
 114   int invocation = 0;
 115   if (C->congraph() != nullptr) {
 116     invocation = C->congraph()->_invocation + 1;
 117   }
 118   ConnectionGraph* congraph = new(C->comp_arena()) ConnectionGraph(C, igvn, invocation);
 119   NOT_PRODUCT(if (C->should_print_igv(/* Any level */ 1)) C->igv_printer()->set_congraph(congraph);)
 120   // Perform escape analysis
 121   if (congraph->compute_escape()) {
 122     // There are non escaping objects.
 123     C->set_congraph(congraph);
 124   }
 125   NOT_PRODUCT(if (C->should_print_igv(/* Any level */ 1)) C->igv_printer()->set_congraph(nullptr);)
 126   // Cleanup.
 127   if (oop_null->outcnt() == 0) {
 128     igvn->hash_delete(oop_null);
 129   }
 130   if (noop_null->outcnt() == 0) {
 131     igvn->hash_delete(noop_null);
 132   }
 133 
 134   C->print_method(PHASE_AFTER_EA, 2);
 135 }
 136 
 137 bool ConnectionGraph::compute_escape() {
 138   Compile* C = _compile;
 139   PhaseGVN* igvn = _igvn;
 140 
 141   // Worklists used by EA.
 142   Unique_Node_List delayed_worklist;
 143   Unique_Node_List reducible_merges;
 144   GrowableArray<Node*> alloc_worklist;
 145   GrowableArray<Node*> ptr_cmp_worklist;
 146   GrowableArray<MemBarStoreStoreNode*> storestore_worklist;
 147   GrowableArray<ArrayCopyNode*>  arraycopy_worklist;
 148   GrowableArray<PointsToNode*>   ptnodes_worklist;
 149   GrowableArray<JavaObjectNode*> java_objects_worklist;
 150   GrowableArray<JavaObjectNode*> non_escaped_allocs_worklist;
 151   GrowableArray<FieldNode*>      oop_fields_worklist;
 152   GrowableArray<SafePointNode*>  sfn_worklist;
 153   GrowableArray<MergeMemNode*>   mergemem_worklist;
 154   DEBUG_ONLY( GrowableArray<Node*> addp_worklist; )
 155 
 156   { Compile::TracePhase tp(Phase::_t_connectionGraph);
 157 
 158   // 1. Populate Connection Graph (CG) with PointsTo nodes.
 159   ideal_nodes.map(C->live_nodes(), nullptr);  // preallocate space
 160   // Initialize worklist
 161   if (C->root() != nullptr) {
 162     ideal_nodes.push(C->root());
 163   }
 164   // Processed ideal nodes are unique on ideal_nodes list
 165   // but several ideal nodes are mapped to the phantom_obj.
 166   // To avoid duplicated entries on the following worklists
 167   // add the phantom_obj only once to them.
 168   ptnodes_worklist.append(phantom_obj);
 169   java_objects_worklist.append(phantom_obj);
 170   for( uint next = 0; next < ideal_nodes.size(); ++next ) {
 171     Node* n = ideal_nodes.at(next);
 172     if ((n->Opcode() == Op_LoadX || n->Opcode() == Op_StoreX) &&
 173         !n->in(MemNode::Address)->is_AddP() &&
 174         _igvn->type(n->in(MemNode::Address))->isa_oopptr()) {
 175       // Load/Store at mark work address is at offset 0 so has no AddP which confuses EA
 176       Node* addp = new AddPNode(n->in(MemNode::Address), n->in(MemNode::Address), _igvn->MakeConX(0));
 177       _igvn->register_new_node_with_optimizer(addp);
 178       _igvn->replace_input_of(n, MemNode::Address, addp);
 179       ideal_nodes.push(addp);
 180       _nodes.at_put_grow(addp->_idx, nullptr, nullptr);
 181     }
 182     // Create PointsTo nodes and add them to Connection Graph. Called
 183     // only once per ideal node since ideal_nodes is Unique_Node list.
 184     add_node_to_connection_graph(n, &delayed_worklist);
 185     PointsToNode* ptn = ptnode_adr(n->_idx);
 186     if (ptn != nullptr && ptn != phantom_obj) {
 187       ptnodes_worklist.append(ptn);
 188       if (ptn->is_JavaObject()) {
 189         java_objects_worklist.append(ptn->as_JavaObject());
 190         if ((n->is_Allocate() || n->is_CallStaticJava()) &&
 191             (ptn->escape_state() < PointsToNode::GlobalEscape)) {
 192           // Only allocations and java static calls results are interesting.
 193           non_escaped_allocs_worklist.append(ptn->as_JavaObject());
 194         }
 195       } else if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
 196         oop_fields_worklist.append(ptn->as_Field());
 197       }
 198     }
 199     // Collect some interesting nodes for further use.
 200     switch (n->Opcode()) {
 201       case Op_MergeMem:
 202         // Collect all MergeMem nodes to add memory slices for
 203         // scalar replaceable objects in split_unique_types().
 204         mergemem_worklist.append(n->as_MergeMem());
 205         break;
 206       case Op_CmpP:
 207       case Op_CmpN:
 208         // Collect compare pointers nodes.
 209         if (OptimizePtrCompare) {
 210           ptr_cmp_worklist.append(n);
 211         }
 212         break;
 213       case Op_MemBarStoreStore:
 214         // Collect all MemBarStoreStore nodes so that depending on the
 215         // escape status of the associated Allocate node some of them
 216         // may be eliminated.
 217         if (!UseStoreStoreForCtor || n->req() > MemBarNode::Precedent) {
 218           storestore_worklist.append(n->as_MemBarStoreStore());
 219         }
 220         // If MemBarStoreStore has a precedent edge add it to the worklist (like MemBarRelease)
 221       case Op_MemBarRelease:
 222         if (n->req() > MemBarNode::Precedent) {
 223           record_for_optimizer(n);
 224         }
 225         break;
 226 #ifdef ASSERT
 227       case Op_AddP:
 228         // Collect address nodes for graph verification.
 229         addp_worklist.append(n);
 230         break;
 231 #endif
 232       case Op_ArrayCopy:
 233         // Keep a list of ArrayCopy nodes so if one of its input is non
 234         // escaping, we can record a unique type
 235         arraycopy_worklist.append(n->as_ArrayCopy());
 236         break;
 237       default:
 238         // not interested now, ignore...
 239         break;
 240     }
 241     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 242       Node* m = n->fast_out(i);   // Get user
 243       ideal_nodes.push(m);
 244     }
 245     if (n->is_SafePoint()) {
 246       sfn_worklist.append(n->as_SafePoint());
 247     }
 248   }
 249 
 250 #ifndef PRODUCT
 251   if (_compile->directive()->TraceEscapeAnalysisOption) {
 252     tty->print("+++++ Initial worklist for ");
 253     _compile->method()->print_name();
 254     tty->print_cr(" (ea_inv=%d)", _invocation);
 255     for (int i = 0; i < ptnodes_worklist.length(); i++) {
 256       PointsToNode* ptn = ptnodes_worklist.at(i);
 257       ptn->dump();
 258     }
 259     tty->print_cr("+++++ Calculating escape states and scalar replaceability");
 260   }
 261 #endif
 262 
 263   if (non_escaped_allocs_worklist.length() == 0) {
 264     _collecting = false;
 265     NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 266     return false; // Nothing to do.
 267   }
 268   // Add final simple edges to graph.
 269   while(delayed_worklist.size() > 0) {
 270     Node* n = delayed_worklist.pop();
 271     add_final_edges(n);
 272   }
 273 
 274 #ifdef ASSERT
 275   if (VerifyConnectionGraph) {
 276     // Verify that no new simple edges could be created and all
 277     // local vars has edges.
 278     _verify = true;
 279     int ptnodes_length = ptnodes_worklist.length();
 280     for (int next = 0; next < ptnodes_length; ++next) {
 281       PointsToNode* ptn = ptnodes_worklist.at(next);
 282       add_final_edges(ptn->ideal_node());
 283       if (ptn->is_LocalVar() && ptn->edge_count() == 0) {
 284         ptn->dump();
 285         assert(ptn->as_LocalVar()->edge_count() > 0, "sanity");
 286       }
 287     }
 288     _verify = false;
 289   }
 290 #endif
 291   // Bytecode analyzer BCEscapeAnalyzer, used for Call nodes
 292   // processing, calls to CI to resolve symbols (types, fields, methods)
 293   // referenced in bytecode. During symbol resolution VM may throw
 294   // an exception which CI cleans and converts to compilation failure.
 295   if (C->failing()) {
 296     NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 297     return false;
 298   }
 299 
 300   _compile->print_method(PHASE_EA_AFTER_INITIAL_CONGRAPH, 4);
 301 
 302   // 2. Finish Graph construction by propagating references to all
 303   //    java objects through graph.
 304   if (!complete_connection_graph(ptnodes_worklist, non_escaped_allocs_worklist,
 305                                  java_objects_worklist, oop_fields_worklist)) {
 306     // All objects escaped or hit time or iterations limits.
 307     _collecting = false;
 308     NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 309     return false;
 310   }
 311 
 312   _compile->print_method(PHASE_EA_AFTER_COMPLETE_CONGRAPH, 4);
 313 
 314   // 3. Adjust scalar_replaceable state of nonescaping objects and push
 315   //    scalar replaceable allocations on alloc_worklist for processing
 316   //    in split_unique_types().
 317   GrowableArray<JavaObjectNode*> jobj_worklist;
 318   int non_escaped_length = non_escaped_allocs_worklist.length();
 319   bool found_nsr_alloc = false;
 320   for (int next = 0; next < non_escaped_length; next++) {
 321     JavaObjectNode* ptn = non_escaped_allocs_worklist.at(next);
 322     bool noescape = (ptn->escape_state() == PointsToNode::NoEscape);
 323     Node* n = ptn->ideal_node();
 324     if (n->is_Allocate()) {
 325       n->as_Allocate()->_is_non_escaping = noescape;
 326     }
 327     if (noescape && ptn->scalar_replaceable()) {
 328       adjust_scalar_replaceable_state(ptn, reducible_merges);
 329       if (ptn->scalar_replaceable()) {
 330         jobj_worklist.push(ptn);
 331       } else {
 332         found_nsr_alloc = true;
 333       }
 334     }
 335     _compile->print_method(PHASE_EA_ADJUST_SCALAR_REPLACEABLE_ITER, 6, n);
 336   }
 337 
 338   // Propagate NSR (Not Scalar Replaceable) state.
 339   if (found_nsr_alloc) {
 340     find_scalar_replaceable_allocs(jobj_worklist, reducible_merges);
 341   }
 342 
 343   // alloc_worklist will be processed in reverse push order.
 344   // Therefore the reducible Phis will be processed for last and that's what we
 345   // want because by then the scalarizable inputs of the merge will already have
 346   // an unique instance type.
 347   for (uint i = 0; i < reducible_merges.size(); i++ ) {
 348     Node* n = reducible_merges.at(i);
 349     alloc_worklist.append(n);
 350   }
 351 
 352   for (int next = 0; next < jobj_worklist.length(); ++next) {
 353     JavaObjectNode* jobj = jobj_worklist.at(next);
 354     if (jobj->scalar_replaceable()) {
 355       alloc_worklist.append(jobj->ideal_node());
 356     }
 357   }
 358 
 359 #ifdef ASSERT
 360   if (VerifyConnectionGraph) {
 361     // Verify that graph is complete - no new edges could be added or needed.
 362     verify_connection_graph(ptnodes_worklist, non_escaped_allocs_worklist,
 363                             java_objects_worklist, addp_worklist);
 364   }
 365   assert(C->unique() == nodes_size(), "no new ideal nodes should be added during ConnectionGraph build");
 366   assert(null_obj->escape_state() == PointsToNode::NoEscape &&
 367          null_obj->edge_count() == 0 &&
 368          !null_obj->arraycopy_src() &&
 369          !null_obj->arraycopy_dst(), "sanity");
 370 #endif
 371 
 372   _collecting = false;
 373 
 374   _compile->print_method(PHASE_EA_AFTER_PROPAGATE_NSR, 4);
 375   } // TracePhase t3("connectionGraph")
 376 
 377   // 4. Optimize ideal graph based on EA information.
 378   bool has_non_escaping_obj = (non_escaped_allocs_worklist.length() > 0);
 379   if (has_non_escaping_obj) {
 380     optimize_ideal_graph(ptr_cmp_worklist, storestore_worklist);
 381   }
 382 
 383 #ifndef PRODUCT
 384   if (PrintEscapeAnalysis) {
 385     dump(ptnodes_worklist); // Dump ConnectionGraph
 386   }
 387 #endif
 388 
 389 #ifdef ASSERT
 390   if (VerifyConnectionGraph) {
 391     int alloc_length = alloc_worklist.length();
 392     for (int next = 0; next < alloc_length; ++next) {
 393       Node* n = alloc_worklist.at(next);
 394       PointsToNode* ptn = ptnode_adr(n->_idx);
 395       assert(ptn->escape_state() == PointsToNode::NoEscape && ptn->scalar_replaceable(), "sanity");
 396     }
 397   }
 398 
 399   if (VerifyReduceAllocationMerges) {
 400     for (uint i = 0; i < reducible_merges.size(); i++ ) {
 401       Node* n = reducible_merges.at(i);
 402       if (!can_reduce_phi(n->as_Phi())) {
 403         TraceReduceAllocationMerges = true;
 404         n->dump(2);
 405         n->dump(-2);
 406         assert(can_reduce_phi(n->as_Phi()), "Sanity: previous reducible Phi is no longer reducible before SUT.");
 407       }
 408     }
 409   }
 410 #endif
 411 
 412   _compile->print_method(PHASE_EA_AFTER_GRAPH_OPTIMIZATION, 4);
 413 
 414   // 5. Separate memory graph for scalar replaceable allcations.
 415   bool has_scalar_replaceable_candidates = (alloc_worklist.length() > 0);
 416   if (has_scalar_replaceable_candidates && EliminateAllocations) {
 417     assert(C->do_aliasing(), "Aliasing should be enabled");
 418     // Now use the escape information to create unique types for
 419     // scalar replaceable objects.
 420     split_unique_types(alloc_worklist, arraycopy_worklist, mergemem_worklist, reducible_merges);
 421     if (C->failing()) {
 422       NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 423       return false;
 424     }
 425 
 426 #ifdef ASSERT
 427   } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
 428     tty->print("=== No allocations eliminated for ");
 429     C->method()->print_short_name();
 430     if (!EliminateAllocations) {
 431       tty->print(" since EliminateAllocations is off ===");
 432     } else if(!has_scalar_replaceable_candidates) {
 433       tty->print(" since there are no scalar replaceable candidates ===");
 434     }
 435     tty->cr();
 436 #endif
 437   }
 438 
 439   // 6. Expand flat accesses if the object does not escape. This adds nodes to
 440   // the graph, so it has to be after split_unique_types. This expands atomic
 441   // mismatched accesses (though encapsulated in LoadFlats and StoreFlats) into
 442   // non-mismatched accesses, so it is better before reduce allocation merges.
 443   if (has_non_escaping_obj) {
 444     optimize_flat_accesses(sfn_worklist);
 445   }
 446 
 447   _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES, 4);
 448 
 449   // 7. Reduce allocation merges used as debug information. This is done after
 450   // split_unique_types because the methods used to create SafePointScalarObject
 451   // need to traverse the memory graph to find values for object fields. We also
 452   // set to null the scalarized inputs of reducible Phis so that the Allocate
 453   // that they point can be later scalar replaced.
 454   bool delay = _igvn->delay_transform();
 455   _igvn->set_delay_transform(true);
 456   for (uint i = 0; i < reducible_merges.size(); i++) {
 457     Node* n = reducible_merges.at(i);
 458     if (n->outcnt() > 0) {
 459       if (!reduce_phi_on_safepoints(n->as_Phi())) {
 460         NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 461         C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
 462         return false;
 463       }
 464 
 465       // Now we set the scalar replaceable inputs of ophi to null, which is
 466       // the last piece that would prevent it from being scalar replaceable.
 467       reset_scalar_replaceable_entries(n->as_Phi());
 468     }
 469   }
 470   _igvn->set_delay_transform(delay);
 471 
 472   // Annotate at safepoints if they have <= ArgEscape objects in their scope and at
 473   // java calls if they pass ArgEscape objects as parameters.
 474   if (has_non_escaping_obj &&
 475       (C->env()->should_retain_local_variables() ||
 476        C->env()->jvmti_can_get_owned_monitor_info() ||
 477        C->env()->jvmti_can_walk_any_space() ||
 478        DeoptimizeObjectsALot)) {
 479     int sfn_length = sfn_worklist.length();
 480     for (int next = 0; next < sfn_length; next++) {
 481       SafePointNode* sfn = sfn_worklist.at(next);
 482       sfn->set_has_ea_local_in_scope(has_ea_local_in_scope(sfn));
 483       if (sfn->is_CallJava()) {
 484         CallJavaNode* call = sfn->as_CallJava();
 485         call->set_arg_escape(has_arg_escape(call));
 486       }
 487     }
 488   }
 489 
 490   _compile->print_method(PHASE_EA_AFTER_REDUCE_PHI_ON_SAFEPOINTS, 4);
 491 
 492   NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 493   return has_non_escaping_obj;
 494 }
 495 
 496 // Check if it's profitable to reduce the Phi passed as parameter.  Returns true
 497 // if at least one scalar replaceable allocation participates in the merge.
 498 bool ConnectionGraph::can_reduce_phi_check_inputs(PhiNode* ophi) const {
 499   bool found_sr_allocate = false;
 500 
 501   for (uint i = 1; i < ophi->req(); i++) {
 502     JavaObjectNode* ptn = unique_java_object(ophi->in(i));
 503     if (ptn != nullptr && ptn->scalar_replaceable()) {
 504       AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
 505 
 506       // Don't handle arrays.
 507       if (alloc->Opcode() != Op_Allocate) {
 508         assert(alloc->Opcode() == Op_AllocateArray, "Unexpected type of allocation.");
 509         continue;
 510       }
 511 
 512       if (PhaseMacroExpand::can_eliminate_allocation(_igvn, alloc, nullptr)) {
 513         found_sr_allocate = true;
 514       } else {
 515         NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("%dth input of Phi %d is SR but can't be eliminated.", i, ophi->_idx);)
 516         ptn->set_scalar_replaceable(false);
 517       }
 518     }
 519   }
 520 
 521   NOT_PRODUCT(if (TraceReduceAllocationMerges && !found_sr_allocate) tty->print_cr("Can NOT reduce Phi %d on invocation %d. No SR Allocate as input.", ophi->_idx, _invocation);)
 522   return found_sr_allocate;
 523 }
 524 
 525 // We can reduce the Cmp if it's a comparison between the Phi and a constant.
 526 // I require the 'other' input to be a constant so that I can move the Cmp
 527 // around safely.
 528 bool ConnectionGraph::can_reduce_cmp(Node* n, Node* cmp) const {
 529   assert(cmp->Opcode() == Op_CmpP || cmp->Opcode() == Op_CmpN, "not expected node: %s", cmp->Name());
 530   Node* left = cmp->in(1);
 531   Node* right = cmp->in(2);
 532 
 533   return (left == n || right == n) &&
 534          (left->is_Con() || right->is_Con()) &&
 535          cmp->outcnt() == 1;
 536 }
 537 
 538 // We are going to check if any of the SafePointScalarMerge entries
 539 // in the SafePoint reference the Phi that we are checking.
 540 bool ConnectionGraph::has_been_reduced(PhiNode* n, SafePointNode* sfpt) const {
 541   JVMState *jvms = sfpt->jvms();
 542 
 543   for (uint i = jvms->debug_start(); i < jvms->debug_end(); i++) {
 544     Node* sfpt_in = sfpt->in(i);
 545     if (sfpt_in->is_SafePointScalarMerge()) {
 546       SafePointScalarMergeNode* smerge = sfpt_in->as_SafePointScalarMerge();
 547       Node* nsr_ptr = sfpt->in(smerge->merge_pointer_idx(jvms));
 548       if (nsr_ptr == n) {
 549         return true;
 550       }
 551     }
 552   }
 553 
 554   return false;
 555 }
 556 
 557 // Check if we are able to untangle the merge. The following patterns are
 558 // supported:
 559 //  - Phi -> SafePoints
 560 //  - Phi -> CmpP/N
 561 //  - Phi -> AddP -> Load
 562 //  - Phi -> CastPP -> SafePoints
 563 //  - Phi -> CastPP -> AddP -> Load
 564 bool ConnectionGraph::can_reduce_check_users(Node* n, uint nesting) const {
 565   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 566     Node* use = n->fast_out(i);
 567 
 568     if (use->is_SafePoint()) {
 569       if (use->is_Call() && use->as_Call()->has_non_debug_use(n)) {
 570         NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. Call has non_debug_use().", n->_idx, _invocation);)
 571         return false;
 572       } else if (has_been_reduced(n->is_Phi() ? n->as_Phi() : n->as_CastPP()->in(1)->as_Phi(), use->as_SafePoint())) {
 573         NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. It has already been reduced.", n->_idx, _invocation);)
 574         return false;
 575       }
 576     } else if (use->is_AddP()) {
 577       Node* addp = use;
 578       for (DUIterator_Fast jmax, j = addp->fast_outs(jmax); j < jmax; j++) {
 579         Node* use_use = addp->fast_out(j);
 580         const Type* load_type = _igvn->type(use_use);
 581 
 582         if (!use_use->is_Load() || !use_use->as_Load()->can_split_through_phi_base(_igvn)) {
 583           NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. AddP user isn't a [splittable] Load(): %s", n->_idx, _invocation, use_use->Name());)
 584           return false;
 585         } else if (load_type->isa_narrowklass() || load_type->isa_klassptr()) {
 586           NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. [Narrow] Klass Load: %s", n->_idx, _invocation, use_use->Name());)
 587           return false;
 588         }
 589       }
 590     } else if (nesting > 0) {
 591       NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. Unsupported user %s at nesting level %d.", n->_idx, _invocation, use->Name(), nesting);)
 592       return false;
 593     } else if (use->is_CastPP()) {
 594       const Type* cast_t = _igvn->type(use);
 595       if (cast_t == nullptr || cast_t->make_ptr()->isa_instptr() == nullptr) {
 596 #ifndef PRODUCT
 597         if (TraceReduceAllocationMerges) {
 598           tty->print_cr("Can NOT reduce Phi %d on invocation %d. CastPP is not to an instance.", n->_idx, _invocation);
 599           use->dump();
 600         }
 601 #endif
 602         return false;
 603       }
 604 
 605       bool is_trivial_control = use->in(0) == nullptr || use->in(0) == n->in(0);
 606       if (!is_trivial_control) {
 607         // If it's not a trivial control then we check if we can reduce the
 608         // CmpP/N used by the If controlling the cast.
 609         if (use->in(0)->is_IfTrue() || use->in(0)->is_IfFalse()) {
 610           Node* iff = use->in(0)->in(0);
 611           // We may have an OpaqueNotNull node between If and Bool nodes. But we could also have a sub class of IfNode,
 612           // for example, an OuterStripMinedLoopEnd or a Parse Predicate. Bail out in all these cases.
 613           bool can_reduce = (iff->Opcode() == Op_If) && iff->in(1)->is_Bool() && iff->in(1)->in(1)->is_Cmp();
 614           if (can_reduce) {
 615             Node* iff_cmp = iff->in(1)->in(1);
 616             int opc = iff_cmp->Opcode();
 617             can_reduce = (opc == Op_CmpP || opc == Op_CmpN) && can_reduce_cmp(n, iff_cmp);
 618           }
 619           if (!can_reduce) {
 620 #ifndef PRODUCT
 621             if (TraceReduceAllocationMerges) {
 622               tty->print_cr("Can NOT reduce Phi %d on invocation %d. CastPP %d doesn't have simple control.", n->_idx, _invocation, use->_idx);
 623               n->dump(5);
 624             }
 625 #endif
 626             return false;
 627           }
 628         }
 629       }
 630 
 631       if (!can_reduce_check_users(use, nesting+1)) {
 632         return false;
 633       }
 634     } else if (use->Opcode() == Op_CmpP || use->Opcode() == Op_CmpN) {
 635       if (!can_reduce_cmp(n, use)) {
 636         NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. CmpP/N %d isn't reducible.", n->_idx, _invocation, use->_idx);)
 637         return false;
 638       }
 639     } else {
 640       NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Can NOT reduce Phi %d on invocation %d. One of the uses is: %d %s", n->_idx, _invocation, use->_idx, use->Name());)
 641       return false;
 642     }
 643   }
 644 
 645   return true;
 646 }
 647 
 648 // Returns true if: 1) It's profitable to reduce the merge, and 2) The Phi is
 649 // only used in some certain code shapes. Check comments in
 650 // 'can_reduce_phi_inputs' and 'can_reduce_phi_users' for more
 651 // details.
 652 bool ConnectionGraph::can_reduce_phi(PhiNode* ophi) const {
 653   // If there was an error attempting to reduce allocation merges for this
 654   // method we might have disabled the compilation and be retrying with RAM
 655   // disabled.
 656   if (!_compile->do_reduce_allocation_merges() || ophi->region()->Opcode() != Op_Region) {
 657     return false;
 658   }
 659 
 660   const Type* phi_t = _igvn->type(ophi);
 661   if (phi_t == nullptr ||
 662       phi_t->make_ptr() == nullptr ||
 663       phi_t->make_ptr()->isa_aryptr() != nullptr) {
 664     return false;
 665   }
 666 
 667   if (!can_reduce_phi_check_inputs(ophi) || !can_reduce_check_users(ophi, /* nesting: */ 0)) {
 668     return false;
 669   }
 670 
 671   NOT_PRODUCT(if (TraceReduceAllocationMerges) { tty->print_cr("Can reduce Phi %d during invocation %d: ", ophi->_idx, _invocation); })
 672   return true;
 673 }
 674 
 675 // This method will return a CmpP/N that we need to use on the If controlling a
 676 // CastPP after it was split. This method is only called on bases that are
 677 // nullable therefore we always need a controlling if for the splitted CastPP.
 678 //
 679 // 'curr_ctrl' is the control of the CastPP that we want to split through phi.
 680 // If the CastPP currently doesn't have a control then the CmpP/N will be
 681 // against the null constant, otherwise it will be against the constant input of
 682 // the existing CmpP/N. It's guaranteed that there will be a CmpP/N in the later
 683 // case because we have constraints on it and because the CastPP has a control
 684 // input.
 685 Node* ConnectionGraph::specialize_cmp(Node* base, Node* curr_ctrl) {
 686   const Type* t = base->bottom_type();
 687   Node* con = nullptr;
 688 
 689   if (curr_ctrl == nullptr || curr_ctrl->is_Region()) {
 690     con = _igvn->zerocon(t->basic_type());
 691   } else {
 692     // can_reduce_check_users() verified graph: true/false -> if -> bool -> cmp
 693     assert(curr_ctrl->in(0)->Opcode() == Op_If, "unexpected node %s", curr_ctrl->in(0)->Name());
 694     Node* bol = curr_ctrl->in(0)->in(1);
 695     assert(bol->is_Bool(), "unexpected node %s", bol->Name());
 696     Node* curr_cmp = bol->in(1);
 697     assert(curr_cmp->Opcode() == Op_CmpP || curr_cmp->Opcode() == Op_CmpN, "unexpected node %s", curr_cmp->Name());
 698     con = curr_cmp->in(1)->is_Con() ? curr_cmp->in(1) : curr_cmp->in(2);
 699   }
 700 
 701   return CmpNode::make(base, con, t->basic_type());
 702 }
 703 
 704 // This method 'specializes' the CastPP passed as parameter to the base passed
 705 // as parameter. Note that the existing CastPP input is a Phi. "Specialize"
 706 // means that the CastPP now will be specific for a given base instead of a Phi.
 707 // An If-Then-Else-Region block is inserted to control the CastPP. The control
 708 // of the CastPP is a copy of the current one (if there is one) or a check
 709 // against null.
 710 //
 711 // Before:
 712 //
 713 //    C1     C2  ... Cn
 714 //     \      |      /
 715 //      \     |     /
 716 //       \    |    /
 717 //        \   |   /
 718 //         \  |  /
 719 //          \ | /
 720 //           \|/
 721 //          Region     B1      B2  ... Bn
 722 //            |          \      |      /
 723 //            |           \     |     /
 724 //            |            \    |    /
 725 //            |             \   |   /
 726 //            |              \  |  /
 727 //            |               \ | /
 728 //            ---------------> Phi
 729 //                              |
 730 //                      X       |
 731 //                      |       |
 732 //                      |       |
 733 //                      ------> CastPP
 734 //
 735 // After (only partial illustration; base = B2, current_control = C2):
 736 //
 737 //                      C2
 738 //                      |
 739 //                      If
 740 //                     / \
 741 //                    /   \
 742 //                   T     F
 743 //                  /\     /
 744 //                 /  \   /
 745 //                /    \ /
 746 //      C1    CastPP   Reg        Cn
 747 //       |              |          |
 748 //       |              |          |
 749 //       |              |          |
 750 //       -------------- | ----------
 751 //                    | | |
 752 //                    Region
 753 //
 754 Node* ConnectionGraph::specialize_castpp(Node* castpp, Node* base, Node* current_control) {
 755   Node* control_successor  = current_control->unique_ctrl_out();
 756   Node* cmp                = _igvn->transform(specialize_cmp(base, castpp->in(0)));
 757   Node* bol                = _igvn->transform(new BoolNode(cmp, BoolTest::ne));
 758   IfNode* if_ne            = _igvn->transform(new IfNode(current_control, bol, PROB_MIN, COUNT_UNKNOWN))->as_If();
 759   Node* not_eq_control     = _igvn->transform(new IfTrueNode(if_ne));
 760   Node* yes_eq_control     = _igvn->transform(new IfFalseNode(if_ne));
 761   Node* end_region         = _igvn->transform(new RegionNode(3));
 762 
 763   // Insert the new if-else-region block into the graph
 764   end_region->set_req(1, not_eq_control);
 765   end_region->set_req(2, yes_eq_control);
 766   control_successor->replace_edge(current_control, end_region, _igvn);
 767 
 768   _igvn->_worklist.push(current_control);
 769   _igvn->_worklist.push(control_successor);
 770 
 771   return _igvn->transform(ConstraintCastNode::make_cast_for_type(not_eq_control, base, _igvn->type(castpp), ConstraintCastNode::DependencyType::NonFloatingNonNarrowing, nullptr));
 772 }
 773 
 774 Node* ConnectionGraph::split_castpp_load_through_phi(Node* curr_addp, Node* curr_load, Node* region, GrowableArray<Node*>* bases_for_loads, GrowableArray<Node *>  &alloc_worklist) {
 775   const Type* load_type = _igvn->type(curr_load);
 776   Node* nsr_value = _igvn->zerocon(load_type->basic_type());
 777   Node* memory = curr_load->in(MemNode::Memory);
 778 
 779   // The data_phi merging the loads needs to be nullable if
 780   // we are loading pointers.
 781   if (load_type->make_ptr() != nullptr) {
 782     if (load_type->isa_narrowoop()) {
 783       load_type = load_type->meet(TypeNarrowOop::NULL_PTR);
 784     } else if (load_type->isa_ptr()) {
 785       load_type = load_type->meet(TypePtr::NULL_PTR);
 786     } else {
 787       assert(false, "Unexpected load ptr type.");
 788     }
 789   }
 790 
 791   Node* data_phi = PhiNode::make(region, nsr_value, load_type);
 792 
 793   for (int i = 1; i < bases_for_loads->length(); i++) {
 794     Node* base = bases_for_loads->at(i);
 795     Node* cmp_region = nullptr;
 796     if (base != nullptr) {
 797       if (base->is_CFG()) { // means that we added a CastPP as child of this CFG node
 798         cmp_region = base->unique_ctrl_out_or_null();
 799         assert(cmp_region != nullptr, "There should be.");
 800         base = base->find_out_with(Op_CastPP);
 801       }
 802 
 803       Node* addr = _igvn->transform(new AddPNode(base, base, curr_addp->in(AddPNode::Offset)));
 804       Node* mem = (memory->is_Phi() && (memory->in(0) == region)) ? memory->in(i) : memory;
 805       Node* load = curr_load->clone();
 806       load->set_req(0, nullptr);
 807       load->set_req(1, mem);
 808       load->set_req(2, addr);
 809 
 810       if (cmp_region != nullptr) { // see comment on previous if
 811         Node* intermediate_phi = PhiNode::make(cmp_region, nsr_value, load_type);
 812         intermediate_phi->set_req(1, _igvn->transform(load));
 813         load = intermediate_phi;
 814       }
 815 
 816       data_phi->set_req(i, _igvn->transform(load));
 817     } else {
 818       // Just use the default, which is already in phi
 819     }
 820   }
 821 
 822   // Takes care of updating CG and split_unique_types worklists due
 823   // to cloned AddP->Load.
 824   updates_after_load_split(data_phi, curr_load, alloc_worklist);
 825 
 826   return _igvn->transform(data_phi);
 827 }
 828 
 829 // This method only reduces CastPP fields loads; SafePoints are handled
 830 // separately. The idea here is basically to clone the CastPP and place copies
 831 // on each input of the Phi, including non-scalar replaceable inputs.
 832 // Experimentation shows that the resulting IR graph is simpler that way than if
 833 // we just split the cast through scalar-replaceable inputs.
 834 //
 835 // The reduction process requires that CastPP's control be one of:
 836 //  1) no control,
 837 //  2) the same region as Ophi, or
 838 //  3) an IfTrue/IfFalse coming from an CmpP/N between Ophi and a constant.
 839 //
 840 // After splitting the CastPP we'll put it under an If-Then-Else-Region control
 841 // flow. If the CastPP originally had an IfTrue/False control input then we'll
 842 // use a similar CmpP/N to control the new If-Then-Else-Region. Otherwise, we'll
 843 // juse use a CmpP/N against the null constant.
 844 //
 845 // The If-Then-Else-Region isn't always needed. For instance, if input to
 846 // splitted cast was not nullable (or if it was the null constant) then we don't
 847 // need (shouldn't) use a CastPP at all.
 848 //
 849 // After the casts are splitted we'll split the AddP->Loads through the Phi and
 850 // connect them to the just split CastPPs.
 851 //
 852 // Before (CastPP control is same as Phi):
 853 //
 854 //          Region     Allocate   Null    Call
 855 //            |             \      |      /
 856 //            |              \     |     /
 857 //            |               \    |    /
 858 //            |                \   |   /
 859 //            |                 \  |  /
 860 //            |                  \ | /
 861 //            ------------------> Phi            # Oop Phi
 862 //            |                    |
 863 //            |                    |
 864 //            |                    |
 865 //            |                    |
 866 //            ----------------> CastPP
 867 //                                 |
 868 //                               AddP
 869 //                                 |
 870 //                               Load
 871 //
 872 // After (Very much simplified):
 873 //
 874 //                         Call  Null
 875 //                            \  /
 876 //                            CmpP
 877 //                             |
 878 //                           Bool#NE
 879 //                             |
 880 //                             If
 881 //                            / \
 882 //                           T   F
 883 //                          / \ /
 884 //                         /   R
 885 //                     CastPP  |
 886 //                       |     |
 887 //                     AddP    |
 888 //                       |     |
 889 //                     Load    |
 890 //                         \   |   0
 891 //            Allocate      \  |  /
 892 //                \          \ | /
 893 //               AddP         Phi
 894 //                  \         /
 895 //                 Load      /
 896 //                    \  0  /
 897 //                     \ | /
 898 //                      \|/
 899 //                      Phi        # "Field" Phi
 900 //
 901 void ConnectionGraph::reduce_phi_on_castpp_field_load(Node* curr_castpp, GrowableArray<Node*> &alloc_worklist) {
 902   Node* ophi = curr_castpp->in(1);
 903   assert(ophi->is_Phi(), "Expected this to be a Phi node.");
 904 
 905   // Identify which base should be used for AddP->Load later when spliting the
 906   // CastPP->Loads through ophi. Three kind of values may be stored in this
 907   // array, depending on the nullability status of the corresponding input in
 908   // ophi.
 909   //
 910   //  - nullptr:    Meaning that the base is actually the null constant and therefore
 911   //                we won't try to load from it.
 912   //
 913   //  - CFG Node:   Meaning that the base is a CastPP that was specialized for
 914   //                this input of Ophi. I.e., we added an If->Then->Else-Region
 915   //                that will 'activate' the CastPp only when the input is not Null.
 916   //
 917   //  - Other Node: Meaning that the base is not nullable and therefore we'll try
 918   //                to load directly from it.
 919   GrowableArray<Node*> bases_for_loads(ophi->req(), ophi->req(), nullptr);
 920 
 921   for (uint i = 1; i < ophi->req(); i++) {
 922     Node* base = ophi->in(i);
 923     const Type* base_t = _igvn->type(base);
 924 
 925     if (base_t->maybe_null()) {
 926       if (base->is_Con()) {
 927         // Nothing todo as bases_for_loads[i] is already null
 928       } else {
 929         Node* new_castpp = specialize_castpp(curr_castpp, base, ophi->in(0)->in(i));
 930         bases_for_loads.at_put(i, new_castpp->in(0)); // Use the ctrl of the new node just as a flag
 931       }
 932     } else {
 933       bases_for_loads.at_put(i, base);
 934     }
 935   }
 936 
 937   // Now let's split the CastPP->Loads through the Phi
 938   for (int i = curr_castpp->outcnt()-1; i >= 0;) {
 939     Node* use = curr_castpp->raw_out(i);
 940     if (use->is_AddP()) {
 941       for (int j = use->outcnt()-1; j >= 0;) {
 942         Node* use_use = use->raw_out(j);
 943         assert(use_use->is_Load(), "Expected this to be a Load node.");
 944 
 945         // We can't make an unconditional load from a nullable input. The
 946         // 'split_castpp_load_through_phi` method will add an
 947         // 'If-Then-Else-Region` around nullable bases and only load from them
 948         // when the input is not null.
 949         Node* phi = split_castpp_load_through_phi(use, use_use, ophi->in(0), &bases_for_loads, alloc_worklist);
 950         _igvn->replace_node(use_use, phi);
 951 
 952         --j;
 953         j = MIN2(j, (int)use->outcnt()-1);
 954       }
 955 
 956       _igvn->remove_dead_node(use);
 957     }
 958     --i;
 959     i = MIN2(i, (int)curr_castpp->outcnt()-1);
 960   }
 961 }
 962 
 963 // This method split a given CmpP/N through the Phi used in one of its inputs.
 964 // As a result we convert a comparison with a pointer to a comparison with an
 965 // integer.
 966 // The only requirement is that one of the inputs of the CmpP/N must be a Phi
 967 // while the other must be a constant.
 968 // The splitting process is basically just cloning the CmpP/N above the input
 969 // Phi.  However, some (most) of the cloned CmpP/Ns won't be requred because we
 970 // can prove at compile time the result of the comparison.
 971 //
 972 // Before:
 973 //
 974 //             in1    in2 ... inN
 975 //              \      |      /
 976 //               \     |     /
 977 //                \    |    /
 978 //                 \   |   /
 979 //                  \  |  /
 980 //                   \ | /
 981 //                    Phi
 982 //                     |   Other
 983 //                     |    /
 984 //                     |   /
 985 //                     |  /
 986 //                    CmpP/N
 987 //
 988 // After:
 989 //
 990 //        in1  Other   in2 Other  inN  Other
 991 //         |    |      |   |      |    |
 992 //         \    |      |   |      |    |
 993 //          \  /       |   /      |    /
 994 //          CmpP/N    CmpP/N     CmpP/N
 995 //          Bool      Bool       Bool
 996 //            \        |        /
 997 //             \       |       /
 998 //              \      |      /
 999 //               \     |     /
1000 //                \    |    /
1001 //                 \   |   /
1002 //                  \  |  /
1003 //                   \ | /
1004 //                    Phi
1005 //                     |
1006 //                     |   Zero
1007 //                     |    /
1008 //                     |   /
1009 //                     |  /
1010 //                     CmpI
1011 //
1012 //
1013 void ConnectionGraph::reduce_phi_on_cmp(Node* cmp) {
1014   Node* ophi = cmp->in(1)->is_Con() ? cmp->in(2) : cmp->in(1);
1015   assert(ophi->is_Phi(), "Expected this to be a Phi node.");
1016 
1017   Node* other = cmp->in(1)->is_Con() ? cmp->in(1) : cmp->in(2);
1018   Node* zero = _igvn->intcon(0);
1019   Node* one = _igvn->intcon(1);
1020   BoolTest::mask mask = cmp->unique_out()->as_Bool()->_test._test;
1021 
1022   // This Phi will merge the result of the Cmps split through the Phi
1023   Node* res_phi = PhiNode::make(ophi->in(0), zero, TypeInt::INT);
1024 
1025   for (uint i=1; i<ophi->req(); i++) {
1026     Node* ophi_input = ophi->in(i);
1027     Node* res_phi_input = nullptr;
1028 
1029     const TypeInt* tcmp = optimize_ptr_compare(ophi_input, other);
1030     if (tcmp->singleton()) {
1031       if ((mask == BoolTest::mask::eq && tcmp == TypeInt::CC_EQ) ||
1032           (mask == BoolTest::mask::ne && tcmp == TypeInt::CC_GT)) {
1033         res_phi_input = one;
1034       } else {
1035         res_phi_input = zero;
1036       }
1037     } else {
1038       Node* ncmp = _igvn->transform(cmp->clone());
1039       ncmp->set_req(1, ophi_input);
1040       ncmp->set_req(2, other);
1041       Node* bol = _igvn->transform(new BoolNode(ncmp, mask));
1042       res_phi_input = bol->as_Bool()->as_int_value(_igvn);
1043     }
1044 
1045     res_phi->set_req(i, res_phi_input);
1046   }
1047 
1048   // This CMP always compares whether the output of "res_phi" is TRUE as far as the "mask".
1049   Node* new_cmp = _igvn->transform(new CmpINode(_igvn->transform(res_phi), (mask == BoolTest::mask::eq) ? one : zero));
1050   _igvn->replace_node(cmp, new_cmp);
1051 }
1052 
1053 // Push the newly created AddP on alloc_worklist and patch
1054 // the connection graph. Note that the changes in the CG below
1055 // won't affect the ES of objects since the new nodes have the
1056 // same status as the old ones.
1057 void ConnectionGraph::updates_after_load_split(Node* data_phi, Node* previous_load, GrowableArray<Node *>  &alloc_worklist) {
1058   assert(data_phi != nullptr, "Output of split_through_phi is null.");
1059   assert(data_phi != previous_load, "Output of split_through_phi is same as input.");
1060   assert(data_phi->is_Phi(), "Output of split_through_phi isn't a Phi.");
1061 
1062   if (data_phi == nullptr || !data_phi->is_Phi()) {
1063     // Make this a retry?
1064     return ;
1065   }
1066 
1067   Node* previous_addp = previous_load->in(MemNode::Address);
1068   FieldNode* fn = ptnode_adr(previous_addp->_idx)->as_Field();
1069   for (uint i = 1; i < data_phi->req(); i++) {
1070     Node* new_load = data_phi->in(i);
1071 
1072     if (new_load->is_Phi()) {
1073       // new_load is currently the "intermediate_phi" from an specialized
1074       // CastPP.
1075       new_load = new_load->in(1);
1076     }
1077 
1078     // "new_load" might actually be a constant, parameter, etc.
1079     if (new_load->is_Load()) {
1080       Node* new_addp = new_load->in(MemNode::Address);
1081       Node* base = get_addp_base(new_addp);
1082 
1083       // The base might not be something that we can create an unique
1084       // type for. If that's the case we are done with that input.
1085       PointsToNode* jobj_ptn = unique_java_object(base);
1086       if (jobj_ptn == nullptr || !jobj_ptn->scalar_replaceable()) {
1087         continue;
1088       }
1089 
1090       // Push to alloc_worklist since the base has an unique_type
1091       alloc_worklist.append_if_missing(new_addp);
1092 
1093       // Now let's add the node to the connection graph
1094       _nodes.at_grow(new_addp->_idx, nullptr);
1095       add_field(new_addp, fn->escape_state(), fn->offset());
1096       add_base(ptnode_adr(new_addp->_idx)->as_Field(), ptnode_adr(base->_idx));
1097 
1098       // If the load doesn't load an object then it won't be
1099       // part of the connection graph
1100       PointsToNode* curr_load_ptn = ptnode_adr(previous_load->_idx);
1101       if (curr_load_ptn != nullptr) {
1102         _nodes.at_grow(new_load->_idx, nullptr);
1103         add_local_var(new_load, curr_load_ptn->escape_state());
1104         add_edge(ptnode_adr(new_load->_idx), ptnode_adr(new_addp->_idx)->as_Field());
1105       }
1106     }
1107   }
1108 }
1109 
1110 void ConnectionGraph::reduce_phi_on_field_access(Node* previous_addp, GrowableArray<Node *>  &alloc_worklist) {
1111   // We'll pass this to 'split_through_phi' so that it'll do the split even
1112   // though the load doesn't have an unique instance type.
1113   bool ignore_missing_instance_id = true;
1114 
1115   // All AddPs are present in the connection graph
1116   FieldNode* fn = ptnode_adr(previous_addp->_idx)->as_Field();
1117 
1118   // Iterate over AddP looking for a Load
1119   for (int k = previous_addp->outcnt()-1; k >= 0;) {
1120     Node* previous_load = previous_addp->raw_out(k);
1121     if (previous_load->is_Load()) {
1122       Node* data_phi = previous_load->as_Load()->split_through_phi(_igvn, ignore_missing_instance_id);
1123 
1124       // Takes care of updating CG and split_unique_types worklists due to cloned
1125       // AddP->Load.
1126       updates_after_load_split(data_phi, previous_load, alloc_worklist);
1127 
1128       _igvn->replace_node(previous_load, data_phi);
1129     }
1130     --k;
1131     k = MIN2(k, (int)previous_addp->outcnt()-1);
1132   }
1133 
1134   // Remove the old AddP from the processing list because it's dead now
1135   assert(previous_addp->outcnt() == 0, "AddP should be dead now.");
1136   alloc_worklist.remove_if_existing(previous_addp);
1137 }
1138 
1139 // Create a 'selector' Phi based on the inputs of 'ophi'. If index 'i' of the
1140 // selector is:
1141 //    -> a '-1' constant, the i'th input of the original Phi is NSR.
1142 //    -> a 'x' constant >=0, the i'th input of of original Phi will be SR and
1143 //       the info about the scalarized object will be at index x of ObjectMergeValue::possible_objects
1144 PhiNode* ConnectionGraph::create_selector(PhiNode* ophi) const {
1145   Node* minus_one = _igvn->register_new_node_with_optimizer(ConINode::make(-1));
1146   Node* selector  = _igvn->register_new_node_with_optimizer(PhiNode::make(ophi->region(), minus_one, TypeInt::INT));
1147   uint number_of_sr_objects = 0;
1148   for (uint i = 1; i < ophi->req(); i++) {
1149     Node* base = ophi->in(i);
1150     JavaObjectNode* ptn = unique_java_object(base);
1151 
1152     if (ptn != nullptr && ptn->scalar_replaceable()) {
1153       Node* sr_obj_idx = _igvn->register_new_node_with_optimizer(ConINode::make(number_of_sr_objects));
1154       selector->set_req(i, sr_obj_idx);
1155       number_of_sr_objects++;
1156     }
1157   }
1158 
1159   return selector->as_Phi();
1160 }
1161 
1162 // Returns true if the AddP node 'n' has at least one base that is a reducible
1163 // merge. If the base is a CastPP/CheckCastPP then the input of the cast is
1164 // checked instead.
1165 bool ConnectionGraph::has_reducible_merge_base(AddPNode* n, Unique_Node_List &reducible_merges) {
1166   PointsToNode* ptn = ptnode_adr(n->_idx);
1167   if (ptn == nullptr || !ptn->is_Field() || ptn->as_Field()->base_count() < 2) {
1168     return false;
1169   }
1170 
1171   for (BaseIterator i(ptn->as_Field()); i.has_next(); i.next()) {
1172     Node* base = i.get()->ideal_node();
1173 
1174     if (reducible_merges.member(base)) {
1175       return true;
1176     }
1177 
1178     if (base->is_CastPP() || base->is_CheckCastPP()) {
1179       base = base->in(1);
1180       if (reducible_merges.member(base)) {
1181         return true;
1182       }
1183     }
1184   }
1185 
1186   return false;
1187 }
1188 
1189 // This method will call its helper method to reduce SafePoint nodes that use
1190 // 'ophi' or a casted version of 'ophi'. All SafePoint nodes using the same
1191 // "version" of Phi use the same debug information (regarding the Phi).
1192 // Therefore, I collect all safepoints and patch them all at once.
1193 //
1194 // The safepoints using the Phi node have to be processed before safepoints of
1195 // CastPP nodes. The reason is, when reducing a CastPP we add a reference (the
1196 // NSR merge pointer) to the input of the CastPP (i.e., the Phi) in the
1197 // safepoint. If we process CastPP's safepoints before Phi's safepoints the
1198 // algorithm that process Phi's safepoints will think that the added Phi
1199 // reference is a regular reference.
1200 bool ConnectionGraph::reduce_phi_on_safepoints(PhiNode* ophi) {
1201   PhiNode* selector = create_selector(ophi);
1202   Unique_Node_List safepoints;
1203   Unique_Node_List casts;
1204 
1205   // Just collect the users of the Phis for later processing
1206   // in the needed order.
1207   for (uint i = 0; i < ophi->outcnt(); i++) {
1208     Node* use = ophi->raw_out(i);
1209     if (use->is_SafePoint()) {
1210       safepoints.push(use);
1211     } else if (use->is_CastPP()) {
1212       casts.push(use);
1213     } else {
1214       assert(use->outcnt() == 0, "Only CastPP & SafePoint users should be left.");
1215     }
1216   }
1217 
1218   // Need to process safepoints using the Phi first
1219   if (!reduce_phi_on_safepoints_helper(ophi, nullptr, selector, safepoints)) {
1220     return false;
1221   }
1222 
1223   // Now process CastPP->safepoints
1224   for (uint i = 0; i < casts.size(); i++) {
1225     Node* cast = casts.at(i);
1226     Unique_Node_List cast_sfpts;
1227 
1228     for (DUIterator_Fast jmax, j = cast->fast_outs(jmax); j < jmax; j++) {
1229       Node* use_use = cast->fast_out(j);
1230       if (use_use->is_SafePoint()) {
1231         cast_sfpts.push(use_use);
1232       } else {
1233         assert(use_use->outcnt() == 0, "Only SafePoint users should be left.");
1234       }
1235     }
1236 
1237     if (!reduce_phi_on_safepoints_helper(ophi, cast, selector, cast_sfpts)) {
1238       return false;
1239     }
1240   }
1241 
1242   return true;
1243 }
1244 
1245 // This method will create a SafePointScalarMERGEnode for each SafePoint in
1246 // 'safepoints'. It then will iterate on the inputs of 'ophi' and create a
1247 // SafePointScalarObjectNode for each scalar replaceable input. Each
1248 // SafePointScalarMergeNode may describe multiple scalar replaced objects -
1249 // check detailed description in SafePointScalarMergeNode class header.
1250 bool ConnectionGraph::reduce_phi_on_safepoints_helper(Node* ophi, Node* cast, Node* selector, Unique_Node_List& safepoints) {
1251   PhaseMacroExpand mexp(*_igvn);
1252   Node* original_sfpt_parent =  cast != nullptr ? cast : ophi;
1253   const TypeOopPtr* merge_t = _igvn->type(original_sfpt_parent)->make_oopptr();
1254 
1255   Node* nsr_merge_pointer = ophi;
1256   if (cast != nullptr) {
1257     const Type* new_t = merge_t->meet(TypePtr::NULL_PTR);
1258     nsr_merge_pointer = _igvn->transform(ConstraintCastNode::make_cast_for_type(cast->in(0), cast->in(1), new_t, ConstraintCastNode::DependencyType::FloatingNarrowing, nullptr));
1259   }
1260 
1261   for (uint spi = 0; spi < safepoints.size(); spi++) {
1262     SafePointNode* sfpt = safepoints.at(spi)->as_SafePoint();
1263     JVMState *jvms      = sfpt->jvms();
1264     uint merge_idx      = (sfpt->req() - jvms->scloff());
1265     int debug_start     = jvms->debug_start();
1266 
1267     SafePointScalarMergeNode* smerge = new SafePointScalarMergeNode(merge_t, merge_idx);
1268     smerge->init_req(0, _compile->root());
1269     _igvn->register_new_node_with_optimizer(smerge);
1270 
1271     // The next two inputs are:
1272     //  (1) A copy of the original pointer to NSR objects.
1273     //  (2) A selector, used to decide if we need to rematerialize an object
1274     //      or use the pointer to a NSR object.
1275     // See more details of these fields in the declaration of SafePointScalarMergeNode
1276     sfpt->add_req(nsr_merge_pointer);
1277     sfpt->add_req(selector);
1278 
1279     for (uint i = 1; i < ophi->req(); i++) {
1280       Node* base = ophi->in(i);
1281       JavaObjectNode* ptn = unique_java_object(base);
1282 
1283       // If the base is not scalar replaceable we don't need to register information about
1284       // it at this time.
1285       if (ptn == nullptr || !ptn->scalar_replaceable()) {
1286         continue;
1287       }
1288 
1289       AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
1290       Unique_Node_List value_worklist;
1291 #ifdef ASSERT
1292       const Type* res_type = alloc->result_cast()->bottom_type();
1293       if (res_type->is_inlinetypeptr() && !Compile::current()->has_circular_inline_type()) {
1294         PhiNode* phi = ophi->as_Phi();
1295         assert(!ophi->as_Phi()->can_push_inline_types_down(_igvn), "missed earlier scalarization opportunity");
1296       }
1297 #endif
1298       SafePointScalarObjectNode* sobj = mexp.create_scalarized_object_description(alloc, sfpt, &value_worklist);
1299       if (sobj == nullptr) {
1300         _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
1301         return false;
1302       }
1303 
1304       // Now make a pass over the debug information replacing any references
1305       // to the allocated object with "sobj"
1306       Node* ccpp = alloc->result_cast();
1307       sfpt->replace_edges_in_range(ccpp, sobj, debug_start, jvms->debug_end(), _igvn);
1308 
1309       // Register the scalarized object as a candidate for reallocation
1310       smerge->add_req(sobj);
1311 
1312       // Scalarize inline types that were added to the safepoint.
1313       // Don't allow linking a constant oop (if available) for flat array elements
1314       // because Deoptimization::reassign_flat_array_elements needs field values.
1315       const bool allow_oop = !merge_t->is_flat();
1316       for (uint j = 0; j < value_worklist.size(); ++j) {
1317         InlineTypeNode* vt = value_worklist.at(j)->as_InlineType();
1318         vt->make_scalar_in_safepoints(_igvn, allow_oop);
1319       }
1320     }
1321 
1322     // Replaces debug information references to "original_sfpt_parent" in "sfpt" with references to "smerge"
1323     sfpt->replace_edges_in_range(original_sfpt_parent, smerge, debug_start, jvms->debug_end(), _igvn);
1324 
1325     // The call to 'replace_edges_in_range' above might have removed the
1326     // reference to ophi that we need at _merge_pointer_idx. The line below make
1327     // sure the reference is maintained.
1328     sfpt->set_req(smerge->merge_pointer_idx(jvms), nsr_merge_pointer);
1329     _igvn->_worklist.push(sfpt);
1330   }
1331 
1332   return true;
1333 }
1334 
1335 void ConnectionGraph::reduce_phi(PhiNode* ophi, GrowableArray<Node*> &alloc_worklist) {
1336   bool delay = _igvn->delay_transform();
1337   _igvn->set_delay_transform(true);
1338   _igvn->hash_delete(ophi);
1339 
1340   // Copying all users first because some will be removed and others won't.
1341   // Ophi also may acquire some new users as part of Cast reduction.
1342   // CastPPs also need to be processed before CmpPs.
1343   Unique_Node_List castpps;
1344   Unique_Node_List others;
1345   for (DUIterator_Fast imax, i = ophi->fast_outs(imax); i < imax; i++) {
1346     Node* use = ophi->fast_out(i);
1347 
1348     if (use->is_CastPP()) {
1349       castpps.push(use);
1350     } else if (use->is_AddP() || use->is_Cmp()) {
1351       others.push(use);
1352     } else {
1353       // Safepoints to be processed later; other users aren't expected here
1354       assert(use->is_SafePoint(), "Unexpected user of reducible Phi %d -> %d:%s:%d", ophi->_idx, use->_idx, use->Name(), use->outcnt());
1355     }
1356   }
1357 
1358   _compile->print_method(PHASE_EA_BEFORE_PHI_REDUCTION, 5, ophi);
1359 
1360   // CastPPs need to be processed before Cmps because during the process of
1361   // splitting CastPPs we make reference to the inputs of the Cmp that is used
1362   // by the If controlling the CastPP.
1363   for (uint i = 0; i < castpps.size(); i++) {
1364     reduce_phi_on_castpp_field_load(castpps.at(i), alloc_worklist);
1365     _compile->print_method(PHASE_EA_AFTER_PHI_CASTPP_REDUCTION, 6, castpps.at(i));
1366   }
1367 
1368   for (uint i = 0; i < others.size(); i++) {
1369     Node* use = others.at(i);
1370 
1371     if (use->is_AddP()) {
1372       reduce_phi_on_field_access(use, alloc_worklist);
1373       _compile->print_method(PHASE_EA_AFTER_PHI_ADDP_REDUCTION, 6, use);
1374     } else if(use->is_Cmp()) {
1375       reduce_phi_on_cmp(use);
1376       _compile->print_method(PHASE_EA_AFTER_PHI_CMP_REDUCTION, 6, use);
1377     }
1378   }
1379 
1380   _igvn->set_delay_transform(delay);
1381 }
1382 
1383 void ConnectionGraph::reset_scalar_replaceable_entries(PhiNode* ophi) {
1384   Node* null_ptr            = _igvn->makecon(TypePtr::NULL_PTR);
1385   const TypeOopPtr* merge_t = _igvn->type(ophi)->make_oopptr();
1386   const Type* new_t         = merge_t->meet(TypePtr::NULL_PTR);
1387   Node* new_phi             = _igvn->register_new_node_with_optimizer(PhiNode::make(ophi->region(), null_ptr, new_t));
1388 
1389   for (uint i = 1; i < ophi->req(); i++) {
1390     Node* base          = ophi->in(i);
1391     JavaObjectNode* ptn = unique_java_object(base);
1392 
1393     if (ptn != nullptr && ptn->scalar_replaceable()) {
1394       new_phi->set_req(i, null_ptr);
1395     } else {
1396       new_phi->set_req(i, ophi->in(i));
1397     }
1398   }
1399 
1400   for (int i = ophi->outcnt()-1; i >= 0;) {
1401     Node* out = ophi->raw_out(i);
1402 
1403     if (out->is_ConstraintCast()) {
1404       const Type* out_t = _igvn->type(out)->make_ptr();
1405       const Type* out_new_t = out_t->meet(TypePtr::NULL_PTR);
1406       bool change = out_new_t != out_t;
1407 
1408       for (int j = out->outcnt()-1; change && j >= 0; --j) {
1409         Node* out2 = out->raw_out(j);
1410         if (!out2->is_SafePoint()) {
1411           change = false;
1412           break;
1413         }
1414       }
1415 
1416       if (change) {
1417         Node* new_cast = ConstraintCastNode::make_cast_for_type(out->in(0), out->in(1), out_new_t, ConstraintCastNode::DependencyType::NonFloatingNarrowing, nullptr);
1418         _igvn->replace_node(out, new_cast);
1419         _igvn->register_new_node_with_optimizer(new_cast);
1420       }
1421     }
1422 
1423     --i;
1424     i = MIN2(i, (int)ophi->outcnt()-1);
1425   }
1426 
1427   _igvn->replace_node(ophi, new_phi);
1428 }
1429 
1430 void ConnectionGraph::verify_ram_nodes(Compile* C, Node* root) {
1431   if (!C->do_reduce_allocation_merges()) return;
1432 
1433   Unique_Node_List ideal_nodes;
1434   ideal_nodes.map(C->live_nodes(), nullptr);  // preallocate space
1435   ideal_nodes.push(root);
1436 
1437   for (uint next = 0; next < ideal_nodes.size(); ++next) {
1438     Node* n = ideal_nodes.at(next);
1439 
1440     if (n->is_SafePointScalarMerge()) {
1441       SafePointScalarMergeNode* merge = n->as_SafePointScalarMerge();
1442 
1443       // Validate inputs of merge
1444       for (uint i = 1; i < merge->req(); i++) {
1445         if (merge->in(i) != nullptr && !merge->in(i)->is_top() && !merge->in(i)->is_SafePointScalarObject()) {
1446           assert(false, "SafePointScalarMerge inputs should be null/top or SafePointScalarObject.");
1447           C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
1448         }
1449       }
1450 
1451       // Validate users of merge
1452       for (DUIterator_Fast imax, i = merge->fast_outs(imax); i < imax; i++) {
1453         Node* sfpt = merge->fast_out(i);
1454         if (sfpt->is_SafePoint()) {
1455           int merge_idx = merge->merge_pointer_idx(sfpt->as_SafePoint()->jvms());
1456 
1457           if (sfpt->in(merge_idx) != nullptr && sfpt->in(merge_idx)->is_SafePointScalarMerge()) {
1458             assert(false, "SafePointScalarMerge nodes can't be nested.");
1459             C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
1460           }
1461         } else {
1462           assert(false, "Only safepoints can use SafePointScalarMerge nodes.");
1463           C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
1464         }
1465       }
1466     }
1467 
1468     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1469       Node* m = n->fast_out(i);
1470       ideal_nodes.push(m);
1471     }
1472   }
1473 }
1474 
1475 // Returns true if there is an object in the scope of sfn that does not escape globally.
1476 bool ConnectionGraph::has_ea_local_in_scope(SafePointNode* sfn) {
1477   Compile* C = _compile;
1478   for (JVMState* jvms = sfn->jvms(); jvms != nullptr; jvms = jvms->caller()) {
1479     if (C->env()->should_retain_local_variables() || C->env()->jvmti_can_walk_any_space() ||
1480         DeoptimizeObjectsALot) {
1481       // Jvmti agents can access locals. Must provide info about local objects at runtime.
1482       int num_locs = jvms->loc_size();
1483       for (int idx = 0; idx < num_locs; idx++) {
1484         Node* l = sfn->local(jvms, idx);
1485         if (not_global_escape(l)) {
1486           return true;
1487         }
1488       }
1489     }
1490     if (C->env()->jvmti_can_get_owned_monitor_info() ||
1491         C->env()->jvmti_can_walk_any_space() || DeoptimizeObjectsALot) {
1492       // Jvmti agents can read monitors. Must provide info about locked objects at runtime.
1493       int num_mon = jvms->nof_monitors();
1494       for (int idx = 0; idx < num_mon; idx++) {
1495         Node* m = sfn->monitor_obj(jvms, idx);
1496         if (m != nullptr && not_global_escape(m)) {
1497           return true;
1498         }
1499       }
1500     }
1501   }
1502   return false;
1503 }
1504 
1505 // Returns true if at least one of the arguments to the call is an object
1506 // that does not escape globally.
1507 bool ConnectionGraph::has_arg_escape(CallJavaNode* call) {
1508   if (call->method() != nullptr) {
1509     uint max_idx = TypeFunc::Parms + call->method()->arg_size();
1510     for (uint idx = TypeFunc::Parms; idx < max_idx; idx++) {
1511       Node* p = call->in(idx);
1512       if (not_global_escape(p)) {
1513         return true;
1514       }
1515     }
1516   } else {
1517     const char* name = call->as_CallStaticJava()->_name;
1518     assert(name != nullptr, "no name");
1519     // no arg escapes through uncommon traps
1520     if (strcmp(name, "uncommon_trap") != 0) {
1521       // process_call_arguments() assumes that all arguments escape globally
1522       const TypeTuple* d = call->tf()->domain_sig();
1523       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1524         const Type* at = d->field_at(i);
1525         if (at->isa_oopptr() != nullptr) {
1526           return true;
1527         }
1528       }
1529     }
1530   }
1531   return false;
1532 }
1533 
1534 
1535 
1536 // Utility function for nodes that load an object
1537 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1538   // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1539   // ThreadLocal has RawPtr type.
1540   const Type* t = _igvn->type(n);
1541   if (t->make_ptr() != nullptr) {
1542     Node* adr = n->in(MemNode::Address);
1543 #ifdef ASSERT
1544     if (!adr->is_AddP()) {
1545       assert(_igvn->type(adr)->isa_rawptr(), "sanity");
1546     } else {
1547       assert((ptnode_adr(adr->_idx) == nullptr ||
1548               ptnode_adr(adr->_idx)->as_Field()->is_oop()), "sanity");
1549     }
1550 #endif
1551     add_local_var_and_edge(n, PointsToNode::NoEscape,
1552                            adr, delayed_worklist);
1553   }
1554 }
1555 
1556 // Populate Connection Graph with PointsTo nodes and create simple
1557 // connection graph edges.
1558 void ConnectionGraph::add_node_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1559   assert(!_verify, "this method should not be called for verification");
1560   PhaseGVN* igvn = _igvn;
1561   uint n_idx = n->_idx;
1562   PointsToNode* n_ptn = ptnode_adr(n_idx);
1563   if (n_ptn != nullptr) {
1564     return; // No need to redefine PointsTo node during first iteration.
1565   }
1566   int opcode = n->Opcode();
1567   bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_to_con_graph(this, igvn, delayed_worklist, n, opcode);
1568   if (gc_handled) {
1569     return; // Ignore node if already handled by GC.
1570   }
1571 
1572   if (n->is_Call()) {
1573     // Arguments to allocation and locking don't escape.
1574     if (n->is_AbstractLock()) {
1575       // Put Lock and Unlock nodes on IGVN worklist to process them during
1576       // first IGVN optimization when escape information is still available.
1577       record_for_optimizer(n);
1578     } else if (n->is_Allocate()) {
1579       add_call_node(n->as_Call());
1580       record_for_optimizer(n);
1581     } else {
1582       if (n->is_CallStaticJava()) {
1583         const char* name = n->as_CallStaticJava()->_name;
1584         if (name != nullptr && strcmp(name, "uncommon_trap") == 0) {
1585           return; // Skip uncommon traps
1586         }
1587       }
1588       // Don't mark as processed since call's arguments have to be processed.
1589       delayed_worklist->push(n);
1590       // Check if a call returns an object.
1591       if ((n->as_Call()->returns_pointer() &&
1592            n->as_Call()->proj_out_or_null(TypeFunc::Parms) != nullptr) ||
1593           (n->is_CallStaticJava() &&
1594            n->as_CallStaticJava()->is_boxing_method())) {
1595         add_call_node(n->as_Call());
1596       } else if (n->as_Call()->tf()->returns_inline_type_as_fields()) {
1597         bool returns_oop = false;
1598         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && !returns_oop; i++) {
1599           ProjNode* pn = n->fast_out(i)->as_Proj();
1600           if (pn->_con >= TypeFunc::Parms && pn->bottom_type()->isa_ptr()) {
1601             returns_oop = true;
1602           }
1603         }
1604         if (returns_oop) {
1605           add_call_node(n->as_Call());
1606         }
1607       }
1608     }
1609     return;
1610   }
1611   // Put this check here to process call arguments since some call nodes
1612   // point to phantom_obj.
1613   if (n_ptn == phantom_obj || n_ptn == null_obj) {
1614     return; // Skip predefined nodes.
1615   }
1616   switch (opcode) {
1617     case Op_AddP: {
1618       Node* base = get_addp_base(n);
1619       PointsToNode* ptn_base = ptnode_adr(base->_idx);
1620       // Field nodes are created for all field types. They are used in
1621       // adjust_scalar_replaceable_state() and split_unique_types().
1622       // Note, non-oop fields will have only base edges in Connection
1623       // Graph because such fields are not used for oop loads and stores.
1624       int offset = address_offset(n, igvn);
1625       add_field(n, PointsToNode::NoEscape, offset);
1626       if (ptn_base == nullptr) {
1627         delayed_worklist->push(n); // Process it later.
1628       } else {
1629         n_ptn = ptnode_adr(n_idx);
1630         add_base(n_ptn->as_Field(), ptn_base);
1631       }
1632       break;
1633     }
1634     case Op_CastX2P:
1635     case Op_CastI2N: {
1636       map_ideal_node(n, phantom_obj);
1637       break;
1638     }
1639     case Op_InlineType:
1640     case Op_CastPP:
1641     case Op_CheckCastPP:
1642     case Op_EncodeP:
1643     case Op_DecodeN:
1644     case Op_EncodePKlass:
1645     case Op_DecodeNKlass: {
1646       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1647       break;
1648     }
1649     case Op_CMoveP: {
1650       add_local_var(n, PointsToNode::NoEscape);
1651       // Do not add edges during first iteration because some could be
1652       // not defined yet.
1653       delayed_worklist->push(n);
1654       break;
1655     }
1656     case Op_ConP:
1657     case Op_ConN:
1658     case Op_ConNKlass: {
1659       // assume all oop constants globally escape except for null
1660       PointsToNode::EscapeState es;
1661       const Type* t = igvn->type(n);
1662       if (t == TypePtr::NULL_PTR || t == TypeNarrowOop::NULL_PTR) {
1663         es = PointsToNode::NoEscape;
1664       } else {
1665         es = PointsToNode::GlobalEscape;
1666       }
1667       PointsToNode* ptn_con = add_java_object(n, es);
1668       set_not_scalar_replaceable(ptn_con NOT_PRODUCT(COMMA "Constant pointer"));
1669       break;
1670     }
1671     case Op_CreateEx: {
1672       // assume that all exception objects globally escape
1673       map_ideal_node(n, phantom_obj);
1674       break;
1675     }
1676     case Op_LoadKlass:
1677     case Op_LoadNKlass: {
1678       // Unknown class is loaded
1679       map_ideal_node(n, phantom_obj);
1680       break;
1681     }
1682     case Op_LoadP:
1683     case Op_LoadN: {
1684       add_objload_to_connection_graph(n, delayed_worklist);
1685       break;
1686     }
1687     case Op_Parm: {
1688       map_ideal_node(n, phantom_obj);
1689       break;
1690     }
1691     case Op_PartialSubtypeCheck: {
1692       // Produces Null or notNull and is used in only in CmpP so
1693       // phantom_obj could be used.
1694       map_ideal_node(n, phantom_obj); // Result is unknown
1695       break;
1696     }
1697     case Op_Phi: {
1698       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1699       // ThreadLocal has RawPtr type.
1700       const Type* t = n->as_Phi()->type();
1701       if (t->make_ptr() != nullptr) {
1702         add_local_var(n, PointsToNode::NoEscape);
1703         // Do not add edges during first iteration because some could be
1704         // not defined yet.
1705         delayed_worklist->push(n);
1706       }
1707       break;
1708     }
1709     case Op_LoadFlat:
1710       // Treat LoadFlat similar to an unknown call that receives nothing and produces its results
1711       map_ideal_node(n, phantom_obj);
1712       break;
1713     case Op_StoreFlat:
1714       // Treat StoreFlat similar to a call that escapes the stored flattened fields
1715       delayed_worklist->push(n);
1716       break;
1717     case Op_Proj: {
1718       // we are only interested in the oop result projection from a call
1719       if (n->as_Proj()->_con >= TypeFunc::Parms && n->in(0)->is_Call() &&
1720           (n->in(0)->as_Call()->returns_pointer() || n->bottom_type()->isa_ptr())) {
1721         assert((n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->as_Call()->returns_pointer()) ||
1722                n->in(0)->as_Call()->tf()->returns_inline_type_as_fields(), "what kind of oop return is it?");
1723         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1724       } else if (n->as_Proj()->_con >= TypeFunc::Parms && n->in(0)->is_LoadFlat() && igvn->type(n)->isa_ptr()) {
1725         // Treat LoadFlat outputs similar to a call return value
1726         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1727       }
1728       break;
1729     }
1730     case Op_Rethrow: // Exception object escapes
1731     case Op_Return: {
1732       if (n->req() > TypeFunc::Parms &&
1733           igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
1734         // Treat Return value as LocalVar with GlobalEscape escape state.
1735         add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), delayed_worklist);
1736       }
1737       break;
1738     }
1739     case Op_CompareAndExchangeP:
1740     case Op_CompareAndExchangeN:
1741     case Op_GetAndSetP:
1742     case Op_GetAndSetN: {
1743       add_objload_to_connection_graph(n, delayed_worklist);
1744       // fall-through
1745     }
1746     case Op_StoreP:
1747     case Op_StoreN:
1748     case Op_StoreNKlass:
1749     case Op_WeakCompareAndSwapP:
1750     case Op_WeakCompareAndSwapN:
1751     case Op_CompareAndSwapP:
1752     case Op_CompareAndSwapN: {
1753       add_to_congraph_unsafe_access(n, opcode, delayed_worklist);
1754       break;
1755     }
1756     case Op_AryEq:
1757     case Op_CountPositives:
1758     case Op_StrComp:
1759     case Op_StrEquals:
1760     case Op_StrIndexOf:
1761     case Op_StrIndexOfChar:
1762     case Op_StrInflatedCopy:
1763     case Op_StrCompressedCopy:
1764     case Op_VectorizedHashCode:
1765     case Op_EncodeISOArray: {
1766       add_local_var(n, PointsToNode::ArgEscape);
1767       delayed_worklist->push(n); // Process it later.
1768       break;
1769     }
1770     case Op_ThreadLocal: {
1771       PointsToNode* ptn_thr = add_java_object(n, PointsToNode::ArgEscape);
1772       set_not_scalar_replaceable(ptn_thr NOT_PRODUCT(COMMA "Constant pointer"));
1773       break;
1774     }
1775     case Op_Blackhole: {
1776       // All blackhole pointer arguments are globally escaping.
1777       // Only do this if there is at least one pointer argument.
1778       // Do not add edges during first iteration because some could be
1779       // not defined yet, defer to final step.
1780       for (uint i = 0; i < n->req(); i++) {
1781         Node* in = n->in(i);
1782         if (in != nullptr) {
1783           const Type* at = _igvn->type(in);
1784           if (!at->isa_ptr()) continue;
1785 
1786           add_local_var(n, PointsToNode::GlobalEscape);
1787           delayed_worklist->push(n);
1788           break;
1789         }
1790       }
1791       break;
1792     }
1793     default:
1794       ; // Do nothing for nodes not related to EA.
1795   }
1796   return;
1797 }
1798 
1799 // Add final simple edges to graph.
1800 void ConnectionGraph::add_final_edges(Node *n) {
1801   PointsToNode* n_ptn = ptnode_adr(n->_idx);
1802 #ifdef ASSERT
1803   if (_verify && n_ptn->is_JavaObject())
1804     return; // This method does not change graph for JavaObject.
1805 #endif
1806 
1807   if (n->is_Call()) {
1808     process_call_arguments(n->as_Call());
1809     return;
1810   }
1811   assert(n->is_Store() || n->is_LoadStore() || n->is_StoreFlat() ||
1812          ((n_ptn != nullptr) && (n_ptn->ideal_node() != nullptr)),
1813          "node should be registered already");
1814   int opcode = n->Opcode();
1815   bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_final_edges(this, _igvn, n, opcode);
1816   if (gc_handled) {
1817     return; // Ignore node if already handled by GC.
1818   }
1819   switch (opcode) {
1820     case Op_AddP: {
1821       Node* base = get_addp_base(n);
1822       PointsToNode* ptn_base = ptnode_adr(base->_idx);
1823       assert(ptn_base != nullptr, "field's base should be registered");
1824       add_base(n_ptn->as_Field(), ptn_base);
1825       break;
1826     }
1827     case Op_InlineType:
1828     case Op_CastPP:
1829     case Op_CheckCastPP:
1830     case Op_EncodeP:
1831     case Op_DecodeN:
1832     case Op_EncodePKlass:
1833     case Op_DecodeNKlass: {
1834       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), nullptr);
1835       break;
1836     }
1837     case Op_CMoveP: {
1838       for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
1839         Node* in = n->in(i);
1840         if (in == nullptr) {
1841           continue;  // ignore null
1842         }
1843         Node* uncast_in = in->uncast();
1844         if (uncast_in->is_top() || uncast_in == n) {
1845           continue;  // ignore top or inputs which go back this node
1846         }
1847         PointsToNode* ptn = ptnode_adr(in->_idx);
1848         assert(ptn != nullptr, "node should be registered");
1849         add_edge(n_ptn, ptn);
1850       }
1851       break;
1852     }
1853     case Op_LoadP:
1854     case Op_LoadN: {
1855       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1856       // ThreadLocal has RawPtr type.
1857       assert(_igvn->type(n)->make_ptr() != nullptr, "Unexpected node type");
1858       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), nullptr);
1859       break;
1860     }
1861     case Op_Phi: {
1862       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1863       // ThreadLocal has RawPtr type.
1864       assert(n->as_Phi()->type()->make_ptr() != nullptr, "Unexpected node type");
1865       for (uint i = 1; i < n->req(); i++) {
1866         Node* in = n->in(i);
1867         if (in == nullptr) {
1868           continue;  // ignore null
1869         }
1870         Node* uncast_in = in->uncast();
1871         if (uncast_in->is_top() || uncast_in == n) {
1872           continue;  // ignore top or inputs which go back this node
1873         }
1874         PointsToNode* ptn = ptnode_adr(in->_idx);
1875         assert(ptn != nullptr, "node should be registered");
1876         add_edge(n_ptn, ptn);
1877       }
1878       break;
1879     }
1880     case Op_StoreFlat: {
1881       // StoreFlat globally escapes its stored flattened fields
1882       InlineTypeNode* value = n->as_StoreFlat()->value();
1883       ciInlineKlass* vk = _igvn->type(value)->inline_klass();
1884       for (int i = 0; i < vk->nof_nonstatic_fields(); i++) {
1885         ciField* field = vk->nonstatic_field_at(i);
1886         if (field->type()->is_primitive_type()) {
1887           continue;
1888         }
1889 
1890         Node* field_value = value->field_value_by_offset(field->offset_in_bytes(), true);
1891         PointsToNode* field_value_ptn = ptnode_adr(field_value->_idx);
1892         set_escape_state(field_value_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "store into a flat field"));
1893       }
1894       break;
1895     }
1896     case Op_Proj: {
1897       if (n->in(0)->is_Call()) {
1898         // we are only interested in the oop result projection from a call
1899         assert((n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->as_Call()->returns_pointer()) ||
1900               n->in(0)->as_Call()->tf()->returns_inline_type_as_fields(), "what kind of oop return is it?");
1901         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), nullptr);
1902       } else if (n->in(0)->is_LoadFlat()) {
1903         // Treat LoadFlat outputs similar to a call return value
1904         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), nullptr);
1905       }
1906       break;
1907     }
1908     case Op_Rethrow: // Exception object escapes
1909     case Op_Return: {
1910       assert(n->req() > TypeFunc::Parms && _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr(),
1911              "Unexpected node type");
1912       // Treat Return value as LocalVar with GlobalEscape escape state.
1913       add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), nullptr);
1914       break;
1915     }
1916     case Op_CompareAndExchangeP:
1917     case Op_CompareAndExchangeN:
1918     case Op_GetAndSetP:
1919     case Op_GetAndSetN:{
1920       assert(_igvn->type(n)->make_ptr() != nullptr, "Unexpected node type");
1921       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), nullptr);
1922       // fall-through
1923     }
1924     case Op_CompareAndSwapP:
1925     case Op_CompareAndSwapN:
1926     case Op_WeakCompareAndSwapP:
1927     case Op_WeakCompareAndSwapN:
1928     case Op_StoreP:
1929     case Op_StoreN:
1930     case Op_StoreNKlass:{
1931       add_final_edges_unsafe_access(n, opcode);
1932       break;
1933     }
1934     case Op_VectorizedHashCode:
1935     case Op_AryEq:
1936     case Op_CountPositives:
1937     case Op_StrComp:
1938     case Op_StrEquals:
1939     case Op_StrIndexOf:
1940     case Op_StrIndexOfChar:
1941     case Op_StrInflatedCopy:
1942     case Op_StrCompressedCopy:
1943     case Op_EncodeISOArray: {
1944       // char[]/byte[] arrays passed to string intrinsic do not escape but
1945       // they are not scalar replaceable. Adjust escape state for them.
1946       // Start from in(2) edge since in(1) is memory edge.
1947       for (uint i = 2; i < n->req(); i++) {
1948         Node* adr = n->in(i);
1949         const Type* at = _igvn->type(adr);
1950         if (!adr->is_top() && at->isa_ptr()) {
1951           assert(at == Type::TOP || at == TypePtr::NULL_PTR ||
1952                  at->isa_ptr() != nullptr, "expecting a pointer");
1953           if (adr->is_AddP()) {
1954             adr = get_addp_base(adr);
1955           }
1956           PointsToNode* ptn = ptnode_adr(adr->_idx);
1957           assert(ptn != nullptr, "node should be registered");
1958           add_edge(n_ptn, ptn);
1959         }
1960       }
1961       break;
1962     }
1963     case Op_Blackhole: {
1964       // All blackhole pointer arguments are globally escaping.
1965       for (uint i = 0; i < n->req(); i++) {
1966         Node* in = n->in(i);
1967         if (in != nullptr) {
1968           const Type* at = _igvn->type(in);
1969           if (!at->isa_ptr()) continue;
1970 
1971           if (in->is_AddP()) {
1972             in = get_addp_base(in);
1973           }
1974 
1975           PointsToNode* ptn = ptnode_adr(in->_idx);
1976           assert(ptn != nullptr, "should be defined already");
1977           set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "blackhole"));
1978           add_edge(n_ptn, ptn);
1979         }
1980       }
1981       break;
1982     }
1983     default: {
1984       // This method should be called only for EA specific nodes which may
1985       // miss some edges when they were created.
1986 #ifdef ASSERT
1987       n->dump(1);
1988 #endif
1989       guarantee(false, "unknown node");
1990     }
1991   }
1992   return;
1993 }
1994 
1995 void ConnectionGraph::add_to_congraph_unsafe_access(Node* n, uint opcode, Unique_Node_List* delayed_worklist) {
1996   Node* adr = n->in(MemNode::Address);
1997   const Type* adr_type = _igvn->type(adr);
1998   adr_type = adr_type->make_ptr();
1999   if (adr_type == nullptr) {
2000     return; // skip dead nodes
2001   }
2002   if (adr_type->isa_oopptr()
2003       || ((opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass)
2004           && adr_type == TypeRawPtr::NOTNULL
2005           && is_captured_store_address(adr))) {
2006     delayed_worklist->push(n); // Process it later.
2007 #ifdef ASSERT
2008     assert (adr->is_AddP(), "expecting an AddP");
2009     if (adr_type == TypeRawPtr::NOTNULL) {
2010       // Verify a raw address for a store captured by Initialize node.
2011       int offs = (int) _igvn->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
2012       assert(offs != Type::OffsetBot, "offset must be a constant");
2013     }
2014 #endif
2015   } else {
2016     // Ignore copy the displaced header to the BoxNode (OSR compilation).
2017     if (adr->is_BoxLock()) {
2018       return;
2019     }
2020     // Stored value escapes in unsafe access.
2021     if ((opcode == Op_StoreP) && adr_type->isa_rawptr()) {
2022       delayed_worklist->push(n); // Process unsafe access later.
2023       return;
2024     }
2025 #ifdef ASSERT
2026     n->dump(1);
2027     assert(false, "not unsafe");
2028 #endif
2029   }
2030 }
2031 
2032 bool ConnectionGraph::add_final_edges_unsafe_access(Node* n, uint opcode) {
2033   Node* adr = n->in(MemNode::Address);
2034   const Type *adr_type = _igvn->type(adr);
2035   adr_type = adr_type->make_ptr();
2036 #ifdef ASSERT
2037   if (adr_type == nullptr) {
2038     n->dump(1);
2039     assert(adr_type != nullptr, "dead node should not be on list");
2040     return true;
2041   }
2042 #endif
2043 
2044   if (adr_type->isa_oopptr()
2045       || ((opcode == Op_StoreP || opcode == Op_StoreN || opcode == Op_StoreNKlass)
2046            && adr_type == TypeRawPtr::NOTNULL
2047            && is_captured_store_address(adr))) {
2048     // Point Address to Value
2049     PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
2050     assert(adr_ptn != nullptr &&
2051            adr_ptn->as_Field()->is_oop(), "node should be registered");
2052     Node* val = n->in(MemNode::ValueIn);
2053     PointsToNode* ptn = ptnode_adr(val->_idx);
2054     assert(ptn != nullptr, "node should be registered");
2055     add_edge(adr_ptn, ptn);
2056     return true;
2057   } else if ((opcode == Op_StoreP) && adr_type->isa_rawptr()) {
2058     // Stored value escapes in unsafe access.
2059     Node* val = n->in(MemNode::ValueIn);
2060     PointsToNode* ptn = ptnode_adr(val->_idx);
2061     assert(ptn != nullptr, "node should be registered");
2062     set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "stored at raw address"));
2063     // Add edge to object for unsafe access with offset.
2064     PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
2065     assert(adr_ptn != nullptr, "node should be registered");
2066     if (adr_ptn->is_Field()) {
2067       assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
2068       add_edge(adr_ptn, ptn);
2069     }
2070     return true;
2071   }
2072 #ifdef ASSERT
2073   n->dump(1);
2074   assert(false, "not unsafe");
2075 #endif
2076   return false;
2077 }
2078 
2079 void ConnectionGraph::add_call_node(CallNode* call) {
2080   assert(call->returns_pointer() || call->tf()->returns_inline_type_as_fields(), "only for call which returns pointer");
2081   uint call_idx = call->_idx;
2082   if (call->is_Allocate()) {
2083     Node* k = call->in(AllocateNode::KlassNode);
2084     const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
2085     assert(kt != nullptr, "TypeKlassPtr  required.");
2086     PointsToNode::EscapeState es = PointsToNode::NoEscape;
2087     bool scalar_replaceable = true;
2088     NOT_PRODUCT(const char* nsr_reason = "");
2089     if (call->is_AllocateArray()) {
2090       if (!kt->isa_aryklassptr()) { // StressReflectiveCode
2091         es = PointsToNode::GlobalEscape;
2092       } else {
2093         int length = call->in(AllocateNode::ALength)->find_int_con(-1);
2094         if (length < 0) {
2095           // Not scalar replaceable if the length is not constant.
2096           scalar_replaceable = false;
2097           NOT_PRODUCT(nsr_reason = "has a non-constant length");
2098         } else if (length > EliminateAllocationArraySizeLimit) {
2099           // Not scalar replaceable if the length is too big.
2100           scalar_replaceable = false;
2101           NOT_PRODUCT(nsr_reason = "has a length that is too big");
2102         }
2103       }
2104     } else {  // Allocate instance
2105       if (!kt->isa_instklassptr()) { // StressReflectiveCode
2106         es = PointsToNode::GlobalEscape;
2107       } else {
2108         const TypeInstKlassPtr* ikt = kt->is_instklassptr();
2109         ciInstanceKlass* ik = ikt->klass_is_exact() ? ikt->exact_klass()->as_instance_klass() : ikt->instance_klass();
2110         if (ik->is_subclass_of(_compile->env()->Thread_klass()) ||
2111             ik->is_subclass_of(_compile->env()->Reference_klass()) ||
2112             !ik->can_be_instantiated() ||
2113             ik->has_finalizer()) {
2114           es = PointsToNode::GlobalEscape;
2115         } else {
2116           int nfields = ik->as_instance_klass()->nof_nonstatic_fields();
2117           if (nfields > EliminateAllocationFieldsLimit) {
2118             // Not scalar replaceable if there are too many fields.
2119             scalar_replaceable = false;
2120             NOT_PRODUCT(nsr_reason = "has too many fields");
2121           }
2122         }
2123       }
2124     }
2125     add_java_object(call, es);
2126     PointsToNode* ptn = ptnode_adr(call_idx);
2127     if (!scalar_replaceable && ptn->scalar_replaceable()) {
2128       set_not_scalar_replaceable(ptn NOT_PRODUCT(COMMA nsr_reason));
2129     }
2130   } else if (call->is_CallStaticJava()) {
2131     // Call nodes could be different types:
2132     //
2133     // 1. CallDynamicJavaNode (what happened during call is unknown):
2134     //
2135     //    - mapped to GlobalEscape JavaObject node if oop is returned;
2136     //
2137     //    - all oop arguments are escaping globally;
2138     //
2139     // 2. CallStaticJavaNode (execute bytecode analysis if possible):
2140     //
2141     //    - the same as CallDynamicJavaNode if can't do bytecode analysis;
2142     //
2143     //    - mapped to GlobalEscape JavaObject node if unknown oop is returned;
2144     //    - mapped to NoEscape JavaObject node if non-escaping object allocated
2145     //      during call is returned;
2146     //    - mapped to ArgEscape LocalVar node pointed to object arguments
2147     //      which are returned and does not escape during call;
2148     //
2149     //    - oop arguments escaping status is defined by bytecode analysis;
2150     //
2151     // For a static call, we know exactly what method is being called.
2152     // Use bytecode estimator to record whether the call's return value escapes.
2153     ciMethod* meth = call->as_CallJava()->method();
2154     if (meth == nullptr) {
2155       const char* name = call->as_CallStaticJava()->_name;
2156       assert(strncmp(name, "C2 Runtime multianewarray", 25) == 0 ||
2157              strncmp(name, "C2 Runtime load_unknown_inline", 30) == 0 ||
2158              strncmp(name, "store_inline_type_fields_to_buf", 31) == 0, "TODO: add failed case check");
2159       // Returns a newly allocated non-escaped object.
2160       add_java_object(call, PointsToNode::NoEscape);
2161       set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of multinewarray"));
2162     } else if (meth->is_boxing_method()) {
2163       // Returns boxing object
2164       PointsToNode::EscapeState es;
2165       vmIntrinsics::ID intr = meth->intrinsic_id();
2166       if (intr == vmIntrinsics::_floatValue || intr == vmIntrinsics::_doubleValue) {
2167         // It does not escape if object is always allocated.
2168         es = PointsToNode::NoEscape;
2169       } else {
2170         // It escapes globally if object could be loaded from cache.
2171         es = PointsToNode::GlobalEscape;
2172       }
2173       add_java_object(call, es);
2174       if (es == PointsToNode::GlobalEscape) {
2175         set_not_scalar_replaceable(ptnode_adr(call->_idx) NOT_PRODUCT(COMMA "object can be loaded from boxing cache"));
2176       }
2177     } else {
2178       BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
2179       call_analyzer->copy_dependencies(_compile->dependencies());
2180       if (call_analyzer->is_return_allocated()) {
2181         // Returns a newly allocated non-escaped object, simply
2182         // update dependency information.
2183         // Mark it as NoEscape so that objects referenced by
2184         // it's fields will be marked as NoEscape at least.
2185         add_java_object(call, PointsToNode::NoEscape);
2186         set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of call"));
2187       } else {
2188         // Determine whether any arguments are returned.
2189         const TypeTuple* d = call->tf()->domain_cc();
2190         bool ret_arg = false;
2191         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2192           if (d->field_at(i)->isa_ptr() != nullptr &&
2193               call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
2194             ret_arg = true;
2195             break;
2196           }
2197         }
2198         if (ret_arg) {
2199           add_local_var(call, PointsToNode::ArgEscape);
2200         } else {
2201           // Returns unknown object.
2202           map_ideal_node(call, phantom_obj);
2203         }
2204       }
2205     }
2206   } else {
2207     // An other type of call, assume the worst case:
2208     // returned value is unknown and globally escapes.
2209     assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
2210     map_ideal_node(call, phantom_obj);
2211   }
2212 }
2213 
2214 void ConnectionGraph::process_call_arguments(CallNode *call) {
2215     bool is_arraycopy = false;
2216     switch (call->Opcode()) {
2217 #ifdef ASSERT
2218     case Op_Allocate:
2219     case Op_AllocateArray:
2220     case Op_Lock:
2221     case Op_Unlock:
2222       assert(false, "should be done already");
2223       break;
2224 #endif
2225     case Op_ArrayCopy:
2226     case Op_CallLeafNoFP:
2227       // Most array copies are ArrayCopy nodes at this point but there
2228       // are still a few direct calls to the copy subroutines (See
2229       // PhaseStringOpts::copy_string())
2230       is_arraycopy = (call->Opcode() == Op_ArrayCopy) ||
2231         call->as_CallLeaf()->is_call_to_arraycopystub();
2232       // fall through
2233     case Op_CallLeafVector:
2234     case Op_CallLeaf: {
2235       // Stub calls, objects do not escape but they are not scale replaceable.
2236       // Adjust escape state for outgoing arguments.
2237       const TypeTuple * d = call->tf()->domain_sig();
2238       bool src_has_oops = false;
2239       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2240         const Type* at = d->field_at(i);
2241         Node *arg = call->in(i);
2242         if (arg == nullptr) {
2243           continue;
2244         }
2245         const Type *aat = _igvn->type(arg);
2246         if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr()) {
2247           continue;
2248         }
2249         if (arg->is_AddP()) {
2250           //
2251           // The inline_native_clone() case when the arraycopy stub is called
2252           // after the allocation before Initialize and CheckCastPP nodes.
2253           // Or normal arraycopy for object arrays case.
2254           //
2255           // Set AddP's base (Allocate) as not scalar replaceable since
2256           // pointer to the base (with offset) is passed as argument.
2257           //
2258           arg = get_addp_base(arg);
2259         }
2260         PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2261         assert(arg_ptn != nullptr, "should be registered");
2262         PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
2263         if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
2264           assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
2265                  aat->isa_ptr() != nullptr, "expecting an Ptr");
2266           bool arg_has_oops = aat->isa_oopptr() &&
2267                               (aat->isa_instptr() ||
2268                                (aat->isa_aryptr() && (aat->isa_aryptr()->elem() == Type::BOTTOM || aat->isa_aryptr()->elem()->make_oopptr() != nullptr)) ||
2269                                (aat->isa_aryptr() && aat->isa_aryptr()->elem() != nullptr &&
2270                                                                aat->isa_aryptr()->is_flat() &&
2271                                                                aat->isa_aryptr()->elem()->inline_klass()->contains_oops()));
2272           if (i == TypeFunc::Parms) {
2273             src_has_oops = arg_has_oops;
2274           }
2275           //
2276           // src or dst could be j.l.Object when other is basic type array:
2277           //
2278           //   arraycopy(char[],0,Object*,0,size);
2279           //   arraycopy(Object*,0,char[],0,size);
2280           //
2281           // Don't add edges in such cases.
2282           //
2283           bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
2284                                        arg_has_oops && (i > TypeFunc::Parms);
2285 #ifdef ASSERT
2286           if (!(is_arraycopy ||
2287                 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(call) ||
2288                 (call->as_CallLeaf()->_name != nullptr &&
2289                  (strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 ||
2290                   strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32C") == 0 ||
2291                   strcmp(call->as_CallLeaf()->_name, "updateBytesAdler32") == 0 ||
2292                   strcmp(call->as_CallLeaf()->_name, "aescrypt_encryptBlock") == 0 ||
2293                   strcmp(call->as_CallLeaf()->_name, "aescrypt_decryptBlock") == 0 ||
2294                   strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_encryptAESCrypt") == 0 ||
2295                   strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_decryptAESCrypt") == 0 ||
2296                   strcmp(call->as_CallLeaf()->_name, "electronicCodeBook_encryptAESCrypt") == 0 ||
2297                   strcmp(call->as_CallLeaf()->_name, "electronicCodeBook_decryptAESCrypt") == 0 ||
2298                   strcmp(call->as_CallLeaf()->_name, "counterMode_AESCrypt") == 0 ||
2299                   strcmp(call->as_CallLeaf()->_name, "galoisCounterMode_AESCrypt") == 0 ||
2300                   strcmp(call->as_CallLeaf()->_name, "poly1305_processBlocks") == 0 ||
2301                   strcmp(call->as_CallLeaf()->_name, "intpoly_montgomeryMult_P256") == 0 ||
2302                   strcmp(call->as_CallLeaf()->_name, "intpoly_assign") == 0 ||
2303                   strcmp(call->as_CallLeaf()->_name, "ghash_processBlocks") == 0 ||
2304                   strcmp(call->as_CallLeaf()->_name, "chacha20Block") == 0 ||
2305                   strcmp(call->as_CallLeaf()->_name, "kyberNtt") == 0 ||
2306                   strcmp(call->as_CallLeaf()->_name, "kyberInverseNtt") == 0 ||
2307                   strcmp(call->as_CallLeaf()->_name, "kyberNttMult") == 0 ||
2308                   strcmp(call->as_CallLeaf()->_name, "kyberAddPoly_2") == 0 ||
2309                   strcmp(call->as_CallLeaf()->_name, "kyberAddPoly_3") == 0 ||
2310                   strcmp(call->as_CallLeaf()->_name, "kyber12To16") == 0 ||
2311                   strcmp(call->as_CallLeaf()->_name, "kyberBarrettReduce") == 0 ||
2312                   strcmp(call->as_CallLeaf()->_name, "dilithiumAlmostNtt") == 0 ||
2313                   strcmp(call->as_CallLeaf()->_name, "dilithiumAlmostInverseNtt") == 0 ||
2314                   strcmp(call->as_CallLeaf()->_name, "dilithiumNttMult") == 0 ||
2315                   strcmp(call->as_CallLeaf()->_name, "dilithiumMontMulByConstant") == 0 ||
2316                   strcmp(call->as_CallLeaf()->_name, "dilithiumDecomposePoly") == 0 ||
2317                   strcmp(call->as_CallLeaf()->_name, "encodeBlock") == 0 ||
2318                   strcmp(call->as_CallLeaf()->_name, "decodeBlock") == 0 ||
2319                   strcmp(call->as_CallLeaf()->_name, "md5_implCompress") == 0 ||
2320                   strcmp(call->as_CallLeaf()->_name, "md5_implCompressMB") == 0 ||
2321                   strcmp(call->as_CallLeaf()->_name, "sha1_implCompress") == 0 ||
2322                   strcmp(call->as_CallLeaf()->_name, "sha1_implCompressMB") == 0 ||
2323                   strcmp(call->as_CallLeaf()->_name, "sha256_implCompress") == 0 ||
2324                   strcmp(call->as_CallLeaf()->_name, "sha256_implCompressMB") == 0 ||
2325                   strcmp(call->as_CallLeaf()->_name, "sha512_implCompress") == 0 ||
2326                   strcmp(call->as_CallLeaf()->_name, "sha512_implCompressMB") == 0 ||
2327                   strcmp(call->as_CallLeaf()->_name, "sha3_implCompress") == 0 ||
2328                   strcmp(call->as_CallLeaf()->_name, "double_keccak") == 0 ||
2329                   strcmp(call->as_CallLeaf()->_name, "sha3_implCompressMB") == 0 ||
2330                   strcmp(call->as_CallLeaf()->_name, "multiplyToLen") == 0 ||
2331                   strcmp(call->as_CallLeaf()->_name, "squareToLen") == 0 ||
2332                   strcmp(call->as_CallLeaf()->_name, "mulAdd") == 0 ||
2333                   strcmp(call->as_CallLeaf()->_name, "montgomery_multiply") == 0 ||
2334                   strcmp(call->as_CallLeaf()->_name, "montgomery_square") == 0 ||
2335                   strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2336                   strcmp(call->as_CallLeaf()->_name, "load_unknown_inline") == 0 ||
2337                   strcmp(call->as_CallLeaf()->_name, "store_unknown_inline") == 0 ||
2338                   strcmp(call->as_CallLeaf()->_name, "store_inline_type_fields_to_buf") == 0 ||
2339                   strcmp(call->as_CallLeaf()->_name, "bigIntegerRightShiftWorker") == 0 ||
2340                   strcmp(call->as_CallLeaf()->_name, "bigIntegerLeftShiftWorker") == 0 ||
2341                   strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2342                   strcmp(call->as_CallLeaf()->_name, "stringIndexOf") == 0 ||
2343                   strcmp(call->as_CallLeaf()->_name, "arraysort_stub") == 0 ||
2344                   strcmp(call->as_CallLeaf()->_name, "array_partition_stub") == 0 ||
2345                   strcmp(call->as_CallLeaf()->_name, "get_class_id_intrinsic") == 0 ||
2346                   strcmp(call->as_CallLeaf()->_name, "unsafe_setmemory") == 0)
2347                  ))) {
2348             call->dump();
2349             fatal("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name);
2350           }
2351 #endif
2352           // Always process arraycopy's destination object since
2353           // we need to add all possible edges to references in
2354           // source object.
2355           if (arg_esc >= PointsToNode::ArgEscape &&
2356               !arg_is_arraycopy_dest) {
2357             continue;
2358           }
2359           PointsToNode::EscapeState es = PointsToNode::ArgEscape;
2360           if (call->is_ArrayCopy()) {
2361             ArrayCopyNode* ac = call->as_ArrayCopy();
2362             if (ac->is_clonebasic() ||
2363                 ac->is_arraycopy_validated() ||
2364                 ac->is_copyof_validated() ||
2365                 ac->is_copyofrange_validated()) {
2366               es = PointsToNode::NoEscape;
2367             }
2368           }
2369           set_escape_state(arg_ptn, es NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2370           if (arg_is_arraycopy_dest) {
2371             Node* src = call->in(TypeFunc::Parms);
2372             if (src->is_AddP()) {
2373               src = get_addp_base(src);
2374             }
2375             PointsToNode* src_ptn = ptnode_adr(src->_idx);
2376             assert(src_ptn != nullptr, "should be registered");
2377             // Special arraycopy edge:
2378             // Only escape state of destination object's fields affects
2379             // escape state of fields in source object.
2380             add_arraycopy(call, es, src_ptn, arg_ptn);
2381           }
2382         }
2383       }
2384       break;
2385     }
2386     case Op_CallStaticJava: {
2387       // For a static call, we know exactly what method is being called.
2388       // Use bytecode estimator to record the call's escape affects
2389 #ifdef ASSERT
2390       const char* name = call->as_CallStaticJava()->_name;
2391       assert((name == nullptr || strcmp(name, "uncommon_trap") != 0), "normal calls only");
2392 #endif
2393       ciMethod* meth = call->as_CallJava()->method();
2394       if ((meth != nullptr) && meth->is_boxing_method()) {
2395         break; // Boxing methods do not modify any oops.
2396       }
2397       BCEscapeAnalyzer* call_analyzer = (meth !=nullptr) ? meth->get_bcea() : nullptr;
2398       // fall-through if not a Java method or no analyzer information
2399       if (call_analyzer != nullptr) {
2400         PointsToNode* call_ptn = ptnode_adr(call->_idx);
2401         const TypeTuple* d = call->tf()->domain_cc();
2402         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2403           const Type* at = d->field_at(i);
2404           int k = i - TypeFunc::Parms;
2405           Node* arg = call->in(i);
2406           PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2407           if (at->isa_ptr() != nullptr &&
2408               call_analyzer->is_arg_returned(k)) {
2409             // The call returns arguments.
2410             if (call_ptn != nullptr) { // Is call's result used?
2411               assert(call_ptn->is_LocalVar(), "node should be registered");
2412               assert(arg_ptn != nullptr, "node should be registered");
2413               add_edge(call_ptn, arg_ptn);
2414             }
2415           }
2416           if (at->isa_oopptr() != nullptr &&
2417               arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
2418             if (!call_analyzer->is_arg_stack(k)) {
2419               // The argument global escapes
2420               set_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2421             } else {
2422               set_escape_state(arg_ptn, PointsToNode::ArgEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2423               if (!call_analyzer->is_arg_local(k)) {
2424                 // The argument itself doesn't escape, but any fields might
2425                 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2426               }
2427             }
2428           }
2429         }
2430         if (call_ptn != nullptr && call_ptn->is_LocalVar()) {
2431           // The call returns arguments.
2432           assert(call_ptn->edge_count() > 0, "sanity");
2433           if (!call_analyzer->is_return_local()) {
2434             // Returns also unknown object.
2435             add_edge(call_ptn, phantom_obj);
2436           }
2437         }
2438         break;
2439       }
2440     }
2441     default: {
2442       // Fall-through here if not a Java method or no analyzer information
2443       // or some other type of call, assume the worst case: all arguments
2444       // globally escape.
2445       const TypeTuple* d = call->tf()->domain_cc();
2446       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2447         const Type* at = d->field_at(i);
2448         if (at->isa_oopptr() != nullptr) {
2449           Node* arg = call->in(i);
2450           if (arg->is_AddP()) {
2451             arg = get_addp_base(arg);
2452           }
2453           assert(ptnode_adr(arg->_idx) != nullptr, "should be defined already");
2454           set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2455         }
2456       }
2457     }
2458   }
2459 }
2460 
2461 
2462 // Finish Graph construction.
2463 bool ConnectionGraph::complete_connection_graph(
2464                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
2465                          GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
2466                          GrowableArray<JavaObjectNode*>& java_objects_worklist,
2467                          GrowableArray<FieldNode*>&      oop_fields_worklist) {
2468   // Normally only 1-3 passes needed to build Connection Graph depending
2469   // on graph complexity. Observed 8 passes in jvm2008 compiler.compiler.
2470   // Set limit to 20 to catch situation when something did go wrong and
2471   // bailout Escape Analysis.
2472   // Also limit build time to 20 sec (60 in debug VM), EscapeAnalysisTimeout flag.
2473 #define GRAPH_BUILD_ITER_LIMIT 20
2474 
2475   // Propagate GlobalEscape and ArgEscape escape states and check that
2476   // we still have non-escaping objects. The method pushs on _worklist
2477   // Field nodes which reference phantom_object.
2478   if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_allocs_worklist)) {
2479     return false; // Nothing to do.
2480   }
2481   // Now propagate references to all JavaObject nodes.
2482   int java_objects_length = java_objects_worklist.length();
2483   elapsedTimer build_time;
2484   build_time.start();
2485   elapsedTimer time;
2486   bool timeout = false;
2487   int new_edges = 1;
2488   int iterations = 0;
2489   do {
2490     while ((new_edges > 0) &&
2491            (iterations++ < GRAPH_BUILD_ITER_LIMIT)) {
2492       double start_time = time.seconds();
2493       time.start();
2494       new_edges = 0;
2495       // Propagate references to phantom_object for nodes pushed on _worklist
2496       // by find_non_escaped_objects() and find_field_value().
2497       new_edges += add_java_object_edges(phantom_obj, false);
2498       for (int next = 0; next < java_objects_length; ++next) {
2499         JavaObjectNode* ptn = java_objects_worklist.at(next);
2500         new_edges += add_java_object_edges(ptn, true);
2501 
2502 #define SAMPLE_SIZE 4
2503         if ((next % SAMPLE_SIZE) == 0) {
2504           // Each 4 iterations calculate how much time it will take
2505           // to complete graph construction.
2506           time.stop();
2507           // Poll for requests from shutdown mechanism to quiesce compiler
2508           // because Connection graph construction may take long time.
2509           CompileBroker::maybe_block();
2510           double stop_time = time.seconds();
2511           double time_per_iter = (stop_time - start_time) / (double)SAMPLE_SIZE;
2512           double time_until_end = time_per_iter * (double)(java_objects_length - next);
2513           if ((start_time + time_until_end) >= EscapeAnalysisTimeout) {
2514             timeout = true;
2515             break; // Timeout
2516           }
2517           start_time = stop_time;
2518           time.start();
2519         }
2520 #undef SAMPLE_SIZE
2521 
2522       }
2523       if (timeout) break;
2524       if (new_edges > 0) {
2525         // Update escape states on each iteration if graph was updated.
2526         if (!find_non_escaped_objects(ptnodes_worklist, non_escaped_allocs_worklist)) {
2527           return false; // Nothing to do.
2528         }
2529       }
2530       time.stop();
2531       if (time.seconds() >= EscapeAnalysisTimeout) {
2532         timeout = true;
2533         break;
2534       }
2535       _compile->print_method(PHASE_EA_COMPLETE_CONNECTION_GRAPH_ITER, 5);
2536     }
2537     if ((iterations < GRAPH_BUILD_ITER_LIMIT) && !timeout) {
2538       time.start();
2539       // Find fields which have unknown value.
2540       int fields_length = oop_fields_worklist.length();
2541       for (int next = 0; next < fields_length; next++) {
2542         FieldNode* field = oop_fields_worklist.at(next);
2543         if (field->edge_count() == 0) {
2544           new_edges += find_field_value(field);
2545           // This code may added new edges to phantom_object.
2546           // Need an other cycle to propagate references to phantom_object.
2547         }
2548       }
2549       time.stop();
2550       if (time.seconds() >= EscapeAnalysisTimeout) {
2551         timeout = true;
2552         break;
2553       }
2554     } else {
2555       new_edges = 0; // Bailout
2556     }
2557   } while (new_edges > 0);
2558 
2559   build_time.stop();
2560   _build_time = build_time.seconds();
2561   _build_iterations = iterations;
2562 
2563   // Bailout if passed limits.
2564   if ((iterations >= GRAPH_BUILD_ITER_LIMIT) || timeout) {
2565     Compile* C = _compile;
2566     if (C->log() != nullptr) {
2567       C->log()->begin_elem("connectionGraph_bailout reason='reached ");
2568       C->log()->text("%s", timeout ? "time" : "iterations");
2569       C->log()->end_elem(" limit'");
2570     }
2571     assert(ExitEscapeAnalysisOnTimeout, "infinite EA connection graph build during invocation %d (%f sec, %d iterations) with %d nodes and worklist size %d",
2572            _invocation, _build_time, _build_iterations, nodes_size(), ptnodes_worklist.length());
2573     // Possible infinite build_connection_graph loop,
2574     // bailout (no changes to ideal graph were made).
2575     return false;
2576   }
2577 
2578 #undef GRAPH_BUILD_ITER_LIMIT
2579 
2580   // Find fields initialized by null for non-escaping Allocations.
2581   int non_escaped_length = non_escaped_allocs_worklist.length();
2582   for (int next = 0; next < non_escaped_length; next++) {
2583     JavaObjectNode* ptn = non_escaped_allocs_worklist.at(next);
2584     PointsToNode::EscapeState es = ptn->escape_state();
2585     assert(es <= PointsToNode::ArgEscape, "sanity");
2586     if (es == PointsToNode::NoEscape) {
2587       if (find_init_values_null(ptn, _igvn) > 0) {
2588         // Adding references to null object does not change escape states
2589         // since it does not escape. Also no fields are added to null object.
2590         add_java_object_edges(null_obj, false);
2591       }
2592     }
2593     Node* n = ptn->ideal_node();
2594     if (n->is_Allocate()) {
2595       // The object allocated by this Allocate node will never be
2596       // seen by an other thread. Mark it so that when it is
2597       // expanded no MemBarStoreStore is added.
2598       InitializeNode* ini = n->as_Allocate()->initialization();
2599       if (ini != nullptr)
2600         ini->set_does_not_escape();
2601     }
2602   }
2603   return true; // Finished graph construction.
2604 }
2605 
2606 // Propagate GlobalEscape and ArgEscape escape states to all nodes
2607 // and check that we still have non-escaping java objects.
2608 bool ConnectionGraph::find_non_escaped_objects(GrowableArray<PointsToNode*>& ptnodes_worklist,
2609                                                GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
2610                                                bool print_method) {
2611   GrowableArray<PointsToNode*> escape_worklist;
2612   // First, put all nodes with GlobalEscape and ArgEscape states on worklist.
2613   int ptnodes_length = ptnodes_worklist.length();
2614   for (int next = 0; next < ptnodes_length; ++next) {
2615     PointsToNode* ptn = ptnodes_worklist.at(next);
2616     if (ptn->escape_state() >= PointsToNode::ArgEscape ||
2617         ptn->fields_escape_state() >= PointsToNode::ArgEscape) {
2618       escape_worklist.push(ptn);
2619     }
2620   }
2621   // Set escape states to referenced nodes (edges list).
2622   while (escape_worklist.length() > 0) {
2623     PointsToNode* ptn = escape_worklist.pop();
2624     PointsToNode::EscapeState es  = ptn->escape_state();
2625     PointsToNode::EscapeState field_es = ptn->fields_escape_state();
2626     if (ptn->is_Field() && ptn->as_Field()->is_oop() &&
2627         es >= PointsToNode::ArgEscape) {
2628       // GlobalEscape or ArgEscape state of field means it has unknown value.
2629       if (add_edge(ptn, phantom_obj)) {
2630         // New edge was added
2631         add_field_uses_to_worklist(ptn->as_Field());
2632       }
2633     }
2634     for (EdgeIterator i(ptn); i.has_next(); i.next()) {
2635       PointsToNode* e = i.get();
2636       if (e->is_Arraycopy()) {
2637         assert(ptn->arraycopy_dst(), "sanity");
2638         // Propagate only fields escape state through arraycopy edge.
2639         if (e->fields_escape_state() < field_es) {
2640           set_fields_escape_state(e, field_es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
2641           escape_worklist.push(e);
2642         }
2643       } else if (es >= field_es) {
2644         // fields_escape_state is also set to 'es' if it is less than 'es'.
2645         if (e->escape_state() < es) {
2646           set_escape_state(e, es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
2647           escape_worklist.push(e);
2648         }
2649       } else {
2650         // Propagate field escape state.
2651         bool es_changed = false;
2652         if (e->fields_escape_state() < field_es) {
2653           set_fields_escape_state(e, field_es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
2654           es_changed = true;
2655         }
2656         if ((e->escape_state() < field_es) &&
2657             e->is_Field() && ptn->is_JavaObject() &&
2658             e->as_Field()->is_oop()) {
2659           // Change escape state of referenced fields.
2660           set_escape_state(e, field_es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
2661           es_changed = true;
2662         } else if (e->escape_state() < es) {
2663           set_escape_state(e, es NOT_PRODUCT(COMMA trace_propagate_message(ptn)));
2664           es_changed = true;
2665         }
2666         if (es_changed) {
2667           escape_worklist.push(e);
2668         }
2669       }
2670       if (print_method) {
2671         _compile->print_method(PHASE_EA_CONNECTION_GRAPH_PROPAGATE_ITER, 6, e->ideal_node());
2672       }
2673     }
2674   }
2675   // Remove escaped objects from non_escaped list.
2676   for (int next = non_escaped_allocs_worklist.length()-1; next >= 0 ; --next) {
2677     JavaObjectNode* ptn = non_escaped_allocs_worklist.at(next);
2678     if (ptn->escape_state() >= PointsToNode::GlobalEscape) {
2679       non_escaped_allocs_worklist.delete_at(next);
2680     }
2681     if (ptn->escape_state() == PointsToNode::NoEscape) {
2682       // Find fields in non-escaped allocations which have unknown value.
2683       find_init_values_phantom(ptn);
2684     }
2685   }
2686   return (non_escaped_allocs_worklist.length() > 0);
2687 }
2688 
2689 // Add all references to JavaObject node by walking over all uses.
2690 int ConnectionGraph::add_java_object_edges(JavaObjectNode* jobj, bool populate_worklist) {
2691   int new_edges = 0;
2692   if (populate_worklist) {
2693     // Populate _worklist by uses of jobj's uses.
2694     for (UseIterator i(jobj); i.has_next(); i.next()) {
2695       PointsToNode* use = i.get();
2696       if (use->is_Arraycopy()) {
2697         continue;
2698       }
2699       add_uses_to_worklist(use);
2700       if (use->is_Field() && use->as_Field()->is_oop()) {
2701         // Put on worklist all field's uses (loads) and
2702         // related field nodes (same base and offset).
2703         add_field_uses_to_worklist(use->as_Field());
2704       }
2705     }
2706   }
2707   for (int l = 0; l < _worklist.length(); l++) {
2708     PointsToNode* use = _worklist.at(l);
2709     if (PointsToNode::is_base_use(use)) {
2710       // Add reference from jobj to field and from field to jobj (field's base).
2711       use = PointsToNode::get_use_node(use)->as_Field();
2712       if (add_base(use->as_Field(), jobj)) {
2713         new_edges++;
2714       }
2715       continue;
2716     }
2717     assert(!use->is_JavaObject(), "sanity");
2718     if (use->is_Arraycopy()) {
2719       if (jobj == null_obj) { // null object does not have field edges
2720         continue;
2721       }
2722       // Added edge from Arraycopy node to arraycopy's source java object
2723       if (add_edge(use, jobj)) {
2724         jobj->set_arraycopy_src();
2725         new_edges++;
2726       }
2727       // and stop here.
2728       continue;
2729     }
2730     if (!add_edge(use, jobj)) {
2731       continue; // No new edge added, there was such edge already.
2732     }
2733     new_edges++;
2734     if (use->is_LocalVar()) {
2735       add_uses_to_worklist(use);
2736       if (use->arraycopy_dst()) {
2737         for (EdgeIterator i(use); i.has_next(); i.next()) {
2738           PointsToNode* e = i.get();
2739           if (e->is_Arraycopy()) {
2740             if (jobj == null_obj) { // null object does not have field edges
2741               continue;
2742             }
2743             // Add edge from arraycopy's destination java object to Arraycopy node.
2744             if (add_edge(jobj, e)) {
2745               new_edges++;
2746               jobj->set_arraycopy_dst();
2747             }
2748           }
2749         }
2750       }
2751     } else {
2752       // Added new edge to stored in field values.
2753       // Put on worklist all field's uses (loads) and
2754       // related field nodes (same base and offset).
2755       add_field_uses_to_worklist(use->as_Field());
2756     }
2757   }
2758   _worklist.clear();
2759   _in_worklist.reset();
2760   return new_edges;
2761 }
2762 
2763 // Put on worklist all related field nodes.
2764 void ConnectionGraph::add_field_uses_to_worklist(FieldNode* field) {
2765   assert(field->is_oop(), "sanity");
2766   int offset = field->offset();
2767   add_uses_to_worklist(field);
2768   // Loop over all bases of this field and push on worklist Field nodes
2769   // with the same offset and base (since they may reference the same field).
2770   for (BaseIterator i(field); i.has_next(); i.next()) {
2771     PointsToNode* base = i.get();
2772     add_fields_to_worklist(field, base);
2773     // Check if the base was source object of arraycopy and go over arraycopy's
2774     // destination objects since values stored to a field of source object are
2775     // accessible by uses (loads) of fields of destination objects.
2776     if (base->arraycopy_src()) {
2777       for (UseIterator j(base); j.has_next(); j.next()) {
2778         PointsToNode* arycp = j.get();
2779         if (arycp->is_Arraycopy()) {
2780           for (UseIterator k(arycp); k.has_next(); k.next()) {
2781             PointsToNode* abase = k.get();
2782             if (abase->arraycopy_dst() && abase != base) {
2783               // Look for the same arraycopy reference.
2784               add_fields_to_worklist(field, abase);
2785             }
2786           }
2787         }
2788       }
2789     }
2790   }
2791 }
2792 
2793 // Put on worklist all related field nodes.
2794 void ConnectionGraph::add_fields_to_worklist(FieldNode* field, PointsToNode* base) {
2795   int offset = field->offset();
2796   if (base->is_LocalVar()) {
2797     for (UseIterator j(base); j.has_next(); j.next()) {
2798       PointsToNode* f = j.get();
2799       if (PointsToNode::is_base_use(f)) { // Field
2800         f = PointsToNode::get_use_node(f);
2801         if (f == field || !f->as_Field()->is_oop()) {
2802           continue;
2803         }
2804         int offs = f->as_Field()->offset();
2805         if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
2806           add_to_worklist(f);
2807         }
2808       }
2809     }
2810   } else {
2811     assert(base->is_JavaObject(), "sanity");
2812     if (// Skip phantom_object since it is only used to indicate that
2813         // this field's content globally escapes.
2814         (base != phantom_obj) &&
2815         // null object node does not have fields.
2816         (base != null_obj)) {
2817       for (EdgeIterator i(base); i.has_next(); i.next()) {
2818         PointsToNode* f = i.get();
2819         // Skip arraycopy edge since store to destination object field
2820         // does not update value in source object field.
2821         if (f->is_Arraycopy()) {
2822           assert(base->arraycopy_dst(), "sanity");
2823           continue;
2824         }
2825         if (f == field || !f->as_Field()->is_oop()) {
2826           continue;
2827         }
2828         int offs = f->as_Field()->offset();
2829         if (offs == offset || offset == Type::OffsetBot || offs == Type::OffsetBot) {
2830           add_to_worklist(f);
2831         }
2832       }
2833     }
2834   }
2835 }
2836 
2837 // Find fields which have unknown value.
2838 int ConnectionGraph::find_field_value(FieldNode* field) {
2839   // Escaped fields should have init value already.
2840   assert(field->escape_state() == PointsToNode::NoEscape, "sanity");
2841   int new_edges = 0;
2842   for (BaseIterator i(field); i.has_next(); i.next()) {
2843     PointsToNode* base = i.get();
2844     if (base->is_JavaObject()) {
2845       // Skip Allocate's fields which will be processed later.
2846       if (base->ideal_node()->is_Allocate()) {
2847         return 0;
2848       }
2849       assert(base == null_obj, "only null ptr base expected here");
2850     }
2851   }
2852   if (add_edge(field, phantom_obj)) {
2853     // New edge was added
2854     new_edges++;
2855     add_field_uses_to_worklist(field);
2856   }
2857   return new_edges;
2858 }
2859 
2860 // Find fields initializing values for allocations.
2861 int ConnectionGraph::find_init_values_phantom(JavaObjectNode* pta) {
2862   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2863   PointsToNode* init_val = phantom_obj;
2864   Node* alloc = pta->ideal_node();
2865 
2866   // Do nothing for Allocate nodes since its fields values are
2867   // "known" unless they are initialized by arraycopy/clone.
2868   if (alloc->is_Allocate() && !pta->arraycopy_dst()) {
2869     if (alloc->as_Allocate()->in(AllocateNode::InitValue) != nullptr) {
2870       // Null-free inline type arrays are initialized with an init value instead of null
2871       init_val = ptnode_adr(alloc->as_Allocate()->in(AllocateNode::InitValue)->_idx);
2872       assert(init_val != nullptr, "init value should be registered");
2873     } else {
2874       return 0;
2875     }
2876   }
2877   // Non-escaped allocation returned from Java or runtime call has unknown values in fields.
2878   assert(pta->arraycopy_dst() || alloc->is_CallStaticJava() || init_val != phantom_obj, "sanity");
2879 #ifdef ASSERT
2880   if (alloc->is_CallStaticJava() && alloc->as_CallStaticJava()->method() == nullptr) {
2881     const char* name = alloc->as_CallStaticJava()->_name;
2882     assert(strncmp(name, "C2 Runtime multianewarray", 25) == 0 ||
2883            strncmp(name, "C2 Runtime load_unknown_inline", 30) == 0 ||
2884            strncmp(name, "store_inline_type_fields_to_buf", 31) == 0, "sanity");
2885   }
2886 #endif
2887   // Non-escaped allocation returned from Java or runtime call have unknown values in fields.
2888   int new_edges = 0;
2889   for (EdgeIterator i(pta); i.has_next(); i.next()) {
2890     PointsToNode* field = i.get();
2891     if (field->is_Field() && field->as_Field()->is_oop()) {
2892       if (add_edge(field, init_val)) {
2893         // New edge was added
2894         new_edges++;
2895         add_field_uses_to_worklist(field->as_Field());
2896       }
2897     }
2898   }
2899   return new_edges;
2900 }
2901 
2902 // Find fields initializing values for allocations.
2903 int ConnectionGraph::find_init_values_null(JavaObjectNode* pta, PhaseValues* phase) {
2904   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2905   Node* alloc = pta->ideal_node();
2906   // Do nothing for Call nodes since its fields values are unknown.
2907   if (!alloc->is_Allocate() || alloc->as_Allocate()->in(AllocateNode::InitValue) != nullptr) {
2908     return 0;
2909   }
2910   InitializeNode* ini = alloc->as_Allocate()->initialization();
2911   bool visited_bottom_offset = false;
2912   GrowableArray<int> offsets_worklist;
2913   int new_edges = 0;
2914 
2915   // Check if an oop field's initializing value is recorded and add
2916   // a corresponding null if field's value if it is not recorded.
2917   // Connection Graph does not record a default initialization by null
2918   // captured by Initialize node.
2919   //
2920   for (EdgeIterator i(pta); i.has_next(); i.next()) {
2921     PointsToNode* field = i.get(); // Field (AddP)
2922     if (!field->is_Field() || !field->as_Field()->is_oop()) {
2923       continue; // Not oop field
2924     }
2925     int offset = field->as_Field()->offset();
2926     if (offset == Type::OffsetBot) {
2927       if (!visited_bottom_offset) {
2928         // OffsetBot is used to reference array's element,
2929         // always add reference to null to all Field nodes since we don't
2930         // known which element is referenced.
2931         if (add_edge(field, null_obj)) {
2932           // New edge was added
2933           new_edges++;
2934           add_field_uses_to_worklist(field->as_Field());
2935           visited_bottom_offset = true;
2936         }
2937       }
2938     } else {
2939       // Check only oop fields.
2940       const Type* adr_type = field->ideal_node()->as_AddP()->bottom_type();
2941       if (adr_type->isa_rawptr()) {
2942 #ifdef ASSERT
2943         // Raw pointers are used for initializing stores so skip it
2944         // since it should be recorded already
2945         Node* base = get_addp_base(field->ideal_node());
2946         assert(adr_type->isa_rawptr() && is_captured_store_address(field->ideal_node()), "unexpected pointer type");
2947 #endif
2948         continue;
2949       }
2950       if (!offsets_worklist.contains(offset)) {
2951         offsets_worklist.append(offset);
2952         Node* value = nullptr;
2953         if (ini != nullptr) {
2954           // StoreP::value_basic_type() == T_ADDRESS
2955           BasicType ft = UseCompressedOops ? T_NARROWOOP : T_ADDRESS;
2956           Node* store = ini->find_captured_store(offset, type2aelembytes(ft, true), phase);
2957           // Make sure initializing store has the same type as this AddP.
2958           // This AddP may reference non existing field because it is on a
2959           // dead branch of bimorphic call which is not eliminated yet.
2960           if (store != nullptr && store->is_Store() &&
2961               store->as_Store()->value_basic_type() == ft) {
2962             value = store->in(MemNode::ValueIn);
2963 #ifdef ASSERT
2964             if (VerifyConnectionGraph) {
2965               // Verify that AddP already points to all objects the value points to.
2966               PointsToNode* val = ptnode_adr(value->_idx);
2967               assert((val != nullptr), "should be processed already");
2968               PointsToNode* missed_obj = nullptr;
2969               if (val->is_JavaObject()) {
2970                 if (!field->points_to(val->as_JavaObject())) {
2971                   missed_obj = val;
2972                 }
2973               } else {
2974                 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
2975                   tty->print_cr("----------init store has invalid value -----");
2976                   store->dump();
2977                   val->dump();
2978                   assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
2979                 }
2980                 for (EdgeIterator j(val); j.has_next(); j.next()) {
2981                   PointsToNode* obj = j.get();
2982                   if (obj->is_JavaObject()) {
2983                     if (!field->points_to(obj->as_JavaObject())) {
2984                       missed_obj = obj;
2985                       break;
2986                     }
2987                   }
2988                 }
2989               }
2990               if (missed_obj != nullptr) {
2991                 tty->print_cr("----------field---------------------------------");
2992                 field->dump();
2993                 tty->print_cr("----------missed reference to object------------");
2994                 missed_obj->dump();
2995                 tty->print_cr("----------object referenced by init store-------");
2996                 store->dump();
2997                 val->dump();
2998                 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
2999               }
3000             }
3001 #endif
3002           } else {
3003             // There could be initializing stores which follow allocation.
3004             // For example, a volatile field store is not collected
3005             // by Initialize node.
3006             //
3007             // Need to check for dependent loads to separate such stores from
3008             // stores which follow loads. For now, add initial value null so
3009             // that compare pointers optimization works correctly.
3010           }
3011         }
3012         if (value == nullptr) {
3013           // A field's initializing value was not recorded. Add null.
3014           if (add_edge(field, null_obj)) {
3015             // New edge was added
3016             new_edges++;
3017             add_field_uses_to_worklist(field->as_Field());
3018           }
3019         }
3020       }
3021     }
3022   }
3023   return new_edges;
3024 }
3025 
3026 // Adjust scalar_replaceable state after Connection Graph is built.
3027 void ConnectionGraph::adjust_scalar_replaceable_state(JavaObjectNode* jobj, Unique_Node_List &reducible_merges) {
3028   // A Phi 'x' is a _candidate_ to be reducible if 'can_reduce_phi(x)'
3029   // returns true. If one of the constraints in this method set 'jobj' to NSR
3030   // then the candidate Phi is discarded. If the Phi has another SR 'jobj' as
3031   // input, 'adjust_scalar_replaceable_state' will eventually be called with
3032   // that other object and the Phi will become a reducible Phi.
3033   // There could be multiple merges involving the same jobj.
3034   Unique_Node_List candidates;
3035 
3036   // Search for non-escaping objects which are not scalar replaceable
3037   // and mark them to propagate the state to referenced objects.
3038 
3039   for (UseIterator i(jobj); i.has_next(); i.next()) {
3040     PointsToNode* use = i.get();
3041     if (use->is_Arraycopy()) {
3042       continue;
3043     }
3044     if (use->is_Field()) {
3045       FieldNode* field = use->as_Field();
3046       assert(field->is_oop() && field->scalar_replaceable(), "sanity");
3047       // 1. An object is not scalar replaceable if the field into which it is
3048       // stored has unknown offset (stored into unknown element of an array).
3049       if (field->offset() == Type::OffsetBot) {
3050         set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is stored at unknown offset"));
3051         return;
3052       }
3053       for (BaseIterator i(field); i.has_next(); i.next()) {
3054         PointsToNode* base = i.get();
3055         // 2. An object is not scalar replaceable if the field into which it is
3056         // stored has multiple bases one of which is null.
3057         if ((base == null_obj) && (field->base_count() > 1)) {
3058           set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is stored into field with potentially null base"));
3059           return;
3060         }
3061         // 2.5. An object is not scalar replaceable if the field into which it is
3062         // stored has NSR base.
3063         if (!base->scalar_replaceable()) {
3064           set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is stored into field with NSR base"));
3065           return;
3066         }
3067       }
3068     }
3069     assert(use->is_Field() || use->is_LocalVar(), "sanity");
3070     // 3. An object is not scalar replaceable if it is merged with other objects
3071     // and we can't remove the merge
3072     for (EdgeIterator j(use); j.has_next(); j.next()) {
3073       PointsToNode* ptn = j.get();
3074       if (ptn->is_JavaObject() && ptn != jobj) {
3075         Node* use_n = use->ideal_node();
3076 
3077         // These other local vars may point to multiple objects through a Phi
3078         // In this case we skip them and see if we can reduce the Phi.
3079         if (use_n->is_CastPP() || use_n->is_CheckCastPP()) {
3080           use_n = use_n->in(1);
3081         }
3082 
3083         // If it's already a candidate or confirmed reducible merge we can skip verification
3084         if (candidates.member(use_n) || reducible_merges.member(use_n)) {
3085           continue;
3086         }
3087 
3088         if (use_n->is_Phi() && can_reduce_phi(use_n->as_Phi())) {
3089           candidates.push(use_n);
3090         } else {
3091           // Mark all objects as NSR if we can't remove the merge
3092           set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA trace_merged_message(ptn)));
3093           set_not_scalar_replaceable(ptn NOT_PRODUCT(COMMA trace_merged_message(jobj)));
3094         }
3095       }
3096     }
3097     if (!jobj->scalar_replaceable()) {
3098       return;
3099     }
3100   }
3101 
3102   for (EdgeIterator j(jobj); j.has_next(); j.next()) {
3103     if (j.get()->is_Arraycopy()) {
3104       continue;
3105     }
3106 
3107     // Non-escaping object node should point only to field nodes.
3108     FieldNode* field = j.get()->as_Field();
3109     int offset = field->as_Field()->offset();
3110 
3111     // 4. An object is not scalar replaceable if it has a field with unknown
3112     // offset (array's element is accessed in loop).
3113     if (offset == Type::OffsetBot) {
3114       set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "has field with unknown offset"));
3115       return;
3116     }
3117     // 5. Currently an object is not scalar replaceable if a LoadStore node
3118     // access its field since the field value is unknown after it.
3119     //
3120     Node* n = field->ideal_node();
3121 
3122     // Test for an unsafe access that was parsed as maybe off heap
3123     // (with a CheckCastPP to raw memory).
3124     assert(n->is_AddP(), "expect an address computation");
3125     if (n->in(AddPNode::Base)->is_top() &&
3126         n->in(AddPNode::Address)->Opcode() == Op_CheckCastPP) {
3127       assert(n->in(AddPNode::Address)->bottom_type()->isa_rawptr(), "raw address so raw cast expected");
3128       assert(_igvn->type(n->in(AddPNode::Address)->in(1))->isa_oopptr(), "cast pattern at unsafe access expected");
3129       set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is used as base of mixed unsafe access"));
3130       return;
3131     }
3132 
3133     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
3134       Node* u = n->fast_out(i);
3135       if (u->is_LoadStore() || (u->is_Mem() && u->as_Mem()->is_mismatched_access())) {
3136         set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is used in LoadStore or mismatched access"));
3137         return;
3138       }
3139     }
3140 
3141     // 6. Or the address may point to more then one object. This may produce
3142     // the false positive result (set not scalar replaceable)
3143     // since the flow-insensitive escape analysis can't separate
3144     // the case when stores overwrite the field's value from the case
3145     // when stores happened on different control branches.
3146     //
3147     // Note: it will disable scalar replacement in some cases:
3148     //
3149     //    Point p[] = new Point[1];
3150     //    p[0] = new Point(); // Will be not scalar replaced
3151     //
3152     // but it will save us from incorrect optimizations in next cases:
3153     //
3154     //    Point p[] = new Point[1];
3155     //    if ( x ) p[0] = new Point(); // Will be not scalar replaced
3156     //
3157     if (field->base_count() > 1 && candidates.size() == 0) {
3158       if (has_non_reducible_merge(field, reducible_merges)) {
3159         for (BaseIterator i(field); i.has_next(); i.next()) {
3160           PointsToNode* base = i.get();
3161           // Don't take into account LocalVar nodes which
3162           // may point to only one object which should be also
3163           // this field's base by now.
3164           if (base->is_JavaObject() && base != jobj) {
3165             // Mark all bases.
3166             set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "may point to more than one object"));
3167             set_not_scalar_replaceable(base NOT_PRODUCT(COMMA "may point to more than one object"));
3168           }
3169         }
3170 
3171         if (!jobj->scalar_replaceable()) {
3172           return;
3173         }
3174       }
3175     }
3176   }
3177 
3178   // The candidate is truly a reducible merge only if none of the other
3179   // constraints ruled it as NSR. There could be multiple merges involving the
3180   // same jobj.
3181   assert(jobj->scalar_replaceable(), "sanity");
3182   for (uint i = 0; i < candidates.size(); i++ ) {
3183     Node* candidate = candidates.at(i);
3184     reducible_merges.push(candidate);
3185   }
3186 }
3187 
3188 bool ConnectionGraph::has_non_reducible_merge(FieldNode* field, Unique_Node_List& reducible_merges) {
3189   for (BaseIterator i(field); i.has_next(); i.next()) {
3190     Node* base = i.get()->ideal_node();
3191     if (base->is_Phi() && !reducible_merges.member(base)) {
3192       return true;
3193     }
3194   }
3195   return false;
3196 }
3197 
3198 void ConnectionGraph::revisit_reducible_phi_status(JavaObjectNode* jobj, Unique_Node_List& reducible_merges) {
3199   assert(jobj != nullptr && !jobj->scalar_replaceable(), "jobj should be set as NSR before calling this function.");
3200 
3201   // Look for 'phis' that refer to 'jobj' as the last
3202   // remaining scalar replaceable input.
3203   uint reducible_merges_cnt = reducible_merges.size();
3204   for (uint i = 0; i < reducible_merges_cnt; i++) {
3205     Node* phi = reducible_merges.at(i);
3206 
3207     // This 'Phi' will be a 'good' if it still points to
3208     // at least one scalar replaceable object. Note that 'obj'
3209     // was/should be marked as NSR before calling this function.
3210     bool good_phi = false;
3211 
3212     for (uint j = 1; j < phi->req(); j++) {
3213       JavaObjectNode* phi_in_obj = unique_java_object(phi->in(j));
3214       if (phi_in_obj != nullptr && phi_in_obj->scalar_replaceable()) {
3215         good_phi = true;
3216         break;
3217       }
3218     }
3219 
3220     if (!good_phi) {
3221       NOT_PRODUCT(if (TraceReduceAllocationMerges) tty->print_cr("Phi %d became non-reducible after node %d became NSR.", phi->_idx, jobj->ideal_node()->_idx);)
3222       reducible_merges.remove(i);
3223 
3224       // Decrement the index because the 'remove' call above actually
3225       // moves the last entry of the list to position 'i'.
3226       i--;
3227 
3228       reducible_merges_cnt--;
3229     }
3230   }
3231 }
3232 
3233 // Propagate NSR (Not scalar replaceable) state.
3234 void ConnectionGraph::find_scalar_replaceable_allocs(GrowableArray<JavaObjectNode*>& jobj_worklist, Unique_Node_List &reducible_merges) {
3235   int jobj_length = jobj_worklist.length();
3236   bool found_nsr_alloc = true;
3237   while (found_nsr_alloc) {
3238     found_nsr_alloc = false;
3239     for (int next = 0; next < jobj_length; ++next) {
3240       JavaObjectNode* jobj = jobj_worklist.at(next);
3241       for (UseIterator i(jobj); (jobj->scalar_replaceable() && i.has_next()); i.next()) {
3242         PointsToNode* use = i.get();
3243         if (use->is_Field()) {
3244           FieldNode* field = use->as_Field();
3245           assert(field->is_oop() && field->scalar_replaceable(), "sanity");
3246           assert(field->offset() != Type::OffsetBot, "sanity");
3247           for (BaseIterator i(field); i.has_next(); i.next()) {
3248             PointsToNode* base = i.get();
3249             // An object is not scalar replaceable if the field into which
3250             // it is stored has NSR base.
3251             if ((base != null_obj) && !base->scalar_replaceable()) {
3252               set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is stored into field with NSR base"));
3253               // Any merge that had only 'jobj' as scalar-replaceable will now be non-reducible,
3254               // because there is no point in reducing a Phi that won't improve the number of SR
3255               // objects.
3256               revisit_reducible_phi_status(jobj, reducible_merges);
3257               found_nsr_alloc = true;
3258               break;
3259             }
3260           }
3261         } else if (use->is_LocalVar()) {
3262           Node* phi = use->ideal_node();
3263           if (phi->Opcode() == Op_Phi && reducible_merges.member(phi) && !can_reduce_phi(phi->as_Phi())) {
3264             set_not_scalar_replaceable(jobj NOT_PRODUCT(COMMA "is merged in a non-reducible phi"));
3265             reducible_merges.yank(phi);
3266             found_nsr_alloc = true;
3267             break;
3268           }
3269         }
3270         _compile->print_method(PHASE_EA_PROPAGATE_NSR_ITER, 5, jobj->ideal_node());
3271       }
3272     }
3273   }
3274 }
3275 
3276 #ifdef ASSERT
3277 void ConnectionGraph::verify_connection_graph(
3278                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
3279                          GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
3280                          GrowableArray<JavaObjectNode*>& java_objects_worklist,
3281                          GrowableArray<Node*>& addp_worklist) {
3282   // Verify that graph is complete - no new edges could be added.
3283   int java_objects_length = java_objects_worklist.length();
3284   int non_escaped_length  = non_escaped_allocs_worklist.length();
3285   int new_edges = 0;
3286   for (int next = 0; next < java_objects_length; ++next) {
3287     JavaObjectNode* ptn = java_objects_worklist.at(next);
3288     new_edges += add_java_object_edges(ptn, true);
3289   }
3290   assert(new_edges == 0, "graph was not complete");
3291   // Verify that escape state is final.
3292   int length = non_escaped_allocs_worklist.length();
3293   find_non_escaped_objects(ptnodes_worklist, non_escaped_allocs_worklist, /*print_method=*/ false);
3294   assert((non_escaped_length == non_escaped_allocs_worklist.length()) &&
3295          (non_escaped_length == length) &&
3296          (_worklist.length() == 0), "escape state was not final");
3297 
3298   // Verify fields information.
3299   int addp_length = addp_worklist.length();
3300   for (int next = 0; next < addp_length; ++next ) {
3301     Node* n = addp_worklist.at(next);
3302     FieldNode* field = ptnode_adr(n->_idx)->as_Field();
3303     if (field->is_oop()) {
3304       // Verify that field has all bases
3305       Node* base = get_addp_base(n);
3306       PointsToNode* ptn = ptnode_adr(base->_idx);
3307       if (ptn->is_JavaObject()) {
3308         assert(field->has_base(ptn->as_JavaObject()), "sanity");
3309       } else {
3310         assert(ptn->is_LocalVar(), "sanity");
3311         for (EdgeIterator i(ptn); i.has_next(); i.next()) {
3312           PointsToNode* e = i.get();
3313           if (e->is_JavaObject()) {
3314             assert(field->has_base(e->as_JavaObject()), "sanity");
3315           }
3316         }
3317       }
3318       // Verify that all fields have initializing values.
3319       if (field->edge_count() == 0) {
3320         tty->print_cr("----------field does not have references----------");
3321         field->dump();
3322         for (BaseIterator i(field); i.has_next(); i.next()) {
3323           PointsToNode* base = i.get();
3324           tty->print_cr("----------field has next base---------------------");
3325           base->dump();
3326           if (base->is_JavaObject() && (base != phantom_obj) && (base != null_obj)) {
3327             tty->print_cr("----------base has fields-------------------------");
3328             for (EdgeIterator j(base); j.has_next(); j.next()) {
3329               j.get()->dump();
3330             }
3331             tty->print_cr("----------base has references---------------------");
3332             for (UseIterator j(base); j.has_next(); j.next()) {
3333               j.get()->dump();
3334             }
3335           }
3336         }
3337         for (UseIterator i(field); i.has_next(); i.next()) {
3338           i.get()->dump();
3339         }
3340         assert(field->edge_count() > 0, "sanity");
3341       }
3342     }
3343   }
3344 }
3345 #endif
3346 
3347 // Optimize ideal graph.
3348 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
3349                                            GrowableArray<MemBarStoreStoreNode*>& storestore_worklist) {
3350   Compile* C = _compile;
3351   PhaseIterGVN* igvn = _igvn;
3352   if (EliminateLocks) {
3353     // Mark locks before changing ideal graph.
3354     int cnt = C->macro_count();
3355     for (int i = 0; i < cnt; i++) {
3356       Node *n = C->macro_node(i);
3357       if (n->is_AbstractLock()) { // Lock and Unlock nodes
3358         AbstractLockNode* alock = n->as_AbstractLock();
3359         if (!alock->is_non_esc_obj()) {
3360           const Type* obj_type = igvn->type(alock->obj_node());
3361           if (can_eliminate_lock(alock) && !obj_type->is_inlinetypeptr()) {
3362             assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
3363             // The lock could be marked eliminated by lock coarsening
3364             // code during first IGVN before EA. Replace coarsened flag
3365             // to eliminate all associated locks/unlocks.
3366 #ifdef ASSERT
3367             alock->log_lock_optimization(C, "eliminate_lock_set_non_esc3");
3368 #endif
3369             alock->set_non_esc_obj();
3370           }
3371         }
3372       }
3373     }
3374   }
3375 
3376   if (OptimizePtrCompare) {
3377     for (int i = 0; i < ptr_cmp_worklist.length(); i++) {
3378       Node *n = ptr_cmp_worklist.at(i);
3379       assert(n->Opcode() == Op_CmpN || n->Opcode() == Op_CmpP, "must be");
3380       const TypeInt* tcmp = optimize_ptr_compare(n->in(1), n->in(2));
3381       if (tcmp->singleton()) {
3382         Node* cmp = igvn->makecon(tcmp);
3383 #ifndef PRODUCT
3384         if (PrintOptimizePtrCompare) {
3385           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"));
3386           if (Verbose) {
3387             n->dump(1);
3388           }
3389         }
3390 #endif
3391         igvn->replace_node(n, cmp);
3392       }
3393     }
3394   }
3395 
3396   // For MemBarStoreStore nodes added in library_call.cpp, check
3397   // escape status of associated AllocateNode and optimize out
3398   // MemBarStoreStore node if the allocated object never escapes.
3399   for (int i = 0; i < storestore_worklist.length(); i++) {
3400     Node* storestore = storestore_worklist.at(i);
3401     Node* alloc = storestore->in(MemBarNode::Precedent)->in(0);
3402     if (alloc->is_Allocate() && not_global_escape(alloc)) {
3403       if (alloc->in(AllocateNode::InlineType) != nullptr) {
3404         // Non-escaping inline type buffer allocations don't require a membar
3405         storestore->as_MemBar()->remove(_igvn);
3406       } else {
3407         MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
3408         mb->init_req(TypeFunc::Memory,  storestore->in(TypeFunc::Memory));
3409         mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
3410         igvn->register_new_node_with_optimizer(mb);
3411         igvn->replace_node(storestore, mb);
3412       }
3413     }
3414   }
3415 }
3416 
3417 // Atomic flat accesses on non-escaping objects can be optimized to non-atomic accesses
3418 void ConnectionGraph::optimize_flat_accesses(GrowableArray<SafePointNode*>& sfn_worklist) {
3419   PhaseIterGVN& igvn = *_igvn;
3420   bool delay = igvn.delay_transform();
3421   igvn.set_delay_transform(true);
3422   igvn.C->for_each_flat_access([&](Node* n) {
3423     Node* base = n->is_LoadFlat() ? n->as_LoadFlat()->base() : n->as_StoreFlat()->base();
3424     if (!not_global_escape(base)) {
3425       return;
3426     }
3427 
3428     bool expanded;
3429     if (n->is_LoadFlat()) {
3430       expanded = n->as_LoadFlat()->expand_non_atomic(igvn);
3431     } else {
3432       expanded = n->as_StoreFlat()->expand_non_atomic(igvn);
3433     }
3434     if (expanded) {
3435       sfn_worklist.remove(n->as_SafePoint());
3436       igvn.C->remove_flat_access(n);
3437     }
3438   });
3439   igvn.set_delay_transform(delay);
3440 }
3441 
3442 // Optimize objects compare.
3443 const TypeInt* ConnectionGraph::optimize_ptr_compare(Node* left, Node* right) {
3444   const TypeInt* UNKNOWN = TypeInt::CC;    // [-1, 0,1]
3445   if (!OptimizePtrCompare) {
3446     return UNKNOWN;
3447   }
3448   const TypeInt* EQ = TypeInt::CC_EQ; // [0] == ZERO
3449   const TypeInt* NE = TypeInt::CC_GT; // [1] == ONE
3450 
3451   PointsToNode* ptn1 = ptnode_adr(left->_idx);
3452   PointsToNode* ptn2 = ptnode_adr(right->_idx);
3453   JavaObjectNode* jobj1 = unique_java_object(left);
3454   JavaObjectNode* jobj2 = unique_java_object(right);
3455 
3456   // The use of this method during allocation merge reduction may cause 'left'
3457   // or 'right' be something (e.g., a Phi) that isn't in the connection graph or
3458   // that doesn't reference an unique java object.
3459   if (ptn1 == nullptr || ptn2 == nullptr ||
3460       jobj1 == nullptr || jobj2 == nullptr) {
3461     return UNKNOWN;
3462   }
3463 
3464   assert(ptn1->is_JavaObject() || ptn1->is_LocalVar(), "sanity");
3465   assert(ptn2->is_JavaObject() || ptn2->is_LocalVar(), "sanity");
3466 
3467   // Check simple cases first.
3468   if (jobj1 != nullptr) {
3469     if (jobj1->escape_state() == PointsToNode::NoEscape) {
3470       if (jobj1 == jobj2) {
3471         // Comparing the same not escaping object.
3472         return EQ;
3473       }
3474       Node* obj = jobj1->ideal_node();
3475       // Comparing not escaping allocation.
3476       if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
3477           !ptn2->points_to(jobj1)) {
3478         return NE; // This includes nullness check.
3479       }
3480     }
3481   }
3482   if (jobj2 != nullptr) {
3483     if (jobj2->escape_state() == PointsToNode::NoEscape) {
3484       Node* obj = jobj2->ideal_node();
3485       // Comparing not escaping allocation.
3486       if ((obj->is_Allocate() || obj->is_CallStaticJava()) &&
3487           !ptn1->points_to(jobj2)) {
3488         return NE; // This includes nullness check.
3489       }
3490     }
3491   }
3492   if (jobj1 != nullptr && jobj1 != phantom_obj &&
3493       jobj2 != nullptr && jobj2 != phantom_obj &&
3494       jobj1->ideal_node()->is_Con() &&
3495       jobj2->ideal_node()->is_Con()) {
3496     // Klass or String constants compare. Need to be careful with
3497     // compressed pointers - compare types of ConN and ConP instead of nodes.
3498     const Type* t1 = jobj1->ideal_node()->get_ptr_type();
3499     const Type* t2 = jobj2->ideal_node()->get_ptr_type();
3500     if (t1->make_ptr() == t2->make_ptr()) {
3501       return EQ;
3502     } else {
3503       return NE;
3504     }
3505   }
3506   if (ptn1->meet(ptn2)) {
3507     return UNKNOWN; // Sets are not disjoint
3508   }
3509 
3510   // Sets are disjoint.
3511   bool set1_has_unknown_ptr = ptn1->points_to(phantom_obj);
3512   bool set2_has_unknown_ptr = ptn2->points_to(phantom_obj);
3513   bool set1_has_null_ptr    = ptn1->points_to(null_obj);
3514   bool set2_has_null_ptr    = ptn2->points_to(null_obj);
3515   if ((set1_has_unknown_ptr && set2_has_null_ptr) ||
3516       (set2_has_unknown_ptr && set1_has_null_ptr)) {
3517     // Check nullness of unknown object.
3518     return UNKNOWN;
3519   }
3520 
3521   // Disjointness by itself is not sufficient since
3522   // alias analysis is not complete for escaped objects.
3523   // Disjoint sets are definitely unrelated only when
3524   // at least one set has only not escaping allocations.
3525   if (!set1_has_unknown_ptr && !set1_has_null_ptr) {
3526     if (ptn1->non_escaping_allocation()) {
3527       return NE;
3528     }
3529   }
3530   if (!set2_has_unknown_ptr && !set2_has_null_ptr) {
3531     if (ptn2->non_escaping_allocation()) {
3532       return NE;
3533     }
3534   }
3535   return UNKNOWN;
3536 }
3537 
3538 // Connection Graph construction functions.
3539 
3540 void ConnectionGraph::add_local_var(Node *n, PointsToNode::EscapeState es) {
3541   PointsToNode* ptadr = _nodes.at(n->_idx);
3542   if (ptadr != nullptr) {
3543     assert(ptadr->is_LocalVar() && ptadr->ideal_node() == n, "sanity");
3544     return;
3545   }
3546   Compile* C = _compile;
3547   ptadr = new (C->comp_arena()) LocalVarNode(this, n, es);
3548   map_ideal_node(n, ptadr);
3549 }
3550 
3551 PointsToNode* ConnectionGraph::add_java_object(Node *n, PointsToNode::EscapeState es) {
3552   PointsToNode* ptadr = _nodes.at(n->_idx);
3553   if (ptadr != nullptr) {
3554     assert(ptadr->is_JavaObject() && ptadr->ideal_node() == n, "sanity");
3555     return ptadr;
3556   }
3557   Compile* C = _compile;
3558   ptadr = new (C->comp_arena()) JavaObjectNode(this, n, es);
3559   map_ideal_node(n, ptadr);
3560   return ptadr;
3561 }
3562 
3563 void ConnectionGraph::add_field(Node *n, PointsToNode::EscapeState es, int offset) {
3564   PointsToNode* ptadr = _nodes.at(n->_idx);
3565   if (ptadr != nullptr) {
3566     assert(ptadr->is_Field() && ptadr->ideal_node() == n, "sanity");
3567     return;
3568   }
3569   bool unsafe = false;
3570   bool is_oop = is_oop_field(n, offset, &unsafe);
3571   if (unsafe) {
3572     es = PointsToNode::GlobalEscape;
3573   }
3574   Compile* C = _compile;
3575   FieldNode* field = new (C->comp_arena()) FieldNode(this, n, es, offset, is_oop);
3576   map_ideal_node(n, field);
3577 }
3578 
3579 void ConnectionGraph::add_arraycopy(Node *n, PointsToNode::EscapeState es,
3580                                     PointsToNode* src, PointsToNode* dst) {
3581   assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
3582   assert((src != null_obj) && (dst != null_obj), "not for ConP null");
3583   PointsToNode* ptadr = _nodes.at(n->_idx);
3584   if (ptadr != nullptr) {
3585     assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
3586     return;
3587   }
3588   Compile* C = _compile;
3589   ptadr = new (C->comp_arena()) ArraycopyNode(this, n, es);
3590   map_ideal_node(n, ptadr);
3591   // Add edge from arraycopy node to source object.
3592   (void)add_edge(ptadr, src);
3593   src->set_arraycopy_src();
3594   // Add edge from destination object to arraycopy node.
3595   (void)add_edge(dst, ptadr);
3596   dst->set_arraycopy_dst();
3597 }
3598 
3599 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
3600   const Type* adr_type = n->as_AddP()->bottom_type();
3601   int field_offset = adr_type->isa_aryptr() ? adr_type->isa_aryptr()->field_offset().get() : Type::OffsetBot;
3602   BasicType bt = T_INT;
3603   if (offset == Type::OffsetBot && field_offset == Type::OffsetBot) {
3604     // Check only oop fields.
3605     if (!adr_type->isa_aryptr() ||
3606         adr_type->isa_aryptr()->elem() == Type::BOTTOM ||
3607         adr_type->isa_aryptr()->elem()->make_oopptr() != nullptr) {
3608       // OffsetBot is used to reference array's element. Ignore first AddP.
3609       if (find_second_addp(n, n->in(AddPNode::Base)) == nullptr) {
3610         bt = T_OBJECT;
3611       }
3612     }
3613   } else if (offset != oopDesc::klass_offset_in_bytes()) {
3614     if (adr_type->isa_instptr()) {
3615       ciField* field = _compile->alias_type(adr_type->is_ptr())->field();
3616       if (field != nullptr) {
3617         bt = field->layout_type();
3618       } else {
3619         // Check for unsafe oop field access
3620         if (n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3621             n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3622             n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3623             BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n)) {
3624           bt = T_OBJECT;
3625           (*unsafe) = true;
3626         }
3627       }
3628     } else if (adr_type->isa_aryptr()) {
3629       if (offset == arrayOopDesc::length_offset_in_bytes()) {
3630         // Ignore array length load.
3631       } else if (find_second_addp(n, n->in(AddPNode::Base)) != nullptr) {
3632         // Ignore first AddP.
3633       } else {
3634         const Type* elemtype = adr_type->is_aryptr()->elem();
3635         if (adr_type->is_aryptr()->is_flat() && field_offset != Type::OffsetBot) {
3636           ciInlineKlass* vk = elemtype->inline_klass();
3637           field_offset += vk->payload_offset();
3638           ciField* field = vk->get_field_by_offset(field_offset, false);
3639           if (field != nullptr) {
3640             bt = field->layout_type();
3641           } else {
3642             assert(field_offset == vk->payload_offset() + vk->null_marker_offset_in_payload(), "no field or null marker of %s at offset %d", vk->name()->as_utf8(), field_offset);
3643             bt = T_BOOLEAN;
3644           }
3645         } else {
3646           bt = elemtype->array_element_basic_type();
3647         }
3648       }
3649     } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
3650       // Allocation initialization, ThreadLocal field access, unsafe access
3651       if (n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3652           n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3653           n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3654           BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n)) {
3655         bt = T_OBJECT;
3656       }
3657     }
3658   }
3659   // Note: T_NARROWOOP is not classed as a real reference type
3660   return (is_reference_type(bt) || bt == T_NARROWOOP);
3661 }
3662 
3663 // Returns unique pointed java object or null.
3664 JavaObjectNode* ConnectionGraph::unique_java_object(Node *n) const {
3665   // If the node was created after the escape computation we can't answer.
3666   uint idx = n->_idx;
3667   if (idx >= nodes_size()) {
3668     return nullptr;
3669   }
3670   PointsToNode* ptn = ptnode_adr(idx);
3671   if (ptn == nullptr) {
3672     return nullptr;
3673   }
3674   if (ptn->is_JavaObject()) {
3675     return ptn->as_JavaObject();
3676   }
3677   assert(ptn->is_LocalVar(), "sanity");
3678   // Check all java objects it points to.
3679   JavaObjectNode* jobj = nullptr;
3680   for (EdgeIterator i(ptn); i.has_next(); i.next()) {
3681     PointsToNode* e = i.get();
3682     if (e->is_JavaObject()) {
3683       if (jobj == nullptr) {
3684         jobj = e->as_JavaObject();
3685       } else if (jobj != e) {
3686         return nullptr;
3687       }
3688     }
3689   }
3690   return jobj;
3691 }
3692 
3693 // Return true if this node points only to non-escaping allocations.
3694 bool PointsToNode::non_escaping_allocation() {
3695   if (is_JavaObject()) {
3696     Node* n = ideal_node();
3697     if (n->is_Allocate() || n->is_CallStaticJava()) {
3698       return (escape_state() == PointsToNode::NoEscape);
3699     } else {
3700       return false;
3701     }
3702   }
3703   assert(is_LocalVar(), "sanity");
3704   // Check all java objects it points to.
3705   for (EdgeIterator i(this); i.has_next(); i.next()) {
3706     PointsToNode* e = i.get();
3707     if (e->is_JavaObject()) {
3708       Node* n = e->ideal_node();
3709       if ((e->escape_state() != PointsToNode::NoEscape) ||
3710           !(n->is_Allocate() || n->is_CallStaticJava())) {
3711         return false;
3712       }
3713     }
3714   }
3715   return true;
3716 }
3717 
3718 // Return true if we know the node does not escape globally.
3719 bool ConnectionGraph::not_global_escape(Node *n) {
3720   assert(!_collecting, "should not call during graph construction");
3721   // If the node was created after the escape computation we can't answer.
3722   uint idx = n->_idx;
3723   if (idx >= nodes_size()) {
3724     return false;
3725   }
3726   PointsToNode* ptn = ptnode_adr(idx);
3727   if (ptn == nullptr) {
3728     return false; // not in congraph (e.g. ConI)
3729   }
3730   PointsToNode::EscapeState es = ptn->escape_state();
3731   // If we have already computed a value, return it.
3732   if (es >= PointsToNode::GlobalEscape) {
3733     return false;
3734   }
3735   if (ptn->is_JavaObject()) {
3736     return true; // (es < PointsToNode::GlobalEscape);
3737   }
3738   assert(ptn->is_LocalVar(), "sanity");
3739   // Check all java objects it points to.
3740   for (EdgeIterator i(ptn); i.has_next(); i.next()) {
3741     if (i.get()->escape_state() >= PointsToNode::GlobalEscape) {
3742       return false;
3743     }
3744   }
3745   return true;
3746 }
3747 
3748 // Return true if locked object does not escape globally
3749 // and locked code region (identified by BoxLockNode) is balanced:
3750 // all compiled code paths have corresponding Lock/Unlock pairs.
3751 bool ConnectionGraph::can_eliminate_lock(AbstractLockNode* alock) {
3752   if (alock->is_balanced() && not_global_escape(alock->obj_node())) {
3753     if (EliminateNestedLocks) {
3754       // We can mark whole locking region as Local only when only
3755       // one object is used for locking.
3756       alock->box_node()->as_BoxLock()->set_local();
3757     }
3758     return true;
3759   }
3760   return false;
3761 }
3762 
3763 // Helper functions
3764 
3765 // Return true if this node points to specified node or nodes it points to.
3766 bool PointsToNode::points_to(JavaObjectNode* ptn) const {
3767   if (is_JavaObject()) {
3768     return (this == ptn);
3769   }
3770   assert(is_LocalVar() || is_Field(), "sanity");
3771   for (EdgeIterator i(this); i.has_next(); i.next()) {
3772     if (i.get() == ptn) {
3773       return true;
3774     }
3775   }
3776   return false;
3777 }
3778 
3779 // Return true if one node points to an other.
3780 bool PointsToNode::meet(PointsToNode* ptn) {
3781   if (this == ptn) {
3782     return true;
3783   } else if (ptn->is_JavaObject()) {
3784     return this->points_to(ptn->as_JavaObject());
3785   } else if (this->is_JavaObject()) {
3786     return ptn->points_to(this->as_JavaObject());
3787   }
3788   assert(this->is_LocalVar() && ptn->is_LocalVar(), "sanity");
3789   int ptn_count =  ptn->edge_count();
3790   for (EdgeIterator i(this); i.has_next(); i.next()) {
3791     PointsToNode* this_e = i.get();
3792     for (int j = 0; j < ptn_count; j++) {
3793       if (this_e == ptn->edge(j)) {
3794         return true;
3795       }
3796     }
3797   }
3798   return false;
3799 }
3800 
3801 #ifdef ASSERT
3802 // Return true if bases point to this java object.
3803 bool FieldNode::has_base(JavaObjectNode* jobj) const {
3804   for (BaseIterator i(this); i.has_next(); i.next()) {
3805     if (i.get() == jobj) {
3806       return true;
3807     }
3808   }
3809   return false;
3810 }
3811 #endif
3812 
3813 bool ConnectionGraph::is_captured_store_address(Node* addp) {
3814   // Handle simple case first.
3815   assert(_igvn->type(addp)->isa_oopptr() == nullptr, "should be raw access");
3816   if (addp->in(AddPNode::Address)->is_Proj() && addp->in(AddPNode::Address)->in(0)->is_Allocate()) {
3817     return true;
3818   } else if (addp->in(AddPNode::Address)->is_Phi()) {
3819     for (DUIterator_Fast imax, i = addp->fast_outs(imax); i < imax; i++) {
3820       Node* addp_use = addp->fast_out(i);
3821       if (addp_use->is_Store()) {
3822         for (DUIterator_Fast jmax, j = addp_use->fast_outs(jmax); j < jmax; j++) {
3823           if (addp_use->fast_out(j)->is_Initialize()) {
3824             return true;
3825           }
3826         }
3827       }
3828     }
3829   }
3830   return false;
3831 }
3832 
3833 int ConnectionGraph::address_offset(Node* adr, PhaseValues* phase) {
3834   const Type *adr_type = phase->type(adr);
3835   if (adr->is_AddP() && adr_type->isa_oopptr() == nullptr && is_captured_store_address(adr)) {
3836     // We are computing a raw address for a store captured by an Initialize
3837     // compute an appropriate address type. AddP cases #3 and #5 (see below).
3838     int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
3839     assert(offs != Type::OffsetBot ||
3840            adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
3841            "offset must be a constant or it is initialization of array");
3842     return offs;
3843   }
3844   return adr_type->is_ptr()->flat_offset();
3845 }
3846 
3847 Node* ConnectionGraph::get_addp_base(Node *addp) {
3848   assert(addp->is_AddP(), "must be AddP");
3849   //
3850   // AddP cases for Base and Address inputs:
3851   // case #1. Direct object's field reference:
3852   //     Allocate
3853   //       |
3854   //     Proj #5 ( oop result )
3855   //       |
3856   //     CheckCastPP (cast to instance type)
3857   //      | |
3858   //     AddP  ( base == address )
3859   //
3860   // case #2. Indirect object's field reference:
3861   //      Phi
3862   //       |
3863   //     CastPP (cast to instance type)
3864   //      | |
3865   //     AddP  ( base == address )
3866   //
3867   // case #3. Raw object's field reference for Initialize node:
3868   //      Allocate
3869   //        |
3870   //      Proj #5 ( oop result )
3871   //  top   |
3872   //     \  |
3873   //     AddP  ( base == top )
3874   //
3875   // case #4. Array's element reference:
3876   //   {CheckCastPP | CastPP}
3877   //     |  | |
3878   //     |  AddP ( array's element offset )
3879   //     |  |
3880   //     AddP ( array's offset )
3881   //
3882   // case #5. Raw object's field reference for arraycopy stub call:
3883   //          The inline_native_clone() case when the arraycopy stub is called
3884   //          after the allocation before Initialize and CheckCastPP nodes.
3885   //      Allocate
3886   //        |
3887   //      Proj #5 ( oop result )
3888   //       | |
3889   //       AddP  ( base == address )
3890   //
3891   // case #6. Constant Pool, ThreadLocal, CastX2P or
3892   //          Raw object's field reference:
3893   //      {ConP, ThreadLocal, CastX2P, raw Load}
3894   //  top   |
3895   //     \  |
3896   //     AddP  ( base == top )
3897   //
3898   // case #7. Klass's field reference.
3899   //      LoadKlass
3900   //       | |
3901   //       AddP  ( base == address )
3902   //
3903   // case #8. narrow Klass's field reference.
3904   //      LoadNKlass
3905   //       |
3906   //      DecodeN
3907   //       | |
3908   //       AddP  ( base == address )
3909   //
3910   // case #9. Mixed unsafe access
3911   //    {instance}
3912   //        |
3913   //      CheckCastPP (raw)
3914   //  top   |
3915   //     \  |
3916   //     AddP  ( base == top )
3917   //
3918   Node *base = addp->in(AddPNode::Base);
3919   if (base->uncast()->is_top()) { // The AddP case #3 and #6 and #9.
3920     base = addp->in(AddPNode::Address);
3921     while (base->is_AddP()) {
3922       // Case #6 (unsafe access) may have several chained AddP nodes.
3923       assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
3924       base = base->in(AddPNode::Address);
3925     }
3926     if (base->Opcode() == Op_CheckCastPP &&
3927         base->bottom_type()->isa_rawptr() &&
3928         _igvn->type(base->in(1))->isa_oopptr()) {
3929       base = base->in(1); // Case #9
3930     } else {
3931       Node* uncast_base = base->uncast();
3932       int opcode = uncast_base->Opcode();
3933       assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
3934              opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() ||
3935              (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_rawptr() != nullptr)) ||
3936              is_captured_store_address(addp), "sanity");
3937     }
3938   }
3939   return base;
3940 }
3941 
3942 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
3943   assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
3944   Node* addp2 = addp->raw_out(0);
3945   if (addp->outcnt() == 1 && addp2->is_AddP() &&
3946       addp2->in(AddPNode::Base) == n &&
3947       addp2->in(AddPNode::Address) == addp) {
3948     assert(addp->in(AddPNode::Base) == n, "expecting the same base");
3949     //
3950     // Find array's offset to push it on worklist first and
3951     // as result process an array's element offset first (pushed second)
3952     // to avoid CastPP for the array's offset.
3953     // Otherwise the inserted CastPP (LocalVar) will point to what
3954     // the AddP (Field) points to. Which would be wrong since
3955     // the algorithm expects the CastPP has the same point as
3956     // as AddP's base CheckCastPP (LocalVar).
3957     //
3958     //    ArrayAllocation
3959     //     |
3960     //    CheckCastPP
3961     //     |
3962     //    memProj (from ArrayAllocation CheckCastPP)
3963     //     |  ||
3964     //     |  ||   Int (element index)
3965     //     |  ||    |   ConI (log(element size))
3966     //     |  ||    |   /
3967     //     |  ||   LShift
3968     //     |  ||  /
3969     //     |  AddP (array's element offset)
3970     //     |  |
3971     //     |  | ConI (array's offset: #12(32-bits) or #24(64-bits))
3972     //     | / /
3973     //     AddP (array's offset)
3974     //      |
3975     //     Load/Store (memory operation on array's element)
3976     //
3977     return addp2;
3978   }
3979   return nullptr;
3980 }
3981 
3982 //
3983 // Adjust the type and inputs of an AddP which computes the
3984 // address of a field of an instance
3985 //
3986 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
3987   PhaseGVN* igvn = _igvn;
3988   const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
3989   assert(base_t != nullptr && base_t->is_known_instance(), "expecting instance oopptr");
3990   const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
3991   if (t == nullptr) {
3992     // We are computing a raw address for a store captured by an Initialize
3993     // compute an appropriate address type (cases #3 and #5).
3994     assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
3995     assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
3996     intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
3997     assert(offs != Type::OffsetBot, "offset must be a constant");
3998     if (base_t->isa_aryptr() != nullptr) {
3999       // In the case of a flat inline type array, each field has its
4000       // own slice so we need to extract the field being accessed from
4001       // the address computation
4002       t = base_t->isa_aryptr()->add_field_offset_and_offset(offs)->is_oopptr();
4003     } else {
4004       t = base_t->add_offset(offs)->is_oopptr();
4005     }
4006   }
4007   int inst_id = base_t->instance_id();
4008   assert(!t->is_known_instance() || t->instance_id() == inst_id,
4009                              "old type must be non-instance or match new type");
4010 
4011   // The type 't' could be subclass of 'base_t'.
4012   // As result t->offset() could be large then base_t's size and it will
4013   // cause the failure in add_offset() with narrow oops since TypeOopPtr()
4014   // constructor verifies correctness of the offset.
4015   //
4016   // It could happened on subclass's branch (from the type profiling
4017   // inlining) which was not eliminated during parsing since the exactness
4018   // of the allocation type was not propagated to the subclass type check.
4019   //
4020   // Or the type 't' could be not related to 'base_t' at all.
4021   // It could happen when CHA type is different from MDO type on a dead path
4022   // (for example, from instanceof check) which is not collapsed during parsing.
4023   //
4024   // Do nothing for such AddP node and don't process its users since
4025   // this code branch will go away.
4026   //
4027   if (!t->is_known_instance() &&
4028       !base_t->maybe_java_subtype_of(t)) {
4029      return false; // bail out
4030   }
4031   const TypePtr* tinst = base_t->add_offset(t->offset());
4032   if (tinst->isa_aryptr() && t->isa_aryptr()) {
4033     // In the case of a flat inline type array, each field has its
4034     // own slice so we need to keep track of the field being accessed.
4035     tinst = tinst->is_aryptr()->with_field_offset(t->is_aryptr()->field_offset().get());
4036     // Keep array properties (not flat/null-free)
4037     tinst = tinst->is_aryptr()->update_properties(t->is_aryptr());
4038     if (tinst == nullptr) {
4039       return false; // Skip dead path with inconsistent properties
4040     }
4041   }
4042 
4043   // Do NOT remove the next line: ensure a new alias index is allocated
4044   // for the instance type. Note: C++ will not remove it since the call
4045   // has side effect.
4046   int alias_idx = _compile->get_alias_index(tinst);
4047   igvn->set_type(addp, tinst);
4048   // record the allocation in the node map
4049   set_map(addp, get_map(base->_idx));
4050   // Set addp's Base and Address to 'base'.
4051   Node *abase = addp->in(AddPNode::Base);
4052   Node *adr   = addp->in(AddPNode::Address);
4053   if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
4054       adr->in(0)->_idx == (uint)inst_id) {
4055     // Skip AddP cases #3 and #5.
4056   } else {
4057     assert(!abase->is_top(), "sanity"); // AddP case #3
4058     if (abase != base) {
4059       igvn->hash_delete(addp);
4060       addp->set_req(AddPNode::Base, base);
4061       if (abase == adr) {
4062         addp->set_req(AddPNode::Address, base);
4063       } else {
4064         // AddP case #4 (adr is array's element offset AddP node)
4065 #ifdef ASSERT
4066         const TypeOopPtr *atype = igvn->type(adr)->isa_oopptr();
4067         assert(adr->is_AddP() && atype != nullptr &&
4068                atype->instance_id() == inst_id, "array's element offset should be processed first");
4069 #endif
4070       }
4071       igvn->hash_insert(addp);
4072     }
4073   }
4074   // Put on IGVN worklist since at least addp's type was changed above.
4075   record_for_optimizer(addp);
4076   return true;
4077 }
4078 
4079 //
4080 // Create a new version of orig_phi if necessary. Returns either the newly
4081 // created phi or an existing phi.  Sets create_new to indicate whether a new
4082 // phi was created.  Cache the last newly created phi in the node map.
4083 //
4084 PhiNode *ConnectionGraph::create_split_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *>  &orig_phi_worklist, bool &new_created) {
4085   Compile *C = _compile;
4086   PhaseGVN* igvn = _igvn;
4087   new_created = false;
4088   int phi_alias_idx = C->get_alias_index(orig_phi->adr_type());
4089   // nothing to do if orig_phi is bottom memory or matches alias_idx
4090   if (phi_alias_idx == alias_idx) {
4091     return orig_phi;
4092   }
4093   // Have we recently created a Phi for this alias index?
4094   PhiNode *result = get_map_phi(orig_phi->_idx);
4095   if (result != nullptr && C->get_alias_index(result->adr_type()) == alias_idx) {
4096     return result;
4097   }
4098   // Previous check may fail when the same wide memory Phi was split into Phis
4099   // for different memory slices. Search all Phis for this region.
4100   if (result != nullptr) {
4101     Node* region = orig_phi->in(0);
4102     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
4103       Node* phi = region->fast_out(i);
4104       if (phi->is_Phi() &&
4105           C->get_alias_index(phi->as_Phi()->adr_type()) == alias_idx) {
4106         assert(phi->_idx >= nodes_size(), "only new Phi per instance memory slice");
4107         return phi->as_Phi();
4108       }
4109     }
4110   }
4111   if (C->live_nodes() + 2*NodeLimitFudgeFactor > C->max_node_limit()) {
4112     if (C->do_escape_analysis() == true && !C->failing()) {
4113       // Retry compilation without escape analysis.
4114       // If this is the first failure, the sentinel string will "stick"
4115       // to the Compile object, and the C2Compiler will see it and retry.
4116       C->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4117     }
4118     return nullptr;
4119   }
4120   orig_phi_worklist.append_if_missing(orig_phi);
4121   const TypePtr *atype = C->get_adr_type(alias_idx);
4122   result = PhiNode::make(orig_phi->in(0), nullptr, Type::MEMORY, atype);
4123   C->copy_node_notes_to(result, orig_phi);
4124   igvn->set_type(result, result->bottom_type());
4125   record_for_optimizer(result);
4126   set_map(orig_phi, result);
4127   new_created = true;
4128   return result;
4129 }
4130 
4131 //
4132 // Return a new version of Memory Phi "orig_phi" with the inputs having the
4133 // specified alias index.
4134 //
4135 PhiNode *ConnectionGraph::split_memory_phi(PhiNode *orig_phi, int alias_idx, GrowableArray<PhiNode *> &orig_phi_worklist, uint rec_depth) {
4136   assert(alias_idx != Compile::AliasIdxBot, "can't split out bottom memory");
4137   Compile *C = _compile;
4138   PhaseGVN* igvn = _igvn;
4139   bool new_phi_created;
4140   PhiNode *result = create_split_phi(orig_phi, alias_idx, orig_phi_worklist, new_phi_created);
4141   if (!new_phi_created) {
4142     return result;
4143   }
4144   GrowableArray<PhiNode *>  phi_list;
4145   GrowableArray<uint>  cur_input;
4146   PhiNode *phi = orig_phi;
4147   uint idx = 1;
4148   bool finished = false;
4149   while(!finished) {
4150     while (idx < phi->req()) {
4151       Node *mem = find_inst_mem(phi->in(idx), alias_idx, orig_phi_worklist, rec_depth + 1);
4152       if (mem != nullptr && mem->is_Phi()) {
4153         PhiNode *newphi = create_split_phi(mem->as_Phi(), alias_idx, orig_phi_worklist, new_phi_created);
4154         if (new_phi_created) {
4155           // found an phi for which we created a new split, push current one on worklist and begin
4156           // processing new one
4157           phi_list.push(phi);
4158           cur_input.push(idx);
4159           phi = mem->as_Phi();
4160           result = newphi;
4161           idx = 1;
4162           continue;
4163         } else {
4164           mem = newphi;
4165         }
4166       }
4167       if (C->failing()) {
4168         return nullptr;
4169       }
4170       result->set_req(idx++, mem);
4171     }
4172 #ifdef ASSERT
4173     // verify that the new Phi has an input for each input of the original
4174     assert( phi->req() == result->req(), "must have same number of inputs.");
4175     assert( result->in(0) != nullptr && result->in(0) == phi->in(0), "regions must match");
4176 #endif
4177     // Check if all new phi's inputs have specified alias index.
4178     // Otherwise use old phi.
4179     for (uint i = 1; i < phi->req(); i++) {
4180       Node* in = result->in(i);
4181       assert((phi->in(i) == nullptr) == (in == nullptr), "inputs must correspond.");
4182     }
4183     // we have finished processing a Phi, see if there are any more to do
4184     finished = (phi_list.length() == 0 );
4185     if (!finished) {
4186       phi = phi_list.pop();
4187       idx = cur_input.pop();
4188       PhiNode *prev_result = get_map_phi(phi->_idx);
4189       prev_result->set_req(idx++, result);
4190       result = prev_result;
4191     }
4192   }
4193   return result;
4194 }
4195 
4196 //
4197 // The next methods are derived from methods in MemNode.
4198 //
4199 Node* ConnectionGraph::step_through_mergemem(MergeMemNode *mmem, int alias_idx, const TypeOopPtr *toop) {
4200   Node *mem = mmem;
4201   // TypeOopPtr::NOTNULL+any is an OOP with unknown offset - generally
4202   // means an array I have not precisely typed yet.  Do not do any
4203   // alias stuff with it any time soon.
4204   if (toop->base() != Type::AnyPtr &&
4205       !(toop->isa_instptr() &&
4206         toop->is_instptr()->instance_klass()->is_java_lang_Object() &&
4207         toop->offset() == Type::OffsetBot)) {
4208     mem = mmem->memory_at(alias_idx);
4209     // Update input if it is progress over what we have now
4210   }
4211   return mem;
4212 }
4213 
4214 //
4215 // Move memory users to their memory slices.
4216 //
4217 void ConnectionGraph::move_inst_mem(Node* n, GrowableArray<PhiNode *>  &orig_phis) {
4218   Compile* C = _compile;
4219   PhaseGVN* igvn = _igvn;
4220   const TypePtr* tp = igvn->type(n->in(MemNode::Address))->isa_ptr();
4221   assert(tp != nullptr, "ptr type");
4222   int alias_idx = C->get_alias_index(tp);
4223   int general_idx = C->get_general_index(alias_idx);
4224 
4225   // Move users first
4226   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4227     Node* use = n->fast_out(i);
4228     if (use->is_MergeMem()) {
4229       MergeMemNode* mmem = use->as_MergeMem();
4230       assert(n == mmem->memory_at(alias_idx), "should be on instance memory slice");
4231       if (n != mmem->memory_at(general_idx) || alias_idx == general_idx) {
4232         continue; // Nothing to do
4233       }
4234       // Replace previous general reference to mem node.
4235       uint orig_uniq = C->unique();
4236       Node* m = find_inst_mem(n, general_idx, orig_phis);
4237       assert(orig_uniq == C->unique(), "no new nodes");
4238       mmem->set_memory_at(general_idx, m);
4239       --imax;
4240       --i;
4241     } else if (use->is_MemBar()) {
4242       assert(!use->is_Initialize(), "initializing stores should not be moved");
4243       if (use->req() > MemBarNode::Precedent &&
4244           use->in(MemBarNode::Precedent) == n) {
4245         // Don't move related membars.
4246         record_for_optimizer(use);
4247         continue;
4248       }
4249       tp = use->as_MemBar()->adr_type()->isa_ptr();
4250       if ((tp != nullptr && C->get_alias_index(tp) == alias_idx) ||
4251           alias_idx == general_idx) {
4252         continue; // Nothing to do
4253       }
4254       // Move to general memory slice.
4255       uint orig_uniq = C->unique();
4256       Node* m = find_inst_mem(n, general_idx, orig_phis);
4257       assert(orig_uniq == C->unique(), "no new nodes");
4258       igvn->hash_delete(use);
4259       imax -= use->replace_edge(n, m, igvn);
4260       igvn->hash_insert(use);
4261       record_for_optimizer(use);
4262       --i;
4263 #ifdef ASSERT
4264     } else if (use->is_Mem()) {
4265       // Memory nodes should have new memory input.
4266       tp = igvn->type(use->in(MemNode::Address))->isa_ptr();
4267       assert(tp != nullptr, "ptr type");
4268       int idx = C->get_alias_index(tp);
4269       assert(get_map(use->_idx) != nullptr || idx == alias_idx,
4270              "Following memory nodes should have new memory input or be on the same memory slice");
4271     } else if (use->is_Phi()) {
4272       // Phi nodes should be split and moved already.
4273       tp = use->as_Phi()->adr_type()->isa_ptr();
4274       assert(tp != nullptr, "ptr type");
4275       int idx = C->get_alias_index(tp);
4276       assert(idx == alias_idx, "Following Phi nodes should be on the same memory slice");
4277     } else {
4278       use->dump();
4279       assert(false, "should not be here");
4280 #endif
4281     }
4282   }
4283 }
4284 
4285 //
4286 // Search memory chain of "mem" to find a MemNode whose address
4287 // is the specified alias index.
4288 //
4289 #define FIND_INST_MEM_RECURSION_DEPTH_LIMIT 1000
4290 Node* ConnectionGraph::find_inst_mem(Node *orig_mem, int alias_idx, GrowableArray<PhiNode *>  &orig_phis, uint rec_depth) {
4291   if (rec_depth > FIND_INST_MEM_RECURSION_DEPTH_LIMIT) {
4292     _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4293     return nullptr;
4294   }
4295   if (orig_mem == nullptr) {
4296     return orig_mem;
4297   }
4298   Compile* C = _compile;
4299   PhaseGVN* igvn = _igvn;
4300   const TypeOopPtr *toop = C->get_adr_type(alias_idx)->isa_oopptr();
4301   bool is_instance = (toop != nullptr) && toop->is_known_instance();
4302   Node *start_mem = C->start()->proj_out_or_null(TypeFunc::Memory);
4303   Node *prev = nullptr;
4304   Node *result = orig_mem;
4305   while (prev != result) {
4306     prev = result;
4307     if (result == start_mem) {
4308       break;  // hit one of our sentinels
4309     }
4310     if (result->is_Mem()) {
4311       const Type *at = igvn->type(result->in(MemNode::Address));
4312       if (at == Type::TOP) {
4313         break; // Dead
4314       }
4315       assert (at->isa_ptr() != nullptr, "pointer type required.");
4316       int idx = C->get_alias_index(at->is_ptr());
4317       if (idx == alias_idx) {
4318         break; // Found
4319       }
4320       if (!is_instance && (at->isa_oopptr() == nullptr ||
4321                            !at->is_oopptr()->is_known_instance())) {
4322         break; // Do not skip store to general memory slice.
4323       }
4324       result = result->in(MemNode::Memory);
4325     }
4326     if (!is_instance) {
4327       continue;  // don't search further for non-instance types
4328     }
4329     // skip over a call which does not affect this memory slice
4330     if (result->is_Proj() && result->as_Proj()->_con == TypeFunc::Memory) {
4331       Node *proj_in = result->in(0);
4332       if (proj_in->is_Allocate() && proj_in->_idx == (uint)toop->instance_id()) {
4333         break;  // hit one of our sentinels
4334       } else if (proj_in->is_Call()) {
4335         // ArrayCopy node processed here as well
4336         CallNode *call = proj_in->as_Call();
4337         if (!call->may_modify(toop, igvn)) {
4338           result = call->in(TypeFunc::Memory);
4339         }
4340       } else if (proj_in->is_Initialize()) {
4341         AllocateNode* alloc = proj_in->as_Initialize()->allocation();
4342         // Stop if this is the initialization for the object instance which
4343         // which contains this memory slice, otherwise skip over it.
4344         if (alloc == nullptr || alloc->_idx != (uint)toop->instance_id()) {
4345           result = proj_in->in(TypeFunc::Memory);
4346 #if 0  // TODO: Fix 8372259
4347         } else if (C->get_alias_index(result->adr_type()) != alias_idx) {
4348           assert(C->get_general_index(alias_idx) == C->get_alias_index(result->adr_type()), "should be projection for the same field/array element");
4349           result = get_map(result->_idx);
4350           assert(result != nullptr, "new projection should have been allocated");
4351           break;
4352         }
4353 #else
4354         }
4355 #endif
4356       } else if (proj_in->is_MemBar()) {
4357         // Check if there is an array copy for a clone
4358         // Step over GC barrier when ReduceInitialCardMarks is disabled
4359         BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4360         Node* control_proj_ac = bs->step_over_gc_barrier(proj_in->in(0));
4361 
4362         if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) {
4363           // Stop if it is a clone
4364           ArrayCopyNode* ac = control_proj_ac->in(0)->as_ArrayCopy();
4365           if (ac->may_modify(toop, igvn)) {
4366             break;
4367           }
4368         }
4369         result = proj_in->in(TypeFunc::Memory);
4370       }
4371     } else if (result->is_MergeMem()) {
4372       MergeMemNode *mmem = result->as_MergeMem();
4373       result = step_through_mergemem(mmem, alias_idx, toop);
4374       if (result == mmem->base_memory()) {
4375         // Didn't find instance memory, search through general slice recursively.
4376         result = mmem->memory_at(C->get_general_index(alias_idx));
4377         result = find_inst_mem(result, alias_idx, orig_phis, rec_depth + 1);
4378         if (C->failing()) {
4379           return nullptr;
4380         }
4381         mmem->set_memory_at(alias_idx, result);
4382       }
4383     } else if (result->is_Phi() &&
4384                C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
4385       Node *un = result->as_Phi()->unique_input(igvn);
4386       if (un != nullptr) {
4387         orig_phis.append_if_missing(result->as_Phi());
4388         result = un;
4389       } else {
4390         break;
4391       }
4392     } else if (result->is_ClearArray()) {
4393       if (!ClearArrayNode::step_through(&result, (uint)toop->instance_id(), igvn)) {
4394         // Can not bypass initialization of the instance
4395         // we are looking for.
4396         break;
4397       }
4398       // Otherwise skip it (the call updated 'result' value).
4399     } else if (result->Opcode() == Op_SCMemProj) {
4400       Node* mem = result->in(0);
4401       Node* adr = nullptr;
4402       if (mem->is_LoadStore()) {
4403         adr = mem->in(MemNode::Address);
4404       } else {
4405         assert(mem->Opcode() == Op_EncodeISOArray ||
4406                mem->Opcode() == Op_StrCompressedCopy, "sanity");
4407         adr = mem->in(3); // Memory edge corresponds to destination array
4408       }
4409       const Type *at = igvn->type(adr);
4410       if (at != Type::TOP) {
4411         assert(at->isa_ptr() != nullptr, "pointer type required.");
4412         int idx = C->get_alias_index(at->is_ptr());
4413         if (idx == alias_idx) {
4414           // Assert in debug mode
4415           assert(false, "Object is not scalar replaceable if a LoadStore node accesses its field");
4416           break; // In product mode return SCMemProj node
4417         }
4418       }
4419       result = mem->in(MemNode::Memory);
4420     } else if (result->Opcode() == Op_StrInflatedCopy) {
4421       Node* adr = result->in(3); // Memory edge corresponds to destination array
4422       const Type *at = igvn->type(adr);
4423       if (at != Type::TOP) {
4424         assert(at->isa_ptr() != nullptr, "pointer type required.");
4425         int idx = C->get_alias_index(at->is_ptr());
4426         if (idx == alias_idx) {
4427           // Assert in debug mode
4428           assert(false, "Object is not scalar replaceable if a StrInflatedCopy node accesses its field");
4429           break; // In product mode return SCMemProj node
4430         }
4431       }
4432       result = result->in(MemNode::Memory);
4433     }
4434   }
4435   if (result->is_Phi()) {
4436     PhiNode *mphi = result->as_Phi();
4437     assert(mphi->bottom_type() == Type::MEMORY, "memory phi required");
4438     const TypePtr *t = mphi->adr_type();
4439     if (!is_instance) {
4440       // Push all non-instance Phis on the orig_phis worklist to update inputs
4441       // during Phase 4 if needed.
4442       orig_phis.append_if_missing(mphi);
4443     } else if (C->get_alias_index(t) != alias_idx) {
4444       // Create a new Phi with the specified alias index type.
4445       result = split_memory_phi(mphi, alias_idx, orig_phis, rec_depth + 1);
4446     }
4447   }
4448   // the result is either MemNode, PhiNode, InitializeNode.
4449   return result;
4450 }
4451 
4452 //
4453 //  Convert the types of non-escaped object to instance types where possible,
4454 //  propagate the new type information through the graph, and update memory
4455 //  edges and MergeMem inputs to reflect the new type.
4456 //
4457 //  We start with allocations (and calls which may be allocations)  on alloc_worklist.
4458 //  The processing is done in 4 phases:
4459 //
4460 //  Phase 1:  Process possible allocations from alloc_worklist.  Create instance
4461 //            types for the CheckCastPP for allocations where possible.
4462 //            Propagate the new types through users as follows:
4463 //               casts and Phi:  push users on alloc_worklist
4464 //               AddP:  cast Base and Address inputs to the instance type
4465 //                      push any AddP users on alloc_worklist and push any memnode
4466 //                      users onto memnode_worklist.
4467 //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
4468 //            search the Memory chain for a store with the appropriate type
4469 //            address type.  If a Phi is found, create a new version with
4470 //            the appropriate memory slices from each of the Phi inputs.
4471 //            For stores, process the users as follows:
4472 //               MemNode:  push on memnode_worklist
4473 //               MergeMem: push on mergemem_worklist
4474 //  Phase 3:  Process MergeMem nodes from mergemem_worklist.  Walk each memory slice
4475 //            moving the first node encountered of each  instance type to the
4476 //            the input corresponding to its alias index.
4477 //            appropriate memory slice.
4478 //  Phase 4:  Update the inputs of non-instance memory Phis and the Memory input of memnodes.
4479 //
4480 // In the following example, the CheckCastPP nodes are the cast of allocation
4481 // results and the allocation of node 29 is non-escaped and eligible to be an
4482 // instance type.
4483 //
4484 // We start with:
4485 //
4486 //     7 Parm #memory
4487 //    10  ConI  "12"
4488 //    19  CheckCastPP   "Foo"
4489 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
4490 //    29  CheckCastPP   "Foo"
4491 //    30  AddP  _ 29 29 10  Foo+12  alias_index=4
4492 //
4493 //    40  StoreP  25   7  20   ... alias_index=4
4494 //    50  StoreP  35  40  30   ... alias_index=4
4495 //    60  StoreP  45  50  20   ... alias_index=4
4496 //    70  LoadP    _  60  30   ... alias_index=4
4497 //    80  Phi     75  50  60   Memory alias_index=4
4498 //    90  LoadP    _  80  30   ... alias_index=4
4499 //   100  LoadP    _  80  20   ... alias_index=4
4500 //
4501 //
4502 // Phase 1 creates an instance type for node 29 assigning it an instance id of 24
4503 // and creating a new alias index for node 30.  This gives:
4504 //
4505 //     7 Parm #memory
4506 //    10  ConI  "12"
4507 //    19  CheckCastPP   "Foo"
4508 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
4509 //    29  CheckCastPP   "Foo"  iid=24
4510 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
4511 //
4512 //    40  StoreP  25   7  20   ... alias_index=4
4513 //    50  StoreP  35  40  30   ... alias_index=6
4514 //    60  StoreP  45  50  20   ... alias_index=4
4515 //    70  LoadP    _  60  30   ... alias_index=6
4516 //    80  Phi     75  50  60   Memory alias_index=4
4517 //    90  LoadP    _  80  30   ... alias_index=6
4518 //   100  LoadP    _  80  20   ... alias_index=4
4519 //
4520 // In phase 2, new memory inputs are computed for the loads and stores,
4521 // And a new version of the phi is created.  In phase 4, the inputs to
4522 // node 80 are updated and then the memory nodes are updated with the
4523 // values computed in phase 2.  This results in:
4524 //
4525 //     7 Parm #memory
4526 //    10  ConI  "12"
4527 //    19  CheckCastPP   "Foo"
4528 //    20  AddP  _ 19 19 10  Foo+12  alias_index=4
4529 //    29  CheckCastPP   "Foo"  iid=24
4530 //    30  AddP  _ 29 29 10  Foo+12  alias_index=6  iid=24
4531 //
4532 //    40  StoreP  25  7   20   ... alias_index=4
4533 //    50  StoreP  35  7   30   ... alias_index=6
4534 //    60  StoreP  45  40  20   ... alias_index=4
4535 //    70  LoadP    _  50  30   ... alias_index=6
4536 //    80  Phi     75  40  60   Memory alias_index=4
4537 //   120  Phi     75  50  50   Memory alias_index=6
4538 //    90  LoadP    _ 120  30   ... alias_index=6
4539 //   100  LoadP    _  80  20   ... alias_index=4
4540 //
4541 void ConnectionGraph::split_unique_types(GrowableArray<Node *>  &alloc_worklist,
4542                                          GrowableArray<ArrayCopyNode*> &arraycopy_worklist,
4543                                          GrowableArray<MergeMemNode*> &mergemem_worklist,
4544                                          Unique_Node_List &reducible_merges) {
4545   DEBUG_ONLY(Unique_Node_List reduced_merges;)
4546   GrowableArray<Node *>  memnode_worklist;
4547   GrowableArray<PhiNode *>  orig_phis;
4548   PhaseIterGVN  *igvn = _igvn;
4549   uint new_index_start = (uint) _compile->num_alias_types();
4550   VectorSet visited;
4551   ideal_nodes.clear(); // Reset for use with set_map/get_map.
4552   uint unique_old = _compile->unique();
4553 
4554   //  Phase 1:  Process possible allocations from alloc_worklist.
4555   //  Create instance types for the CheckCastPP for allocations where possible.
4556   //
4557   // (Note: don't forget to change the order of the second AddP node on
4558   //  the alloc_worklist if the order of the worklist processing is changed,
4559   //  see the comment in find_second_addp().)
4560   //
4561   while (alloc_worklist.length() != 0) {
4562     Node *n = alloc_worklist.pop();
4563     uint ni = n->_idx;
4564     if (n->is_Call()) {
4565       CallNode *alloc = n->as_Call();
4566       // copy escape information to call node
4567       PointsToNode* ptn = ptnode_adr(alloc->_idx);
4568       PointsToNode::EscapeState es = ptn->escape_state();
4569       // We have an allocation or call which returns a Java object,
4570       // see if it is non-escaped.
4571       if (es != PointsToNode::NoEscape || !ptn->scalar_replaceable()) {
4572         continue;
4573       }
4574       // Find CheckCastPP for the allocate or for the return value of a call
4575       n = alloc->result_cast();
4576       if (n == nullptr) {            // No uses except Initialize node
4577         if (alloc->is_Allocate()) {
4578           // Set the scalar_replaceable flag for allocation
4579           // so it could be eliminated if it has no uses.
4580           alloc->as_Allocate()->_is_scalar_replaceable = true;
4581         }
4582         continue;
4583       }
4584       if (!n->is_CheckCastPP()) { // not unique CheckCastPP.
4585         // we could reach here for allocate case if one init is associated with many allocs.
4586         if (alloc->is_Allocate()) {
4587           alloc->as_Allocate()->_is_scalar_replaceable = false;
4588         }
4589         continue;
4590       }
4591 
4592       // The inline code for Object.clone() casts the allocation result to
4593       // java.lang.Object and then to the actual type of the allocated
4594       // object. Detect this case and use the second cast.
4595       // Also detect j.l.reflect.Array.newInstance(jobject, jint) case when
4596       // the allocation result is cast to java.lang.Object and then
4597       // to the actual Array type.
4598       if (alloc->is_Allocate() && n->as_Type()->type() == TypeInstPtr::NOTNULL
4599           && (alloc->is_AllocateArray() ||
4600               igvn->type(alloc->in(AllocateNode::KlassNode)) != TypeInstKlassPtr::OBJECT)) {
4601         Node *cast2 = nullptr;
4602         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4603           Node *use = n->fast_out(i);
4604           if (use->is_CheckCastPP()) {
4605             cast2 = use;
4606             break;
4607           }
4608         }
4609         if (cast2 != nullptr) {
4610           n = cast2;
4611         } else {
4612           // Non-scalar replaceable if the allocation type is unknown statically
4613           // (reflection allocation), the object can't be restored during
4614           // deoptimization without precise type.
4615           continue;
4616         }
4617       }
4618 
4619       const TypeOopPtr *t = igvn->type(n)->isa_oopptr();
4620       if (t == nullptr) {
4621         continue;  // not a TypeOopPtr
4622       }
4623       if (!t->klass_is_exact()) {
4624         continue; // not an unique type
4625       }
4626       if (alloc->is_Allocate()) {
4627         // Set the scalar_replaceable flag for allocation
4628         // so it could be eliminated.
4629         alloc->as_Allocate()->_is_scalar_replaceable = true;
4630       }
4631       set_escape_state(ptnode_adr(n->_idx), es NOT_PRODUCT(COMMA trace_propagate_message(ptn))); // CheckCastPP escape state
4632       // in order for an object to be scalar-replaceable, it must be:
4633       //   - a direct allocation (not a call returning an object)
4634       //   - non-escaping
4635       //   - eligible to be a unique type
4636       //   - not determined to be ineligible by escape analysis
4637       set_map(alloc, n);
4638       set_map(n, alloc);
4639       const TypeOopPtr* tinst = t->cast_to_instance_id(ni);
4640       igvn->hash_delete(n);
4641       igvn->set_type(n,  tinst);
4642       n->raise_bottom_type(tinst);
4643       igvn->hash_insert(n);
4644       record_for_optimizer(n);
4645       // Allocate an alias index for the header fields. Accesses to
4646       // the header emitted during macro expansion wouldn't have
4647       // correct memory state otherwise.
4648       _compile->get_alias_index(tinst->add_offset(oopDesc::mark_offset_in_bytes()));
4649       _compile->get_alias_index(tinst->add_offset(oopDesc::klass_offset_in_bytes()));
4650       if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
4651         // Add a new NarrowMem projection for each existing NarrowMem projection with new adr type
4652         InitializeNode* init = alloc->as_Allocate()->initialization();
4653         assert(init != nullptr, "can't find Initialization node for this Allocate node");
4654         auto process_narrow_proj = [&](NarrowMemProjNode* proj) {
4655           const TypePtr* adr_type = proj->adr_type();
4656           const TypePtr* new_adr_type = tinst->with_offset(adr_type->offset());
4657           if (adr_type->isa_aryptr()) {
4658             // In the case of a flat inline type array, each field has its own slice so we need a
4659             // NarrowMemProj for each field of the flat array elements
4660             new_adr_type = new_adr_type->is_aryptr()->with_field_offset(adr_type->is_aryptr()->field_offset().get());
4661           }
4662           if (adr_type != new_adr_type && !init->already_has_narrow_mem_proj_with_adr_type(new_adr_type)) {
4663             DEBUG_ONLY( uint alias_idx = _compile->get_alias_index(new_adr_type); )
4664             assert(_compile->get_general_index(alias_idx) == _compile->get_alias_index(adr_type), "new adr type should be narrowed down from existing adr type");
4665             NarrowMemProjNode* new_proj = new NarrowMemProjNode(init, new_adr_type);
4666             igvn->set_type(new_proj, new_proj->bottom_type());
4667             record_for_optimizer(new_proj);
4668             set_map(proj, new_proj); // record it so ConnectionGraph::find_inst_mem() can find it
4669           }
4670         };
4671         init->for_each_narrow_mem_proj_with_new_uses(process_narrow_proj);
4672 
4673         // First, put on the worklist all Field edges from Connection Graph
4674         // which is more accurate than putting immediate users from Ideal Graph.
4675         for (EdgeIterator e(ptn); e.has_next(); e.next()) {
4676           PointsToNode* tgt = e.get();
4677           if (tgt->is_Arraycopy()) {
4678             continue;
4679           }
4680           Node* use = tgt->ideal_node();
4681           assert(tgt->is_Field() && use->is_AddP(),
4682                  "only AddP nodes are Field edges in CG");
4683           if (use->outcnt() > 0) { // Don't process dead nodes
4684             Node* addp2 = find_second_addp(use, use->in(AddPNode::Base));
4685             if (addp2 != nullptr) {
4686               assert(alloc->is_AllocateArray(),"array allocation was expected");
4687               alloc_worklist.append_if_missing(addp2);
4688             }
4689             alloc_worklist.append_if_missing(use);
4690           }
4691         }
4692 
4693         // An allocation may have an Initialize which has raw stores. Scan
4694         // the users of the raw allocation result and push AddP users
4695         // on alloc_worklist.
4696         Node *raw_result = alloc->proj_out_or_null(TypeFunc::Parms);
4697         assert (raw_result != nullptr, "must have an allocation result");
4698         for (DUIterator_Fast imax, i = raw_result->fast_outs(imax); i < imax; i++) {
4699           Node *use = raw_result->fast_out(i);
4700           if (use->is_AddP() && use->outcnt() > 0) { // Don't process dead nodes
4701             Node* addp2 = find_second_addp(use, raw_result);
4702             if (addp2 != nullptr) {
4703               assert(alloc->is_AllocateArray(),"array allocation was expected");
4704               alloc_worklist.append_if_missing(addp2);
4705             }
4706             alloc_worklist.append_if_missing(use);
4707           } else if (use->is_MemBar()) {
4708             memnode_worklist.append_if_missing(use);
4709           }
4710         }
4711       }
4712     } else if (n->is_AddP()) {
4713       if (has_reducible_merge_base(n->as_AddP(), reducible_merges)) {
4714         // This AddP will go away when we reduce the Phi
4715         continue;
4716       }
4717       Node* addp_base = get_addp_base(n);
4718       JavaObjectNode* jobj = unique_java_object(addp_base);
4719       if (jobj == nullptr || jobj == phantom_obj) {
4720 #ifdef ASSERT
4721         ptnode_adr(get_addp_base(n)->_idx)->dump();
4722         ptnode_adr(n->_idx)->dump();
4723         assert(jobj != nullptr && jobj != phantom_obj, "escaped allocation");
4724 #endif
4725         _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4726         return;
4727       }
4728       Node *base = get_map(jobj->idx());  // CheckCastPP node
4729       if (!split_AddP(n, base)) continue; // wrong type from dead path
4730     } else if (n->is_Phi() ||
4731                n->is_CheckCastPP() ||
4732                n->is_EncodeP() ||
4733                n->is_DecodeN() ||
4734                (n->is_ConstraintCast() && n->Opcode() == Op_CastPP)) {
4735       if (visited.test_set(n->_idx)) {
4736         assert(n->is_Phi(), "loops only through Phi's");
4737         continue;  // already processed
4738       }
4739       // Reducible Phi's will be removed from the graph after split_unique_types
4740       // finishes. For now we just try to split out the SR inputs of the merge.
4741       Node* parent = n->in(1);
4742       if (reducible_merges.member(n)) {
4743         reduce_phi(n->as_Phi(), alloc_worklist);
4744 #ifdef ASSERT
4745         if (VerifyReduceAllocationMerges) {
4746           reduced_merges.push(n);
4747         }
4748 #endif
4749         continue;
4750       } else if (reducible_merges.member(parent)) {
4751         // 'n' is an user of a reducible merge (a Phi). It will be simplified as
4752         // part of reduce_merge.
4753         continue;
4754       }
4755       JavaObjectNode* jobj = unique_java_object(n);
4756       if (jobj == nullptr || jobj == phantom_obj) {
4757 #ifdef ASSERT
4758         ptnode_adr(n->_idx)->dump();
4759         assert(jobj != nullptr && jobj != phantom_obj, "escaped allocation");
4760 #endif
4761         _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4762         return;
4763       } else {
4764         Node *val = get_map(jobj->idx());   // CheckCastPP node
4765         TypeNode *tn = n->as_Type();
4766         const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
4767         assert(tinst != nullptr && tinst->is_known_instance() &&
4768                tinst->instance_id() == jobj->idx() , "instance type expected.");
4769 
4770         const Type *tn_type = igvn->type(tn);
4771         const TypeOopPtr *tn_t;
4772         if (tn_type->isa_narrowoop()) {
4773           tn_t = tn_type->make_ptr()->isa_oopptr();
4774         } else {
4775           tn_t = tn_type->isa_oopptr();
4776         }
4777         if (tn_t != nullptr && tinst->maybe_java_subtype_of(tn_t)) {
4778           if (tn_t->isa_aryptr()) {
4779             // Keep array properties (not flat/null-free)
4780             tinst = tinst->is_aryptr()->update_properties(tn_t->is_aryptr());
4781             if (tinst == nullptr) {
4782               continue; // Skip dead path with inconsistent properties
4783             }
4784           }
4785           if (tn_type->isa_narrowoop()) {
4786             tn_type = tinst->make_narrowoop();
4787           } else {
4788             tn_type = tinst;
4789           }
4790           igvn->hash_delete(tn);
4791           igvn->set_type(tn, tn_type);
4792           tn->set_type(tn_type);
4793           igvn->hash_insert(tn);
4794           record_for_optimizer(n);
4795         } else {
4796           assert(tn_type == TypePtr::NULL_PTR ||
4797                  (tn_t != nullptr && !tinst->maybe_java_subtype_of(tn_t)),
4798                  "unexpected type");
4799           continue; // Skip dead path with different type
4800         }
4801       }
4802     } else {
4803       DEBUG_ONLY(n->dump();)
4804       assert(false, "EA: unexpected node");
4805       continue;
4806     }
4807     // push allocation's users on appropriate worklist
4808     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4809       Node *use = n->fast_out(i);
4810       if (use->is_Mem() && use->in(MemNode::Address) == n) {
4811         // Load/store to instance's field
4812         memnode_worklist.append_if_missing(use);
4813       } else if (use->is_MemBar()) {
4814         if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4815           memnode_worklist.append_if_missing(use);
4816         }
4817       } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
4818         Node* addp2 = find_second_addp(use, n);
4819         if (addp2 != nullptr) {
4820           alloc_worklist.append_if_missing(addp2);
4821         }
4822         alloc_worklist.append_if_missing(use);
4823       } else if (use->is_Phi() ||
4824                  use->is_CheckCastPP() ||
4825                  use->is_EncodeNarrowPtr() ||
4826                  use->is_DecodeNarrowPtr() ||
4827                  (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
4828         alloc_worklist.append_if_missing(use);
4829 #ifdef ASSERT
4830       } else if (use->is_Mem()) {
4831         assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
4832       } else if (use->is_MergeMem()) {
4833         assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4834       } else if (use->is_SafePoint()) {
4835         // Look for MergeMem nodes for calls which reference unique allocation
4836         // (through CheckCastPP nodes) even for debug info.
4837         Node* m = use->in(TypeFunc::Memory);
4838         if (m->is_MergeMem()) {
4839           assert(mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4840         }
4841       } else if (use->Opcode() == Op_EncodeISOArray) {
4842         if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4843           // EncodeISOArray overwrites destination array
4844           memnode_worklist.append_if_missing(use);
4845         }
4846       } else if (use->Opcode() == Op_Return) {
4847         // Allocation is referenced by field of returned inline type
4848         assert(_compile->tf()->returns_inline_type_as_fields(), "EA: unexpected reference by ReturnNode");
4849       } else {
4850         uint op = use->Opcode();
4851         if ((op == Op_StrCompressedCopy || op == Op_StrInflatedCopy) &&
4852             (use->in(MemNode::Memory) == n)) {
4853           // They overwrite memory edge corresponding to destination array,
4854           memnode_worklist.append_if_missing(use);
4855         } else if (!(op == Op_CmpP || op == Op_Conv2B ||
4856               op == Op_CastP2X ||
4857               op == Op_FastLock || op == Op_AryEq ||
4858               op == Op_StrComp || op == Op_CountPositives ||
4859               op == Op_StrCompressedCopy || op == Op_StrInflatedCopy ||
4860               op == Op_StrEquals || op == Op_VectorizedHashCode ||
4861               op == Op_StrIndexOf || op == Op_StrIndexOfChar ||
4862               op == Op_SubTypeCheck || op == Op_InlineType || op == Op_FlatArrayCheck ||
4863               op == Op_ReinterpretS2HF ||
4864               BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use))) {
4865           n->dump();
4866           use->dump();
4867           assert(false, "EA: missing allocation reference path");
4868         }
4869 #endif
4870       }
4871     }
4872 
4873   }
4874 
4875 #ifdef ASSERT
4876   if (VerifyReduceAllocationMerges) {
4877     for (uint i = 0; i < reducible_merges.size(); i++) {
4878       Node* phi = reducible_merges.at(i);
4879 
4880       if (!reduced_merges.member(phi)) {
4881         phi->dump(2);
4882         phi->dump(-2);
4883         assert(false, "This reducible merge wasn't reduced.");
4884       }
4885 
4886       // At this point reducible Phis shouldn't have AddP users anymore; only SafePoints or Casts.
4887       for (DUIterator_Fast jmax, j = phi->fast_outs(jmax); j < jmax; j++) {
4888         Node* use = phi->fast_out(j);
4889         if (!use->is_SafePoint() && !use->is_CastPP()) {
4890           phi->dump(2);
4891           phi->dump(-2);
4892           assert(false, "Unexpected user of reducible Phi -> %d:%s:%d", use->_idx, use->Name(), use->outcnt());
4893         }
4894       }
4895     }
4896   }
4897 #endif
4898 
4899   // Go over all ArrayCopy nodes and if one of the inputs has a unique
4900   // type, record it in the ArrayCopy node so we know what memory this
4901   // node uses/modified.
4902   for (int next = 0; next < arraycopy_worklist.length(); next++) {
4903     ArrayCopyNode* ac = arraycopy_worklist.at(next);
4904     Node* dest = ac->in(ArrayCopyNode::Dest);
4905     if (dest->is_AddP()) {
4906       dest = get_addp_base(dest);
4907     }
4908     JavaObjectNode* jobj = unique_java_object(dest);
4909     if (jobj != nullptr) {
4910       Node *base = get_map(jobj->idx());
4911       if (base != nullptr) {
4912         const TypeOopPtr *base_t = _igvn->type(base)->isa_oopptr();
4913         ac->_dest_type = base_t;
4914       }
4915     }
4916     Node* src = ac->in(ArrayCopyNode::Src);
4917     if (src->is_AddP()) {
4918       src = get_addp_base(src);
4919     }
4920     jobj = unique_java_object(src);
4921     if (jobj != nullptr) {
4922       Node* base = get_map(jobj->idx());
4923       if (base != nullptr) {
4924         const TypeOopPtr *base_t = _igvn->type(base)->isa_oopptr();
4925         ac->_src_type = base_t;
4926       }
4927     }
4928   }
4929 
4930   // New alias types were created in split_AddP().
4931   uint new_index_end = (uint) _compile->num_alias_types();
4932 
4933   _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_1, 5);
4934 
4935   //  Phase 2:  Process MemNode's from memnode_worklist. compute new address type and
4936   //            compute new values for Memory inputs  (the Memory inputs are not
4937   //            actually updated until phase 4.)
4938   if (memnode_worklist.length() == 0)
4939     return;  // nothing to do
4940   while (memnode_worklist.length() != 0) {
4941     Node *n = memnode_worklist.pop();
4942     if (visited.test_set(n->_idx)) {
4943       continue;
4944     }
4945     if (n->is_Phi() || n->is_ClearArray()) {
4946       // we don't need to do anything, but the users must be pushed
4947     } else if (n->is_MemBar()) { // MemBar nodes
4948       if (!n->is_Initialize()) { // memory projections for Initialize pushed below (so we get to all their uses)
4949         // we don't need to do anything, but the users must be pushed
4950         n = n->as_MemBar()->proj_out_or_null(TypeFunc::Memory);
4951         if (n == nullptr) {
4952           continue;
4953         }
4954       }
4955     } else if (n->is_CallLeaf()) {
4956       // Runtime calls with narrow memory input (no MergeMem node)
4957       // get the memory projection
4958       n = n->as_Call()->proj_out_or_null(TypeFunc::Memory);
4959       if (n == nullptr) {
4960         continue;
4961       }
4962     } else if (n->Opcode() == Op_StrInflatedCopy) {
4963       // Check direct uses of StrInflatedCopy.
4964       // It is memory type Node - no special SCMemProj node.
4965     } else if (n->Opcode() == Op_StrCompressedCopy ||
4966                n->Opcode() == Op_EncodeISOArray) {
4967       // get the memory projection
4968       n = n->find_out_with(Op_SCMemProj);
4969       assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
4970     } else if (n->is_CallLeaf() && n->as_CallLeaf()->_name != nullptr &&
4971                strcmp(n->as_CallLeaf()->_name, "store_unknown_inline") == 0) {
4972       n = n->as_CallLeaf()->proj_out(TypeFunc::Memory);
4973     } else if (n->is_Proj()) {
4974       assert(n->in(0)->is_Initialize(), "we only push memory projections for Initialize");
4975     } else {
4976 #ifdef ASSERT
4977       if (!n->is_Mem()) {
4978         n->dump();
4979       }
4980       assert(n->is_Mem(), "memory node required.");
4981 #endif
4982       Node *addr = n->in(MemNode::Address);
4983       const Type *addr_t = igvn->type(addr);
4984       if (addr_t == Type::TOP) {
4985         continue;
4986       }
4987       assert (addr_t->isa_ptr() != nullptr, "pointer type required.");
4988       int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
4989       assert ((uint)alias_idx < new_index_end, "wrong alias index");
4990       Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
4991       if (_compile->failing()) {
4992         return;
4993       }
4994       if (mem != n->in(MemNode::Memory)) {
4995         // We delay the memory edge update since we need old one in
4996         // MergeMem code below when instances memory slices are separated.
4997         set_map(n, mem);
4998       }
4999       if (n->is_Load()) {
5000         continue;  // don't push users
5001       } else if (n->is_LoadStore()) {
5002         // get the memory projection
5003         n = n->find_out_with(Op_SCMemProj);
5004         assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
5005       }
5006     }
5007     // push user on appropriate worklist
5008     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5009       Node *use = n->fast_out(i);
5010       if (use->is_Phi() || use->is_ClearArray()) {
5011         memnode_worklist.append_if_missing(use);
5012       } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
5013         memnode_worklist.append_if_missing(use);
5014       } else if (use->is_MemBar() || use->is_CallLeaf()) {
5015         if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
5016           memnode_worklist.append_if_missing(use);
5017         }
5018       } else if (use->is_Proj()) {
5019         assert(n->is_Initialize(), "We only push projections of Initialize");
5020         if (use->as_Proj()->_con == TypeFunc::Memory) { // Ignore precedent edge
5021           memnode_worklist.append_if_missing(use);
5022         }
5023 #ifdef ASSERT
5024       } else if (use->is_Mem()) {
5025         assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
5026       } else if (use->is_MergeMem()) {
5027         assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
5028       } else if (use->Opcode() == Op_EncodeISOArray) {
5029         if (use->in(MemNode::Memory) == n || use->in(3) == n) {
5030           // EncodeISOArray overwrites destination array
5031           memnode_worklist.append_if_missing(use);
5032         }
5033       } else if (use->is_CallLeaf() && use->as_CallLeaf()->_name != nullptr &&
5034                  strcmp(use->as_CallLeaf()->_name, "store_unknown_inline") == 0) {
5035         // store_unknown_inline overwrites destination array
5036         memnode_worklist.append_if_missing(use);
5037       } else {
5038         uint op = use->Opcode();
5039         if ((use->in(MemNode::Memory) == n) &&
5040             (op == Op_StrCompressedCopy || op == Op_StrInflatedCopy)) {
5041           // They overwrite memory edge corresponding to destination array,
5042           memnode_worklist.append_if_missing(use);
5043         } else if (!(BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use) ||
5044               op == Op_AryEq || op == Op_StrComp || op == Op_CountPositives ||
5045               op == Op_StrCompressedCopy || op == Op_StrInflatedCopy || op == Op_VectorizedHashCode ||
5046               op == Op_StrEquals || op == Op_StrIndexOf || op == Op_StrIndexOfChar || op == Op_FlatArrayCheck)) {
5047           n->dump();
5048           use->dump();
5049           assert(false, "EA: missing memory path");
5050         }
5051 #endif
5052       }
5053     }
5054   }
5055 
5056   //  Phase 3:  Process MergeMem nodes from mergemem_worklist.
5057   //            Walk each memory slice moving the first node encountered of each
5058   //            instance type to the input corresponding to its alias index.
5059   uint length = mergemem_worklist.length();
5060   for( uint next = 0; next < length; ++next ) {
5061     MergeMemNode* nmm = mergemem_worklist.at(next);
5062     assert(!visited.test_set(nmm->_idx), "should not be visited before");
5063     // Note: we don't want to use MergeMemStream here because we only want to
5064     // scan inputs which exist at the start, not ones we add during processing.
5065     // Note 2: MergeMem may already contains instance memory slices added
5066     // during find_inst_mem() call when memory nodes were processed above.
5067     igvn->hash_delete(nmm);
5068     uint nslices = MIN2(nmm->req(), new_index_start);
5069     for (uint i = Compile::AliasIdxRaw+1; i < nslices; i++) {
5070       Node* mem = nmm->in(i);
5071       Node* cur = nullptr;
5072       if (mem == nullptr || mem->is_top()) {
5073         continue;
5074       }
5075       // First, update mergemem by moving memory nodes to corresponding slices
5076       // if their type became more precise since this mergemem was created.
5077       while (mem->is_Mem()) {
5078         const Type* at = igvn->type(mem->in(MemNode::Address));
5079         if (at != Type::TOP) {
5080           assert (at->isa_ptr() != nullptr, "pointer type required.");
5081           uint idx = (uint)_compile->get_alias_index(at->is_ptr());
5082           if (idx == i) {
5083             if (cur == nullptr) {
5084               cur = mem;
5085             }
5086           } else {
5087             if (idx >= nmm->req() || nmm->is_empty_memory(nmm->in(idx))) {
5088               nmm->set_memory_at(idx, mem);
5089             }
5090           }
5091         }
5092         mem = mem->in(MemNode::Memory);
5093       }
5094       nmm->set_memory_at(i, (cur != nullptr) ? cur : mem);
5095       // Find any instance of the current type if we haven't encountered
5096       // already a memory slice of the instance along the memory chain.
5097       for (uint ni = new_index_start; ni < new_index_end; ni++) {
5098         if((uint)_compile->get_general_index(ni) == i) {
5099           Node *m = (ni >= nmm->req()) ? nmm->empty_memory() : nmm->in(ni);
5100           if (nmm->is_empty_memory(m)) {
5101             Node* result = find_inst_mem(mem, ni, orig_phis);
5102             if (_compile->failing()) {
5103               return;
5104             }
5105             nmm->set_memory_at(ni, result);
5106           }
5107         }
5108       }
5109     }
5110     // Find the rest of instances values
5111     for (uint ni = new_index_start; ni < new_index_end; ni++) {
5112       const TypeOopPtr *tinst = _compile->get_adr_type(ni)->isa_oopptr();
5113       Node* result = step_through_mergemem(nmm, ni, tinst);
5114       if (result == nmm->base_memory()) {
5115         // Didn't find instance memory, search through general slice recursively.
5116         result = nmm->memory_at(_compile->get_general_index(ni));
5117         result = find_inst_mem(result, ni, orig_phis);
5118         if (_compile->failing()) {
5119           return;
5120         }
5121         nmm->set_memory_at(ni, result);
5122       }
5123     }
5124 
5125     // If we have crossed the 3/4 point of max node limit it's too risky
5126     // to continue with EA/SR because we might hit the max node limit.
5127     if (_compile->live_nodes() >= _compile->max_node_limit() * 0.75) {
5128       if (_compile->do_reduce_allocation_merges()) {
5129         _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
5130       } else if (_invocation > 0) {
5131         _compile->record_failure(C2Compiler::retry_no_iterative_escape_analysis());
5132       } else {
5133         _compile->record_failure(C2Compiler::retry_no_escape_analysis());
5134       }
5135       return;
5136     }
5137 
5138     igvn->hash_insert(nmm);
5139     record_for_optimizer(nmm);
5140   }
5141 
5142   _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_3, 5);
5143 
5144   //  Phase 4:  Update the inputs of non-instance memory Phis and
5145   //            the Memory input of memnodes
5146   // First update the inputs of any non-instance Phi's from
5147   // which we split out an instance Phi.  Note we don't have
5148   // to recursively process Phi's encountered on the input memory
5149   // chains as is done in split_memory_phi() since they will
5150   // also be processed here.
5151   for (int j = 0; j < orig_phis.length(); j++) {
5152     PhiNode *phi = orig_phis.at(j);
5153     int alias_idx = _compile->get_alias_index(phi->adr_type());
5154     igvn->hash_delete(phi);
5155     for (uint i = 1; i < phi->req(); i++) {
5156       Node *mem = phi->in(i);
5157       Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
5158       if (_compile->failing()) {
5159         return;
5160       }
5161       if (mem != new_mem) {
5162         phi->set_req(i, new_mem);
5163       }
5164     }
5165     igvn->hash_insert(phi);
5166     record_for_optimizer(phi);
5167   }
5168 
5169   // Update the memory inputs of MemNodes with the value we computed
5170   // in Phase 2 and move stores memory users to corresponding memory slices.
5171   // Disable memory split verification code until the fix for 6984348.
5172   // Currently it produces false negative results since it does not cover all cases.
5173 #if 0 // ifdef ASSERT
5174   visited.Reset();
5175   Node_Stack old_mems(arena, _compile->unique() >> 2);
5176 #endif
5177   for (uint i = 0; i < ideal_nodes.size(); i++) {
5178     Node*    n = ideal_nodes.at(i);
5179     Node* nmem = get_map(n->_idx);
5180     assert(nmem != nullptr, "sanity");
5181     if (n->is_Mem()) {
5182 #if 0 // ifdef ASSERT
5183       Node* old_mem = n->in(MemNode::Memory);
5184       if (!visited.test_set(old_mem->_idx)) {
5185         old_mems.push(old_mem, old_mem->outcnt());
5186       }
5187 #endif
5188       assert(n->in(MemNode::Memory) != nmem, "sanity");
5189       if (!n->is_Load()) {
5190         // Move memory users of a store first.
5191         move_inst_mem(n, orig_phis);
5192       }
5193       // Now update memory input
5194       igvn->hash_delete(n);
5195       n->set_req(MemNode::Memory, nmem);
5196       igvn->hash_insert(n);
5197       record_for_optimizer(n);
5198     } else {
5199       assert(n->is_Allocate() || n->is_CheckCastPP() ||
5200              n->is_AddP() || n->is_Phi() || n->is_NarrowMemProj(), "unknown node used for set_map()");
5201     }
5202   }
5203 #if 0 // ifdef ASSERT
5204   // Verify that memory was split correctly
5205   while (old_mems.is_nonempty()) {
5206     Node* old_mem = old_mems.node();
5207     uint  old_cnt = old_mems.index();
5208     old_mems.pop();
5209     assert(old_cnt == old_mem->outcnt(), "old mem could be lost");
5210   }
5211 #endif
5212   _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_4, 5);
5213 }
5214 
5215 #ifndef PRODUCT
5216 int ConnectionGraph::_no_escape_counter = 0;
5217 int ConnectionGraph::_arg_escape_counter = 0;
5218 int ConnectionGraph::_global_escape_counter = 0;
5219 
5220 static const char *node_type_names[] = {
5221   "UnknownType",
5222   "JavaObject",
5223   "LocalVar",
5224   "Field",
5225   "Arraycopy"
5226 };
5227 
5228 static const char *esc_names[] = {
5229   "UnknownEscape",
5230   "NoEscape",
5231   "ArgEscape",
5232   "GlobalEscape"
5233 };
5234 
5235 const char* PointsToNode::esc_name() const {
5236   return esc_names[(int)escape_state()];
5237 }
5238 
5239 void PointsToNode::dump_header(bool print_state, outputStream* out) const {
5240   NodeType nt = node_type();
5241   out->print("%s(%d) ", node_type_names[(int) nt], _pidx);
5242   if (print_state) {
5243     EscapeState es = escape_state();
5244     EscapeState fields_es = fields_escape_state();
5245     out->print("%s(%s) ", esc_names[(int)es], esc_names[(int)fields_es]);
5246     if (nt == PointsToNode::JavaObject && !this->scalar_replaceable()) {
5247       out->print("NSR ");
5248     }
5249   }
5250 }
5251 
5252 void PointsToNode::dump(bool print_state, outputStream* out, bool newline) const {
5253   dump_header(print_state, out);
5254   if (is_Field()) {
5255     FieldNode* f = (FieldNode*)this;
5256     if (f->is_oop()) {
5257       out->print("oop ");
5258     }
5259     if (f->offset() > 0) {
5260       out->print("+%d ", f->offset());
5261     }
5262     out->print("(");
5263     for (BaseIterator i(f); i.has_next(); i.next()) {
5264       PointsToNode* b = i.get();
5265       out->print(" %d%s", b->idx(),(b->is_JavaObject() ? "P" : ""));
5266     }
5267     out->print(" )");
5268   }
5269   out->print("[");
5270   for (EdgeIterator i(this); i.has_next(); i.next()) {
5271     PointsToNode* e = i.get();
5272     out->print(" %d%s%s", e->idx(),(e->is_JavaObject() ? "P" : (e->is_Field() ? "F" : "")), e->is_Arraycopy() ? "cp" : "");
5273   }
5274   out->print(" [");
5275   for (UseIterator i(this); i.has_next(); i.next()) {
5276     PointsToNode* u = i.get();
5277     bool is_base = false;
5278     if (PointsToNode::is_base_use(u)) {
5279       is_base = true;
5280       u = PointsToNode::get_use_node(u)->as_Field();
5281     }
5282     out->print(" %d%s%s", u->idx(), is_base ? "b" : "", u->is_Arraycopy() ? "cp" : "");
5283   }
5284   out->print(" ]]  ");
5285   if (_node == nullptr) {
5286     out->print("<null>%s", newline ? "\n" : "");
5287   } else {
5288     _node->dump(newline ? "\n" : "", false, out);
5289   }
5290 }
5291 
5292 void ConnectionGraph::dump(GrowableArray<PointsToNode*>& ptnodes_worklist) {
5293   bool first = true;
5294   int ptnodes_length = ptnodes_worklist.length();
5295   for (int i = 0; i < ptnodes_length; i++) {
5296     PointsToNode *ptn = ptnodes_worklist.at(i);
5297     if (ptn == nullptr || !ptn->is_JavaObject()) {
5298       continue;
5299     }
5300     PointsToNode::EscapeState es = ptn->escape_state();
5301     if ((es != PointsToNode::NoEscape) && !Verbose) {
5302       continue;
5303     }
5304     Node* n = ptn->ideal_node();
5305     if (n->is_Allocate() || (n->is_CallStaticJava() &&
5306                              n->as_CallStaticJava()->is_boxing_method())) {
5307       if (first) {
5308         tty->cr();
5309         tty->print("======== Connection graph for ");
5310         _compile->method()->print_short_name();
5311         tty->cr();
5312         tty->print_cr("invocation #%d: %d iterations and %f sec to build connection graph with %d nodes and worklist size %d",
5313                       _invocation, _build_iterations, _build_time, nodes_size(), ptnodes_worklist.length());
5314         tty->cr();
5315         first = false;
5316       }
5317       ptn->dump();
5318       // Print all locals and fields which reference this allocation
5319       for (UseIterator j(ptn); j.has_next(); j.next()) {
5320         PointsToNode* use = j.get();
5321         if (use->is_LocalVar()) {
5322           use->dump(Verbose);
5323         } else if (Verbose) {
5324           use->dump();
5325         }
5326       }
5327       tty->cr();
5328     }
5329   }
5330 }
5331 
5332 void ConnectionGraph::print_statistics() {
5333   tty->print_cr("No escape = %d, Arg escape = %d, Global escape = %d", AtomicAccess::load(&_no_escape_counter), AtomicAccess::load(&_arg_escape_counter), AtomicAccess::load(&_global_escape_counter));
5334 }
5335 
5336 void ConnectionGraph::escape_state_statistics(GrowableArray<JavaObjectNode*>& java_objects_worklist) {
5337   if (!PrintOptoStatistics || (_invocation > 0)) { // Collect data only for the first invocation
5338     return;
5339   }
5340   for (int next = 0; next < java_objects_worklist.length(); ++next) {
5341     JavaObjectNode* ptn = java_objects_worklist.at(next);
5342     if (ptn->ideal_node()->is_Allocate()) {
5343       if (ptn->escape_state() == PointsToNode::NoEscape) {
5344         AtomicAccess::inc(&ConnectionGraph::_no_escape_counter);
5345       } else if (ptn->escape_state() == PointsToNode::ArgEscape) {
5346         AtomicAccess::inc(&ConnectionGraph::_arg_escape_counter);
5347       } else if (ptn->escape_state() == PointsToNode::GlobalEscape) {
5348         AtomicAccess::inc(&ConnectionGraph::_global_escape_counter);
5349       } else {
5350         assert(false, "Unexpected Escape State");
5351       }
5352     }
5353   }
5354 }
5355 
5356 void ConnectionGraph::trace_es_update_helper(PointsToNode* ptn, PointsToNode::EscapeState es, bool fields, const char* reason) const {
5357   if (_compile->directive()->TraceEscapeAnalysisOption) {
5358     assert(ptn != nullptr, "should not be null");
5359     assert(reason != nullptr, "should not be null");
5360     ptn->dump_header(true);
5361     PointsToNode::EscapeState new_es = fields ? ptn->escape_state() : es;
5362     PointsToNode::EscapeState new_fields_es = fields ? es : ptn->fields_escape_state();
5363     tty->print_cr("-> %s(%s) %s", esc_names[(int)new_es], esc_names[(int)new_fields_es], reason);
5364   }
5365 }
5366 
5367 const char* ConnectionGraph::trace_propagate_message(PointsToNode* from) const {
5368   if (_compile->directive()->TraceEscapeAnalysisOption) {
5369     stringStream ss;
5370     ss.print("propagated from: ");
5371     from->dump(true, &ss, false);
5372     return ss.as_string();
5373   } else {
5374     return nullptr;
5375   }
5376 }
5377 
5378 const char* ConnectionGraph::trace_arg_escape_message(CallNode* call) const {
5379   if (_compile->directive()->TraceEscapeAnalysisOption) {
5380     stringStream ss;
5381     ss.print("escapes as arg to:");
5382     call->dump("", false, &ss);
5383     return ss.as_string();
5384   } else {
5385     return nullptr;
5386   }
5387 }
5388 
5389 const char* ConnectionGraph::trace_merged_message(PointsToNode* other) const {
5390   if (_compile->directive()->TraceEscapeAnalysisOption) {
5391     stringStream ss;
5392     ss.print("is merged with other object: ");
5393     other->dump_header(true, &ss);
5394     return ss.as_string();
5395   } else {
5396     return nullptr;
5397   }
5398 }
5399 
5400 #endif
5401 
5402 void ConnectionGraph::record_for_optimizer(Node *n) {
5403   _igvn->_worklist.push(n);
5404   _igvn->add_users_to_worklist(n);
5405 }