< prev index next >

src/hotspot/share/opto/escape.cpp

Print this page

  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/resourceArea.hpp"
  32 #include "opto/arraycopynode.hpp"
  33 #include "opto/c2compiler.hpp"
  34 #include "opto/callnode.hpp"
  35 #include "opto/castnode.hpp"
  36 #include "opto/cfgnode.hpp"
  37 #include "opto/compile.hpp"
  38 #include "opto/escape.hpp"

  39 #include "opto/locknode.hpp"
  40 #include "opto/macro.hpp"
  41 #include "opto/movenode.hpp"
  42 #include "opto/narrowptrnode.hpp"
  43 #include "opto/phaseX.hpp"
  44 #include "opto/rootnode.hpp"
  45 #include "utilities/macros.hpp"
  46 
  47 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn, int invocation) :
  48   // If ReduceAllocationMerges is enabled we might call split_through_phi during
  49   // split_unique_types and that will create additional nodes that need to be
  50   // pushed to the ConnectionGraph. The code below bumps the initial capacity of
  51   // _nodes by 10% to account for these additional nodes. If capacity is exceeded
  52   // the array will be reallocated.
  53   _nodes(C->comp_arena(), C->do_reduce_allocation_merges() ? C->unique()*1.10 : C->unique(), C->unique(), nullptr),
  54   _in_worklist(C->comp_arena()),
  55   _next_pidx(0),
  56   _collecting(true),
  57   _verify(false),
  58   _compile(C),

 150   GrowableArray<SafePointNode*>  sfn_worklist;
 151   GrowableArray<MergeMemNode*>   mergemem_worklist;
 152   DEBUG_ONLY( GrowableArray<Node*> addp_worklist; )
 153 
 154   { Compile::TracePhase tp(Phase::_t_connectionGraph);
 155 
 156   // 1. Populate Connection Graph (CG) with PointsTo nodes.
 157   ideal_nodes.map(C->live_nodes(), nullptr);  // preallocate space
 158   // Initialize worklist
 159   if (C->root() != nullptr) {
 160     ideal_nodes.push(C->root());
 161   }
 162   // Processed ideal nodes are unique on ideal_nodes list
 163   // but several ideal nodes are mapped to the phantom_obj.
 164   // To avoid duplicated entries on the following worklists
 165   // add the phantom_obj only once to them.
 166   ptnodes_worklist.append(phantom_obj);
 167   java_objects_worklist.append(phantom_obj);
 168   for( uint next = 0; next < ideal_nodes.size(); ++next ) {
 169     Node* n = ideal_nodes.at(next);










 170     // Create PointsTo nodes and add them to Connection Graph. Called
 171     // only once per ideal node since ideal_nodes is Unique_Node list.
 172     add_node_to_connection_graph(n, &delayed_worklist);
 173     PointsToNode* ptn = ptnode_adr(n->_idx);
 174     if (ptn != nullptr && ptn != phantom_obj) {
 175       ptnodes_worklist.append(ptn);
 176       if (ptn->is_JavaObject()) {
 177         java_objects_worklist.append(ptn->as_JavaObject());
 178         if ((n->is_Allocate() || n->is_CallStaticJava()) &&
 179             (ptn->escape_state() < PointsToNode::GlobalEscape)) {
 180           // Only allocations and java static calls results are interesting.
 181           non_escaped_allocs_worklist.append(ptn->as_JavaObject());
 182         }
 183       } else if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
 184         oop_fields_worklist.append(ptn->as_Field());
 185       }
 186     }
 187     // Collect some interesting nodes for further use.
 188     switch (n->Opcode()) {
 189       case Op_MergeMem:

 407     // scalar replaceable objects.
 408     split_unique_types(alloc_worklist, arraycopy_worklist, mergemem_worklist, reducible_merges);
 409     if (C->failing()) {
 410       NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 411       return false;
 412     }
 413 
 414 #ifdef ASSERT
 415   } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
 416     tty->print("=== No allocations eliminated for ");
 417     C->method()->print_short_name();
 418     if (!EliminateAllocations) {
 419       tty->print(" since EliminateAllocations is off ===");
 420     } else if(!has_scalar_replaceable_candidates) {
 421       tty->print(" since there are no scalar replaceable candidates ===");
 422     }
 423     tty->cr();
 424 #endif
 425   }
 426 








 427   _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES, 4);
 428 
 429   // 6. Reduce allocation merges used as debug information. This is done after
 430   // split_unique_types because the methods used to create SafePointScalarObject
 431   // need to traverse the memory graph to find values for object fields. We also
 432   // set to null the scalarized inputs of reducible Phis so that the Allocate
 433   // that they point can be later scalar replaced.
 434   bool delay = _igvn->delay_transform();
 435   _igvn->set_delay_transform(true);
 436   for (uint i = 0; i < reducible_merges.size(); i++) {
 437     Node* n = reducible_merges.at(i);
 438     if (n->outcnt() > 0) {
 439       if (!reduce_phi_on_safepoints(n->as_Phi())) {
 440         NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
 441         C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
 442         return false;
 443       }
 444 
 445       // Now we set the scalar replaceable inputs of ophi to null, which is
 446       // the last piece that would prevent it from being scalar replaceable.
 447       reset_scalar_replaceable_entries(n->as_Phi());
 448     }
 449   }

1283 
1284     // The next two inputs are:
1285     //  (1) A copy of the original pointer to NSR objects.
1286     //  (2) A selector, used to decide if we need to rematerialize an object
1287     //      or use the pointer to a NSR object.
1288     // See more details of these fields in the declaration of SafePointScalarMergeNode
1289     sfpt->add_req(nsr_merge_pointer);
1290     sfpt->add_req(selector);
1291 
1292     for (uint i = 1; i < ophi->req(); i++) {
1293       Node* base = ophi->in(i);
1294       JavaObjectNode* ptn = unique_java_object(base);
1295 
1296       // If the base is not scalar replaceable we don't need to register information about
1297       // it at this time.
1298       if (ptn == nullptr || !ptn->scalar_replaceable()) {
1299         continue;
1300       }
1301 
1302       AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
1303       SafePointScalarObjectNode* sobj = mexp.create_scalarized_object_description(alloc, sfpt);








1304       if (sobj == nullptr) {

1305         return false;
1306       }
1307 
1308       // Now make a pass over the debug information replacing any references
1309       // to the allocated object with "sobj"
1310       Node* ccpp = alloc->result_cast();
1311       sfpt->replace_edges_in_range(ccpp, sobj, debug_start, jvms->debug_end(), _igvn);
1312 
1313       // Register the scalarized object as a candidate for reallocation
1314       smerge->add_req(sobj);









1315     }
1316 
1317     // Replaces debug information references to "original_sfpt_parent" in "sfpt" with references to "smerge"
1318     sfpt->replace_edges_in_range(original_sfpt_parent, smerge, debug_start, jvms->debug_end(), _igvn);
1319 
1320     // The call to 'replace_edges_in_range' above might have removed the
1321     // reference to ophi that we need at _merge_pointer_idx. The line below make
1322     // sure the reference is maintained.
1323     sfpt->set_req(smerge->merge_pointer_idx(jvms), nsr_merge_pointer);
1324     _igvn->_worklist.push(sfpt);
1325   }
1326 
1327   return true;
1328 }
1329 
1330 void ConnectionGraph::reduce_phi(PhiNode* ophi, GrowableArray<Node*> &alloc_worklist) {
1331   bool delay = _igvn->delay_transform();
1332   _igvn->set_delay_transform(true);
1333   _igvn->hash_delete(ophi);
1334 

1497   return false;
1498 }
1499 
1500 // Returns true if at least one of the arguments to the call is an object
1501 // that does not escape globally.
1502 bool ConnectionGraph::has_arg_escape(CallJavaNode* call) {
1503   if (call->method() != nullptr) {
1504     uint max_idx = TypeFunc::Parms + call->method()->arg_size();
1505     for (uint idx = TypeFunc::Parms; idx < max_idx; idx++) {
1506       Node* p = call->in(idx);
1507       if (not_global_escape(p)) {
1508         return true;
1509       }
1510     }
1511   } else {
1512     const char* name = call->as_CallStaticJava()->_name;
1513     assert(name != nullptr, "no name");
1514     // no arg escapes through uncommon traps
1515     if (strcmp(name, "uncommon_trap") != 0) {
1516       // process_call_arguments() assumes that all arguments escape globally
1517       const TypeTuple* d = call->tf()->domain();
1518       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1519         const Type* at = d->field_at(i);
1520         if (at->isa_oopptr() != nullptr) {
1521           return true;
1522         }
1523       }
1524     }
1525   }
1526   return false;
1527 }
1528 
1529 
1530 
1531 // Utility function for nodes that load an object
1532 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1533   // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1534   // ThreadLocal has RawPtr type.
1535   const Type* t = _igvn->type(n);
1536   if (t->make_ptr() != nullptr) {
1537     Node* adr = n->in(MemNode::Address);

1571       // first IGVN optimization when escape information is still available.
1572       record_for_optimizer(n);
1573     } else if (n->is_Allocate()) {
1574       add_call_node(n->as_Call());
1575       record_for_optimizer(n);
1576     } else {
1577       if (n->is_CallStaticJava()) {
1578         const char* name = n->as_CallStaticJava()->_name;
1579         if (name != nullptr && strcmp(name, "uncommon_trap") == 0) {
1580           return; // Skip uncommon traps
1581         }
1582       }
1583       // Don't mark as processed since call's arguments have to be processed.
1584       delayed_worklist->push(n);
1585       // Check if a call returns an object.
1586       if ((n->as_Call()->returns_pointer() &&
1587            n->as_Call()->proj_out_or_null(TypeFunc::Parms) != nullptr) ||
1588           (n->is_CallStaticJava() &&
1589            n->as_CallStaticJava()->is_boxing_method())) {
1590         add_call_node(n->as_Call());











1591       }
1592     }
1593     return;
1594   }
1595   // Put this check here to process call arguments since some call nodes
1596   // point to phantom_obj.
1597   if (n_ptn == phantom_obj || n_ptn == null_obj) {
1598     return; // Skip predefined nodes.
1599   }
1600   switch (opcode) {
1601     case Op_AddP: {
1602       Node* base = get_addp_base(n);
1603       PointsToNode* ptn_base = ptnode_adr(base->_idx);
1604       // Field nodes are created for all field types. They are used in
1605       // adjust_scalar_replaceable_state() and split_unique_types().
1606       // Note, non-oop fields will have only base edges in Connection
1607       // Graph because such fields are not used for oop loads and stores.
1608       int offset = address_offset(n, igvn);
1609       add_field(n, PointsToNode::NoEscape, offset);
1610       if (ptn_base == nullptr) {
1611         delayed_worklist->push(n); // Process it later.
1612       } else {
1613         n_ptn = ptnode_adr(n_idx);
1614         add_base(n_ptn->as_Field(), ptn_base);
1615       }
1616       break;
1617     }
1618     case Op_CastX2P: {

1619       map_ideal_node(n, phantom_obj);
1620       break;
1621     }

1622     case Op_CastPP:
1623     case Op_CheckCastPP:
1624     case Op_EncodeP:
1625     case Op_DecodeN:
1626     case Op_EncodePKlass:
1627     case Op_DecodeNKlass: {
1628       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1629       break;
1630     }
1631     case Op_CMoveP: {
1632       add_local_var(n, PointsToNode::NoEscape);
1633       // Do not add edges during first iteration because some could be
1634       // not defined yet.
1635       delayed_worklist->push(n);
1636       break;
1637     }
1638     case Op_ConP:
1639     case Op_ConN:
1640     case Op_ConNKlass: {
1641       // assume all oop constants globally escape except for null

1671       break;
1672     }
1673     case Op_PartialSubtypeCheck: {
1674       // Produces Null or notNull and is used in only in CmpP so
1675       // phantom_obj could be used.
1676       map_ideal_node(n, phantom_obj); // Result is unknown
1677       break;
1678     }
1679     case Op_Phi: {
1680       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1681       // ThreadLocal has RawPtr type.
1682       const Type* t = n->as_Phi()->type();
1683       if (t->make_ptr() != nullptr) {
1684         add_local_var(n, PointsToNode::NoEscape);
1685         // Do not add edges during first iteration because some could be
1686         // not defined yet.
1687         delayed_worklist->push(n);
1688       }
1689       break;
1690     }








1691     case Op_Proj: {
1692       // we are only interested in the oop result projection from a call
1693       if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
1694           n->in(0)->as_Call()->returns_pointer()) {





1695         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1696       }
1697       break;
1698     }
1699     case Op_Rethrow: // Exception object escapes
1700     case Op_Return: {
1701       if (n->req() > TypeFunc::Parms &&
1702           igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
1703         // Treat Return value as LocalVar with GlobalEscape escape state.
1704         add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), delayed_worklist);
1705       }
1706       break;
1707     }
1708     case Op_CompareAndExchangeP:
1709     case Op_CompareAndExchangeN:
1710     case Op_GetAndSetP:
1711     case Op_GetAndSetN: {
1712       add_objload_to_connection_graph(n, delayed_worklist);
1713       // fall-through
1714     }

1760       break;
1761     }
1762     default:
1763       ; // Do nothing for nodes not related to EA.
1764   }
1765   return;
1766 }
1767 
1768 // Add final simple edges to graph.
1769 void ConnectionGraph::add_final_edges(Node *n) {
1770   PointsToNode* n_ptn = ptnode_adr(n->_idx);
1771 #ifdef ASSERT
1772   if (_verify && n_ptn->is_JavaObject())
1773     return; // This method does not change graph for JavaObject.
1774 #endif
1775 
1776   if (n->is_Call()) {
1777     process_call_arguments(n->as_Call());
1778     return;
1779   }
1780   assert(n->is_Store() || n->is_LoadStore() ||
1781          ((n_ptn != nullptr) && (n_ptn->ideal_node() != nullptr)),
1782          "node should be registered already");
1783   int opcode = n->Opcode();
1784   bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_final_edges(this, _igvn, n, opcode);
1785   if (gc_handled) {
1786     return; // Ignore node if already handled by GC.
1787   }
1788   switch (opcode) {
1789     case Op_AddP: {
1790       Node* base = get_addp_base(n);
1791       PointsToNode* ptn_base = ptnode_adr(base->_idx);
1792       assert(ptn_base != nullptr, "field's base should be registered");
1793       add_base(n_ptn->as_Field(), ptn_base);
1794       break;
1795     }

1796     case Op_CastPP:
1797     case Op_CheckCastPP:
1798     case Op_EncodeP:
1799     case Op_DecodeN:
1800     case Op_EncodePKlass:
1801     case Op_DecodeNKlass: {
1802       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), nullptr);
1803       break;
1804     }
1805     case Op_CMoveP: {
1806       for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
1807         Node* in = n->in(i);
1808         if (in == nullptr) {
1809           continue;  // ignore null
1810         }
1811         Node* uncast_in = in->uncast();
1812         if (uncast_in->is_top() || uncast_in == n) {
1813           continue;  // ignore top or inputs which go back this node
1814         }
1815         PointsToNode* ptn = ptnode_adr(in->_idx);

1828     }
1829     case Op_Phi: {
1830       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1831       // ThreadLocal has RawPtr type.
1832       assert(n->as_Phi()->type()->make_ptr() != nullptr, "Unexpected node type");
1833       for (uint i = 1; i < n->req(); i++) {
1834         Node* in = n->in(i);
1835         if (in == nullptr) {
1836           continue;  // ignore null
1837         }
1838         Node* uncast_in = in->uncast();
1839         if (uncast_in->is_top() || uncast_in == n) {
1840           continue;  // ignore top or inputs which go back this node
1841         }
1842         PointsToNode* ptn = ptnode_adr(in->_idx);
1843         assert(ptn != nullptr, "node should be registered");
1844         add_edge(n_ptn, ptn);
1845       }
1846       break;
1847     }
















1848     case Op_Proj: {
1849       // we are only interested in the oop result projection from a call
1850       assert(n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
1851              n->in(0)->as_Call()->returns_pointer(), "Unexpected node type");
1852       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), nullptr);





1853       break;
1854     }
1855     case Op_Rethrow: // Exception object escapes
1856     case Op_Return: {
1857       assert(n->req() > TypeFunc::Parms && _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr(),
1858              "Unexpected node type");
1859       // Treat Return value as LocalVar with GlobalEscape escape state.
1860       add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), nullptr);
1861       break;
1862     }
1863     case Op_CompareAndExchangeP:
1864     case Op_CompareAndExchangeN:
1865     case Op_GetAndSetP:
1866     case Op_GetAndSetN:{
1867       assert(_igvn->type(n)->make_ptr() != nullptr, "Unexpected node type");
1868       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), nullptr);
1869       // fall-through
1870     }
1871     case Op_CompareAndSwapP:
1872     case Op_CompareAndSwapN:

2006     Node* val = n->in(MemNode::ValueIn);
2007     PointsToNode* ptn = ptnode_adr(val->_idx);
2008     assert(ptn != nullptr, "node should be registered");
2009     set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "stored at raw address"));
2010     // Add edge to object for unsafe access with offset.
2011     PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
2012     assert(adr_ptn != nullptr, "node should be registered");
2013     if (adr_ptn->is_Field()) {
2014       assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
2015       add_edge(adr_ptn, ptn);
2016     }
2017     return true;
2018   }
2019 #ifdef ASSERT
2020   n->dump(1);
2021   assert(false, "not unsafe");
2022 #endif
2023   return false;
2024 }
2025 


























































































2026 void ConnectionGraph::add_call_node(CallNode* call) {
2027   assert(call->returns_pointer(), "only for call which returns pointer");
2028   uint call_idx = call->_idx;
2029   if (call->is_Allocate()) {
2030     Node* k = call->in(AllocateNode::KlassNode);
2031     const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
2032     assert(kt != nullptr, "TypeKlassPtr  required.");
2033     PointsToNode::EscapeState es = PointsToNode::NoEscape;
2034     bool scalar_replaceable = true;
2035     NOT_PRODUCT(const char* nsr_reason = "");
2036     if (call->is_AllocateArray()) {
2037       if (!kt->isa_aryklassptr()) { // StressReflectiveCode
2038         es = PointsToNode::GlobalEscape;
2039       } else {
2040         int length = call->in(AllocateNode::ALength)->find_int_con(-1);
2041         if (length < 0) {
2042           // Not scalar replaceable if the length is not constant.
2043           scalar_replaceable = false;
2044           NOT_PRODUCT(nsr_reason = "has a non-constant length");
2045         } else if (length > EliminateAllocationArraySizeLimit) {
2046           // Not scalar replaceable if the length is too big.
2047           scalar_replaceable = false;

2082     //    - mapped to GlobalEscape JavaObject node if oop is returned;
2083     //
2084     //    - all oop arguments are escaping globally;
2085     //
2086     // 2. CallStaticJavaNode (execute bytecode analysis if possible):
2087     //
2088     //    - the same as CallDynamicJavaNode if can't do bytecode analysis;
2089     //
2090     //    - mapped to GlobalEscape JavaObject node if unknown oop is returned;
2091     //    - mapped to NoEscape JavaObject node if non-escaping object allocated
2092     //      during call is returned;
2093     //    - mapped to ArgEscape LocalVar node pointed to object arguments
2094     //      which are returned and does not escape during call;
2095     //
2096     //    - oop arguments escaping status is defined by bytecode analysis;
2097     //
2098     // For a static call, we know exactly what method is being called.
2099     // Use bytecode estimator to record whether the call's return value escapes.
2100     ciMethod* meth = call->as_CallJava()->method();
2101     if (meth == nullptr) {
2102       assert(call->as_CallStaticJava()->is_call_to_multianewarray_stub(), "TODO: add failed case check");



2103       // Returns a newly allocated non-escaped object.
2104       add_java_object(call, PointsToNode::NoEscape);
2105       set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of multinewarray"));
2106     } else if (meth->is_boxing_method()) {
2107       // Returns boxing object
2108       PointsToNode::EscapeState es;
2109       vmIntrinsics::ID intr = meth->intrinsic_id();
2110       if (intr == vmIntrinsics::_floatValue || intr == vmIntrinsics::_doubleValue) {
2111         // It does not escape if object is always allocated.
2112         es = PointsToNode::NoEscape;
2113       } else {
2114         // It escapes globally if object could be loaded from cache.
2115         es = PointsToNode::GlobalEscape;
2116       }
2117       add_java_object(call, es);
2118       if (es == PointsToNode::GlobalEscape) {
2119         set_not_scalar_replaceable(ptnode_adr(call->_idx) NOT_PRODUCT(COMMA "object can be loaded from boxing cache"));
2120       }
2121     } else {
2122       BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
2123       call_analyzer->copy_dependencies(_compile->dependencies());
2124       if (call_analyzer->is_return_allocated()) {
2125         // Returns a newly allocated non-escaped object, simply
2126         // update dependency information.
2127         // Mark it as NoEscape so that objects referenced by
2128         // it's fields will be marked as NoEscape at least.
2129         add_java_object(call, PointsToNode::NoEscape);
2130         set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of call"));
2131       } else {
2132         // Determine whether any arguments are returned.
2133         const TypeTuple* d = call->tf()->domain();
2134         bool ret_arg = false;
2135         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2136           if (d->field_at(i)->isa_ptr() != nullptr &&
2137               call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {



2138             ret_arg = true;
2139             break;
2140           }
2141         }
2142         if (ret_arg) {
2143           add_local_var(call, PointsToNode::ArgEscape);
2144         } else {
2145           // Returns unknown object.
2146           map_ideal_node(call, phantom_obj);
2147         }
2148       }
2149     }
2150   } else {
2151     // An other type of call, assume the worst case:
2152     // returned value is unknown and globally escapes.
2153     assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
2154     map_ideal_node(call, phantom_obj);
2155   }
2156 }
2157 

2161 #ifdef ASSERT
2162     case Op_Allocate:
2163     case Op_AllocateArray:
2164     case Op_Lock:
2165     case Op_Unlock:
2166       assert(false, "should be done already");
2167       break;
2168 #endif
2169     case Op_ArrayCopy:
2170     case Op_CallLeafNoFP:
2171       // Most array copies are ArrayCopy nodes at this point but there
2172       // are still a few direct calls to the copy subroutines (See
2173       // PhaseStringOpts::copy_string())
2174       is_arraycopy = (call->Opcode() == Op_ArrayCopy) ||
2175         call->as_CallLeaf()->is_call_to_arraycopystub();
2176       // fall through
2177     case Op_CallLeafVector:
2178     case Op_CallLeaf: {
2179       // Stub calls, objects do not escape but they are not scale replaceable.
2180       // Adjust escape state for outgoing arguments.
2181       const TypeTuple * d = call->tf()->domain();
2182       bool src_has_oops = false;
2183       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2184         const Type* at = d->field_at(i);
2185         Node *arg = call->in(i);
2186         if (arg == nullptr) {
2187           continue;
2188         }
2189         const Type *aat = _igvn->type(arg);
2190         if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr()) {
2191           continue;
2192         }
2193         if (arg->is_AddP()) {
2194           //
2195           // The inline_native_clone() case when the arraycopy stub is called
2196           // after the allocation before Initialize and CheckCastPP nodes.
2197           // Or normal arraycopy for object arrays case.
2198           //
2199           // Set AddP's base (Allocate) as not scalar replaceable since
2200           // pointer to the base (with offset) is passed as argument.
2201           //
2202           arg = get_addp_base(arg);
2203         }
2204         PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2205         assert(arg_ptn != nullptr, "should be registered");
2206         PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
2207         if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
2208           assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
2209                  aat->isa_ptr() != nullptr, "expecting an Ptr");
2210           bool arg_has_oops = aat->isa_oopptr() &&
2211                               (aat->isa_instptr() ||
2212                                (aat->isa_aryptr() && (aat->isa_aryptr()->elem() == Type::BOTTOM || aat->isa_aryptr()->elem()->make_oopptr() != nullptr)));



2213           if (i == TypeFunc::Parms) {
2214             src_has_oops = arg_has_oops;
2215           }
2216           //
2217           // src or dst could be j.l.Object when other is basic type array:
2218           //
2219           //   arraycopy(char[],0,Object*,0,size);
2220           //   arraycopy(Object*,0,char[],0,size);
2221           //
2222           // Don't add edges in such cases.
2223           //
2224           bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
2225                                        arg_has_oops && (i > TypeFunc::Parms);
2226 #ifdef ASSERT
2227           if (!(is_arraycopy ||
2228                 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(call) ||
2229                 (call->as_CallLeaf()->_name != nullptr &&
2230                  (strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 ||
2231                   strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32C") == 0 ||
2232                   strcmp(call->as_CallLeaf()->_name, "updateBytesAdler32") == 0 ||

2256                   strcmp(call->as_CallLeaf()->_name, "dilithiumMontMulByConstant") == 0 ||
2257                   strcmp(call->as_CallLeaf()->_name, "dilithiumDecomposePoly") == 0 ||
2258                   strcmp(call->as_CallLeaf()->_name, "encodeBlock") == 0 ||
2259                   strcmp(call->as_CallLeaf()->_name, "decodeBlock") == 0 ||
2260                   strcmp(call->as_CallLeaf()->_name, "md5_implCompress") == 0 ||
2261                   strcmp(call->as_CallLeaf()->_name, "md5_implCompressMB") == 0 ||
2262                   strcmp(call->as_CallLeaf()->_name, "sha1_implCompress") == 0 ||
2263                   strcmp(call->as_CallLeaf()->_name, "sha1_implCompressMB") == 0 ||
2264                   strcmp(call->as_CallLeaf()->_name, "sha256_implCompress") == 0 ||
2265                   strcmp(call->as_CallLeaf()->_name, "sha256_implCompressMB") == 0 ||
2266                   strcmp(call->as_CallLeaf()->_name, "sha512_implCompress") == 0 ||
2267                   strcmp(call->as_CallLeaf()->_name, "sha512_implCompressMB") == 0 ||
2268                   strcmp(call->as_CallLeaf()->_name, "sha3_implCompress") == 0 ||
2269                   strcmp(call->as_CallLeaf()->_name, "double_keccak") == 0 ||
2270                   strcmp(call->as_CallLeaf()->_name, "sha3_implCompressMB") == 0 ||
2271                   strcmp(call->as_CallLeaf()->_name, "multiplyToLen") == 0 ||
2272                   strcmp(call->as_CallLeaf()->_name, "squareToLen") == 0 ||
2273                   strcmp(call->as_CallLeaf()->_name, "mulAdd") == 0 ||
2274                   strcmp(call->as_CallLeaf()->_name, "montgomery_multiply") == 0 ||
2275                   strcmp(call->as_CallLeaf()->_name, "montgomery_square") == 0 ||




2276                   strcmp(call->as_CallLeaf()->_name, "bigIntegerRightShiftWorker") == 0 ||
2277                   strcmp(call->as_CallLeaf()->_name, "bigIntegerLeftShiftWorker") == 0 ||
2278                   strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2279                   strcmp(call->as_CallLeaf()->_name, "stringIndexOf") == 0 ||
2280                   strcmp(call->as_CallLeaf()->_name, "arraysort_stub") == 0 ||
2281                   strcmp(call->as_CallLeaf()->_name, "array_partition_stub") == 0 ||
2282                   strcmp(call->as_CallLeaf()->_name, "get_class_id_intrinsic") == 0 ||
2283                   strcmp(call->as_CallLeaf()->_name, "unsafe_setmemory") == 0)
2284                  ))) {
2285             call->dump();
2286             fatal("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name);
2287           }
2288 #endif
2289           // Always process arraycopy's destination object since
2290           // we need to add all possible edges to references in
2291           // source object.
2292           if (arg_esc >= PointsToNode::ArgEscape &&
2293               !arg_is_arraycopy_dest) {
2294             continue;
2295           }

2318           }
2319         }
2320       }
2321       break;
2322     }
2323     case Op_CallStaticJava: {
2324       // For a static call, we know exactly what method is being called.
2325       // Use bytecode estimator to record the call's escape affects
2326 #ifdef ASSERT
2327       const char* name = call->as_CallStaticJava()->_name;
2328       assert((name == nullptr || strcmp(name, "uncommon_trap") != 0), "normal calls only");
2329 #endif
2330       ciMethod* meth = call->as_CallJava()->method();
2331       if ((meth != nullptr) && meth->is_boxing_method()) {
2332         break; // Boxing methods do not modify any oops.
2333       }
2334       BCEscapeAnalyzer* call_analyzer = (meth !=nullptr) ? meth->get_bcea() : nullptr;
2335       // fall-through if not a Java method or no analyzer information
2336       if (call_analyzer != nullptr) {
2337         PointsToNode* call_ptn = ptnode_adr(call->_idx);
2338         const TypeTuple* d = call->tf()->domain();
2339         for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2340           const Type* at = d->field_at(i);
2341           int k = i - TypeFunc::Parms;
2342           Node* arg = call->in(i);
2343           PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2344           if (at->isa_ptr() != nullptr &&
2345               call_analyzer->is_arg_returned(k)) {

2346             // The call returns arguments.
2347             if (call_ptn != nullptr) { // Is call's result used?
2348               assert(call_ptn->is_LocalVar(), "node should be registered");
2349               assert(arg_ptn != nullptr, "node should be registered");
2350               add_edge(call_ptn, arg_ptn);
2351             }
2352           }
2353           if (at->isa_oopptr() != nullptr &&
2354               arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
2355             if (!call_analyzer->is_arg_stack(k)) {
2356               // The argument global escapes
2357               set_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2358             } else {
2359               set_escape_state(arg_ptn, PointsToNode::ArgEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2360               if (!call_analyzer->is_arg_local(k)) {
2361                 // The argument itself doesn't escape, but any fields might
2362                 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2363               }
2364             }
2365           }
2366         }
2367         if (call_ptn != nullptr && call_ptn->is_LocalVar()) {
2368           // The call returns arguments.
2369           assert(call_ptn->edge_count() > 0, "sanity");
2370           if (!call_analyzer->is_return_local()) {
2371             // Returns also unknown object.
2372             add_edge(call_ptn, phantom_obj);
2373           }
2374         }
2375         break;
2376       }
2377     }
2378     default: {
2379       // Fall-through here if not a Java method or no analyzer information
2380       // or some other type of call, assume the worst case: all arguments
2381       // globally escape.
2382       const TypeTuple* d = call->tf()->domain();
2383       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2384         const Type* at = d->field_at(i);
2385         if (at->isa_oopptr() != nullptr) {
2386           Node* arg = call->in(i);
2387           if (arg->is_AddP()) {
2388             arg = get_addp_base(arg);
2389           }
2390           assert(ptnode_adr(arg->_idx) != nullptr, "should be defined already");
2391           set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2392         }
2393       }
2394     }
2395   }
2396 }
2397 
2398 
2399 // Finish Graph construction.
2400 bool ConnectionGraph::complete_connection_graph(
2401                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
2402                          GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,

2780     PointsToNode* base = i.get();
2781     if (base->is_JavaObject()) {
2782       // Skip Allocate's fields which will be processed later.
2783       if (base->ideal_node()->is_Allocate()) {
2784         return 0;
2785       }
2786       assert(base == null_obj, "only null ptr base expected here");
2787     }
2788   }
2789   if (add_edge(field, phantom_obj)) {
2790     // New edge was added
2791     new_edges++;
2792     add_field_uses_to_worklist(field);
2793   }
2794   return new_edges;
2795 }
2796 
2797 // Find fields initializing values for allocations.
2798 int ConnectionGraph::find_init_values_phantom(JavaObjectNode* pta) {
2799   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");

2800   Node* alloc = pta->ideal_node();
2801 
2802   // Do nothing for Allocate nodes since its fields values are
2803   // "known" unless they are initialized by arraycopy/clone.
2804   if (alloc->is_Allocate() && !pta->arraycopy_dst()) {
2805     return 0;






2806   }
2807   assert(pta->arraycopy_dst() || alloc->as_CallStaticJava(), "sanity");

2808 #ifdef ASSERT
2809   if (!pta->arraycopy_dst() && alloc->as_CallStaticJava()->method() == nullptr) {
2810     assert(alloc->as_CallStaticJava()->is_call_to_multianewarray_stub(), "sanity");



2811   }
2812 #endif
2813   // Non-escaped allocation returned from Java or runtime call have unknown values in fields.
2814   int new_edges = 0;
2815   for (EdgeIterator i(pta); i.has_next(); i.next()) {
2816     PointsToNode* field = i.get();
2817     if (field->is_Field() && field->as_Field()->is_oop()) {
2818       if (add_edge(field, phantom_obj)) {
2819         // New edge was added
2820         new_edges++;
2821         add_field_uses_to_worklist(field->as_Field());
2822       }
2823     }
2824   }
2825   return new_edges;
2826 }
2827 
2828 // Find fields initializing values for allocations.
2829 int ConnectionGraph::find_init_values_null(JavaObjectNode* pta, PhaseValues* phase) {
2830   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2831   Node* alloc = pta->ideal_node();
2832   // Do nothing for Call nodes since its fields values are unknown.
2833   if (!alloc->is_Allocate()) {
2834     return 0;
2835   }
2836   InitializeNode* ini = alloc->as_Allocate()->initialization();
2837   bool visited_bottom_offset = false;
2838   GrowableArray<int> offsets_worklist;
2839   int new_edges = 0;
2840 
2841   // Check if an oop field's initializing value is recorded and add
2842   // a corresponding null if field's value if it is not recorded.
2843   // Connection Graph does not record a default initialization by null
2844   // captured by Initialize node.
2845   //
2846   for (EdgeIterator i(pta); i.has_next(); i.next()) {
2847     PointsToNode* field = i.get(); // Field (AddP)
2848     if (!field->is_Field() || !field->as_Field()->is_oop()) {
2849       continue; // Not oop field
2850     }
2851     int offset = field->as_Field()->offset();
2852     if (offset == Type::OffsetBot) {
2853       if (!visited_bottom_offset) {

2899               } else {
2900                 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
2901                   tty->print_cr("----------init store has invalid value -----");
2902                   store->dump();
2903                   val->dump();
2904                   assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
2905                 }
2906                 for (EdgeIterator j(val); j.has_next(); j.next()) {
2907                   PointsToNode* obj = j.get();
2908                   if (obj->is_JavaObject()) {
2909                     if (!field->points_to(obj->as_JavaObject())) {
2910                       missed_obj = obj;
2911                       break;
2912                     }
2913                   }
2914                 }
2915               }
2916               if (missed_obj != nullptr) {
2917                 tty->print_cr("----------field---------------------------------");
2918                 field->dump();
2919                 tty->print_cr("----------missed referernce to object-----------");
2920                 missed_obj->dump();
2921                 tty->print_cr("----------object referernced by init store -----");
2922                 store->dump();
2923                 val->dump();
2924                 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
2925               }
2926             }
2927 #endif
2928           } else {
2929             // There could be initializing stores which follow allocation.
2930             // For example, a volatile field store is not collected
2931             // by Initialize node.
2932             //
2933             // Need to check for dependent loads to separate such stores from
2934             // stores which follow loads. For now, add initial value null so
2935             // that compare pointers optimization works correctly.
2936           }
2937         }
2938         if (value == nullptr) {
2939           // A field's initializing value was not recorded. Add null.
2940           if (add_edge(field, null_obj)) {
2941             // New edge was added

3266         assert(field->edge_count() > 0, "sanity");
3267       }
3268     }
3269   }
3270 }
3271 #endif
3272 
3273 // Optimize ideal graph.
3274 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
3275                                            GrowableArray<MemBarStoreStoreNode*>& storestore_worklist) {
3276   Compile* C = _compile;
3277   PhaseIterGVN* igvn = _igvn;
3278   if (EliminateLocks) {
3279     // Mark locks before changing ideal graph.
3280     int cnt = C->macro_count();
3281     for (int i = 0; i < cnt; i++) {
3282       Node *n = C->macro_node(i);
3283       if (n->is_AbstractLock()) { // Lock and Unlock nodes
3284         AbstractLockNode* alock = n->as_AbstractLock();
3285         if (!alock->is_non_esc_obj()) {
3286           if (can_eliminate_lock(alock)) {

3287             assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
3288             // The lock could be marked eliminated by lock coarsening
3289             // code during first IGVN before EA. Replace coarsened flag
3290             // to eliminate all associated locks/unlocks.
3291 #ifdef ASSERT
3292             alock->log_lock_optimization(C, "eliminate_lock_set_non_esc3");
3293 #endif
3294             alock->set_non_esc_obj();
3295           }
3296         }
3297       }
3298     }
3299   }
3300 
3301   if (OptimizePtrCompare) {
3302     for (int i = 0; i < ptr_cmp_worklist.length(); i++) {
3303       Node *n = ptr_cmp_worklist.at(i);
3304       assert(n->Opcode() == Op_CmpN || n->Opcode() == Op_CmpP, "must be");
3305       const TypeInt* tcmp = optimize_ptr_compare(n->in(1), n->in(2));
3306       if (tcmp->singleton()) {

3308 #ifndef PRODUCT
3309         if (PrintOptimizePtrCompare) {
3310           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"));
3311           if (Verbose) {
3312             n->dump(1);
3313           }
3314         }
3315 #endif
3316         igvn->replace_node(n, cmp);
3317       }
3318     }
3319   }
3320 
3321   // For MemBarStoreStore nodes added in library_call.cpp, check
3322   // escape status of associated AllocateNode and optimize out
3323   // MemBarStoreStore node if the allocated object never escapes.
3324   for (int i = 0; i < storestore_worklist.length(); i++) {
3325     Node* storestore = storestore_worklist.at(i);
3326     Node* alloc = storestore->in(MemBarNode::Precedent)->in(0);
3327     if (alloc->is_Allocate() && not_global_escape(alloc)) {
3328       MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
3329       mb->init_req(TypeFunc::Memory,  storestore->in(TypeFunc::Memory));
3330       mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
3331       igvn->register_new_node_with_optimizer(mb);
3332       igvn->replace_node(storestore, mb);





3333     }
3334   }
3335 }
3336 

























3337 // Optimize objects compare.
3338 const TypeInt* ConnectionGraph::optimize_ptr_compare(Node* left, Node* right) {
3339   const TypeInt* UNKNOWN = TypeInt::CC;    // [-1, 0,1]
3340   if (!OptimizePtrCompare) {
3341     return UNKNOWN;
3342   }
3343   const TypeInt* EQ = TypeInt::CC_EQ; // [0] == ZERO
3344   const TypeInt* NE = TypeInt::CC_GT; // [1] == ONE
3345 
3346   PointsToNode* ptn1 = ptnode_adr(left->_idx);
3347   PointsToNode* ptn2 = ptnode_adr(right->_idx);
3348   JavaObjectNode* jobj1 = unique_java_object(left);
3349   JavaObjectNode* jobj2 = unique_java_object(right);
3350 
3351   // The use of this method during allocation merge reduction may cause 'left'
3352   // or 'right' be something (e.g., a Phi) that isn't in the connection graph or
3353   // that doesn't reference an unique java object.
3354   if (ptn1 == nullptr || ptn2 == nullptr ||
3355       jobj1 == nullptr || jobj2 == nullptr) {
3356     return UNKNOWN;

3476   assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
3477   assert((src != null_obj) && (dst != null_obj), "not for ConP null");
3478   PointsToNode* ptadr = _nodes.at(n->_idx);
3479   if (ptadr != nullptr) {
3480     assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
3481     return;
3482   }
3483   Compile* C = _compile;
3484   ptadr = new (C->comp_arena()) ArraycopyNode(this, n, es);
3485   map_ideal_node(n, ptadr);
3486   // Add edge from arraycopy node to source object.
3487   (void)add_edge(ptadr, src);
3488   src->set_arraycopy_src();
3489   // Add edge from destination object to arraycopy node.
3490   (void)add_edge(dst, ptadr);
3491   dst->set_arraycopy_dst();
3492 }
3493 
3494 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
3495   const Type* adr_type = n->as_AddP()->bottom_type();

3496   BasicType bt = T_INT;
3497   if (offset == Type::OffsetBot) {
3498     // Check only oop fields.
3499     if (!adr_type->isa_aryptr() ||
3500         adr_type->isa_aryptr()->elem() == Type::BOTTOM ||
3501         adr_type->isa_aryptr()->elem()->make_oopptr() != nullptr) {
3502       // OffsetBot is used to reference array's element. Ignore first AddP.
3503       if (find_second_addp(n, n->in(AddPNode::Base)) == nullptr) {
3504         bt = T_OBJECT;
3505       }
3506     }
3507   } else if (offset != oopDesc::klass_offset_in_bytes()) {
3508     if (adr_type->isa_instptr()) {
3509       ciField* field = _compile->alias_type(adr_type->isa_instptr())->field();
3510       if (field != nullptr) {
3511         bt = field->layout_type();
3512       } else {
3513         // Check for unsafe oop field access
3514         if (has_oop_node_outs(n)) {
3515           bt = T_OBJECT;
3516           (*unsafe) = true;
3517         }
3518       }
3519     } else if (adr_type->isa_aryptr()) {
3520       if (offset == arrayOopDesc::length_offset_in_bytes()) {
3521         // Ignore array length load.
3522       } else if (find_second_addp(n, n->in(AddPNode::Base)) != nullptr) {
3523         // Ignore first AddP.
3524       } else {
3525         const Type* elemtype = adr_type->isa_aryptr()->elem();
3526         bt = elemtype->array_element_basic_type();












3527       }
3528     } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
3529       // Allocation initialization, ThreadLocal field access, unsafe access
3530       if (has_oop_node_outs(n)) {
3531         bt = T_OBJECT;
3532       }
3533     }
3534   }
3535   // Note: T_NARROWOOP is not classed as a real reference type
3536   bool res = (is_reference_type(bt) || bt == T_NARROWOOP);
3537   assert(!has_oop_node_outs(n) || res, "sanity: AddP has oop outs, needs to be treated as oop field");
3538   return res;
3539 }
3540 
3541 bool ConnectionGraph::has_oop_node_outs(Node* n) {
3542   return n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3543          n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3544          n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3545          BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n);
3546 }

3709             return true;
3710           }
3711         }
3712       }
3713     }
3714   }
3715   return false;
3716 }
3717 
3718 int ConnectionGraph::address_offset(Node* adr, PhaseValues* phase) {
3719   const Type *adr_type = phase->type(adr);
3720   if (adr->is_AddP() && adr_type->isa_oopptr() == nullptr && is_captured_store_address(adr)) {
3721     // We are computing a raw address for a store captured by an Initialize
3722     // compute an appropriate address type. AddP cases #3 and #5 (see below).
3723     int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
3724     assert(offs != Type::OffsetBot ||
3725            adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
3726            "offset must be a constant or it is initialization of array");
3727     return offs;
3728   }
3729   const TypePtr *t_ptr = adr_type->isa_ptr();
3730   assert(t_ptr != nullptr, "must be a pointer type");
3731   return t_ptr->offset();
3732 }
3733 
3734 Node* ConnectionGraph::get_addp_base(Node *addp) {
3735   assert(addp->is_AddP(), "must be AddP");
3736   //
3737   // AddP cases for Base and Address inputs:
3738   // case #1. Direct object's field reference:
3739   //     Allocate
3740   //       |
3741   //     Proj #5 ( oop result )
3742   //       |
3743   //     CheckCastPP (cast to instance type)
3744   //      | |
3745   //     AddP  ( base == address )
3746   //
3747   // case #2. Indirect object's field reference:
3748   //      Phi
3749   //       |
3750   //     CastPP (cast to instance type)
3751   //      | |
3752   //     AddP  ( base == address )
3753   //
3754   // case #3. Raw object's field reference for Initialize node:

3755   //      Allocate
3756   //        |
3757   //      Proj #5 ( oop result )
3758   //  top   |
3759   //     \  |
3760   //     AddP  ( base == top )
3761   //
3762   // case #4. Array's element reference:
3763   //   {CheckCastPP | CastPP}
3764   //     |  | |
3765   //     |  AddP ( array's element offset )
3766   //     |  |
3767   //     AddP ( array's offset )
3768   //
3769   // case #5. Raw object's field reference for arraycopy stub call:
3770   //          The inline_native_clone() case when the arraycopy stub is called
3771   //          after the allocation before Initialize and CheckCastPP nodes.
3772   //      Allocate
3773   //        |
3774   //      Proj #5 ( oop result )

3785   // case #7. Klass's field reference.
3786   //      LoadKlass
3787   //       | |
3788   //       AddP  ( base == address )
3789   //
3790   // case #8. narrow Klass's field reference.
3791   //      LoadNKlass
3792   //       |
3793   //      DecodeN
3794   //       | |
3795   //       AddP  ( base == address )
3796   //
3797   // case #9. Mixed unsafe access
3798   //    {instance}
3799   //        |
3800   //      CheckCastPP (raw)
3801   //  top   |
3802   //     \  |
3803   //     AddP  ( base == top )
3804   //












3805   Node *base = addp->in(AddPNode::Base);
3806   if (base->uncast()->is_top()) { // The AddP case #3 and #6 and #9.
3807     base = addp->in(AddPNode::Address);
3808     while (base->is_AddP()) {
3809       // Case #6 (unsafe access) may have several chained AddP nodes.
3810       assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
3811       base = base->in(AddPNode::Address);
3812     }
3813     if (base->Opcode() == Op_CheckCastPP &&
3814         base->bottom_type()->isa_rawptr() &&
3815         _igvn->type(base->in(1))->isa_oopptr()) {
3816       base = base->in(1); // Case #9
3817     } else {

3818       Node* uncast_base = base->uncast();
3819       int opcode = uncast_base->Opcode();
3820       assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
3821              opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() ||
3822              (_igvn->C->is_osr_compilation() && uncast_base->is_Parm() && uncast_base->as_Parm()->_con == TypeFunc::Parms)||
3823              (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_rawptr() != nullptr)) ||
3824              (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_klassptr() != nullptr)) ||
3825              is_captured_store_address(addp), "sanity");

3826     }
3827   }
3828   return base;
3829 }
3830 













3831 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
3832   assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
3833   Node* addp2 = addp->raw_out(0);
3834   if (addp->outcnt() == 1 && addp2->is_AddP() &&
3835       addp2->in(AddPNode::Base) == n &&
3836       addp2->in(AddPNode::Address) == addp) {
3837     assert(addp->in(AddPNode::Base) == n, "expecting the same base");
3838     //
3839     // Find array's offset to push it on worklist first and
3840     // as result process an array's element offset first (pushed second)
3841     // to avoid CastPP for the array's offset.
3842     // Otherwise the inserted CastPP (LocalVar) will point to what
3843     // the AddP (Field) points to. Which would be wrong since
3844     // the algorithm expects the CastPP has the same point as
3845     // as AddP's base CheckCastPP (LocalVar).
3846     //
3847     //    ArrayAllocation
3848     //     |
3849     //    CheckCastPP
3850     //     |

3867   }
3868   return nullptr;
3869 }
3870 
3871 //
3872 // Adjust the type and inputs of an AddP which computes the
3873 // address of a field of an instance
3874 //
3875 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
3876   PhaseGVN* igvn = _igvn;
3877   const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
3878   assert(base_t != nullptr && base_t->is_known_instance(), "expecting instance oopptr");
3879   const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
3880   if (t == nullptr) {
3881     // We are computing a raw address for a store captured by an Initialize
3882     // compute an appropriate address type (cases #3 and #5).
3883     assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
3884     assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
3885     intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
3886     assert(offs != Type::OffsetBot, "offset must be a constant");
3887     t = base_t->add_offset(offs)->is_oopptr();







3888   }
3889   int inst_id =  base_t->instance_id();
3890   assert(!t->is_known_instance() || t->instance_id() == inst_id,
3891                              "old type must be non-instance or match new type");
3892 
3893   // The type 't' could be subclass of 'base_t'.
3894   // As result t->offset() could be large then base_t's size and it will
3895   // cause the failure in add_offset() with narrow oops since TypeOopPtr()
3896   // constructor verifies correctness of the offset.
3897   //
3898   // It could happened on subclass's branch (from the type profiling
3899   // inlining) which was not eliminated during parsing since the exactness
3900   // of the allocation type was not propagated to the subclass type check.
3901   //
3902   // Or the type 't' could be not related to 'base_t' at all.
3903   // It could happened when CHA type is different from MDO type on a dead path
3904   // (for example, from instanceof check) which is not collapsed during parsing.
3905   //
3906   // Do nothing for such AddP node and don't process its users since
3907   // this code branch will go away.
3908   //
3909   if (!t->is_known_instance() &&
3910       !base_t->maybe_java_subtype_of(t)) {
3911      return false; // bail out
3912   }
3913   const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();











3914   // Do NOT remove the next line: ensure a new alias index is allocated
3915   // for the instance type. Note: C++ will not remove it since the call
3916   // has side effect.
3917   int alias_idx = _compile->get_alias_index(tinst);
3918   igvn->set_type(addp, tinst);
3919   // record the allocation in the node map
3920   set_map(addp, get_map(base->_idx));
3921   // Set addp's Base and Address to 'base'.
3922   Node *abase = addp->in(AddPNode::Base);
3923   Node *adr   = addp->in(AddPNode::Address);
3924   if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
3925       adr->in(0)->_idx == (uint)inst_id) {
3926     // Skip AddP cases #3 and #5.
3927   } else {
3928     assert(!abase->is_top(), "sanity"); // AddP case #3
3929     if (abase != base) {
3930       igvn->hash_delete(addp);
3931       addp->set_req(AddPNode::Base, base);
3932       if (abase == adr) {
3933         addp->set_req(AddPNode::Address, base);

4502       //   - not determined to be ineligible by escape analysis
4503       set_map(alloc, n);
4504       set_map(n, alloc);
4505       const TypeOopPtr* tinst = t->cast_to_instance_id(ni);
4506       igvn->hash_delete(n);
4507       igvn->set_type(n,  tinst);
4508       n->raise_bottom_type(tinst);
4509       igvn->hash_insert(n);
4510       record_for_optimizer(n);
4511       // Allocate an alias index for the header fields. Accesses to
4512       // the header emitted during macro expansion wouldn't have
4513       // correct memory state otherwise.
4514       _compile->get_alias_index(tinst->add_offset(oopDesc::mark_offset_in_bytes()));
4515       _compile->get_alias_index(tinst->add_offset(oopDesc::klass_offset_in_bytes()));
4516       if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
4517         // Add a new NarrowMem projection for each existing NarrowMem projection with new adr type
4518         InitializeNode* init = alloc->as_Allocate()->initialization();
4519         assert(init != nullptr, "can't find Initialization node for this Allocate node");
4520         auto process_narrow_proj = [&](NarrowMemProjNode* proj) {
4521           const TypePtr* adr_type = proj->adr_type();
4522           const TypePtr* new_adr_type = tinst->add_offset(adr_type->offset());





4523           if (adr_type != new_adr_type && !init->already_has_narrow_mem_proj_with_adr_type(new_adr_type)) {
4524             DEBUG_ONLY( uint alias_idx = _compile->get_alias_index(new_adr_type); )
4525             assert(_compile->get_general_index(alias_idx) == _compile->get_alias_index(adr_type), "new adr type should be narrowed down from existing adr type");
4526             NarrowMemProjNode* new_proj = new NarrowMemProjNode(init, new_adr_type);
4527             igvn->set_type(new_proj, new_proj->bottom_type());
4528             record_for_optimizer(new_proj);
4529             set_map(proj, new_proj); // record it so ConnectionGraph::find_inst_mem() can find it
4530           }
4531         };
4532         init->for_each_narrow_mem_proj_with_new_uses(process_narrow_proj);
4533 
4534         // First, put on the worklist all Field edges from Connection Graph
4535         // which is more accurate than putting immediate users from Ideal Graph.
4536         for (EdgeIterator e(ptn); e.has_next(); e.next()) {
4537           PointsToNode* tgt = e.get();
4538           if (tgt->is_Arraycopy()) {
4539             continue;
4540           }
4541           Node* use = tgt->ideal_node();
4542           assert(tgt->is_Field() && use->is_AddP(),

4619         ptnode_adr(n->_idx)->dump();
4620         assert(jobj != nullptr && jobj != phantom_obj, "escaped allocation");
4621 #endif
4622         _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4623         return;
4624       } else {
4625         Node *val = get_map(jobj->idx());   // CheckCastPP node
4626         TypeNode *tn = n->as_Type();
4627         const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
4628         assert(tinst != nullptr && tinst->is_known_instance() &&
4629                tinst->instance_id() == jobj->idx() , "instance type expected.");
4630 
4631         const Type *tn_type = igvn->type(tn);
4632         const TypeOopPtr *tn_t;
4633         if (tn_type->isa_narrowoop()) {
4634           tn_t = tn_type->make_ptr()->isa_oopptr();
4635         } else {
4636           tn_t = tn_type->isa_oopptr();
4637         }
4638         if (tn_t != nullptr && tinst->maybe_java_subtype_of(tn_t)) {







4639           if (tn_type->isa_narrowoop()) {
4640             tn_type = tinst->make_narrowoop();
4641           } else {
4642             tn_type = tinst;
4643           }
4644           igvn->hash_delete(tn);
4645           igvn->set_type(tn, tn_type);
4646           tn->set_type(tn_type);
4647           igvn->hash_insert(tn);
4648           record_for_optimizer(n);
4649         } else {
4650           assert(tn_type == TypePtr::NULL_PTR ||
4651                  (tn_t != nullptr && !tinst->maybe_java_subtype_of(tn_t)),
4652                  "unexpected type");
4653           continue; // Skip dead path with different type
4654         }
4655       }
4656     } else {
4657       DEBUG_ONLY(n->dump();)
4658       assert(false, "EA: unexpected node");
4659       continue;
4660     }
4661     // push allocation's users on appropriate worklist
4662     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4663       Node *use = n->fast_out(i);
4664       if(use->is_Mem() && use->in(MemNode::Address) == n) {
4665         // Load/store to instance's field
4666         memnode_worklist.append_if_missing(use);
4667       } else if (use->is_MemBar()) {
4668         if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4669           memnode_worklist.append_if_missing(use);
4670         }
4671       } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
4672         Node* addp2 = find_second_addp(use, n);
4673         if (addp2 != nullptr) {
4674           alloc_worklist.append_if_missing(addp2);
4675         }
4676         alloc_worklist.append_if_missing(use);
4677       } else if (use->is_Phi() ||
4678                  use->is_CheckCastPP() ||
4679                  use->is_EncodeNarrowPtr() ||
4680                  use->is_DecodeNarrowPtr() ||
4681                  (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
4682         alloc_worklist.append_if_missing(use);
4683 #ifdef ASSERT
4684       } else if (use->is_Mem()) {
4685         assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
4686       } else if (use->is_MergeMem()) {
4687         assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4688       } else if (use->is_SafePoint()) {
4689         // Look for MergeMem nodes for calls which reference unique allocation
4690         // (through CheckCastPP nodes) even for debug info.
4691         Node* m = use->in(TypeFunc::Memory);
4692         if (m->is_MergeMem()) {
4693           assert(mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4694         }
4695       } else if (use->Opcode() == Op_EncodeISOArray) {
4696         if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4697           // EncodeISOArray overwrites destination array
4698           memnode_worklist.append_if_missing(use);
4699         }



4700       } else {
4701         uint op = use->Opcode();
4702         if ((op == Op_StrCompressedCopy || op == Op_StrInflatedCopy) &&
4703             (use->in(MemNode::Memory) == n)) {
4704           // They overwrite memory edge corresponding to destination array,
4705           memnode_worklist.append_if_missing(use);
4706         } else if (!(op == Op_CmpP || op == Op_Conv2B ||
4707               op == Op_CastP2X ||
4708               op == Op_FastLock || op == Op_AryEq ||
4709               op == Op_StrComp || op == Op_CountPositives ||
4710               op == Op_StrCompressedCopy || op == Op_StrInflatedCopy ||
4711               op == Op_StrEquals || op == Op_VectorizedHashCode ||
4712               op == Op_StrIndexOf || op == Op_StrIndexOfChar ||
4713               op == Op_SubTypeCheck ||
4714               op == Op_ReinterpretS2HF ||
4715               BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use))) {
4716           n->dump();
4717           use->dump();
4718           assert(false, "EA: missing allocation reference path");
4719         }
4720 #endif
4721       }
4722     }
4723 
4724   }
4725 
4726 #ifdef ASSERT
4727   if (VerifyReduceAllocationMerges) {
4728     for (uint i = 0; i < reducible_merges.size(); i++) {
4729       Node* phi = reducible_merges.at(i);
4730 
4731       if (!reduced_merges.member(phi)) {
4732         phi->dump(2);
4733         phi->dump(-2);

4801         n = n->as_MemBar()->proj_out_or_null(TypeFunc::Memory);
4802         if (n == nullptr) {
4803           continue;
4804         }
4805       }
4806     } else if (n->is_CallLeaf()) {
4807       // Runtime calls with narrow memory input (no MergeMem node)
4808       // get the memory projection
4809       n = n->as_Call()->proj_out_or_null(TypeFunc::Memory);
4810       if (n == nullptr) {
4811         continue;
4812       }
4813     } else if (n->Opcode() == Op_StrInflatedCopy) {
4814       // Check direct uses of StrInflatedCopy.
4815       // It is memory type Node - no special SCMemProj node.
4816     } else if (n->Opcode() == Op_StrCompressedCopy ||
4817                n->Opcode() == Op_EncodeISOArray) {
4818       // get the memory projection
4819       n = n->find_out_with(Op_SCMemProj);
4820       assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");



4821     } else if (n->is_Proj()) {
4822       assert(n->in(0)->is_Initialize(), "we only push memory projections for Initialize");
4823     } else {
4824 #ifdef ASSERT
4825       if (!n->is_Mem()) {
4826         n->dump();
4827       }
4828       assert(n->is_Mem(), "memory node required.");
4829 #endif
4830       Node *addr = n->in(MemNode::Address);
4831       const Type *addr_t = igvn->type(addr);
4832       if (addr_t == Type::TOP) {
4833         continue;
4834       }
4835       assert (addr_t->isa_ptr() != nullptr, "pointer type required.");
4836       int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
4837       assert ((uint)alias_idx < new_index_end, "wrong alias index");
4838       Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
4839       if (_compile->failing()) {
4840         return;

4852         assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
4853       }
4854     }
4855     // push user on appropriate worklist
4856     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4857       Node *use = n->fast_out(i);
4858       if (use->is_Phi() || use->is_ClearArray()) {
4859         memnode_worklist.append_if_missing(use);
4860       } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
4861         memnode_worklist.append_if_missing(use);
4862       } else if (use->is_MemBar() || use->is_CallLeaf()) {
4863         if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4864           memnode_worklist.append_if_missing(use);
4865         }
4866       } else if (use->is_Proj()) {
4867         assert(n->is_Initialize(), "We only push projections of Initialize");
4868         if (use->as_Proj()->_con == TypeFunc::Memory) { // Ignore precedent edge
4869           memnode_worklist.append_if_missing(use);
4870         }
4871 #ifdef ASSERT
4872       } else if(use->is_Mem()) {
4873         assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
4874       } else if (use->is_MergeMem()) {
4875         assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4876       } else if (use->Opcode() == Op_EncodeISOArray) {
4877         if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4878           // EncodeISOArray overwrites destination array
4879           memnode_worklist.append_if_missing(use);
4880         }




4881       } else {
4882         uint op = use->Opcode();
4883         if ((use->in(MemNode::Memory) == n) &&
4884             (op == Op_StrCompressedCopy || op == Op_StrInflatedCopy)) {
4885           // They overwrite memory edge corresponding to destination array,
4886           memnode_worklist.append_if_missing(use);
4887         } else if (!(BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use) ||
4888               op == Op_AryEq || op == Op_StrComp || op == Op_CountPositives ||
4889               op == Op_StrCompressedCopy || op == Op_StrInflatedCopy || op == Op_VectorizedHashCode ||
4890               op == Op_StrEquals || op == Op_StrIndexOf || op == Op_StrIndexOfChar)) {
4891           n->dump();
4892           use->dump();
4893           assert(false, "EA: missing memory path");
4894         }
4895 #endif
4896       }
4897     }
4898   }
4899 
4900   //  Phase 3:  Process MergeMem nodes from mergemem_worklist.
4901   //            Walk each memory slice moving the first node encountered of each
4902   //            instance type to the input corresponding to its alias index.
4903   uint length = mergemem_worklist.length();
4904   for( uint next = 0; next < length; ++next ) {
4905     MergeMemNode* nmm = mergemem_worklist.at(next);
4906     assert(!visited.test_set(nmm->_idx), "should not be visited before");
4907     // Note: we don't want to use MergeMemStream here because we only want to
4908     // scan inputs which exist at the start, not ones we add during processing.
4909     // Note 2: MergeMem may already contains instance memory slices added
4910     // during find_inst_mem() call when memory nodes were processed above.

4973         _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
4974       } else if (_invocation > 0) {
4975         _compile->record_failure(C2Compiler::retry_no_iterative_escape_analysis());
4976       } else {
4977         _compile->record_failure(C2Compiler::retry_no_escape_analysis());
4978       }
4979       return;
4980     }
4981 
4982     igvn->hash_insert(nmm);
4983     record_for_optimizer(nmm);
4984   }
4985 
4986   _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_3, 5);
4987 
4988   //  Phase 4:  Update the inputs of non-instance memory Phis and
4989   //            the Memory input of memnodes
4990   // First update the inputs of any non-instance Phi's from
4991   // which we split out an instance Phi.  Note we don't have
4992   // to recursively process Phi's encountered on the input memory
4993   // chains as is done in split_memory_phi() since they  will
4994   // also be processed here.
4995   for (int j = 0; j < orig_phis.length(); j++) {
4996     PhiNode *phi = orig_phis.at(j);
4997     int alias_idx = _compile->get_alias_index(phi->adr_type());
4998     igvn->hash_delete(phi);
4999     for (uint i = 1; i < phi->req(); i++) {
5000       Node *mem = phi->in(i);
5001       Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
5002       if (_compile->failing()) {
5003         return;
5004       }
5005       if (mem != new_mem) {
5006         phi->set_req(i, new_mem);
5007       }
5008     }
5009     igvn->hash_insert(phi);
5010     record_for_optimizer(phi);
5011   }
5012 
5013   // Update the memory inputs of MemNodes with the value we computed

  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),

 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:

 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   }

1303 
1304     // The next two inputs are:
1305     //  (1) A copy of the original pointer to NSR objects.
1306     //  (2) A selector, used to decide if we need to rematerialize an object
1307     //      or use the pointer to a NSR object.
1308     // See more details of these fields in the declaration of SafePointScalarMergeNode
1309     sfpt->add_req(nsr_merge_pointer);
1310     sfpt->add_req(selector);
1311 
1312     for (uint i = 1; i < ophi->req(); i++) {
1313       Node* base = ophi->in(i);
1314       JavaObjectNode* ptn = unique_java_object(base);
1315 
1316       // If the base is not scalar replaceable we don't need to register information about
1317       // it at this time.
1318       if (ptn == nullptr || !ptn->scalar_replaceable()) {
1319         continue;
1320       }
1321 
1322       AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
1323       Unique_Node_List value_worklist;
1324 #ifdef ASSERT
1325       const Type* res_type = alloc->result_cast()->bottom_type();
1326       if (res_type->is_inlinetypeptr() && !Compile::current()->has_circular_inline_type()) {
1327         PhiNode* phi = ophi->as_Phi();
1328         assert(!ophi->as_Phi()->can_push_inline_types_down(_igvn), "missed earlier scalarization opportunity");
1329       }
1330 #endif
1331       SafePointScalarObjectNode* sobj = mexp.create_scalarized_object_description(alloc, sfpt, &value_worklist);
1332       if (sobj == nullptr) {
1333         _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
1334         return false;
1335       }
1336 
1337       // Now make a pass over the debug information replacing any references
1338       // to the allocated object with "sobj"
1339       Node* ccpp = alloc->result_cast();
1340       sfpt->replace_edges_in_range(ccpp, sobj, debug_start, jvms->debug_end(), _igvn);
1341 
1342       // Register the scalarized object as a candidate for reallocation
1343       smerge->add_req(sobj);
1344 
1345       // Scalarize inline types that were added to the safepoint.
1346       // Don't allow linking a constant oop (if available) for flat array elements
1347       // because Deoptimization::reassign_flat_array_elements needs field values.
1348       const bool allow_oop = !merge_t->is_flat();
1349       for (uint j = 0; j < value_worklist.size(); ++j) {
1350         InlineTypeNode* vt = value_worklist.at(j)->as_InlineType();
1351         vt->make_scalar_in_safepoints(_igvn, allow_oop);
1352       }
1353     }
1354 
1355     // Replaces debug information references to "original_sfpt_parent" in "sfpt" with references to "smerge"
1356     sfpt->replace_edges_in_range(original_sfpt_parent, smerge, debug_start, jvms->debug_end(), _igvn);
1357 
1358     // The call to 'replace_edges_in_range' above might have removed the
1359     // reference to ophi that we need at _merge_pointer_idx. The line below make
1360     // sure the reference is maintained.
1361     sfpt->set_req(smerge->merge_pointer_idx(jvms), nsr_merge_pointer);
1362     _igvn->_worklist.push(sfpt);
1363   }
1364 
1365   return true;
1366 }
1367 
1368 void ConnectionGraph::reduce_phi(PhiNode* ophi, GrowableArray<Node*> &alloc_worklist) {
1369   bool delay = _igvn->delay_transform();
1370   _igvn->set_delay_transform(true);
1371   _igvn->hash_delete(ophi);
1372 

1535   return false;
1536 }
1537 
1538 // Returns true if at least one of the arguments to the call is an object
1539 // that does not escape globally.
1540 bool ConnectionGraph::has_arg_escape(CallJavaNode* call) {
1541   if (call->method() != nullptr) {
1542     uint max_idx = TypeFunc::Parms + call->method()->arg_size();
1543     for (uint idx = TypeFunc::Parms; idx < max_idx; idx++) {
1544       Node* p = call->in(idx);
1545       if (not_global_escape(p)) {
1546         return true;
1547       }
1548     }
1549   } else {
1550     const char* name = call->as_CallStaticJava()->_name;
1551     assert(name != nullptr, "no name");
1552     // no arg escapes through uncommon traps
1553     if (strcmp(name, "uncommon_trap") != 0) {
1554       // process_call_arguments() assumes that all arguments escape globally
1555       const TypeTuple* d = call->tf()->domain_sig();
1556       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1557         const Type* at = d->field_at(i);
1558         if (at->isa_oopptr() != nullptr) {
1559           return true;
1560         }
1561       }
1562     }
1563   }
1564   return false;
1565 }
1566 
1567 
1568 
1569 // Utility function for nodes that load an object
1570 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1571   // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1572   // ThreadLocal has RawPtr type.
1573   const Type* t = _igvn->type(n);
1574   if (t->make_ptr() != nullptr) {
1575     Node* adr = n->in(MemNode::Address);

1609       // first IGVN optimization when escape information is still available.
1610       record_for_optimizer(n);
1611     } else if (n->is_Allocate()) {
1612       add_call_node(n->as_Call());
1613       record_for_optimizer(n);
1614     } else {
1615       if (n->is_CallStaticJava()) {
1616         const char* name = n->as_CallStaticJava()->_name;
1617         if (name != nullptr && strcmp(name, "uncommon_trap") == 0) {
1618           return; // Skip uncommon traps
1619         }
1620       }
1621       // Don't mark as processed since call's arguments have to be processed.
1622       delayed_worklist->push(n);
1623       // Check if a call returns an object.
1624       if ((n->as_Call()->returns_pointer() &&
1625            n->as_Call()->proj_out_or_null(TypeFunc::Parms) != nullptr) ||
1626           (n->is_CallStaticJava() &&
1627            n->as_CallStaticJava()->is_boxing_method())) {
1628         add_call_node(n->as_Call());
1629       } else if (n->as_Call()->tf()->returns_inline_type_as_fields()) {
1630         bool returns_oop = false;
1631         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && !returns_oop; i++) {
1632           ProjNode* pn = n->fast_out(i)->as_Proj();
1633           if (pn->_con >= TypeFunc::Parms && pn->bottom_type()->isa_ptr()) {
1634             returns_oop = true;
1635           }
1636         }
1637         if (returns_oop) {
1638           add_call_node(n->as_Call());
1639         }
1640       }
1641     }
1642     return;
1643   }
1644   // Put this check here to process call arguments since some call nodes
1645   // point to phantom_obj.
1646   if (n_ptn == phantom_obj || n_ptn == null_obj) {
1647     return; // Skip predefined nodes.
1648   }
1649   switch (opcode) {
1650     case Op_AddP: {
1651       Node* base = get_addp_base(n);
1652       PointsToNode* ptn_base = ptnode_adr(base->_idx);
1653       // Field nodes are created for all field types. They are used in
1654       // adjust_scalar_replaceable_state() and split_unique_types().
1655       // Note, non-oop fields will have only base edges in Connection
1656       // Graph because such fields are not used for oop loads and stores.
1657       int offset = address_offset(n, igvn);
1658       add_field(n, PointsToNode::NoEscape, offset);
1659       if (ptn_base == nullptr) {
1660         delayed_worklist->push(n); // Process it later.
1661       } else {
1662         n_ptn = ptnode_adr(n_idx);
1663         add_base(n_ptn->as_Field(), ptn_base);
1664       }
1665       break;
1666     }
1667     case Op_CastX2P:
1668     case Op_CastI2N: {
1669       map_ideal_node(n, phantom_obj);
1670       break;
1671     }
1672     case Op_InlineType:
1673     case Op_CastPP:
1674     case Op_CheckCastPP:
1675     case Op_EncodeP:
1676     case Op_DecodeN:
1677     case Op_EncodePKlass:
1678     case Op_DecodeNKlass: {
1679       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1680       break;
1681     }
1682     case Op_CMoveP: {
1683       add_local_var(n, PointsToNode::NoEscape);
1684       // Do not add edges during first iteration because some could be
1685       // not defined yet.
1686       delayed_worklist->push(n);
1687       break;
1688     }
1689     case Op_ConP:
1690     case Op_ConN:
1691     case Op_ConNKlass: {
1692       // assume all oop constants globally escape except for null

1722       break;
1723     }
1724     case Op_PartialSubtypeCheck: {
1725       // Produces Null or notNull and is used in only in CmpP so
1726       // phantom_obj could be used.
1727       map_ideal_node(n, phantom_obj); // Result is unknown
1728       break;
1729     }
1730     case Op_Phi: {
1731       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1732       // ThreadLocal has RawPtr type.
1733       const Type* t = n->as_Phi()->type();
1734       if (t->make_ptr() != nullptr) {
1735         add_local_var(n, PointsToNode::NoEscape);
1736         // Do not add edges during first iteration because some could be
1737         // not defined yet.
1738         delayed_worklist->push(n);
1739       }
1740       break;
1741     }
1742     case Op_LoadFlat:
1743       // Treat LoadFlat similar to an unknown call that receives nothing and produces its results
1744       map_ideal_node(n, phantom_obj);
1745       break;
1746     case Op_StoreFlat:
1747       // Treat StoreFlat similar to a call that escapes the stored flattened fields
1748       delayed_worklist->push(n);
1749       break;
1750     case Op_Proj: {
1751       // we are only interested in the oop result projection from a call
1752       if (n->as_Proj()->_con >= TypeFunc::Parms && n->in(0)->is_Call() &&
1753           (n->in(0)->as_Call()->returns_pointer() || n->bottom_type()->isa_ptr())) {
1754         assert((n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->as_Call()->returns_pointer()) ||
1755                n->in(0)->as_Call()->tf()->returns_inline_type_as_fields(), "what kind of oop return is it?");
1756         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1757       } else if (n->as_Proj()->_con >= TypeFunc::Parms && n->in(0)->is_LoadFlat() && igvn->type(n)->isa_ptr()) {
1758         // Treat LoadFlat outputs similar to a call return value
1759         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1760       }
1761       break;
1762     }
1763     case Op_Rethrow: // Exception object escapes
1764     case Op_Return: {
1765       if (n->req() > TypeFunc::Parms &&
1766           igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
1767         // Treat Return value as LocalVar with GlobalEscape escape state.
1768         add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), delayed_worklist);
1769       }
1770       break;
1771     }
1772     case Op_CompareAndExchangeP:
1773     case Op_CompareAndExchangeN:
1774     case Op_GetAndSetP:
1775     case Op_GetAndSetN: {
1776       add_objload_to_connection_graph(n, delayed_worklist);
1777       // fall-through
1778     }

1824       break;
1825     }
1826     default:
1827       ; // Do nothing for nodes not related to EA.
1828   }
1829   return;
1830 }
1831 
1832 // Add final simple edges to graph.
1833 void ConnectionGraph::add_final_edges(Node *n) {
1834   PointsToNode* n_ptn = ptnode_adr(n->_idx);
1835 #ifdef ASSERT
1836   if (_verify && n_ptn->is_JavaObject())
1837     return; // This method does not change graph for JavaObject.
1838 #endif
1839 
1840   if (n->is_Call()) {
1841     process_call_arguments(n->as_Call());
1842     return;
1843   }
1844   assert(n->is_Store() || n->is_LoadStore() || n->is_StoreFlat() ||
1845          ((n_ptn != nullptr) && (n_ptn->ideal_node() != nullptr)),
1846          "node should be registered already");
1847   int opcode = n->Opcode();
1848   bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_final_edges(this, _igvn, n, opcode);
1849   if (gc_handled) {
1850     return; // Ignore node if already handled by GC.
1851   }
1852   switch (opcode) {
1853     case Op_AddP: {
1854       Node* base = get_addp_base(n);
1855       PointsToNode* ptn_base = ptnode_adr(base->_idx);
1856       assert(ptn_base != nullptr, "field's base should be registered");
1857       add_base(n_ptn->as_Field(), ptn_base);
1858       break;
1859     }
1860     case Op_InlineType:
1861     case Op_CastPP:
1862     case Op_CheckCastPP:
1863     case Op_EncodeP:
1864     case Op_DecodeN:
1865     case Op_EncodePKlass:
1866     case Op_DecodeNKlass: {
1867       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), nullptr);
1868       break;
1869     }
1870     case Op_CMoveP: {
1871       for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
1872         Node* in = n->in(i);
1873         if (in == nullptr) {
1874           continue;  // ignore null
1875         }
1876         Node* uncast_in = in->uncast();
1877         if (uncast_in->is_top() || uncast_in == n) {
1878           continue;  // ignore top or inputs which go back this node
1879         }
1880         PointsToNode* ptn = ptnode_adr(in->_idx);

1893     }
1894     case Op_Phi: {
1895       // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1896       // ThreadLocal has RawPtr type.
1897       assert(n->as_Phi()->type()->make_ptr() != nullptr, "Unexpected node type");
1898       for (uint i = 1; i < n->req(); i++) {
1899         Node* in = n->in(i);
1900         if (in == nullptr) {
1901           continue;  // ignore null
1902         }
1903         Node* uncast_in = in->uncast();
1904         if (uncast_in->is_top() || uncast_in == n) {
1905           continue;  // ignore top or inputs which go back this node
1906         }
1907         PointsToNode* ptn = ptnode_adr(in->_idx);
1908         assert(ptn != nullptr, "node should be registered");
1909         add_edge(n_ptn, ptn);
1910       }
1911       break;
1912     }
1913     case Op_StoreFlat: {
1914       // StoreFlat globally escapes its stored flattened fields
1915       InlineTypeNode* value = n->as_StoreFlat()->value();
1916       ciInlineKlass* vk = _igvn->type(value)->inline_klass();
1917       for (int i = 0; i < vk->nof_nonstatic_fields(); i++) {
1918         ciField* field = vk->nonstatic_field_at(i);
1919         if (field->type()->is_primitive_type()) {
1920           continue;
1921         }
1922 
1923         Node* field_value = value->field_value_by_offset(field->offset_in_bytes(), true);
1924         PointsToNode* field_value_ptn = ptnode_adr(field_value->_idx);
1925         set_escape_state(field_value_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "store into a flat field"));
1926       }
1927       break;
1928     }
1929     case Op_Proj: {
1930       if (n->in(0)->is_Call()) {
1931         // we are only interested in the oop result projection from a call
1932         assert((n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->as_Call()->returns_pointer()) ||
1933               n->in(0)->as_Call()->tf()->returns_inline_type_as_fields(), "what kind of oop return is it?");
1934         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), nullptr);
1935       } else if (n->in(0)->is_LoadFlat()) {
1936         // Treat LoadFlat outputs similar to a call return value
1937         add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), nullptr);
1938       }
1939       break;
1940     }
1941     case Op_Rethrow: // Exception object escapes
1942     case Op_Return: {
1943       assert(n->req() > TypeFunc::Parms && _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr(),
1944              "Unexpected node type");
1945       // Treat Return value as LocalVar with GlobalEscape escape state.
1946       add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), nullptr);
1947       break;
1948     }
1949     case Op_CompareAndExchangeP:
1950     case Op_CompareAndExchangeN:
1951     case Op_GetAndSetP:
1952     case Op_GetAndSetN:{
1953       assert(_igvn->type(n)->make_ptr() != nullptr, "Unexpected node type");
1954       add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), nullptr);
1955       // fall-through
1956     }
1957     case Op_CompareAndSwapP:
1958     case Op_CompareAndSwapN:

2092     Node* val = n->in(MemNode::ValueIn);
2093     PointsToNode* ptn = ptnode_adr(val->_idx);
2094     assert(ptn != nullptr, "node should be registered");
2095     set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "stored at raw address"));
2096     // Add edge to object for unsafe access with offset.
2097     PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
2098     assert(adr_ptn != nullptr, "node should be registered");
2099     if (adr_ptn->is_Field()) {
2100       assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
2101       add_edge(adr_ptn, ptn);
2102     }
2103     return true;
2104   }
2105 #ifdef ASSERT
2106   n->dump(1);
2107   assert(false, "not unsafe");
2108 #endif
2109   return false;
2110 }
2111 
2112 // Iterate over the domains for the scalarized and non scalarized calling conventions: Only move to the next element
2113 // in the non scalarized calling convention once all elements of the scalarized calling convention for that parameter
2114 // have been iterated over. So (ignoring hidden arguments such as the null marker) iterating over:
2115 // value class MyValue {
2116 //   int f1;
2117 //   float f2;
2118 // }
2119 // void m(Object o, MyValue v, int i)
2120 // produces the pairs:
2121 // (Object, Object), (Myvalue, int), (MyValue, float), (int, int)
2122 class DomainIterator : public StackObj {
2123 private:
2124   const TypeTuple* _domain;
2125   const TypeTuple* _domain_cc;
2126   const GrowableArray<SigEntry>* _sig_cc;
2127 
2128   uint _i_domain;
2129   uint _i_domain_cc;
2130   int _i_sig_cc;
2131   uint _depth;
2132 
2133   void next_helper() {
2134     if (_sig_cc == nullptr) {
2135       return;
2136     }
2137     BasicType prev_bt = _i_sig_cc > 0 ? _sig_cc->at(_i_sig_cc-1)._bt : T_ILLEGAL;
2138     while (_i_sig_cc < _sig_cc->length()) {
2139       BasicType bt = _sig_cc->at(_i_sig_cc)._bt;
2140       assert(bt != T_VOID || _sig_cc->at(_i_sig_cc-1)._bt == prev_bt, "");
2141       if (bt == T_METADATA) {
2142         _depth++;
2143       } else if (bt == T_VOID && (prev_bt != T_LONG && prev_bt != T_DOUBLE)) {
2144         _depth--;
2145         if (_depth == 0) {
2146           _i_domain++;
2147         }
2148       } else {
2149         return;
2150       }
2151       prev_bt = bt;
2152       _i_sig_cc++;
2153     }
2154   }
2155 
2156 public:
2157 
2158   DomainIterator(CallJavaNode* call) :
2159     _domain(call->tf()->domain_sig()),
2160     _domain_cc(call->tf()->domain_cc()),
2161     _sig_cc(call->method()->get_sig_cc()),
2162     _i_domain(TypeFunc::Parms),
2163     _i_domain_cc(TypeFunc::Parms),
2164     _i_sig_cc(0),
2165     _depth(0) {
2166     next_helper();
2167   }
2168 
2169   bool has_next() const {
2170     assert(_sig_cc == nullptr || (_i_sig_cc < _sig_cc->length()) == (_i_domain < _domain->cnt()), "should reach end in sync");
2171     assert((_i_domain < _domain->cnt()) == (_i_domain_cc < _domain_cc->cnt()), "should reach end in sync");
2172     return _i_domain < _domain->cnt();
2173   }
2174 
2175   void next() {
2176     assert(_depth != 0 || _domain->field_at(_i_domain) == _domain_cc->field_at(_i_domain_cc), "should produce same non scalarized elements");
2177     _i_sig_cc++;
2178     if (_depth == 0) {
2179       _i_domain++;
2180     }
2181     _i_domain_cc++;
2182     next_helper();
2183   }
2184 
2185   uint i_domain() const {
2186     return _i_domain;
2187   }
2188 
2189   uint i_domain_cc() const {
2190     return _i_domain_cc;
2191   }
2192 
2193   const Type* current_domain() const {
2194     return _domain->field_at(_i_domain);
2195   }
2196 
2197   const Type* current_domain_cc() const {
2198     return _domain_cc->field_at(_i_domain_cc);
2199   }
2200 };
2201 
2202 void ConnectionGraph::add_call_node(CallNode* call) {
2203   assert(call->returns_pointer() || call->tf()->returns_inline_type_as_fields(), "only for call which returns pointer");
2204   uint call_idx = call->_idx;
2205   if (call->is_Allocate()) {
2206     Node* k = call->in(AllocateNode::KlassNode);
2207     const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
2208     assert(kt != nullptr, "TypeKlassPtr  required.");
2209     PointsToNode::EscapeState es = PointsToNode::NoEscape;
2210     bool scalar_replaceable = true;
2211     NOT_PRODUCT(const char* nsr_reason = "");
2212     if (call->is_AllocateArray()) {
2213       if (!kt->isa_aryklassptr()) { // StressReflectiveCode
2214         es = PointsToNode::GlobalEscape;
2215       } else {
2216         int length = call->in(AllocateNode::ALength)->find_int_con(-1);
2217         if (length < 0) {
2218           // Not scalar replaceable if the length is not constant.
2219           scalar_replaceable = false;
2220           NOT_PRODUCT(nsr_reason = "has a non-constant length");
2221         } else if (length > EliminateAllocationArraySizeLimit) {
2222           // Not scalar replaceable if the length is too big.
2223           scalar_replaceable = false;

2258     //    - mapped to GlobalEscape JavaObject node if oop is returned;
2259     //
2260     //    - all oop arguments are escaping globally;
2261     //
2262     // 2. CallStaticJavaNode (execute bytecode analysis if possible):
2263     //
2264     //    - the same as CallDynamicJavaNode if can't do bytecode analysis;
2265     //
2266     //    - mapped to GlobalEscape JavaObject node if unknown oop is returned;
2267     //    - mapped to NoEscape JavaObject node if non-escaping object allocated
2268     //      during call is returned;
2269     //    - mapped to ArgEscape LocalVar node pointed to object arguments
2270     //      which are returned and does not escape during call;
2271     //
2272     //    - oop arguments escaping status is defined by bytecode analysis;
2273     //
2274     // For a static call, we know exactly what method is being called.
2275     // Use bytecode estimator to record whether the call's return value escapes.
2276     ciMethod* meth = call->as_CallJava()->method();
2277     if (meth == nullptr) {
2278       const char* name = call->as_CallStaticJava()->_name;
2279       assert(call->as_CallStaticJava()->is_call_to_multianewarray_stub() ||
2280              strncmp(name, "load_unknown_inline", 19) == 0 ||
2281              strncmp(name, "store_inline_type_fields_to_buf", 31) == 0, "TODO: add failed case check");
2282       // Returns a newly allocated non-escaped object.
2283       add_java_object(call, PointsToNode::NoEscape);
2284       set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of multinewarray"));
2285     } else if (meth->is_boxing_method()) {
2286       // Returns boxing object
2287       PointsToNode::EscapeState es;
2288       vmIntrinsics::ID intr = meth->intrinsic_id();
2289       if (intr == vmIntrinsics::_floatValue || intr == vmIntrinsics::_doubleValue) {
2290         // It does not escape if object is always allocated.
2291         es = PointsToNode::NoEscape;
2292       } else {
2293         // It escapes globally if object could be loaded from cache.
2294         es = PointsToNode::GlobalEscape;
2295       }
2296       add_java_object(call, es);
2297       if (es == PointsToNode::GlobalEscape) {
2298         set_not_scalar_replaceable(ptnode_adr(call->_idx) NOT_PRODUCT(COMMA "object can be loaded from boxing cache"));
2299       }
2300     } else {
2301       BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
2302       call_analyzer->copy_dependencies(_compile->dependencies());
2303       if (call_analyzer->is_return_allocated()) {
2304         // Returns a newly allocated non-escaped object, simply
2305         // update dependency information.
2306         // Mark it as NoEscape so that objects referenced by
2307         // it's fields will be marked as NoEscape at least.
2308         add_java_object(call, PointsToNode::NoEscape);
2309         set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of call"));
2310       } else {


2311         bool ret_arg = false;
2312         // Determine whether any arguments are returned.
2313         for (DomainIterator di(call->as_CallJava()); di.has_next(); di.next()) {
2314           uint arg = di.i_domain() - TypeFunc::Parms;
2315           if (di.current_domain_cc()->isa_ptr() != nullptr &&
2316               call_analyzer->is_arg_returned(arg) &&
2317               !meth->is_scalarized_arg(arg)) {
2318             ret_arg = true;
2319             break;
2320           }
2321         }
2322         if (ret_arg) {
2323           add_local_var(call, PointsToNode::ArgEscape);
2324         } else {
2325           // Returns unknown object.
2326           map_ideal_node(call, phantom_obj);
2327         }
2328       }
2329     }
2330   } else {
2331     // An other type of call, assume the worst case:
2332     // returned value is unknown and globally escapes.
2333     assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
2334     map_ideal_node(call, phantom_obj);
2335   }
2336 }
2337 

2341 #ifdef ASSERT
2342     case Op_Allocate:
2343     case Op_AllocateArray:
2344     case Op_Lock:
2345     case Op_Unlock:
2346       assert(false, "should be done already");
2347       break;
2348 #endif
2349     case Op_ArrayCopy:
2350     case Op_CallLeafNoFP:
2351       // Most array copies are ArrayCopy nodes at this point but there
2352       // are still a few direct calls to the copy subroutines (See
2353       // PhaseStringOpts::copy_string())
2354       is_arraycopy = (call->Opcode() == Op_ArrayCopy) ||
2355         call->as_CallLeaf()->is_call_to_arraycopystub();
2356       // fall through
2357     case Op_CallLeafVector:
2358     case Op_CallLeaf: {
2359       // Stub calls, objects do not escape but they are not scale replaceable.
2360       // Adjust escape state for outgoing arguments.
2361       const TypeTuple * d = call->tf()->domain_sig();
2362       bool src_has_oops = false;
2363       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2364         const Type* at = d->field_at(i);
2365         Node *arg = call->in(i);
2366         if (arg == nullptr) {
2367           continue;
2368         }
2369         const Type *aat = _igvn->type(arg);
2370         if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr()) {
2371           continue;
2372         }
2373         if (arg->is_AddP()) {
2374           //
2375           // The inline_native_clone() case when the arraycopy stub is called
2376           // after the allocation before Initialize and CheckCastPP nodes.
2377           // Or normal arraycopy for object arrays case.
2378           //
2379           // Set AddP's base (Allocate) as not scalar replaceable since
2380           // pointer to the base (with offset) is passed as argument.
2381           //
2382           arg = get_addp_base(arg);
2383         }
2384         PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2385         assert(arg_ptn != nullptr, "should be registered");
2386         PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
2387         if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
2388           assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
2389                  aat->isa_ptr() != nullptr, "expecting an Ptr");
2390           bool arg_has_oops = aat->isa_oopptr() &&
2391                               (aat->isa_instptr() ||
2392                                (aat->isa_aryptr() && (aat->isa_aryptr()->elem() == Type::BOTTOM || aat->isa_aryptr()->elem()->make_oopptr() != nullptr)) ||
2393                                (aat->isa_aryptr() && aat->isa_aryptr()->elem() != nullptr &&
2394                                                                aat->isa_aryptr()->is_flat() &&
2395                                                                aat->isa_aryptr()->elem()->inline_klass()->contains_oops()));
2396           if (i == TypeFunc::Parms) {
2397             src_has_oops = arg_has_oops;
2398           }
2399           //
2400           // src or dst could be j.l.Object when other is basic type array:
2401           //
2402           //   arraycopy(char[],0,Object*,0,size);
2403           //   arraycopy(Object*,0,char[],0,size);
2404           //
2405           // Don't add edges in such cases.
2406           //
2407           bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
2408                                        arg_has_oops && (i > TypeFunc::Parms);
2409 #ifdef ASSERT
2410           if (!(is_arraycopy ||
2411                 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(call) ||
2412                 (call->as_CallLeaf()->_name != nullptr &&
2413                  (strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 ||
2414                   strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32C") == 0 ||
2415                   strcmp(call->as_CallLeaf()->_name, "updateBytesAdler32") == 0 ||

2439                   strcmp(call->as_CallLeaf()->_name, "dilithiumMontMulByConstant") == 0 ||
2440                   strcmp(call->as_CallLeaf()->_name, "dilithiumDecomposePoly") == 0 ||
2441                   strcmp(call->as_CallLeaf()->_name, "encodeBlock") == 0 ||
2442                   strcmp(call->as_CallLeaf()->_name, "decodeBlock") == 0 ||
2443                   strcmp(call->as_CallLeaf()->_name, "md5_implCompress") == 0 ||
2444                   strcmp(call->as_CallLeaf()->_name, "md5_implCompressMB") == 0 ||
2445                   strcmp(call->as_CallLeaf()->_name, "sha1_implCompress") == 0 ||
2446                   strcmp(call->as_CallLeaf()->_name, "sha1_implCompressMB") == 0 ||
2447                   strcmp(call->as_CallLeaf()->_name, "sha256_implCompress") == 0 ||
2448                   strcmp(call->as_CallLeaf()->_name, "sha256_implCompressMB") == 0 ||
2449                   strcmp(call->as_CallLeaf()->_name, "sha512_implCompress") == 0 ||
2450                   strcmp(call->as_CallLeaf()->_name, "sha512_implCompressMB") == 0 ||
2451                   strcmp(call->as_CallLeaf()->_name, "sha3_implCompress") == 0 ||
2452                   strcmp(call->as_CallLeaf()->_name, "double_keccak") == 0 ||
2453                   strcmp(call->as_CallLeaf()->_name, "sha3_implCompressMB") == 0 ||
2454                   strcmp(call->as_CallLeaf()->_name, "multiplyToLen") == 0 ||
2455                   strcmp(call->as_CallLeaf()->_name, "squareToLen") == 0 ||
2456                   strcmp(call->as_CallLeaf()->_name, "mulAdd") == 0 ||
2457                   strcmp(call->as_CallLeaf()->_name, "montgomery_multiply") == 0 ||
2458                   strcmp(call->as_CallLeaf()->_name, "montgomery_square") == 0 ||
2459                   strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2460                   strcmp(call->as_CallLeaf()->_name, "load_unknown_inline") == 0 ||
2461                   strcmp(call->as_CallLeaf()->_name, "store_unknown_inline") == 0 ||
2462                   strcmp(call->as_CallLeaf()->_name, "store_inline_type_fields_to_buf") == 0 ||
2463                   strcmp(call->as_CallLeaf()->_name, "bigIntegerRightShiftWorker") == 0 ||
2464                   strcmp(call->as_CallLeaf()->_name, "bigIntegerLeftShiftWorker") == 0 ||
2465                   strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2466                   strcmp(call->as_CallLeaf()->_name, "stringIndexOf") == 0 ||
2467                   strcmp(call->as_CallLeaf()->_name, "arraysort_stub") == 0 ||
2468                   strcmp(call->as_CallLeaf()->_name, "array_partition_stub") == 0 ||
2469                   strcmp(call->as_CallLeaf()->_name, "get_class_id_intrinsic") == 0 ||
2470                   strcmp(call->as_CallLeaf()->_name, "unsafe_setmemory") == 0)
2471                  ))) {
2472             call->dump();
2473             fatal("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name);
2474           }
2475 #endif
2476           // Always process arraycopy's destination object since
2477           // we need to add all possible edges to references in
2478           // source object.
2479           if (arg_esc >= PointsToNode::ArgEscape &&
2480               !arg_is_arraycopy_dest) {
2481             continue;
2482           }

2505           }
2506         }
2507       }
2508       break;
2509     }
2510     case Op_CallStaticJava: {
2511       // For a static call, we know exactly what method is being called.
2512       // Use bytecode estimator to record the call's escape affects
2513 #ifdef ASSERT
2514       const char* name = call->as_CallStaticJava()->_name;
2515       assert((name == nullptr || strcmp(name, "uncommon_trap") != 0), "normal calls only");
2516 #endif
2517       ciMethod* meth = call->as_CallJava()->method();
2518       if ((meth != nullptr) && meth->is_boxing_method()) {
2519         break; // Boxing methods do not modify any oops.
2520       }
2521       BCEscapeAnalyzer* call_analyzer = (meth !=nullptr) ? meth->get_bcea() : nullptr;
2522       // fall-through if not a Java method or no analyzer information
2523       if (call_analyzer != nullptr) {
2524         PointsToNode* call_ptn = ptnode_adr(call->_idx);
2525         for (DomainIterator di(call->as_CallJava()); di.has_next(); di.next()) {
2526           int k = di.i_domain() - TypeFunc::Parms;
2527           const Type* at = di.current_domain_cc();
2528           Node* arg = call->in(di.i_domain_cc());

2529           PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2530           if (at->isa_ptr() != nullptr &&
2531               call_analyzer->is_arg_returned(k) &&
2532               !meth->is_scalarized_arg(k)) {
2533             // The call returns arguments.
2534             if (call_ptn != nullptr) { // Is call's result used?
2535               assert(call_ptn->is_LocalVar(), "node should be registered");
2536               assert(arg_ptn != nullptr, "node should be registered");
2537               add_edge(call_ptn, arg_ptn);
2538             }
2539           }
2540           if (at->isa_oopptr() != nullptr &&
2541               arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
2542             if (!call_analyzer->is_arg_stack(k)) {
2543               // The argument global escapes
2544               set_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2545             } else {
2546               set_escape_state(arg_ptn, PointsToNode::ArgEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2547               if (!call_analyzer->is_arg_local(k)) {
2548                 // The argument itself doesn't escape, but any fields might
2549                 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2550               }
2551             }
2552           }
2553         }
2554         if (call_ptn != nullptr && call_ptn->is_LocalVar()) {
2555           // The call returns arguments.
2556           assert(call_ptn->edge_count() > 0, "sanity");
2557           if (!call_analyzer->is_return_local()) {
2558             // Returns also unknown object.
2559             add_edge(call_ptn, phantom_obj);
2560           }
2561         }
2562         break;
2563       }
2564     }
2565     default: {
2566       // Fall-through here if not a Java method or no analyzer information
2567       // or some other type of call, assume the worst case: all arguments
2568       // globally escape.
2569       const TypeTuple* d = call->tf()->domain_cc();
2570       for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2571         const Type* at = d->field_at(i);
2572         if (at->isa_oopptr() != nullptr) {
2573           Node* arg = call->in(i);
2574           if (arg->is_AddP()) {
2575             arg = get_addp_base(arg);
2576           }
2577           assert(ptnode_adr(arg->_idx) != nullptr, "should be defined already");
2578           set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2579         }
2580       }
2581     }
2582   }
2583 }
2584 
2585 
2586 // Finish Graph construction.
2587 bool ConnectionGraph::complete_connection_graph(
2588                          GrowableArray<PointsToNode*>&   ptnodes_worklist,
2589                          GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,

2967     PointsToNode* base = i.get();
2968     if (base->is_JavaObject()) {
2969       // Skip Allocate's fields which will be processed later.
2970       if (base->ideal_node()->is_Allocate()) {
2971         return 0;
2972       }
2973       assert(base == null_obj, "only null ptr base expected here");
2974     }
2975   }
2976   if (add_edge(field, phantom_obj)) {
2977     // New edge was added
2978     new_edges++;
2979     add_field_uses_to_worklist(field);
2980   }
2981   return new_edges;
2982 }
2983 
2984 // Find fields initializing values for allocations.
2985 int ConnectionGraph::find_init_values_phantom(JavaObjectNode* pta) {
2986   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2987   PointsToNode* init_val = phantom_obj;
2988   Node* alloc = pta->ideal_node();
2989 
2990   // Do nothing for Allocate nodes since its fields values are
2991   // "known" unless they are initialized by arraycopy/clone.
2992   if (alloc->is_Allocate() && !pta->arraycopy_dst()) {
2993     if (alloc->as_Allocate()->in(AllocateNode::InitValue) != nullptr) {
2994       // Null-free inline type arrays are initialized with an init value instead of null
2995       init_val = ptnode_adr(alloc->as_Allocate()->in(AllocateNode::InitValue)->_idx);
2996       assert(init_val != nullptr, "init value should be registered");
2997     } else {
2998       return 0;
2999     }
3000   }
3001   // Non-escaped allocation returned from Java or runtime call has unknown values in fields.
3002   assert(pta->arraycopy_dst() || alloc->is_CallStaticJava() || init_val != phantom_obj, "sanity");
3003 #ifdef ASSERT
3004   if (alloc->is_CallStaticJava() && alloc->as_CallStaticJava()->method() == nullptr) {
3005     const char* name = alloc->as_CallStaticJava()->_name;
3006     assert(alloc->as_CallStaticJava()->is_call_to_multianewarray_stub() ||
3007            strncmp(name, "load_unknown_inline", 19) == 0 ||
3008            strncmp(name, "store_inline_type_fields_to_buf", 31) == 0, "sanity");
3009   }
3010 #endif
3011   // Non-escaped allocation returned from Java or runtime call have unknown values in fields.
3012   int new_edges = 0;
3013   for (EdgeIterator i(pta); i.has_next(); i.next()) {
3014     PointsToNode* field = i.get();
3015     if (field->is_Field() && field->as_Field()->is_oop()) {
3016       if (add_edge(field, init_val)) {
3017         // New edge was added
3018         new_edges++;
3019         add_field_uses_to_worklist(field->as_Field());
3020       }
3021     }
3022   }
3023   return new_edges;
3024 }
3025 
3026 // Find fields initializing values for allocations.
3027 int ConnectionGraph::find_init_values_null(JavaObjectNode* pta, PhaseValues* phase) {
3028   assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
3029   Node* alloc = pta->ideal_node();
3030   // Do nothing for Call nodes since its fields values are unknown.
3031   if (!alloc->is_Allocate() || alloc->as_Allocate()->in(AllocateNode::InitValue) != nullptr) {
3032     return 0;
3033   }
3034   InitializeNode* ini = alloc->as_Allocate()->initialization();
3035   bool visited_bottom_offset = false;
3036   GrowableArray<int> offsets_worklist;
3037   int new_edges = 0;
3038 
3039   // Check if an oop field's initializing value is recorded and add
3040   // a corresponding null if field's value if it is not recorded.
3041   // Connection Graph does not record a default initialization by null
3042   // captured by Initialize node.
3043   //
3044   for (EdgeIterator i(pta); i.has_next(); i.next()) {
3045     PointsToNode* field = i.get(); // Field (AddP)
3046     if (!field->is_Field() || !field->as_Field()->is_oop()) {
3047       continue; // Not oop field
3048     }
3049     int offset = field->as_Field()->offset();
3050     if (offset == Type::OffsetBot) {
3051       if (!visited_bottom_offset) {

3097               } else {
3098                 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
3099                   tty->print_cr("----------init store has invalid value -----");
3100                   store->dump();
3101                   val->dump();
3102                   assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
3103                 }
3104                 for (EdgeIterator j(val); j.has_next(); j.next()) {
3105                   PointsToNode* obj = j.get();
3106                   if (obj->is_JavaObject()) {
3107                     if (!field->points_to(obj->as_JavaObject())) {
3108                       missed_obj = obj;
3109                       break;
3110                     }
3111                   }
3112                 }
3113               }
3114               if (missed_obj != nullptr) {
3115                 tty->print_cr("----------field---------------------------------");
3116                 field->dump();
3117                 tty->print_cr("----------missed reference to object------------");
3118                 missed_obj->dump();
3119                 tty->print_cr("----------object referenced by init store-------");
3120                 store->dump();
3121                 val->dump();
3122                 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
3123               }
3124             }
3125 #endif
3126           } else {
3127             // There could be initializing stores which follow allocation.
3128             // For example, a volatile field store is not collected
3129             // by Initialize node.
3130             //
3131             // Need to check for dependent loads to separate such stores from
3132             // stores which follow loads. For now, add initial value null so
3133             // that compare pointers optimization works correctly.
3134           }
3135         }
3136         if (value == nullptr) {
3137           // A field's initializing value was not recorded. Add null.
3138           if (add_edge(field, null_obj)) {
3139             // New edge was added

3464         assert(field->edge_count() > 0, "sanity");
3465       }
3466     }
3467   }
3468 }
3469 #endif
3470 
3471 // Optimize ideal graph.
3472 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
3473                                            GrowableArray<MemBarStoreStoreNode*>& storestore_worklist) {
3474   Compile* C = _compile;
3475   PhaseIterGVN* igvn = _igvn;
3476   if (EliminateLocks) {
3477     // Mark locks before changing ideal graph.
3478     int cnt = C->macro_count();
3479     for (int i = 0; i < cnt; i++) {
3480       Node *n = C->macro_node(i);
3481       if (n->is_AbstractLock()) { // Lock and Unlock nodes
3482         AbstractLockNode* alock = n->as_AbstractLock();
3483         if (!alock->is_non_esc_obj()) {
3484           const Type* obj_type = igvn->type(alock->obj_node());
3485           if (can_eliminate_lock(alock) && !obj_type->is_inlinetypeptr()) {
3486             assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
3487             // The lock could be marked eliminated by lock coarsening
3488             // code during first IGVN before EA. Replace coarsened flag
3489             // to eliminate all associated locks/unlocks.
3490 #ifdef ASSERT
3491             alock->log_lock_optimization(C, "eliminate_lock_set_non_esc3");
3492 #endif
3493             alock->set_non_esc_obj();
3494           }
3495         }
3496       }
3497     }
3498   }
3499 
3500   if (OptimizePtrCompare) {
3501     for (int i = 0; i < ptr_cmp_worklist.length(); i++) {
3502       Node *n = ptr_cmp_worklist.at(i);
3503       assert(n->Opcode() == Op_CmpN || n->Opcode() == Op_CmpP, "must be");
3504       const TypeInt* tcmp = optimize_ptr_compare(n->in(1), n->in(2));
3505       if (tcmp->singleton()) {

3507 #ifndef PRODUCT
3508         if (PrintOptimizePtrCompare) {
3509           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"));
3510           if (Verbose) {
3511             n->dump(1);
3512           }
3513         }
3514 #endif
3515         igvn->replace_node(n, cmp);
3516       }
3517     }
3518   }
3519 
3520   // For MemBarStoreStore nodes added in library_call.cpp, check
3521   // escape status of associated AllocateNode and optimize out
3522   // MemBarStoreStore node if the allocated object never escapes.
3523   for (int i = 0; i < storestore_worklist.length(); i++) {
3524     Node* storestore = storestore_worklist.at(i);
3525     Node* alloc = storestore->in(MemBarNode::Precedent)->in(0);
3526     if (alloc->is_Allocate() && not_global_escape(alloc)) {
3527       if (alloc->in(AllocateNode::InlineType) != nullptr) {
3528         // Non-escaping inline type buffer allocations don't require a membar
3529         storestore->as_MemBar()->remove(_igvn);
3530       } else {
3531         MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
3532         mb->init_req(TypeFunc::Memory,  storestore->in(TypeFunc::Memory));
3533         mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
3534         igvn->register_new_node_with_optimizer(mb);
3535         igvn->replace_node(storestore, mb);
3536       }
3537     }
3538   }
3539 }
3540 
3541 // Atomic flat accesses on non-escaping objects can be optimized to non-atomic accesses
3542 void ConnectionGraph::optimize_flat_accesses(GrowableArray<SafePointNode*>& sfn_worklist) {
3543   PhaseIterGVN& igvn = *_igvn;
3544   bool delay = igvn.delay_transform();
3545   igvn.set_delay_transform(true);
3546   igvn.C->for_each_flat_access([&](Node* n) {
3547     Node* base = n->is_LoadFlat() ? n->as_LoadFlat()->base() : n->as_StoreFlat()->base();
3548     if (!not_global_escape(base)) {
3549       return;
3550     }
3551 
3552     bool expanded;
3553     if (n->is_LoadFlat()) {
3554       expanded = n->as_LoadFlat()->expand_non_atomic(igvn);
3555     } else {
3556       expanded = n->as_StoreFlat()->expand_non_atomic(igvn);
3557     }
3558     if (expanded) {
3559       sfn_worklist.remove(n->as_SafePoint());
3560       igvn.C->remove_flat_access(n);
3561     }
3562   });
3563   igvn.set_delay_transform(delay);
3564 }
3565 
3566 // Optimize objects compare.
3567 const TypeInt* ConnectionGraph::optimize_ptr_compare(Node* left, Node* right) {
3568   const TypeInt* UNKNOWN = TypeInt::CC;    // [-1, 0,1]
3569   if (!OptimizePtrCompare) {
3570     return UNKNOWN;
3571   }
3572   const TypeInt* EQ = TypeInt::CC_EQ; // [0] == ZERO
3573   const TypeInt* NE = TypeInt::CC_GT; // [1] == ONE
3574 
3575   PointsToNode* ptn1 = ptnode_adr(left->_idx);
3576   PointsToNode* ptn2 = ptnode_adr(right->_idx);
3577   JavaObjectNode* jobj1 = unique_java_object(left);
3578   JavaObjectNode* jobj2 = unique_java_object(right);
3579 
3580   // The use of this method during allocation merge reduction may cause 'left'
3581   // or 'right' be something (e.g., a Phi) that isn't in the connection graph or
3582   // that doesn't reference an unique java object.
3583   if (ptn1 == nullptr || ptn2 == nullptr ||
3584       jobj1 == nullptr || jobj2 == nullptr) {
3585     return UNKNOWN;

3705   assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
3706   assert((src != null_obj) && (dst != null_obj), "not for ConP null");
3707   PointsToNode* ptadr = _nodes.at(n->_idx);
3708   if (ptadr != nullptr) {
3709     assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
3710     return;
3711   }
3712   Compile* C = _compile;
3713   ptadr = new (C->comp_arena()) ArraycopyNode(this, n, es);
3714   map_ideal_node(n, ptadr);
3715   // Add edge from arraycopy node to source object.
3716   (void)add_edge(ptadr, src);
3717   src->set_arraycopy_src();
3718   // Add edge from destination object to arraycopy node.
3719   (void)add_edge(dst, ptadr);
3720   dst->set_arraycopy_dst();
3721 }
3722 
3723 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
3724   const Type* adr_type = n->as_AddP()->bottom_type();
3725   int field_offset = adr_type->isa_aryptr() ? adr_type->isa_aryptr()->field_offset().get() : Type::OffsetBot;
3726   BasicType bt = T_INT;
3727   if (offset == Type::OffsetBot && field_offset == Type::OffsetBot) {
3728     // Check only oop fields.
3729     if (!adr_type->isa_aryptr() ||
3730         adr_type->isa_aryptr()->elem() == Type::BOTTOM ||
3731         adr_type->isa_aryptr()->elem()->make_oopptr() != nullptr) {
3732       // OffsetBot is used to reference array's element. Ignore first AddP.
3733       if (find_second_addp(n, n->in(AddPNode::Base)) == nullptr) {
3734         bt = T_OBJECT;
3735       }
3736     }
3737   } else if (offset != oopDesc::klass_offset_in_bytes()) {
3738     if (adr_type->isa_instptr()) {
3739       ciField* field = _compile->alias_type(adr_type->is_ptr())->field();
3740       if (field != nullptr) {
3741         bt = field->layout_type();
3742       } else {
3743         // Check for unsafe oop field access
3744         if (has_oop_node_outs(n)) {
3745           bt = T_OBJECT;
3746           (*unsafe) = true;
3747         }
3748       }
3749     } else if (adr_type->isa_aryptr()) {
3750       if (offset == arrayOopDesc::length_offset_in_bytes()) {
3751         // Ignore array length load.
3752       } else if (find_second_addp(n, n->in(AddPNode::Base)) != nullptr) {
3753         // Ignore first AddP.
3754       } else {
3755         const Type* elemtype = adr_type->is_aryptr()->elem();
3756         if (adr_type->is_aryptr()->is_flat() && field_offset != Type::OffsetBot) {
3757           ciInlineKlass* vk = elemtype->inline_klass();
3758           field_offset += vk->payload_offset();
3759           ciField* field = vk->get_field_by_offset(field_offset, false);
3760           if (field != nullptr) {
3761             bt = field->layout_type();
3762           } else {
3763             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);
3764             bt = T_BOOLEAN;
3765           }
3766         } else {
3767           bt = elemtype->array_element_basic_type();
3768         }
3769       }
3770     } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
3771       // Allocation initialization, ThreadLocal field access, unsafe access
3772       if (has_oop_node_outs(n)) {
3773         bt = T_OBJECT;
3774       }
3775     }
3776   }
3777   // Note: T_NARROWOOP is not classed as a real reference type
3778   bool res = (is_reference_type(bt) || bt == T_NARROWOOP);
3779   assert(!has_oop_node_outs(n) || res, "sanity: AddP has oop outs, needs to be treated as oop field");
3780   return res;
3781 }
3782 
3783 bool ConnectionGraph::has_oop_node_outs(Node* n) {
3784   return n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3785          n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3786          n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3787          BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n);
3788 }

3951             return true;
3952           }
3953         }
3954       }
3955     }
3956   }
3957   return false;
3958 }
3959 
3960 int ConnectionGraph::address_offset(Node* adr, PhaseValues* phase) {
3961   const Type *adr_type = phase->type(adr);
3962   if (adr->is_AddP() && adr_type->isa_oopptr() == nullptr && is_captured_store_address(adr)) {
3963     // We are computing a raw address for a store captured by an Initialize
3964     // compute an appropriate address type. AddP cases #3 and #5 (see below).
3965     int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
3966     assert(offs != Type::OffsetBot ||
3967            adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
3968            "offset must be a constant or it is initialization of array");
3969     return offs;
3970   }
3971   return adr_type->is_ptr()->flat_offset();


3972 }
3973 
3974 Node* ConnectionGraph::get_addp_base(Node *addp) {
3975   assert(addp->is_AddP(), "must be AddP");
3976   //
3977   // AddP cases for Base and Address inputs:
3978   // case #1. Direct object's field reference:
3979   //     Allocate
3980   //       |
3981   //     Proj #5 ( oop result )
3982   //       |
3983   //     CheckCastPP (cast to instance type)
3984   //      | |
3985   //     AddP  ( base == address )
3986   //
3987   // case #2. Indirect object's field reference:
3988   //      Phi
3989   //       |
3990   //     CastPP (cast to instance type)
3991   //      | |
3992   //     AddP  ( base == address )
3993   //
3994   // case #3. Raw object's field reference for Initialize node.
3995   //          Could have an additional Phi merging multiple allocations.
3996   //      Allocate
3997   //        |
3998   //      Proj #5 ( oop result )
3999   //  top   |
4000   //     \  |
4001   //     AddP  ( base == top )
4002   //
4003   // case #4. Array's element reference:
4004   //   {CheckCastPP | CastPP}
4005   //     |  | |
4006   //     |  AddP ( array's element offset )
4007   //     |  |
4008   //     AddP ( array's offset )
4009   //
4010   // case #5. Raw object's field reference for arraycopy stub call:
4011   //          The inline_native_clone() case when the arraycopy stub is called
4012   //          after the allocation before Initialize and CheckCastPP nodes.
4013   //      Allocate
4014   //        |
4015   //      Proj #5 ( oop result )

4026   // case #7. Klass's field reference.
4027   //      LoadKlass
4028   //       | |
4029   //       AddP  ( base == address )
4030   //
4031   // case #8. narrow Klass's field reference.
4032   //      LoadNKlass
4033   //       |
4034   //      DecodeN
4035   //       | |
4036   //       AddP  ( base == address )
4037   //
4038   // case #9. Mixed unsafe access
4039   //    {instance}
4040   //        |
4041   //      CheckCastPP (raw)
4042   //  top   |
4043   //     \  |
4044   //     AddP  ( base == top )
4045   //
4046   // case #10. Klass fetched with
4047   //           LibraryCallKit::load_*_refined_array_klass()
4048   //           which has en extra Phi.
4049   //  LoadKlass   LoadKlass
4050   //       |          |
4051   //     CastPP    CastPP
4052   //          \   /
4053   //           Phi
4054   //      top   |
4055   //         \  |
4056   //         AddP  ( base == top )
4057   //
4058   Node *base = addp->in(AddPNode::Base);
4059   if (base->uncast()->is_top()) { // The AddP case #3, #6, #9, and #10.
4060     base = addp->in(AddPNode::Address);
4061     while (base->is_AddP()) {
4062       // Case #6 (unsafe access) may have several chained AddP nodes.
4063       assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
4064       base = base->in(AddPNode::Address);
4065     }
4066     if (base->Opcode() == Op_CheckCastPP &&
4067         base->bottom_type()->isa_rawptr() &&
4068         _igvn->type(base->in(1))->isa_oopptr()) {
4069       base = base->in(1); // Case #9
4070     } else {
4071       // Case #3, #6, and #10
4072       Node* uncast_base = base->uncast();
4073       int opcode = uncast_base->Opcode();
4074       assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
4075              opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() ||
4076              (_igvn->C->is_osr_compilation() && uncast_base->is_Parm() && uncast_base->as_Parm()->_con == TypeFunc::Parms)||
4077              (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_rawptr() != nullptr)) ||
4078              (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_klassptr() != nullptr)) ||
4079              is_captured_store_address(addp) ||
4080              is_load_array_klass_related(uncast_base), "sanity");
4081     }
4082   }
4083   return base;
4084 }
4085 
4086 #ifdef ASSERT
4087 // Case #10
4088 bool ConnectionGraph::is_load_array_klass_related(const Node* uncast_base) {
4089   if (!uncast_base->is_Phi() || uncast_base->req() != 3) {
4090     return false;
4091   }
4092   Node* in1 = uncast_base->in(1);
4093   Node* in2 = uncast_base->in(2);
4094   return in1->uncast()->Opcode() == Op_LoadKlass &&
4095          in2->uncast()->Opcode() == Op_LoadKlass;
4096 }
4097 #endif
4098 
4099 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
4100   assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
4101   Node* addp2 = addp->raw_out(0);
4102   if (addp->outcnt() == 1 && addp2->is_AddP() &&
4103       addp2->in(AddPNode::Base) == n &&
4104       addp2->in(AddPNode::Address) == addp) {
4105     assert(addp->in(AddPNode::Base) == n, "expecting the same base");
4106     //
4107     // Find array's offset to push it on worklist first and
4108     // as result process an array's element offset first (pushed second)
4109     // to avoid CastPP for the array's offset.
4110     // Otherwise the inserted CastPP (LocalVar) will point to what
4111     // the AddP (Field) points to. Which would be wrong since
4112     // the algorithm expects the CastPP has the same point as
4113     // as AddP's base CheckCastPP (LocalVar).
4114     //
4115     //    ArrayAllocation
4116     //     |
4117     //    CheckCastPP
4118     //     |

4135   }
4136   return nullptr;
4137 }
4138 
4139 //
4140 // Adjust the type and inputs of an AddP which computes the
4141 // address of a field of an instance
4142 //
4143 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
4144   PhaseGVN* igvn = _igvn;
4145   const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
4146   assert(base_t != nullptr && base_t->is_known_instance(), "expecting instance oopptr");
4147   const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
4148   if (t == nullptr) {
4149     // We are computing a raw address for a store captured by an Initialize
4150     // compute an appropriate address type (cases #3 and #5).
4151     assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
4152     assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
4153     intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
4154     assert(offs != Type::OffsetBot, "offset must be a constant");
4155     if (base_t->isa_aryptr() != nullptr) {
4156       // In the case of a flat inline type array, each field has its
4157       // own slice so we need to extract the field being accessed from
4158       // the address computation
4159       t = base_t->isa_aryptr()->add_field_offset_and_offset(offs)->is_oopptr();
4160     } else {
4161       t = base_t->add_offset(offs)->is_oopptr();
4162     }
4163   }
4164   int inst_id = base_t->instance_id();
4165   assert(!t->is_known_instance() || t->instance_id() == inst_id,
4166                              "old type must be non-instance or match new type");
4167 
4168   // The type 't' could be subclass of 'base_t'.
4169   // As result t->offset() could be large then base_t's size and it will
4170   // cause the failure in add_offset() with narrow oops since TypeOopPtr()
4171   // constructor verifies correctness of the offset.
4172   //
4173   // It could happened on subclass's branch (from the type profiling
4174   // inlining) which was not eliminated during parsing since the exactness
4175   // of the allocation type was not propagated to the subclass type check.
4176   //
4177   // Or the type 't' could be not related to 'base_t' at all.
4178   // It could happen when CHA type is different from MDO type on a dead path
4179   // (for example, from instanceof check) which is not collapsed during parsing.
4180   //
4181   // Do nothing for such AddP node and don't process its users since
4182   // this code branch will go away.
4183   //
4184   if (!t->is_known_instance() &&
4185       !base_t->maybe_java_subtype_of(t)) {
4186      return false; // bail out
4187   }
4188   const TypePtr* tinst = base_t->add_offset(t->offset());
4189   if (tinst->isa_aryptr() && t->isa_aryptr()) {
4190     // In the case of a flat inline type array, each field has its
4191     // own slice so we need to keep track of the field being accessed.
4192     tinst = tinst->is_aryptr()->with_field_offset(t->is_aryptr()->field_offset().get());
4193     // Keep array properties (not flat/null-free)
4194     tinst = tinst->is_aryptr()->update_properties(t->is_aryptr());
4195     if (tinst == nullptr) {
4196       return false; // Skip dead path with inconsistent properties
4197     }
4198   }
4199 
4200   // Do NOT remove the next line: ensure a new alias index is allocated
4201   // for the instance type. Note: C++ will not remove it since the call
4202   // has side effect.
4203   int alias_idx = _compile->get_alias_index(tinst);
4204   igvn->set_type(addp, tinst);
4205   // record the allocation in the node map
4206   set_map(addp, get_map(base->_idx));
4207   // Set addp's Base and Address to 'base'.
4208   Node *abase = addp->in(AddPNode::Base);
4209   Node *adr   = addp->in(AddPNode::Address);
4210   if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
4211       adr->in(0)->_idx == (uint)inst_id) {
4212     // Skip AddP cases #3 and #5.
4213   } else {
4214     assert(!abase->is_top(), "sanity"); // AddP case #3
4215     if (abase != base) {
4216       igvn->hash_delete(addp);
4217       addp->set_req(AddPNode::Base, base);
4218       if (abase == adr) {
4219         addp->set_req(AddPNode::Address, base);

4788       //   - not determined to be ineligible by escape analysis
4789       set_map(alloc, n);
4790       set_map(n, alloc);
4791       const TypeOopPtr* tinst = t->cast_to_instance_id(ni);
4792       igvn->hash_delete(n);
4793       igvn->set_type(n,  tinst);
4794       n->raise_bottom_type(tinst);
4795       igvn->hash_insert(n);
4796       record_for_optimizer(n);
4797       // Allocate an alias index for the header fields. Accesses to
4798       // the header emitted during macro expansion wouldn't have
4799       // correct memory state otherwise.
4800       _compile->get_alias_index(tinst->add_offset(oopDesc::mark_offset_in_bytes()));
4801       _compile->get_alias_index(tinst->add_offset(oopDesc::klass_offset_in_bytes()));
4802       if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
4803         // Add a new NarrowMem projection for each existing NarrowMem projection with new adr type
4804         InitializeNode* init = alloc->as_Allocate()->initialization();
4805         assert(init != nullptr, "can't find Initialization node for this Allocate node");
4806         auto process_narrow_proj = [&](NarrowMemProjNode* proj) {
4807           const TypePtr* adr_type = proj->adr_type();
4808           const TypePtr* new_adr_type = tinst->with_offset(adr_type->offset());
4809           if (adr_type->isa_aryptr()) {
4810             // In the case of a flat inline type array, each field has its own slice so we need a
4811             // NarrowMemProj for each field of the flat array elements
4812             new_adr_type = new_adr_type->is_aryptr()->with_field_offset(adr_type->is_aryptr()->field_offset().get());
4813           }
4814           if (adr_type != new_adr_type && !init->already_has_narrow_mem_proj_with_adr_type(new_adr_type)) {
4815             DEBUG_ONLY( uint alias_idx = _compile->get_alias_index(new_adr_type); )
4816             assert(_compile->get_general_index(alias_idx) == _compile->get_alias_index(adr_type), "new adr type should be narrowed down from existing adr type");
4817             NarrowMemProjNode* new_proj = new NarrowMemProjNode(init, new_adr_type);
4818             igvn->set_type(new_proj, new_proj->bottom_type());
4819             record_for_optimizer(new_proj);
4820             set_map(proj, new_proj); // record it so ConnectionGraph::find_inst_mem() can find it
4821           }
4822         };
4823         init->for_each_narrow_mem_proj_with_new_uses(process_narrow_proj);
4824 
4825         // First, put on the worklist all Field edges from Connection Graph
4826         // which is more accurate than putting immediate users from Ideal Graph.
4827         for (EdgeIterator e(ptn); e.has_next(); e.next()) {
4828           PointsToNode* tgt = e.get();
4829           if (tgt->is_Arraycopy()) {
4830             continue;
4831           }
4832           Node* use = tgt->ideal_node();
4833           assert(tgt->is_Field() && use->is_AddP(),

4910         ptnode_adr(n->_idx)->dump();
4911         assert(jobj != nullptr && jobj != phantom_obj, "escaped allocation");
4912 #endif
4913         _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4914         return;
4915       } else {
4916         Node *val = get_map(jobj->idx());   // CheckCastPP node
4917         TypeNode *tn = n->as_Type();
4918         const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
4919         assert(tinst != nullptr && tinst->is_known_instance() &&
4920                tinst->instance_id() == jobj->idx() , "instance type expected.");
4921 
4922         const Type *tn_type = igvn->type(tn);
4923         const TypeOopPtr *tn_t;
4924         if (tn_type->isa_narrowoop()) {
4925           tn_t = tn_type->make_ptr()->isa_oopptr();
4926         } else {
4927           tn_t = tn_type->isa_oopptr();
4928         }
4929         if (tn_t != nullptr && tinst->maybe_java_subtype_of(tn_t)) {
4930           if (tn_t->isa_aryptr()) {
4931             // Keep array properties (not flat/null-free)
4932             tinst = tinst->is_aryptr()->update_properties(tn_t->is_aryptr());
4933             if (tinst == nullptr) {
4934               continue; // Skip dead path with inconsistent properties
4935             }
4936           }
4937           if (tn_type->isa_narrowoop()) {
4938             tn_type = tinst->make_narrowoop();
4939           } else {
4940             tn_type = tinst;
4941           }
4942           igvn->hash_delete(tn);
4943           igvn->set_type(tn, tn_type);
4944           tn->set_type(tn_type);
4945           igvn->hash_insert(tn);
4946           record_for_optimizer(n);
4947         } else {
4948           assert(tn_type == TypePtr::NULL_PTR ||
4949                  (tn_t != nullptr && !tinst->maybe_java_subtype_of(tn_t)),
4950                  "unexpected type");
4951           continue; // Skip dead path with different type
4952         }
4953       }
4954     } else {
4955       DEBUG_ONLY(n->dump();)
4956       assert(false, "EA: unexpected node");
4957       continue;
4958     }
4959     // push allocation's users on appropriate worklist
4960     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4961       Node *use = n->fast_out(i);
4962       if (use->is_Mem() && use->in(MemNode::Address) == n) {
4963         // Load/store to instance's field
4964         memnode_worklist.append_if_missing(use);
4965       } else if (use->is_MemBar()) {
4966         if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4967           memnode_worklist.append_if_missing(use);
4968         }
4969       } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
4970         Node* addp2 = find_second_addp(use, n);
4971         if (addp2 != nullptr) {
4972           alloc_worklist.append_if_missing(addp2);
4973         }
4974         alloc_worklist.append_if_missing(use);
4975       } else if (use->is_Phi() ||
4976                  use->is_CheckCastPP() ||
4977                  use->is_EncodeNarrowPtr() ||
4978                  use->is_DecodeNarrowPtr() ||
4979                  (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
4980         alloc_worklist.append_if_missing(use);
4981 #ifdef ASSERT
4982       } else if (use->is_Mem()) {
4983         assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
4984       } else if (use->is_MergeMem()) {
4985         assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4986       } else if (use->is_SafePoint()) {
4987         // Look for MergeMem nodes for calls which reference unique allocation
4988         // (through CheckCastPP nodes) even for debug info.
4989         Node* m = use->in(TypeFunc::Memory);
4990         if (m->is_MergeMem()) {
4991           assert(mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4992         }
4993       } else if (use->Opcode() == Op_EncodeISOArray) {
4994         if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4995           // EncodeISOArray overwrites destination array
4996           memnode_worklist.append_if_missing(use);
4997         }
4998       } else if (use->Opcode() == Op_Return) {
4999         // Allocation is referenced by field of returned inline type
5000         assert(_compile->tf()->returns_inline_type_as_fields(), "EA: unexpected reference by ReturnNode");
5001       } else {
5002         uint op = use->Opcode();
5003         if ((op == Op_StrCompressedCopy || op == Op_StrInflatedCopy) &&
5004             (use->in(MemNode::Memory) == n)) {
5005           // They overwrite memory edge corresponding to destination array,
5006           memnode_worklist.append_if_missing(use);
5007         } else if (!(op == Op_CmpP || op == Op_Conv2B ||
5008               op == Op_CastP2X ||
5009               op == Op_FastLock || op == Op_AryEq ||
5010               op == Op_StrComp || op == Op_CountPositives ||
5011               op == Op_StrCompressedCopy || op == Op_StrInflatedCopy ||
5012               op == Op_StrEquals || op == Op_VectorizedHashCode ||
5013               op == Op_StrIndexOf || op == Op_StrIndexOfChar ||
5014               op == Op_SubTypeCheck || op == Op_InlineType || op == Op_FlatArrayCheck ||
5015               op == Op_ReinterpretS2HF ||
5016               BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use))) {
5017           n->dump();
5018           use->dump();
5019           assert(false, "EA: missing allocation reference path");
5020         }
5021 #endif
5022       }
5023     }
5024 
5025   }
5026 
5027 #ifdef ASSERT
5028   if (VerifyReduceAllocationMerges) {
5029     for (uint i = 0; i < reducible_merges.size(); i++) {
5030       Node* phi = reducible_merges.at(i);
5031 
5032       if (!reduced_merges.member(phi)) {
5033         phi->dump(2);
5034         phi->dump(-2);

5102         n = n->as_MemBar()->proj_out_or_null(TypeFunc::Memory);
5103         if (n == nullptr) {
5104           continue;
5105         }
5106       }
5107     } else if (n->is_CallLeaf()) {
5108       // Runtime calls with narrow memory input (no MergeMem node)
5109       // get the memory projection
5110       n = n->as_Call()->proj_out_or_null(TypeFunc::Memory);
5111       if (n == nullptr) {
5112         continue;
5113       }
5114     } else if (n->Opcode() == Op_StrInflatedCopy) {
5115       // Check direct uses of StrInflatedCopy.
5116       // It is memory type Node - no special SCMemProj node.
5117     } else if (n->Opcode() == Op_StrCompressedCopy ||
5118                n->Opcode() == Op_EncodeISOArray) {
5119       // get the memory projection
5120       n = n->find_out_with(Op_SCMemProj);
5121       assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
5122     } else if (n->is_CallLeaf() && n->as_CallLeaf()->_name != nullptr &&
5123                strcmp(n->as_CallLeaf()->_name, "store_unknown_inline") == 0) {
5124       n = n->as_CallLeaf()->proj_out(TypeFunc::Memory);
5125     } else if (n->is_Proj()) {
5126       assert(n->in(0)->is_Initialize(), "we only push memory projections for Initialize");
5127     } else {
5128 #ifdef ASSERT
5129       if (!n->is_Mem()) {
5130         n->dump();
5131       }
5132       assert(n->is_Mem(), "memory node required.");
5133 #endif
5134       Node *addr = n->in(MemNode::Address);
5135       const Type *addr_t = igvn->type(addr);
5136       if (addr_t == Type::TOP) {
5137         continue;
5138       }
5139       assert (addr_t->isa_ptr() != nullptr, "pointer type required.");
5140       int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
5141       assert ((uint)alias_idx < new_index_end, "wrong alias index");
5142       Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
5143       if (_compile->failing()) {
5144         return;

5156         assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
5157       }
5158     }
5159     // push user on appropriate worklist
5160     for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5161       Node *use = n->fast_out(i);
5162       if (use->is_Phi() || use->is_ClearArray()) {
5163         memnode_worklist.append_if_missing(use);
5164       } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
5165         memnode_worklist.append_if_missing(use);
5166       } else if (use->is_MemBar() || use->is_CallLeaf()) {
5167         if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
5168           memnode_worklist.append_if_missing(use);
5169         }
5170       } else if (use->is_Proj()) {
5171         assert(n->is_Initialize(), "We only push projections of Initialize");
5172         if (use->as_Proj()->_con == TypeFunc::Memory) { // Ignore precedent edge
5173           memnode_worklist.append_if_missing(use);
5174         }
5175 #ifdef ASSERT
5176       } else if (use->is_Mem()) {
5177         assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
5178       } else if (use->is_MergeMem()) {
5179         assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
5180       } else if (use->Opcode() == Op_EncodeISOArray) {
5181         if (use->in(MemNode::Memory) == n || use->in(3) == n) {
5182           // EncodeISOArray overwrites destination array
5183           memnode_worklist.append_if_missing(use);
5184         }
5185       } else if (use->is_CallLeaf() && use->as_CallLeaf()->_name != nullptr &&
5186                  strcmp(use->as_CallLeaf()->_name, "store_unknown_inline") == 0) {
5187         // store_unknown_inline overwrites destination array
5188         memnode_worklist.append_if_missing(use);
5189       } else {
5190         uint op = use->Opcode();
5191         if ((use->in(MemNode::Memory) == n) &&
5192             (op == Op_StrCompressedCopy || op == Op_StrInflatedCopy)) {
5193           // They overwrite memory edge corresponding to destination array,
5194           memnode_worklist.append_if_missing(use);
5195         } else if (!(BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use) ||
5196               op == Op_AryEq || op == Op_StrComp || op == Op_CountPositives ||
5197               op == Op_StrCompressedCopy || op == Op_StrInflatedCopy || op == Op_VectorizedHashCode ||
5198               op == Op_StrEquals || op == Op_StrIndexOf || op == Op_StrIndexOfChar || op == Op_FlatArrayCheck)) {
5199           n->dump();
5200           use->dump();
5201           assert(false, "EA: missing memory path");
5202         }
5203 #endif
5204       }
5205     }
5206   }
5207 
5208   //  Phase 3:  Process MergeMem nodes from mergemem_worklist.
5209   //            Walk each memory slice moving the first node encountered of each
5210   //            instance type to the input corresponding to its alias index.
5211   uint length = mergemem_worklist.length();
5212   for( uint next = 0; next < length; ++next ) {
5213     MergeMemNode* nmm = mergemem_worklist.at(next);
5214     assert(!visited.test_set(nmm->_idx), "should not be visited before");
5215     // Note: we don't want to use MergeMemStream here because we only want to
5216     // scan inputs which exist at the start, not ones we add during processing.
5217     // Note 2: MergeMem may already contains instance memory slices added
5218     // during find_inst_mem() call when memory nodes were processed above.

5281         _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
5282       } else if (_invocation > 0) {
5283         _compile->record_failure(C2Compiler::retry_no_iterative_escape_analysis());
5284       } else {
5285         _compile->record_failure(C2Compiler::retry_no_escape_analysis());
5286       }
5287       return;
5288     }
5289 
5290     igvn->hash_insert(nmm);
5291     record_for_optimizer(nmm);
5292   }
5293 
5294   _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_3, 5);
5295 
5296   //  Phase 4:  Update the inputs of non-instance memory Phis and
5297   //            the Memory input of memnodes
5298   // First update the inputs of any non-instance Phi's from
5299   // which we split out an instance Phi.  Note we don't have
5300   // to recursively process Phi's encountered on the input memory
5301   // chains as is done in split_memory_phi() since they will
5302   // also be processed here.
5303   for (int j = 0; j < orig_phis.length(); j++) {
5304     PhiNode *phi = orig_phis.at(j);
5305     int alias_idx = _compile->get_alias_index(phi->adr_type());
5306     igvn->hash_delete(phi);
5307     for (uint i = 1; i < phi->req(); i++) {
5308       Node *mem = phi->in(i);
5309       Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
5310       if (_compile->failing()) {
5311         return;
5312       }
5313       if (mem != new_mem) {
5314         phi->set_req(i, new_mem);
5315       }
5316     }
5317     igvn->hash_insert(phi);
5318     record_for_optimizer(phi);
5319   }
5320 
5321   // Update the memory inputs of MemNodes with the value we computed
< prev index next >