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 }
1308 // (2) A selector, used to decide if we need to rematerialize an object
1309 // or use the pointer to a NSR object.
1310 // See more details of these fields in the declaration of SafePointScalarMergeNode.
1311 // It is safe to include them into debug info straight away since create_scalarized_object_description()
1312 // will include all newly added inputs into debug info anyway.
1313 sfpt->add_req(nsr_merge_pointer);
1314 sfpt->add_req(selector);
1315 sfpt->jvms()->set_endoff(sfpt->req());
1316
1317 for (uint i = 1; i < ophi->req(); i++) {
1318 Node* base = ophi->in(i);
1319 JavaObjectNode* ptn = unique_java_object(base);
1320
1321 // If the base is not scalar replaceable we don't need to register information about
1322 // it at this time.
1323 if (ptn == nullptr || !ptn->scalar_replaceable()) {
1324 continue;
1325 }
1326
1327 AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
1328 SafePointScalarObjectNode* sobj = mexp.create_scalarized_object_description(alloc, sfpt);
1329 if (sobj == nullptr) {
1330 sfpt->restore_non_debug_edges(non_debug_edges_worklist);
1331 return false; // non-recoverable failure; recompile
1332 }
1333
1334 // Now make a pass over the debug information replacing any references
1335 // to the allocated object with "sobj"
1336 Node* ccpp = alloc->result_cast();
1337 sfpt->replace_edges_in_range(ccpp, sobj, debug_start, jvms->debug_end(), _igvn);
1338 non_debug_edges_worklist.remove_edge_if_present(ccpp); // drop scalarized input from non-debug info
1339
1340 // Register the scalarized object as a candidate for reallocation
1341 smerge->add_req(sobj);
1342 }
1343
1344 // Replaces debug information references to "original_sfpt_parent" in "sfpt" with references to "smerge"
1345 sfpt->replace_edges_in_range(original_sfpt_parent, smerge, debug_start, jvms->debug_end(), _igvn);
1346 non_debug_edges_worklist.remove_edge_if_present(original_sfpt_parent); // drop scalarized input from non-debug info
1347
1348 // The call to 'replace_edges_in_range' above might have removed the
1349 // reference to ophi that we need at _merge_pointer_idx. The line below make
1350 // sure the reference is maintained.
1351 sfpt->set_req(smerge->merge_pointer_idx(jvms), nsr_merge_pointer);
1352
1353 sfpt->restore_non_debug_edges(non_debug_edges_worklist);
1354
1355 _igvn->_worklist.push(sfpt);
1356 }
1357
1358 return true;
1359 }
1360
1361 void ConnectionGraph::reduce_phi(PhiNode* ophi, GrowableArray<Node*> &alloc_worklist) {
1528 return false;
1529 }
1530
1531 // Returns true if at least one of the arguments to the call is an object
1532 // that does not escape globally.
1533 bool ConnectionGraph::has_arg_escape(CallJavaNode* call) {
1534 if (call->method() != nullptr) {
1535 uint max_idx = TypeFunc::Parms + call->method()->arg_size();
1536 for (uint idx = TypeFunc::Parms; idx < max_idx; idx++) {
1537 Node* p = call->in(idx);
1538 if (not_global_escape(p)) {
1539 return true;
1540 }
1541 }
1542 } else {
1543 const char* name = call->as_CallStaticJava()->_name;
1544 assert(name != nullptr, "no name");
1545 // no arg escapes through uncommon traps
1546 if (strcmp(name, "uncommon_trap") != 0) {
1547 // process_call_arguments() assumes that all arguments escape globally
1548 const TypeTuple* d = call->tf()->domain();
1549 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1550 const Type* at = d->field_at(i);
1551 if (at->isa_oopptr() != nullptr) {
1552 return true;
1553 }
1554 }
1555 }
1556 }
1557 return false;
1558 }
1559
1560
1561
1562 // Utility function for nodes that load an object
1563 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1564 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1565 // ThreadLocal has RawPtr type.
1566 const Type* t = _igvn->type(n);
1567 if (t->make_ptr() != nullptr) {
1568 Node* adr = n->in(MemNode::Address);
1569 #ifdef ASSERT
1570 if (!adr->is_AddP()) {
1571 assert(_igvn->type(adr)->isa_rawptr(), "sanity");
1572 } else {
1573 assert((ptnode_adr(adr->_idx) == nullptr ||
1574 ptnode_adr(adr->_idx)->as_Field()->is_oop()), "sanity");
1575 }
1576 #endif
1577 add_local_var_and_edge(n, PointsToNode::NoEscape,
1578 adr, delayed_worklist);
1579 }
1580 }
1581
1582 // Populate Connection Graph with PointsTo nodes and create simple
1583 // connection graph edges.
1584 void ConnectionGraph::add_node_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1585 assert(!_verify, "this method should not be called for verification");
1586 PhaseGVN* igvn = _igvn;
1587 uint n_idx = n->_idx;
1588 PointsToNode* n_ptn = ptnode_adr(n_idx);
1589 if (n_ptn != nullptr) {
1590 return; // No need to redefine PointsTo node during first iteration.
1591 }
1592 int opcode = n->Opcode();
1593 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_to_con_graph(this, igvn, delayed_worklist, n, opcode);
1594 if (gc_handled) {
1595 return; // Ignore node if already handled by GC.
1596 }
1597
1598 if (n->is_Call()) {
1599 // Arguments to allocation and locking don't escape.
1600 if (n->is_AbstractLock()) {
1601 // Put Lock and Unlock nodes on IGVN worklist to process them during
1602 // first IGVN optimization when escape information is still available.
1603 record_for_optimizer(n);
1604 } else if (n->is_Allocate()) {
1605 add_call_node(n->as_Call());
1606 record_for_optimizer(n);
1607 } else {
1608 if (n->is_CallStaticJava()) {
1609 const char* name = n->as_CallStaticJava()->_name;
1610 if (name != nullptr && strcmp(name, "uncommon_trap") == 0) {
1611 return; // Skip uncommon traps
1612 }
1613 }
1614 // Don't mark as processed since call's arguments have to be processed.
1615 delayed_worklist->push(n);
1616 // Check if a call returns an object.
1617 if ((n->as_Call()->returns_pointer() &&
1618 n->as_Call()->proj_out_or_null(TypeFunc::Parms) != nullptr) ||
1619 (n->is_CallStaticJava() &&
1620 n->as_CallStaticJava()->is_boxing_method())) {
1621 add_call_node(n->as_Call());
1622 }
1623 }
1624 return;
1625 }
1626 // Put this check here to process call arguments since some call nodes
1627 // point to phantom_obj.
1628 if (n_ptn == phantom_obj || n_ptn == null_obj) {
1629 return; // Skip predefined nodes.
1630 }
1631 switch (opcode) {
1632 case Op_AddP: {
1633 Node* base = get_addp_base(n);
1634 PointsToNode* ptn_base = ptnode_adr(base->_idx);
1635 // Field nodes are created for all field types. They are used in
1636 // adjust_scalar_replaceable_state() and split_unique_types().
1637 // Note, non-oop fields will have only base edges in Connection
1638 // Graph because such fields are not used for oop loads and stores.
1639 int offset = address_offset(n, igvn);
1640 add_field(n, PointsToNode::NoEscape, offset);
1641 if (ptn_base == nullptr) {
1642 delayed_worklist->push(n); // Process it later.
1643 } else {
1644 n_ptn = ptnode_adr(n_idx);
1645 add_base(n_ptn->as_Field(), ptn_base);
1646 }
1647 break;
1648 }
1649 case Op_CastX2P: {
1650 map_ideal_node(n, phantom_obj);
1651 break;
1652 }
1653 case Op_CastPP:
1654 case Op_CheckCastPP:
1655 case Op_EncodeP:
1656 case Op_DecodeN:
1657 case Op_EncodePKlass:
1658 case Op_DecodeNKlass: {
1659 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1660 break;
1661 }
1662 case Op_CMoveP: {
1663 add_local_var(n, PointsToNode::NoEscape);
1664 // Do not add edges during first iteration because some could be
1665 // not defined yet.
1666 delayed_worklist->push(n);
1667 break;
1668 }
1669 case Op_ConP:
1670 case Op_ConN:
1671 case Op_ConNKlass: {
1672 // assume all oop constants globally escape except for null
1702 break;
1703 }
1704 case Op_PartialSubtypeCheck: {
1705 // Produces Null or notNull and is used in only in CmpP so
1706 // phantom_obj could be used.
1707 map_ideal_node(n, phantom_obj); // Result is unknown
1708 break;
1709 }
1710 case Op_Phi: {
1711 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1712 // ThreadLocal has RawPtr type.
1713 const Type* t = n->as_Phi()->type();
1714 if (t->make_ptr() != nullptr) {
1715 add_local_var(n, PointsToNode::NoEscape);
1716 // Do not add edges during first iteration because some could be
1717 // not defined yet.
1718 delayed_worklist->push(n);
1719 }
1720 break;
1721 }
1722 case Op_Proj: {
1723 // we are only interested in the oop result projection from a call
1724 if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
1725 n->in(0)->as_Call()->returns_pointer()) {
1726 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1727 }
1728 break;
1729 }
1730 case Op_Rethrow: // Exception object escapes
1731 case Op_Return: {
1732 if (n->req() > TypeFunc::Parms &&
1733 igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
1734 // Treat Return value as LocalVar with GlobalEscape escape state.
1735 add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), delayed_worklist);
1736 }
1737 break;
1738 }
1739 case Op_CompareAndExchangeP:
1740 case Op_CompareAndExchangeN:
1741 case Op_GetAndSetP:
1742 case Op_GetAndSetN: {
1743 add_objload_to_connection_graph(n, delayed_worklist);
1744 // fall-through
1745 }
1746 case Op_StoreP:
1747 case Op_StoreN:
1791 break;
1792 }
1793 default:
1794 ; // Do nothing for nodes not related to EA.
1795 }
1796 return;
1797 }
1798
1799 // Add final simple edges to graph.
1800 void ConnectionGraph::add_final_edges(Node *n) {
1801 PointsToNode* n_ptn = ptnode_adr(n->_idx);
1802 #ifdef ASSERT
1803 if (_verify && n_ptn->is_JavaObject())
1804 return; // This method does not change graph for JavaObject.
1805 #endif
1806
1807 if (n->is_Call()) {
1808 process_call_arguments(n->as_Call());
1809 return;
1810 }
1811 assert(n->is_Store() || n->is_LoadStore() ||
1812 ((n_ptn != nullptr) && (n_ptn->ideal_node() != nullptr)),
1813 "node should be registered already");
1814 int opcode = n->Opcode();
1815 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_final_edges(this, _igvn, n, opcode);
1816 if (gc_handled) {
1817 return; // Ignore node if already handled by GC.
1818 }
1819 switch (opcode) {
1820 case Op_AddP: {
1821 Node* base = get_addp_base(n);
1822 PointsToNode* ptn_base = ptnode_adr(base->_idx);
1823 assert(ptn_base != nullptr, "field's base should be registered");
1824 add_base(n_ptn->as_Field(), ptn_base);
1825 break;
1826 }
1827 case Op_CastPP:
1828 case Op_CheckCastPP:
1829 case Op_EncodeP:
1830 case Op_DecodeN:
1831 case Op_EncodePKlass:
1832 case Op_DecodeNKlass: {
1833 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), nullptr);
1834 break;
1835 }
1836 case Op_CMoveP: {
1837 for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
1838 Node* in = n->in(i);
1839 if (in == nullptr) {
1840 continue; // ignore null
1841 }
1842 Node* uncast_in = in->uncast();
1843 if (uncast_in->is_top() || uncast_in == n) {
1844 continue; // ignore top or inputs which go back this node
1845 }
1846 PointsToNode* ptn = ptnode_adr(in->_idx);
1859 }
1860 case Op_Phi: {
1861 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1862 // ThreadLocal has RawPtr type.
1863 assert(n->as_Phi()->type()->make_ptr() != nullptr, "Unexpected node type");
1864 for (uint i = 1; i < n->req(); i++) {
1865 Node* in = n->in(i);
1866 if (in == nullptr) {
1867 continue; // ignore null
1868 }
1869 Node* uncast_in = in->uncast();
1870 if (uncast_in->is_top() || uncast_in == n) {
1871 continue; // ignore top or inputs which go back this node
1872 }
1873 PointsToNode* ptn = ptnode_adr(in->_idx);
1874 assert(ptn != nullptr, "node should be registered");
1875 add_edge(n_ptn, ptn);
1876 }
1877 break;
1878 }
1879 case Op_Proj: {
1880 // we are only interested in the oop result projection from a call
1881 assert(n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
1882 n->in(0)->as_Call()->returns_pointer(), "Unexpected node type");
1883 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), nullptr);
1884 break;
1885 }
1886 case Op_Rethrow: // Exception object escapes
1887 case Op_Return: {
1888 assert(n->req() > TypeFunc::Parms && _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr(),
1889 "Unexpected node type");
1890 // Treat Return value as LocalVar with GlobalEscape escape state.
1891 add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), nullptr);
1892 break;
1893 }
1894 case Op_CompareAndExchangeP:
1895 case Op_CompareAndExchangeN:
1896 case Op_GetAndSetP:
1897 case Op_GetAndSetN:{
1898 assert(_igvn->type(n)->make_ptr() != nullptr, "Unexpected node type");
1899 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), nullptr);
1900 // fall-through
1901 }
1902 case Op_CompareAndSwapP:
1903 case Op_CompareAndSwapN:
2037 Node* val = n->in(MemNode::ValueIn);
2038 PointsToNode* ptn = ptnode_adr(val->_idx);
2039 assert(ptn != nullptr, "node should be registered");
2040 set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "stored at raw address"));
2041 // Add edge to object for unsafe access with offset.
2042 PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
2043 assert(adr_ptn != nullptr, "node should be registered");
2044 if (adr_ptn->is_Field()) {
2045 assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
2046 add_edge(adr_ptn, ptn);
2047 }
2048 return true;
2049 }
2050 #ifdef ASSERT
2051 n->dump(1);
2052 assert(false, "not unsafe");
2053 #endif
2054 return false;
2055 }
2056
2057 void ConnectionGraph::add_call_node(CallNode* call) {
2058 assert(call->returns_pointer(), "only for call which returns pointer");
2059 uint call_idx = call->_idx;
2060 if (call->is_Allocate()) {
2061 Node* k = call->in(AllocateNode::KlassNode);
2062 const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
2063 assert(kt != nullptr, "TypeKlassPtr required.");
2064 PointsToNode::EscapeState es = PointsToNode::NoEscape;
2065 bool scalar_replaceable = true;
2066 NOT_PRODUCT(const char* nsr_reason = "");
2067 if (call->is_AllocateArray()) {
2068 if (!kt->isa_aryklassptr()) { // StressReflectiveCode
2069 es = PointsToNode::GlobalEscape;
2070 } else {
2071 int length = call->in(AllocateNode::ALength)->find_int_con(-1);
2072 if (length < 0) {
2073 // Not scalar replaceable if the length is not constant.
2074 scalar_replaceable = false;
2075 NOT_PRODUCT(nsr_reason = "has a non-constant length");
2076 } else if (length > EliminateAllocationArraySizeLimit) {
2077 // Not scalar replaceable if the length is too big.
2078 scalar_replaceable = false;
2113 // - mapped to GlobalEscape JavaObject node if oop is returned;
2114 //
2115 // - all oop arguments are escaping globally;
2116 //
2117 // 2. CallStaticJavaNode (execute bytecode analysis if possible):
2118 //
2119 // - the same as CallDynamicJavaNode if can't do bytecode analysis;
2120 //
2121 // - mapped to GlobalEscape JavaObject node if unknown oop is returned;
2122 // - mapped to NoEscape JavaObject node if non-escaping object allocated
2123 // during call is returned;
2124 // - mapped to ArgEscape LocalVar node pointed to object arguments
2125 // which are returned and does not escape during call;
2126 //
2127 // - oop arguments escaping status is defined by bytecode analysis;
2128 //
2129 // For a static call, we know exactly what method is being called.
2130 // Use bytecode estimator to record whether the call's return value escapes.
2131 ciMethod* meth = call->as_CallJava()->method();
2132 if (meth == nullptr) {
2133 assert(call->as_CallStaticJava()->is_call_to_multianewarray_stub(), "TODO: add failed case check");
2134 // Returns a newly allocated non-escaped object.
2135 add_java_object(call, PointsToNode::NoEscape);
2136 set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of multinewarray"));
2137 } else if (meth->is_boxing_method()) {
2138 // Returns boxing object
2139 PointsToNode::EscapeState es;
2140 vmIntrinsics::ID intr = meth->intrinsic_id();
2141 if (intr == vmIntrinsics::_floatValue || intr == vmIntrinsics::_doubleValue) {
2142 // It does not escape if object is always allocated.
2143 es = PointsToNode::NoEscape;
2144 } else {
2145 // It escapes globally if object could be loaded from cache.
2146 es = PointsToNode::GlobalEscape;
2147 }
2148 add_java_object(call, es);
2149 if (es == PointsToNode::GlobalEscape) {
2150 set_not_scalar_replaceable(ptnode_adr(call->_idx) NOT_PRODUCT(COMMA "object can be loaded from boxing cache"));
2151 }
2152 } else {
2153 BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
2154 call_analyzer->copy_dependencies(_compile->dependencies());
2155 if (call_analyzer->is_return_allocated()) {
2156 // Returns a newly allocated non-escaped object, simply
2157 // update dependency information.
2158 // Mark it as NoEscape so that objects referenced by
2159 // it's fields will be marked as NoEscape at least.
2160 add_java_object(call, PointsToNode::NoEscape);
2161 set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of call"));
2162 } else {
2163 // Determine whether any arguments are returned.
2164 const TypeTuple* d = call->tf()->domain();
2165 bool ret_arg = false;
2166 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2167 if (d->field_at(i)->isa_ptr() != nullptr &&
2168 call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
2169 ret_arg = true;
2170 break;
2171 }
2172 }
2173 if (ret_arg) {
2174 add_local_var(call, PointsToNode::ArgEscape);
2175 } else {
2176 // Returns unknown object.
2177 map_ideal_node(call, phantom_obj);
2178 }
2179 }
2180 }
2181 } else {
2182 // An other type of call, assume the worst case:
2183 // returned value is unknown and globally escapes.
2184 assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
2185 map_ideal_node(call, phantom_obj);
2186 }
2187 }
2188
2189 void ConnectionGraph::process_call_arguments(CallNode *call) {
2190 bool is_arraycopy = false;
2191 switch (call->Opcode()) {
2192 #ifdef ASSERT
2193 case Op_Allocate:
2194 case Op_AllocateArray:
2195 case Op_Lock:
2196 case Op_Unlock:
2197 assert(false, "should be done already");
2198 break;
2199 #endif
2200 case Op_ArrayCopy:
2201 case Op_CallLeafNoFP:
2202 // Most array copies are ArrayCopy nodes at this point but there
2203 // are still a few direct calls to the copy subroutines (See
2204 // PhaseStringOpts::copy_string())
2205 is_arraycopy = (call->Opcode() == Op_ArrayCopy) ||
2206 call->as_CallLeaf()->is_call_to_arraycopystub();
2207 // fall through
2208 case Op_CallLeafVector:
2209 case Op_CallLeaf: {
2210 // Stub calls, objects do not escape but they are not scale replaceable.
2211 // Adjust escape state for outgoing arguments.
2212 const TypeTuple * d = call->tf()->domain();
2213 bool src_has_oops = false;
2214 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2215 const Type* at = d->field_at(i);
2216 Node *arg = call->in(i);
2217 if (arg == nullptr) {
2218 continue;
2219 }
2220 const Type *aat = _igvn->type(arg);
2221 if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr()) {
2222 continue;
2223 }
2224 if (arg->is_AddP()) {
2225 //
2226 // The inline_native_clone() case when the arraycopy stub is called
2227 // after the allocation before Initialize and CheckCastPP nodes.
2228 // Or normal arraycopy for object arrays case.
2229 //
2230 // Set AddP's base (Allocate) as not scalar replaceable since
2231 // pointer to the base (with offset) is passed as argument.
2232 //
2233 arg = get_addp_base(arg);
2234 }
2235 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2236 assert(arg_ptn != nullptr, "should be registered");
2237 PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
2238 if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
2239 assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
2240 aat->isa_ptr() != nullptr, "expecting an Ptr");
2241 bool arg_has_oops = aat->isa_oopptr() &&
2242 (aat->isa_instptr() ||
2243 (aat->isa_aryptr() && (aat->isa_aryptr()->elem() == Type::BOTTOM || aat->isa_aryptr()->elem()->make_oopptr() != nullptr)));
2244 if (i == TypeFunc::Parms) {
2245 src_has_oops = arg_has_oops;
2246 }
2247 //
2248 // src or dst could be j.l.Object when other is basic type array:
2249 //
2250 // arraycopy(char[],0,Object*,0,size);
2251 // arraycopy(Object*,0,char[],0,size);
2252 //
2253 // Don't add edges in such cases.
2254 //
2255 bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
2256 arg_has_oops && (i > TypeFunc::Parms);
2257 #ifdef ASSERT
2258 if (!(is_arraycopy ||
2259 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(call) ||
2260 (call->as_CallLeaf()->_name != nullptr &&
2261 (strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 ||
2262 strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32C") == 0 ||
2263 strcmp(call->as_CallLeaf()->_name, "updateBytesAdler32") == 0 ||
2288 strcmp(call->as_CallLeaf()->_name, "dilithiumDecomposePoly") == 0 ||
2289 strcmp(call->as_CallLeaf()->_name, "encodeBlock") == 0 ||
2290 strcmp(call->as_CallLeaf()->_name, "decodeBlock") == 0 ||
2291 strcmp(call->as_CallLeaf()->_name, "md5_implCompress") == 0 ||
2292 strcmp(call->as_CallLeaf()->_name, "md5_implCompressMB") == 0 ||
2293 strcmp(call->as_CallLeaf()->_name, "sha1_implCompress") == 0 ||
2294 strcmp(call->as_CallLeaf()->_name, "sha1_implCompressMB") == 0 ||
2295 strcmp(call->as_CallLeaf()->_name, "sha256_implCompress") == 0 ||
2296 strcmp(call->as_CallLeaf()->_name, "sha256_implCompressMB") == 0 ||
2297 strcmp(call->as_CallLeaf()->_name, "sha512_implCompress") == 0 ||
2298 strcmp(call->as_CallLeaf()->_name, "sha512_implCompressMB") == 0 ||
2299 strcmp(call->as_CallLeaf()->_name, "sha3_implCompress") == 0 ||
2300 strcmp(call->as_CallLeaf()->_name, "double_keccak") == 0 ||
2301 strcmp(call->as_CallLeaf()->_name, "quad_keccak") == 0 ||
2302 strcmp(call->as_CallLeaf()->_name, "sha3_implCompressMB") == 0 ||
2303 strcmp(call->as_CallLeaf()->_name, "multiplyToLen") == 0 ||
2304 strcmp(call->as_CallLeaf()->_name, "squareToLen") == 0 ||
2305 strcmp(call->as_CallLeaf()->_name, "mulAdd") == 0 ||
2306 strcmp(call->as_CallLeaf()->_name, "montgomery_multiply") == 0 ||
2307 strcmp(call->as_CallLeaf()->_name, "montgomery_square") == 0 ||
2308 strcmp(call->as_CallLeaf()->_name, "bigIntegerRightShiftWorker") == 0 ||
2309 strcmp(call->as_CallLeaf()->_name, "bigIntegerLeftShiftWorker") == 0 ||
2310 strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2311 strcmp(call->as_CallLeaf()->_name, "stringIndexOf") == 0 ||
2312 strcmp(call->as_CallLeaf()->_name, "arraysort_stub") == 0 ||
2313 strcmp(call->as_CallLeaf()->_name, "array_partition_stub") == 0 ||
2314 strcmp(call->as_CallLeaf()->_name, "get_class_id_intrinsic") == 0 ||
2315 strcmp(call->as_CallLeaf()->_name, "unsafe_setmemory") == 0)
2316 ))) {
2317 call->dump();
2318 fatal("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name);
2319 }
2320 #endif
2321 // Always process arraycopy's destination object since
2322 // we need to add all possible edges to references in
2323 // source object.
2324 if (arg_esc >= PointsToNode::ArgEscape &&
2325 !arg_is_arraycopy_dest) {
2326 continue;
2327 }
2350 }
2351 }
2352 }
2353 break;
2354 }
2355 case Op_CallStaticJava: {
2356 // For a static call, we know exactly what method is being called.
2357 // Use bytecode estimator to record the call's escape affects
2358 #ifdef ASSERT
2359 const char* name = call->as_CallStaticJava()->_name;
2360 assert((name == nullptr || strcmp(name, "uncommon_trap") != 0), "normal calls only");
2361 #endif
2362 ciMethod* meth = call->as_CallJava()->method();
2363 if ((meth != nullptr) && meth->is_boxing_method()) {
2364 break; // Boxing methods do not modify any oops.
2365 }
2366 BCEscapeAnalyzer* call_analyzer = (meth !=nullptr) ? meth->get_bcea() : nullptr;
2367 // fall-through if not a Java method or no analyzer information
2368 if (call_analyzer != nullptr) {
2369 PointsToNode* call_ptn = ptnode_adr(call->_idx);
2370 const TypeTuple* d = call->tf()->domain();
2371 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2372 const Type* at = d->field_at(i);
2373 int k = i - TypeFunc::Parms;
2374 Node* arg = call->in(i);
2375 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2376 if (at->isa_ptr() != nullptr &&
2377 call_analyzer->is_arg_returned(k)) {
2378 // The call returns arguments.
2379 if (call_ptn != nullptr) { // Is call's result used?
2380 assert(call_ptn->is_LocalVar(), "node should be registered");
2381 assert(arg_ptn != nullptr, "node should be registered");
2382 add_edge(call_ptn, arg_ptn);
2383 }
2384 }
2385 if (at->isa_oopptr() != nullptr &&
2386 arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
2387 if (!call_analyzer->is_arg_stack(k)) {
2388 // The argument global escapes
2389 set_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2390 } else {
2391 set_escape_state(arg_ptn, PointsToNode::ArgEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2392 if (!call_analyzer->is_arg_local(k)) {
2393 // The argument itself doesn't escape, but any fields might
2394 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2395 }
2396 }
2397 }
2398 }
2399 if (call_ptn != nullptr && call_ptn->is_LocalVar()) {
2400 // The call returns arguments.
2401 assert(call_ptn->edge_count() > 0, "sanity");
2402 if (!call_analyzer->is_return_local()) {
2403 // Returns also unknown object.
2404 add_edge(call_ptn, phantom_obj);
2405 }
2406 }
2407 break;
2408 }
2409 }
2410 default: {
2411 // Fall-through here if not a Java method or no analyzer information
2412 // or some other type of call, assume the worst case: all arguments
2413 // globally escape.
2414 const TypeTuple* d = call->tf()->domain();
2415 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2416 const Type* at = d->field_at(i);
2417 if (at->isa_oopptr() != nullptr) {
2418 Node* arg = call->in(i);
2419 if (arg->is_AddP()) {
2420 arg = get_addp_base(arg);
2421 }
2422 assert(ptnode_adr(arg->_idx) != nullptr, "should be defined already");
2423 set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2424 }
2425 }
2426 }
2427 }
2428 }
2429
2430
2431 // Finish Graph construction.
2432 bool ConnectionGraph::complete_connection_graph(
2433 GrowableArray<PointsToNode*>& ptnodes_worklist,
2434 GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
2812 PointsToNode* base = i.get();
2813 if (base->is_JavaObject()) {
2814 // Skip Allocate's fields which will be processed later.
2815 if (base->ideal_node()->is_Allocate()) {
2816 return 0;
2817 }
2818 assert(base == null_obj, "only null ptr base expected here");
2819 }
2820 }
2821 if (add_edge(field, phantom_obj)) {
2822 // New edge was added
2823 new_edges++;
2824 add_field_uses_to_worklist(field);
2825 }
2826 return new_edges;
2827 }
2828
2829 // Find fields initializing values for allocations.
2830 int ConnectionGraph::find_init_values_phantom(JavaObjectNode* pta) {
2831 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2832 Node* alloc = pta->ideal_node();
2833
2834 // Do nothing for Allocate nodes since its fields values are
2835 // "known" unless they are initialized by arraycopy/clone.
2836 if (alloc->is_Allocate() && !pta->arraycopy_dst()) {
2837 return 0;
2838 }
2839 assert(pta->arraycopy_dst() || alloc->as_CallStaticJava(), "sanity");
2840 #ifdef ASSERT
2841 if (!pta->arraycopy_dst() && alloc->as_CallStaticJava()->method() == nullptr) {
2842 assert(alloc->as_CallStaticJava()->is_call_to_multianewarray_stub(), "sanity");
2843 }
2844 #endif
2845 // Non-escaped allocation returned from Java or runtime call have unknown values in fields.
2846 int new_edges = 0;
2847 for (EdgeIterator i(pta); i.has_next(); i.next()) {
2848 PointsToNode* field = i.get();
2849 if (field->is_Field() && field->as_Field()->is_oop()) {
2850 if (add_edge(field, phantom_obj)) {
2851 // New edge was added
2852 new_edges++;
2853 add_field_uses_to_worklist(field->as_Field());
2854 }
2855 }
2856 }
2857 return new_edges;
2858 }
2859
2860 // Find fields initializing values for allocations.
2861 int ConnectionGraph::find_init_values_null(JavaObjectNode* pta, PhaseValues* phase) {
2862 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2863 Node* alloc = pta->ideal_node();
2864 // Do nothing for Call nodes since its fields values are unknown.
2865 if (!alloc->is_Allocate()) {
2866 return 0;
2867 }
2868 InitializeNode* ini = alloc->as_Allocate()->initialization();
2869 bool visited_bottom_offset = false;
2870 GrowableArray<int> offsets_worklist;
2871 int new_edges = 0;
2872
2873 // Check if an oop field's initializing value is recorded and add
2874 // a corresponding null if field's value if it is not recorded.
2875 // Connection Graph does not record a default initialization by null
2876 // captured by Initialize node.
2877 //
2878 for (EdgeIterator i(pta); i.has_next(); i.next()) {
2879 PointsToNode* field = i.get(); // Field (AddP)
2880 if (!field->is_Field() || !field->as_Field()->is_oop()) {
2881 continue; // Not oop field
2882 }
2883 int offset = field->as_Field()->offset();
2884 if (offset == Type::OffsetBot) {
2885 if (!visited_bottom_offset) {
2931 } else {
2932 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
2933 tty->print_cr("----------init store has invalid value -----");
2934 store->dump();
2935 val->dump();
2936 assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
2937 }
2938 for (EdgeIterator j(val); j.has_next(); j.next()) {
2939 PointsToNode* obj = j.get();
2940 if (obj->is_JavaObject()) {
2941 if (!field->points_to(obj->as_JavaObject())) {
2942 missed_obj = obj;
2943 break;
2944 }
2945 }
2946 }
2947 }
2948 if (missed_obj != nullptr) {
2949 tty->print_cr("----------field---------------------------------");
2950 field->dump();
2951 tty->print_cr("----------missed referernce to object-----------");
2952 missed_obj->dump();
2953 tty->print_cr("----------object referernced by init store -----");
2954 store->dump();
2955 val->dump();
2956 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
2957 }
2958 }
2959 #endif
2960 } else {
2961 // There could be initializing stores which follow allocation.
2962 // For example, a volatile field store is not collected
2963 // by Initialize node.
2964 //
2965 // Need to check for dependent loads to separate such stores from
2966 // stores which follow loads. For now, add initial value null so
2967 // that compare pointers optimization works correctly.
2968 }
2969 }
2970 if (value == nullptr) {
2971 // A field's initializing value was not recorded. Add null.
2972 if (add_edge(field, null_obj)) {
2973 // New edge was added
3298 assert(field->edge_count() > 0, "sanity");
3299 }
3300 }
3301 }
3302 }
3303 #endif
3304
3305 // Optimize ideal graph.
3306 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
3307 GrowableArray<MemBarStoreStoreNode*>& storestore_worklist) {
3308 Compile* C = _compile;
3309 PhaseIterGVN* igvn = _igvn;
3310 if (EliminateLocks) {
3311 // Mark locks before changing ideal graph.
3312 int cnt = C->macro_count();
3313 for (int i = 0; i < cnt; i++) {
3314 Node *n = C->macro_node(i);
3315 if (n->is_AbstractLock()) { // Lock and Unlock nodes
3316 AbstractLockNode* alock = n->as_AbstractLock();
3317 if (!alock->is_non_esc_obj()) {
3318 if (can_eliminate_lock(alock)) {
3319 assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
3320 // The lock could be marked eliminated by lock coarsening
3321 // code during first IGVN before EA. Replace coarsened flag
3322 // to eliminate all associated locks/unlocks.
3323 #ifdef ASSERT
3324 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc3");
3325 #endif
3326 alock->set_non_esc_obj();
3327 }
3328 }
3329 }
3330 }
3331 }
3332
3333 if (OptimizePtrCompare) {
3334 for (int i = 0; i < ptr_cmp_worklist.length(); i++) {
3335 Node *n = ptr_cmp_worklist.at(i);
3336 assert(n->Opcode() == Op_CmpN || n->Opcode() == Op_CmpP, "must be");
3337 const TypeInt* tcmp = optimize_ptr_compare(n->in(1), n->in(2));
3338 if (tcmp->singleton()) {
3340 #ifndef PRODUCT
3341 if (PrintOptimizePtrCompare) {
3342 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"));
3343 if (Verbose) {
3344 n->dump(1);
3345 }
3346 }
3347 #endif
3348 igvn->replace_node(n, cmp);
3349 }
3350 }
3351 }
3352
3353 // For MemBarStoreStore nodes added in library_call.cpp, check
3354 // escape status of associated AllocateNode and optimize out
3355 // MemBarStoreStore node if the allocated object never escapes.
3356 for (int i = 0; i < storestore_worklist.length(); i++) {
3357 Node* storestore = storestore_worklist.at(i);
3358 Node* alloc = storestore->in(MemBarNode::Precedent)->in(0);
3359 if (alloc->is_Allocate() && not_global_escape(alloc)) {
3360 MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
3361 mb->init_req(TypeFunc::Memory, storestore->in(TypeFunc::Memory));
3362 mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
3363 igvn->register_new_node_with_optimizer(mb);
3364 igvn->replace_node(storestore, mb);
3365 }
3366 }
3367 }
3368
3369 // Optimize objects compare.
3370 const TypeInt* ConnectionGraph::optimize_ptr_compare(Node* left, Node* right) {
3371 const TypeInt* UNKNOWN = TypeInt::CC; // [-1, 0,1]
3372 if (!OptimizePtrCompare) {
3373 return UNKNOWN;
3374 }
3375 const TypeInt* EQ = TypeInt::CC_EQ; // [0] == ZERO
3376 const TypeInt* NE = TypeInt::CC_GT; // [1] == ONE
3377
3378 PointsToNode* ptn1 = ptnode_adr(left->_idx);
3379 PointsToNode* ptn2 = ptnode_adr(right->_idx);
3380 JavaObjectNode* jobj1 = unique_java_object(left);
3381 JavaObjectNode* jobj2 = unique_java_object(right);
3382
3383 // The use of this method during allocation merge reduction may cause 'left'
3384 // or 'right' be something (e.g., a Phi) that isn't in the connection graph or
3385 // that doesn't reference an unique java object.
3386 if (ptn1 == nullptr || ptn2 == nullptr ||
3387 jobj1 == nullptr || jobj2 == nullptr) {
3388 return UNKNOWN;
3508 assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
3509 assert((src != null_obj) && (dst != null_obj), "not for ConP null");
3510 PointsToNode* ptadr = _nodes.at(n->_idx);
3511 if (ptadr != nullptr) {
3512 assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
3513 return;
3514 }
3515 Compile* C = _compile;
3516 ptadr = new (C->comp_arena()) ArraycopyNode(this, n, es);
3517 map_ideal_node(n, ptadr);
3518 // Add edge from arraycopy node to source object.
3519 (void)add_edge(ptadr, src);
3520 src->set_arraycopy_src();
3521 // Add edge from destination object to arraycopy node.
3522 (void)add_edge(dst, ptadr);
3523 dst->set_arraycopy_dst();
3524 }
3525
3526 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
3527 const Type* adr_type = n->as_AddP()->bottom_type();
3528 BasicType bt = T_INT;
3529 if (offset == Type::OffsetBot) {
3530 // Check only oop fields.
3531 if (!adr_type->isa_aryptr() ||
3532 adr_type->isa_aryptr()->elem() == Type::BOTTOM ||
3533 adr_type->isa_aryptr()->elem()->make_oopptr() != nullptr) {
3534 // OffsetBot is used to reference array's element. Ignore first AddP.
3535 if (find_second_addp(n, n->in(AddPNode::Base)) == nullptr) {
3536 bt = T_OBJECT;
3537 }
3538 }
3539 } else if (offset != oopDesc::klass_offset_in_bytes()) {
3540 if (adr_type->isa_instptr()) {
3541 ciField* field = _compile->alias_type(adr_type->isa_instptr())->field();
3542 if (field != nullptr) {
3543 bt = field->layout_type();
3544 } else {
3545 // Check for unsafe oop field access
3546 if (has_oop_node_outs(n)) {
3547 bt = T_OBJECT;
3548 (*unsafe) = true;
3549 }
3550 }
3551 } else if (adr_type->isa_aryptr()) {
3552 if (offset == arrayOopDesc::length_offset_in_bytes()) {
3553 // Ignore array length load.
3554 } else if (find_second_addp(n, n->in(AddPNode::Base)) != nullptr) {
3555 // Ignore first AddP.
3556 } else {
3557 const Type* elemtype = adr_type->isa_aryptr()->elem();
3558 bt = elemtype->array_element_basic_type();
3559 }
3560 } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
3561 // Allocation initialization, ThreadLocal field access, unsafe access
3562 if (has_oop_node_outs(n)) {
3563 bt = T_OBJECT;
3564 }
3565 }
3566 }
3567 // Note: T_NARROWOOP is not classed as a real reference type
3568 bool res = (is_reference_type(bt) || bt == T_NARROWOOP);
3569 assert(!has_oop_node_outs(n) || res, "sanity: AddP has oop outs, needs to be treated as oop field");
3570 return res;
3571 }
3572
3573 bool ConnectionGraph::has_oop_node_outs(Node* n) {
3574 return n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3575 n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3576 n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3577 BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n);
3578 }
3741 return true;
3742 }
3743 }
3744 }
3745 }
3746 }
3747 return false;
3748 }
3749
3750 int ConnectionGraph::address_offset(Node* adr, PhaseValues* phase) {
3751 const Type *adr_type = phase->type(adr);
3752 if (adr->is_AddP() && adr_type->isa_oopptr() == nullptr && is_captured_store_address(adr)) {
3753 // We are computing a raw address for a store captured by an Initialize
3754 // compute an appropriate address type. AddP cases #3 and #5 (see below).
3755 int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
3756 assert(offs != Type::OffsetBot ||
3757 adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
3758 "offset must be a constant or it is initialization of array");
3759 return offs;
3760 }
3761 const TypePtr *t_ptr = adr_type->isa_ptr();
3762 assert(t_ptr != nullptr, "must be a pointer type");
3763 return t_ptr->offset();
3764 }
3765
3766 Node* ConnectionGraph::get_addp_base(Node *addp) {
3767 assert(addp->is_AddP(), "must be AddP");
3768 //
3769 // AddP cases for Base and Address inputs:
3770 // case #1. Direct object's field reference:
3771 // Allocate
3772 // |
3773 // Proj #5 ( oop result )
3774 // |
3775 // CheckCastPP (cast to instance type)
3776 // | |
3777 // AddP ( base == address )
3778 //
3779 // case #2. Indirect object's field reference:
3780 // Phi
3781 // |
3782 // CastPP (cast to instance type)
3783 // | |
3784 // AddP ( base == address )
3785 //
3786 // case #3. Raw object's field reference for Initialize node:
3787 // Allocate
3788 // |
3789 // Proj #5 ( oop result )
3790 // top |
3791 // \ |
3792 // AddP ( base == top )
3793 //
3794 // case #4. Array's element reference:
3795 // {CheckCastPP | CastPP}
3796 // | | |
3797 // | AddP ( array's element offset )
3798 // | |
3799 // AddP ( array's offset )
3800 //
3801 // case #5. Raw object's field reference for arraycopy stub call:
3802 // The inline_native_clone() case when the arraycopy stub is called
3803 // after the allocation before Initialize and CheckCastPP nodes.
3804 // Allocate
3805 // |
3806 // Proj #5 ( oop result )
3817 // case #7. Klass's field reference.
3818 // LoadKlass
3819 // | |
3820 // AddP ( base == address )
3821 //
3822 // case #8. narrow Klass's field reference.
3823 // LoadNKlass
3824 // |
3825 // DecodeN
3826 // | |
3827 // AddP ( base == address )
3828 //
3829 // case #9. Mixed unsafe access
3830 // {instance}
3831 // |
3832 // CheckCastPP (raw)
3833 // top |
3834 // \ |
3835 // AddP ( base == top )
3836 //
3837 Node *base = addp->in(AddPNode::Base);
3838 if (base->uncast()->is_top()) { // The AddP case #3 and #6 and #9.
3839 base = addp->in(AddPNode::Address);
3840 while (base->is_AddP()) {
3841 // Case #6 (unsafe access) may have several chained AddP nodes.
3842 assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
3843 base = base->in(AddPNode::Address);
3844 }
3845 if (base->Opcode() == Op_CheckCastPP &&
3846 base->bottom_type()->isa_rawptr() &&
3847 _igvn->type(base->in(1))->isa_oopptr()) {
3848 base = base->in(1); // Case #9
3849 } else {
3850 Node* uncast_base = base->uncast();
3851 int opcode = uncast_base->Opcode();
3852 assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
3853 opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() ||
3854 (_igvn->C->is_osr_compilation() && uncast_base->is_Parm() && uncast_base->as_Parm()->_con == TypeFunc::Parms)||
3855 (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_rawptr() != nullptr)) ||
3856 (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_klassptr() != nullptr)) ||
3857 is_captured_store_address(addp), "sanity");
3858 }
3859 }
3860 return base;
3861 }
3862
3863 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
3864 assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
3865 Node* addp2 = addp->raw_out(0);
3866 if (addp->outcnt() == 1 && addp2->is_AddP() &&
3867 addp2->in(AddPNode::Base) == n &&
3868 addp2->in(AddPNode::Address) == addp) {
3869 assert(addp->in(AddPNode::Base) == n, "expecting the same base");
3870 //
3871 // Find array's offset to push it on worklist first and
3872 // as result process an array's element offset first (pushed second)
3873 // to avoid CastPP for the array's offset.
3874 // Otherwise the inserted CastPP (LocalVar) will point to what
3875 // the AddP (Field) points to. Which would be wrong since
3876 // the algorithm expects the CastPP has the same point as
3877 // as AddP's base CheckCastPP (LocalVar).
3878 //
3879 // ArrayAllocation
3880 // |
3881 // CheckCastPP
3882 // |
3899 }
3900 return nullptr;
3901 }
3902
3903 //
3904 // Adjust the type and inputs of an AddP which computes the
3905 // address of a field of an instance
3906 //
3907 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
3908 PhaseGVN* igvn = _igvn;
3909 const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
3910 assert(base_t != nullptr && base_t->is_known_instance(), "expecting instance oopptr");
3911 const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
3912 if (t == nullptr) {
3913 // We are computing a raw address for a store captured by an Initialize
3914 // compute an appropriate address type (cases #3 and #5).
3915 assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
3916 assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
3917 intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
3918 assert(offs != Type::OffsetBot, "offset must be a constant");
3919 t = base_t->add_offset(offs)->is_oopptr();
3920 }
3921 int inst_id = base_t->instance_id();
3922 assert(!t->is_known_instance() || t->instance_id() == inst_id,
3923 "old type must be non-instance or match new type");
3924
3925 // The type 't' could be subclass of 'base_t'.
3926 // As result t->offset() could be large then base_t's size and it will
3927 // cause the failure in add_offset() with narrow oops since TypeOopPtr()
3928 // constructor verifies correctness of the offset.
3929 //
3930 // It could happened on subclass's branch (from the type profiling
3931 // inlining) which was not eliminated during parsing since the exactness
3932 // of the allocation type was not propagated to the subclass type check.
3933 //
3934 // Or the type 't' could be not related to 'base_t' at all.
3935 // It could happened when CHA type is different from MDO type on a dead path
3936 // (for example, from instanceof check) which is not collapsed during parsing.
3937 //
3938 // Do nothing for such AddP node and don't process its users since
3939 // this code branch will go away.
3940 //
3941 if (!t->is_known_instance() &&
3942 !base_t->maybe_java_subtype_of(t)) {
3943 return false; // bail out
3944 }
3945 const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();
3946 // Do NOT remove the next line: ensure a new alias index is allocated
3947 // for the instance type. Note: C++ will not remove it since the call
3948 // has side effect.
3949 int alias_idx = _compile->get_alias_index(tinst);
3950 igvn->set_type(addp, tinst);
3951 // record the allocation in the node map
3952 set_map(addp, get_map(base->_idx));
3953 // Set addp's Base and Address to 'base'.
3954 Node *abase = addp->in(AddPNode::Base);
3955 Node *adr = addp->in(AddPNode::Address);
3956 if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
3957 adr->in(0)->_idx == (uint)inst_id) {
3958 // Skip AddP cases #3 and #5.
3959 } else {
3960 assert(!abase->is_top(), "sanity"); // AddP case #3
3961 if (abase != base) {
3962 igvn->hash_delete(addp);
3963 addp->set_req(AddPNode::Base, base);
3964 if (abase == adr) {
3965 addp->set_req(AddPNode::Address, base);
4249 } else if (C->get_alias_index(result->adr_type()) != alias_idx) {
4250 assert(C->get_general_index(alias_idx) == C->get_alias_index(result->adr_type()), "should be projection for the same field/array element");
4251 result = get_map(result->_idx);
4252 assert(result != nullptr, "new projection should have been allocated");
4253 break;
4254 }
4255 } else if (proj_in->is_MemBar()) {
4256 // Check if there is an array copy for a clone
4257 // Step over GC barrier when ReduceInitialCardMarks is disabled
4258 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4259 Node* control_proj_ac = bs->step_over_gc_barrier(proj_in->in(0));
4260
4261 if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) {
4262 // Stop if it is a clone
4263 ArrayCopyNode* ac = control_proj_ac->in(0)->as_ArrayCopy();
4264 if (ac->may_modify(toop, igvn)) {
4265 break;
4266 }
4267 }
4268 result = proj_in->in(TypeFunc::Memory);
4269 }
4270 } else if (result->is_MergeMem()) {
4271 MergeMemNode *mmem = result->as_MergeMem();
4272 result = step_through_mergemem(mmem, alias_idx, toop);
4273 if (result == mmem->base_memory()) {
4274 // Didn't find instance memory, search through general slice recursively.
4275 result = mmem->memory_at(C->get_general_index(alias_idx));
4276 result = find_inst_mem(result, alias_idx, orig_phis, rec_depth + 1);
4277 if (C->failing()) {
4278 return nullptr;
4279 }
4280 mmem->set_memory_at(alias_idx, result);
4281 }
4282 } else if (result->is_Phi() &&
4283 C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
4284 Node *un = result->as_Phi()->unique_input(igvn);
4285 if (un != nullptr) {
4286 orig_phis.push(result);
4287 result = un;
4288 } else {
4534 // - not determined to be ineligible by escape analysis
4535 set_map(alloc, n);
4536 set_map(n, alloc);
4537 const TypeOopPtr* tinst = t->cast_to_instance_id(ni);
4538 igvn->hash_delete(n);
4539 igvn->set_type(n, tinst);
4540 n->raise_bottom_type(tinst);
4541 igvn->hash_insert(n);
4542 record_for_optimizer(n);
4543 // Allocate an alias index for the header fields. Accesses to
4544 // the header emitted during macro expansion wouldn't have
4545 // correct memory state otherwise.
4546 _compile->get_alias_index(tinst->add_offset(oopDesc::mark_offset_in_bytes()));
4547 _compile->get_alias_index(tinst->add_offset(oopDesc::klass_offset_in_bytes()));
4548 if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
4549 // Add a new NarrowMem projection for each existing NarrowMem projection with new adr type
4550 InitializeNode* init = alloc->as_Allocate()->initialization();
4551 assert(init != nullptr, "can't find Initialization node for this Allocate node");
4552 auto process_narrow_proj = [&](NarrowMemProjNode* proj) {
4553 const TypePtr* adr_type = proj->adr_type();
4554 const TypePtr* new_adr_type = tinst->add_offset(adr_type->offset());
4555 if (adr_type != new_adr_type && !init->already_has_narrow_mem_proj_with_adr_type(new_adr_type)) {
4556 // Do NOT remove the next line: ensure a new alias index is allocated for the instance type.
4557 uint alias_idx = _compile->get_alias_index(new_adr_type);
4558 assert(_compile->get_general_index(alias_idx) == _compile->get_alias_index(adr_type), "new adr type should be narrowed down from existing adr type");
4559 NarrowMemProjNode* new_proj = new NarrowMemProjNode(init, new_adr_type);
4560 igvn->set_type(new_proj, new_proj->bottom_type());
4561 record_for_optimizer(new_proj);
4562 set_map(proj, new_proj); // record it so ConnectionGraph::find_inst_mem() can find it
4563 }
4564 };
4565 init->for_each_narrow_mem_proj_with_new_uses(process_narrow_proj);
4566
4567 // First, put on the worklist all Field edges from Connection Graph
4568 // which is more accurate than putting immediate users from Ideal Graph.
4569 for (EdgeIterator e(ptn); e.has_next(); e.next()) {
4570 PointsToNode* tgt = e.get();
4571 if (tgt->is_Arraycopy()) {
4572 continue;
4573 }
4574 Node* use = tgt->ideal_node();
4652 ptnode_adr(n->_idx)->dump();
4653 assert(jobj != nullptr && jobj != phantom_obj, "escaped allocation");
4654 #endif
4655 _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4656 return;
4657 } else {
4658 Node *val = get_map(jobj->idx()); // CheckCastPP node
4659 TypeNode *tn = n->as_Type();
4660 const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
4661 assert(tinst != nullptr && tinst->is_known_instance() &&
4662 tinst->instance_id() == jobj->idx() , "instance type expected.");
4663
4664 const Type *tn_type = igvn->type(tn);
4665 const TypeOopPtr *tn_t;
4666 if (tn_type->isa_narrowoop()) {
4667 tn_t = tn_type->make_ptr()->isa_oopptr();
4668 } else {
4669 tn_t = tn_type->isa_oopptr();
4670 }
4671 if (tn_t != nullptr && tinst->maybe_java_subtype_of(tn_t)) {
4672 if (tn_type->isa_narrowoop()) {
4673 tn_type = tinst->make_narrowoop();
4674 } else {
4675 tn_type = tinst;
4676 }
4677 igvn->hash_delete(tn);
4678 igvn->set_type(tn, tn_type);
4679 tn->set_type(tn_type);
4680 igvn->hash_insert(tn);
4681 record_for_optimizer(n);
4682 } else {
4683 assert(tn_type == TypePtr::NULL_PTR ||
4684 (tn_t != nullptr && !tinst->maybe_java_subtype_of(tn_t)),
4685 "unexpected type");
4686 continue; // Skip dead path with different type
4687 }
4688 }
4689 } else {
4690 DEBUG_ONLY(n->dump();)
4691 assert(false, "EA: unexpected node");
4692 continue;
4693 }
4694 // push allocation's users on appropriate worklist
4695 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4696 Node *use = n->fast_out(i);
4697 if(use->is_Mem() && use->in(MemNode::Address) == n) {
4698 // Load/store to instance's field
4699 memnode_worklist.push(use);
4700 } else if (use->is_MemBar()) {
4701 if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4702 memnode_worklist.push(use);
4703 }
4704 } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
4705 Node* addp2 = find_second_addp(use, n);
4706 if (addp2 != nullptr) {
4707 alloc_worklist.append_if_missing(addp2);
4708 }
4709 alloc_worklist.append_if_missing(use);
4710 } else if (use->is_Phi() ||
4711 use->is_CheckCastPP() ||
4712 use->is_EncodeNarrowPtr() ||
4713 use->is_DecodeNarrowPtr() ||
4714 (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
4715 alloc_worklist.append_if_missing(use);
4716 #ifdef ASSERT
4717 } else if (use->is_Mem()) {
4718 assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
4719 } else if (use->is_MergeMem()) {
4720 assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4721 } else if (use->is_SafePoint()) {
4722 // Look for MergeMem nodes for calls which reference unique allocation
4723 // (through CheckCastPP nodes) even for debug info.
4724 Node* m = use->in(TypeFunc::Memory);
4725 if (m->is_MergeMem()) {
4726 assert(mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4727 }
4728 } else if (use->Opcode() == Op_EncodeISOArray) {
4729 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4730 // EncodeISOArray overwrites destination array
4731 memnode_worklist.push(use);
4732 }
4733 } else {
4734 uint op = use->Opcode();
4735 if ((op == Op_StrCompressedCopy || op == Op_StrInflatedCopy) &&
4736 (use->in(MemNode::Memory) == n)) {
4737 // They overwrite memory edge corresponding to destination array,
4738 memnode_worklist.push(use);
4739 } else if (!(op == Op_CmpP || op == Op_Conv2B ||
4740 op == Op_CastP2X ||
4741 op == Op_FastLock || op == Op_AryEq ||
4742 op == Op_StrComp || op == Op_CountPositives ||
4743 op == Op_StrCompressedCopy || op == Op_StrInflatedCopy ||
4744 op == Op_StrEquals || op == Op_VectorizedHashCode ||
4745 op == Op_StrIndexOf || op == Op_StrIndexOfChar ||
4746 op == Op_SubTypeCheck ||
4747 op == Op_ReinterpretS2HF ||
4748 op == Op_ReachabilityFence ||
4749 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use))) {
4750 n->dump();
4751 use->dump();
4752 assert(false, "EA: missing allocation reference path");
4753 }
4754 #endif
4755 }
4756 }
4757
4758 }
4759
4760 #ifdef ASSERT
4761 if (VerifyReduceAllocationMerges) {
4762 for (uint i = 0; i < reducible_merges.size(); i++) {
4763 Node* phi = reducible_merges.at(i);
4764
4765 if (!reduced_merges.member(phi)) {
4766 phi->dump(2);
4842 n = n->as_MemBar()->proj_out_or_null(TypeFunc::Memory);
4843 if (n == nullptr) {
4844 continue;
4845 }
4846 }
4847 } else if (n->is_CallLeaf()) {
4848 // Runtime calls with narrow memory input (no MergeMem node)
4849 // get the memory projection
4850 n = n->as_Call()->proj_out_or_null(TypeFunc::Memory);
4851 if (n == nullptr) {
4852 continue;
4853 }
4854 } else if (n->Opcode() == Op_StrInflatedCopy) {
4855 // Check direct uses of StrInflatedCopy.
4856 // It is memory type Node - no special SCMemProj node.
4857 } else if (n->Opcode() == Op_StrCompressedCopy ||
4858 n->Opcode() == Op_EncodeISOArray) {
4859 // get the memory projection
4860 n = n->find_out_with(Op_SCMemProj);
4861 assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
4862 } else if (n->is_Proj()) {
4863 assert(n->in(0)->is_Initialize(), "we only push memory projections for Initialize");
4864 } else {
4865 #ifdef ASSERT
4866 if (!n->is_Mem()) {
4867 n->dump();
4868 }
4869 assert(n->is_Mem(), "memory node required.");
4870 #endif
4871 Node *addr = n->in(MemNode::Address);
4872 const Type *addr_t = igvn->type(addr);
4873 if (addr_t == Type::TOP) {
4874 continue;
4875 }
4876 assert (addr_t->isa_ptr() != nullptr, "pointer type required.");
4877 int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
4878 assert ((uint)alias_idx < new_index_end, "wrong alias index");
4879 Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
4880 if (_compile->failing()) {
4881 return;
4893 assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
4894 }
4895 }
4896 // push user on appropriate worklist
4897 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4898 Node *use = n->fast_out(i);
4899 if (use->is_Phi() || use->is_ClearArray()) {
4900 memnode_worklist.push(use);
4901 } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
4902 memnode_worklist.push(use);
4903 } else if (use->is_MemBar() || use->is_CallLeaf()) {
4904 if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4905 memnode_worklist.push(use);
4906 }
4907 } else if (use->is_Proj()) {
4908 assert(n->is_Initialize(), "We only push projections of Initialize");
4909 if (use->as_Proj()->_con == TypeFunc::Memory) { // Ignore precedent edge
4910 memnode_worklist.push(use);
4911 }
4912 #ifdef ASSERT
4913 } else if(use->is_Mem()) {
4914 assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
4915 } else if (use->is_MergeMem()) {
4916 assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4917 } else if (use->Opcode() == Op_EncodeISOArray) {
4918 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4919 // EncodeISOArray overwrites destination array
4920 memnode_worklist.push(use);
4921 }
4922 } else {
4923 uint op = use->Opcode();
4924 if ((use->in(MemNode::Memory) == n) &&
4925 (op == Op_StrCompressedCopy || op == Op_StrInflatedCopy)) {
4926 // They overwrite memory edge corresponding to destination array,
4927 memnode_worklist.push(use);
4928 } else if (!(BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use) ||
4929 op == Op_AryEq || op == Op_StrComp || op == Op_CountPositives ||
4930 op == Op_StrCompressedCopy || op == Op_StrInflatedCopy || op == Op_VectorizedHashCode ||
4931 op == Op_StrEquals || op == Op_StrIndexOf || op == Op_StrIndexOfChar)) {
4932 n->dump();
4933 use->dump();
4934 assert(false, "EA: missing memory path");
4935 }
4936 #endif
4937 }
4938 }
4939 }
4940
4941 // Phase 3: Process MergeMem nodes from mergemem_worklist.
4942 // Walk each memory slice moving the first node encountered of each
4943 // instance type to the input corresponding to its alias index.
4944 uint length = mergemem_worklist.length();
4945 for( uint next = 0; next < length; ++next ) {
4946 MergeMemNode* nmm = mergemem_worklist.at(next);
4947 assert(!visited.test_set(nmm->_idx), "should not be visited before");
4948 // Note: we don't want to use MergeMemStream here because we only want to
4949 // scan inputs which exist at the start, not ones we add during processing.
4950 // Note 2: MergeMem may already contains instance memory slices added
4951 // during find_inst_mem() call when memory nodes were processed above.
5014 _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
5015 } else if (_invocation > 0) {
5016 _compile->record_failure(C2Compiler::retry_no_iterative_escape_analysis());
5017 } else {
5018 _compile->record_failure(C2Compiler::retry_no_escape_analysis());
5019 }
5020 return;
5021 }
5022
5023 igvn->hash_insert(nmm);
5024 record_for_optimizer(nmm);
5025 }
5026
5027 _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_3, 5);
5028
5029 // Phase 4: Update the inputs of non-instance memory Phis and
5030 // the Memory input of memnodes
5031 // First update the inputs of any non-instance Phi's from
5032 // which we split out an instance Phi. Note we don't have
5033 // to recursively process Phi's encountered on the input memory
5034 // chains as is done in split_memory_phi() since they will
5035 // also be processed here.
5036 for (uint j = 0; j < orig_phis.size(); j++) {
5037 PhiNode* phi = orig_phis.at(j)->as_Phi();
5038 int alias_idx = _compile->get_alias_index(phi->adr_type());
5039 igvn->hash_delete(phi);
5040 for (uint i = 1; i < phi->req(); i++) {
5041 Node *mem = phi->in(i);
5042 Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
5043 if (_compile->failing()) {
5044 return;
5045 }
5046 if (mem != new_mem) {
5047 phi->set_req(i, new_mem);
5048 }
5049 }
5050 igvn->hash_insert(phi);
5051 record_for_optimizer(phi);
5052 }
5053
5054 // 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 = AddPNode::make_with_base(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 }
1328 // (2) A selector, used to decide if we need to rematerialize an object
1329 // or use the pointer to a NSR object.
1330 // See more details of these fields in the declaration of SafePointScalarMergeNode.
1331 // It is safe to include them into debug info straight away since create_scalarized_object_description()
1332 // will include all newly added inputs into debug info anyway.
1333 sfpt->add_req(nsr_merge_pointer);
1334 sfpt->add_req(selector);
1335 sfpt->jvms()->set_endoff(sfpt->req());
1336
1337 for (uint i = 1; i < ophi->req(); i++) {
1338 Node* base = ophi->in(i);
1339 JavaObjectNode* ptn = unique_java_object(base);
1340
1341 // If the base is not scalar replaceable we don't need to register information about
1342 // it at this time.
1343 if (ptn == nullptr || !ptn->scalar_replaceable()) {
1344 continue;
1345 }
1346
1347 AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
1348 Unique_Node_List value_worklist;
1349 #ifdef ASSERT
1350 const Type* res_type = alloc->result_cast()->bottom_type();
1351 if (res_type->is_inlinetypeptr() && !Compile::current()->has_circular_inline_type()) {
1352 assert(!ophi->as_Phi()->can_push_inline_types_down(_igvn), "missed earlier scalarization opportunity");
1353 }
1354 #endif
1355 SafePointScalarObjectNode* sobj = mexp.create_scalarized_object_description(alloc, sfpt, &value_worklist);
1356 if (sobj == nullptr) {
1357 _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
1358 sfpt->restore_non_debug_edges(non_debug_edges_worklist);
1359 return false; // non-recoverable failure; recompile
1360 }
1361
1362 // Now make a pass over the debug information replacing any references
1363 // to the allocated object with "sobj"
1364 Node* ccpp = alloc->result_cast();
1365 sfpt->replace_edges_in_range(ccpp, sobj, debug_start, jvms->debug_end(), _igvn);
1366 non_debug_edges_worklist.remove_edge_if_present(ccpp); // drop scalarized input from non-debug info
1367
1368 // Register the scalarized object as a candidate for reallocation
1369 smerge->add_req(sobj);
1370
1371 // Scalarize inline types that were added to the safepoint.
1372 // Don't allow linking a constant oop (if available) for flat array elements
1373 // because Deoptimization::reassign_flat_array_elements needs field values.
1374 const bool allow_oop = !merge_t->is_flat();
1375 for (uint j = 0; j < value_worklist.size(); ++j) {
1376 InlineTypeNode* vt = value_worklist.at(j)->as_InlineType();
1377 vt->make_scalar_in_safepoints(_igvn, allow_oop);
1378 }
1379 }
1380
1381 // Replaces debug information references to "original_sfpt_parent" in "sfpt" with references to "smerge"
1382 sfpt->replace_edges_in_range(original_sfpt_parent, smerge, debug_start, jvms->debug_end(), _igvn);
1383 non_debug_edges_worklist.remove_edge_if_present(original_sfpt_parent); // drop scalarized input from non-debug info
1384
1385 // The call to 'replace_edges_in_range' above might have removed the
1386 // reference to ophi that we need at _merge_pointer_idx. The line below make
1387 // sure the reference is maintained.
1388 sfpt->set_req(smerge->merge_pointer_idx(jvms), nsr_merge_pointer);
1389
1390 sfpt->restore_non_debug_edges(non_debug_edges_worklist);
1391
1392 _igvn->_worklist.push(sfpt);
1393 }
1394
1395 return true;
1396 }
1397
1398 void ConnectionGraph::reduce_phi(PhiNode* ophi, GrowableArray<Node*> &alloc_worklist) {
1565 return false;
1566 }
1567
1568 // Returns true if at least one of the arguments to the call is an object
1569 // that does not escape globally.
1570 bool ConnectionGraph::has_arg_escape(CallJavaNode* call) {
1571 if (call->method() != nullptr) {
1572 uint max_idx = TypeFunc::Parms + call->method()->arg_size();
1573 for (uint idx = TypeFunc::Parms; idx < max_idx; idx++) {
1574 Node* p = call->in(idx);
1575 if (not_global_escape(p)) {
1576 return true;
1577 }
1578 }
1579 } else {
1580 const char* name = call->as_CallStaticJava()->_name;
1581 assert(name != nullptr, "no name");
1582 // no arg escapes through uncommon traps
1583 if (strcmp(name, "uncommon_trap") != 0) {
1584 // process_call_arguments() assumes that all arguments escape globally
1585 const TypeTuple* d = call->tf()->domain_sig();
1586 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1587 const Type* at = d->field_at(i);
1588 if (at->isa_oopptr() != nullptr) {
1589 return true;
1590 }
1591 }
1592 }
1593 }
1594 return false;
1595 }
1596
1597
1598
1599 // Utility function for nodes that load an object
1600 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1601 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1602 // ThreadLocal has RawPtr type.
1603 const Type* t = _igvn->type(n);
1604 if (t->make_ptr() != nullptr) {
1605 Node* adr = n->in(MemNode::Address);
1606 #ifdef ASSERT
1607 if (!adr->is_AddP()) {
1608 assert(_igvn->type(adr)->isa_rawptr(), "sanity");
1609 } else {
1610 assert((ptnode_adr(adr->_idx) == nullptr ||
1611 ptnode_adr(adr->_idx)->as_Field()->is_oop()), "sanity");
1612 }
1613 #endif
1614 add_local_var_and_edge(n, PointsToNode::NoEscape,
1615 adr, delayed_worklist);
1616 }
1617 }
1618
1619 void ConnectionGraph::add_proj(Node* n, Unique_Node_List* delayed_worklist) {
1620 if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() && n->in(0)->as_Call()->returns_pointer()) {
1621 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1622 } else if (n->in(0)->is_LoadFlat()) {
1623 // Treat LoadFlat outputs similar to a call return value
1624 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1625 } else if (n->as_Proj()->_con >= TypeFunc::Parms && n->in(0)->is_Call() && n->bottom_type()->isa_ptr()) {
1626 CallNode* call = n->in(0)->as_Call();
1627 assert(call->tf()->returns_inline_type_as_fields(), "");
1628 if (n->as_Proj()->_con == TypeFunc::Parms || !returns_an_argument(call)) {
1629 // either:
1630 // - not an argument returned
1631 // - the returned buffer for a returned scalarized argument
1632 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1633 } else {
1634 add_local_var(n, PointsToNode::NoEscape);
1635 }
1636 }
1637 }
1638
1639 // Populate Connection Graph with PointsTo nodes and create simple
1640 // connection graph edges.
1641 void ConnectionGraph::add_node_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1642 assert(!_verify, "this method should not be called for verification");
1643 PhaseGVN* igvn = _igvn;
1644 uint n_idx = n->_idx;
1645 PointsToNode* n_ptn = ptnode_adr(n_idx);
1646 if (n_ptn != nullptr) {
1647 return; // No need to redefine PointsTo node during first iteration.
1648 }
1649 int opcode = n->Opcode();
1650 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_to_con_graph(this, igvn, delayed_worklist, n, opcode);
1651 if (gc_handled) {
1652 return; // Ignore node if already handled by GC.
1653 }
1654
1655 if (n->is_Call()) {
1656 // Arguments to allocation and locking don't escape.
1657 if (n->is_AbstractLock()) {
1658 // Put Lock and Unlock nodes on IGVN worklist to process them during
1659 // first IGVN optimization when escape information is still available.
1660 record_for_optimizer(n);
1661 } else if (n->is_Allocate()) {
1662 add_call_node(n->as_Call());
1663 record_for_optimizer(n);
1664 } else {
1665 if (n->is_CallStaticJava()) {
1666 const char* name = n->as_CallStaticJava()->_name;
1667 if (name != nullptr && strcmp(name, "uncommon_trap") == 0) {
1668 return; // Skip uncommon traps
1669 }
1670 }
1671 // Don't mark as processed since call's arguments have to be processed.
1672 delayed_worklist->push(n);
1673 // Check if a call returns an object.
1674 if ((n->as_Call()->returns_pointer() &&
1675 n->as_Call()->proj_out_or_null(TypeFunc::Parms) != nullptr) ||
1676 (n->is_CallStaticJava() &&
1677 n->as_CallStaticJava()->is_boxing_method())) {
1678 add_call_node(n->as_Call());
1679 } else if (n->as_Call()->tf()->returns_inline_type_as_fields()) {
1680 bool returns_oop = false;
1681 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && !returns_oop; i++) {
1682 ProjNode* pn = n->fast_out(i)->as_Proj();
1683 if (pn->_con >= TypeFunc::Parms && pn->bottom_type()->isa_ptr()) {
1684 returns_oop = true;
1685 }
1686 }
1687 if (returns_oop) {
1688 add_call_node(n->as_Call());
1689 }
1690 }
1691 }
1692 return;
1693 }
1694 // Put this check here to process call arguments since some call nodes
1695 // point to phantom_obj.
1696 if (n_ptn == phantom_obj || n_ptn == null_obj) {
1697 return; // Skip predefined nodes.
1698 }
1699 switch (opcode) {
1700 case Op_AddP: {
1701 Node* base = get_addp_base(n);
1702 PointsToNode* ptn_base = ptnode_adr(base->_idx);
1703 // Field nodes are created for all field types. They are used in
1704 // adjust_scalar_replaceable_state() and split_unique_types().
1705 // Note, non-oop fields will have only base edges in Connection
1706 // Graph because such fields are not used for oop loads and stores.
1707 int offset = address_offset(n, igvn);
1708 add_field(n, PointsToNode::NoEscape, offset);
1709 if (ptn_base == nullptr) {
1710 delayed_worklist->push(n); // Process it later.
1711 } else {
1712 n_ptn = ptnode_adr(n_idx);
1713 add_base(n_ptn->as_Field(), ptn_base);
1714 }
1715 break;
1716 }
1717 case Op_CastX2P:
1718 case Op_CastI2N: {
1719 map_ideal_node(n, phantom_obj);
1720 break;
1721 }
1722 case Op_InlineType:
1723 case Op_CastPP:
1724 case Op_CheckCastPP:
1725 case Op_EncodeP:
1726 case Op_DecodeN:
1727 case Op_EncodePKlass:
1728 case Op_DecodeNKlass: {
1729 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1730 break;
1731 }
1732 case Op_CMoveP: {
1733 add_local_var(n, PointsToNode::NoEscape);
1734 // Do not add edges during first iteration because some could be
1735 // not defined yet.
1736 delayed_worklist->push(n);
1737 break;
1738 }
1739 case Op_ConP:
1740 case Op_ConN:
1741 case Op_ConNKlass: {
1742 // assume all oop constants globally escape except for null
1772 break;
1773 }
1774 case Op_PartialSubtypeCheck: {
1775 // Produces Null or notNull and is used in only in CmpP so
1776 // phantom_obj could be used.
1777 map_ideal_node(n, phantom_obj); // Result is unknown
1778 break;
1779 }
1780 case Op_Phi: {
1781 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1782 // ThreadLocal has RawPtr type.
1783 const Type* t = n->as_Phi()->type();
1784 if (t->make_ptr() != nullptr) {
1785 add_local_var(n, PointsToNode::NoEscape);
1786 // Do not add edges during first iteration because some could be
1787 // not defined yet.
1788 delayed_worklist->push(n);
1789 }
1790 break;
1791 }
1792 case Op_LoadFlat:
1793 // Treat LoadFlat similar to an unknown call that receives nothing and produces its results
1794 map_ideal_node(n, phantom_obj);
1795 break;
1796 case Op_StoreFlat:
1797 // Treat StoreFlat similar to a call that escapes the stored flattened fields
1798 delayed_worklist->push(n);
1799 break;
1800 case Op_Proj: {
1801 // we are only interested in the oop result projection from a call
1802 add_proj(n, delayed_worklist);
1803 break;
1804 }
1805 case Op_Rethrow: // Exception object escapes
1806 case Op_Return: {
1807 if (n->req() > TypeFunc::Parms &&
1808 igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
1809 // Treat Return value as LocalVar with GlobalEscape escape state.
1810 add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), delayed_worklist);
1811 }
1812 break;
1813 }
1814 case Op_CompareAndExchangeP:
1815 case Op_CompareAndExchangeN:
1816 case Op_GetAndSetP:
1817 case Op_GetAndSetN: {
1818 add_objload_to_connection_graph(n, delayed_worklist);
1819 // fall-through
1820 }
1821 case Op_StoreP:
1822 case Op_StoreN:
1866 break;
1867 }
1868 default:
1869 ; // Do nothing for nodes not related to EA.
1870 }
1871 return;
1872 }
1873
1874 // Add final simple edges to graph.
1875 void ConnectionGraph::add_final_edges(Node *n) {
1876 PointsToNode* n_ptn = ptnode_adr(n->_idx);
1877 #ifdef ASSERT
1878 if (_verify && n_ptn->is_JavaObject())
1879 return; // This method does not change graph for JavaObject.
1880 #endif
1881
1882 if (n->is_Call()) {
1883 process_call_arguments(n->as_Call());
1884 return;
1885 }
1886 assert(n->is_Store() || n->is_LoadStore() || n->is_StoreFlat() ||
1887 ((n_ptn != nullptr) && (n_ptn->ideal_node() != nullptr)),
1888 "node should be registered already");
1889 int opcode = n->Opcode();
1890 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_final_edges(this, _igvn, n, opcode);
1891 if (gc_handled) {
1892 return; // Ignore node if already handled by GC.
1893 }
1894 switch (opcode) {
1895 case Op_AddP: {
1896 Node* base = get_addp_base(n);
1897 PointsToNode* ptn_base = ptnode_adr(base->_idx);
1898 assert(ptn_base != nullptr, "field's base should be registered");
1899 add_base(n_ptn->as_Field(), ptn_base);
1900 break;
1901 }
1902 case Op_InlineType:
1903 case Op_CastPP:
1904 case Op_CheckCastPP:
1905 case Op_EncodeP:
1906 case Op_DecodeN:
1907 case Op_EncodePKlass:
1908 case Op_DecodeNKlass: {
1909 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), nullptr);
1910 break;
1911 }
1912 case Op_CMoveP: {
1913 for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
1914 Node* in = n->in(i);
1915 if (in == nullptr) {
1916 continue; // ignore null
1917 }
1918 Node* uncast_in = in->uncast();
1919 if (uncast_in->is_top() || uncast_in == n) {
1920 continue; // ignore top or inputs which go back this node
1921 }
1922 PointsToNode* ptn = ptnode_adr(in->_idx);
1935 }
1936 case Op_Phi: {
1937 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1938 // ThreadLocal has RawPtr type.
1939 assert(n->as_Phi()->type()->make_ptr() != nullptr, "Unexpected node type");
1940 for (uint i = 1; i < n->req(); i++) {
1941 Node* in = n->in(i);
1942 if (in == nullptr) {
1943 continue; // ignore null
1944 }
1945 Node* uncast_in = in->uncast();
1946 if (uncast_in->is_top() || uncast_in == n) {
1947 continue; // ignore top or inputs which go back this node
1948 }
1949 PointsToNode* ptn = ptnode_adr(in->_idx);
1950 assert(ptn != nullptr, "node should be registered");
1951 add_edge(n_ptn, ptn);
1952 }
1953 break;
1954 }
1955 case Op_StoreFlat: {
1956 // StoreFlat globally escapes its stored flattened fields
1957 InlineTypeNode* value = n->as_StoreFlat()->value();
1958 ciInlineKlass* vk = _igvn->type(value)->inline_klass();
1959 for (int i = 0; i < vk->nof_nonstatic_fields(); i++) {
1960 ciField* field = vk->nonstatic_field_at(i);
1961 if (field->type()->is_primitive_type()) {
1962 continue;
1963 }
1964
1965 Node* field_value = value->field_value_by_offset(field->offset_in_bytes(), true);
1966 PointsToNode* field_value_ptn = ptnode_adr(field_value->_idx);
1967 set_escape_state(field_value_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "store into a flat field"));
1968 }
1969 break;
1970 }
1971 case Op_Proj: {
1972 add_proj(n, nullptr);
1973 break;
1974 }
1975 case Op_Rethrow: // Exception object escapes
1976 case Op_Return: {
1977 assert(n->req() > TypeFunc::Parms && _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr(),
1978 "Unexpected node type");
1979 // Treat Return value as LocalVar with GlobalEscape escape state.
1980 add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), nullptr);
1981 break;
1982 }
1983 case Op_CompareAndExchangeP:
1984 case Op_CompareAndExchangeN:
1985 case Op_GetAndSetP:
1986 case Op_GetAndSetN:{
1987 assert(_igvn->type(n)->make_ptr() != nullptr, "Unexpected node type");
1988 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), nullptr);
1989 // fall-through
1990 }
1991 case Op_CompareAndSwapP:
1992 case Op_CompareAndSwapN:
2126 Node* val = n->in(MemNode::ValueIn);
2127 PointsToNode* ptn = ptnode_adr(val->_idx);
2128 assert(ptn != nullptr, "node should be registered");
2129 set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "stored at raw address"));
2130 // Add edge to object for unsafe access with offset.
2131 PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
2132 assert(adr_ptn != nullptr, "node should be registered");
2133 if (adr_ptn->is_Field()) {
2134 assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
2135 add_edge(adr_ptn, ptn);
2136 }
2137 return true;
2138 }
2139 #ifdef ASSERT
2140 n->dump(1);
2141 assert(false, "not unsafe");
2142 #endif
2143 return false;
2144 }
2145
2146 // Iterate over the domains for the scalarized and non scalarized calling conventions: Only move to the next element
2147 // in the non scalarized calling convention once all elements of the scalarized calling convention for that parameter
2148 // have been iterated over. So (ignoring hidden arguments such as the null marker) iterating over:
2149 // value class MyValue {
2150 // int f1;
2151 // float f2;
2152 // }
2153 // void m(Object o, MyValue v, int i)
2154 // produces the pairs:
2155 // (Object, Object), (Myvalue, int), (MyValue, float), (int, int)
2156 class DomainIterator : public StackObj {
2157 private:
2158 const TypeTuple* _domain;
2159 const TypeTuple* _domain_cc;
2160 const GrowableArray<SigEntry>* _sig_cc;
2161
2162 uint _i_domain;
2163 uint _i_domain_cc;
2164 int _i_sig_cc;
2165 uint _depth;
2166 uint _first_field_pos;
2167 const bool _is_static;
2168
2169 void next_helper() {
2170 if (_sig_cc == nullptr) {
2171 return;
2172 }
2173 BasicType prev_bt = _i_sig_cc > 0 ? _sig_cc->at(_i_sig_cc-1)._bt : T_ILLEGAL;
2174 BasicType prev_prev_bt = _i_sig_cc > 1 ? _sig_cc->at(_i_sig_cc-2)._bt : T_ILLEGAL;
2175 while (_i_sig_cc < _sig_cc->length()) {
2176 BasicType bt = _sig_cc->at(_i_sig_cc)._bt;
2177 assert(bt != T_VOID || _sig_cc->at(_i_sig_cc-1)._bt == prev_bt, "incorrect prev bt");
2178 if (bt == T_METADATA) {
2179 if (_depth == 0) {
2180 _first_field_pos = _i_domain_cc;
2181 }
2182 _depth++;
2183 } else if (bt == T_VOID && (prev_bt != T_LONG && prev_bt != T_DOUBLE)) {
2184 _depth--;
2185 if (_depth == 0) {
2186 _i_domain++;
2187 }
2188 } else if (bt == T_OBJECT && prev_bt == T_METADATA && (_is_static || _i_domain > 0) && _sig_cc->at(_i_sig_cc)._offset == 0) {
2189 assert(_sig_cc->at(_i_sig_cc)._vt_oop, "buffer expected right after T_METADATA");
2190 assert(_depth == 1, "only root value has buffer");
2191 _i_domain_cc++;
2192 _first_field_pos = _i_domain_cc;
2193 } else if (bt == T_BOOLEAN && prev_prev_bt == T_METADATA && (_is_static || _i_domain > 0) && _sig_cc->at(_i_sig_cc)._offset == -1) {
2194 assert(_sig_cc->at(_i_sig_cc)._null_marker, "null marker expected right after T_METADATA");
2195 assert(_depth == 1, "only root value null marker");
2196 _i_domain_cc++;
2197 _first_field_pos = _i_domain_cc;
2198 } else {
2199 return;
2200 }
2201 prev_prev_bt = prev_bt;
2202 prev_bt = bt;
2203 _i_sig_cc++;
2204 }
2205 }
2206
2207 public:
2208
2209 DomainIterator(CallJavaNode* call) :
2210 _domain(call->tf()->domain_sig()),
2211 _domain_cc(call->tf()->domain_cc()),
2212 _sig_cc(call->method()->get_sig_cc()),
2213 _i_domain(TypeFunc::Parms),
2214 _i_domain_cc(TypeFunc::Parms),
2215 _i_sig_cc(0),
2216 _depth(0),
2217 _first_field_pos(0),
2218 _is_static(call->method()->is_static()) {
2219 next_helper();
2220 }
2221
2222 bool has_next() const {
2223 assert(_sig_cc == nullptr || (_i_sig_cc < _sig_cc->length()) == (_i_domain < _domain->cnt()), "should reach end in sync");
2224 assert((_i_domain < _domain->cnt()) == (_i_domain_cc < _domain_cc->cnt()), "should reach end in sync");
2225 return _i_domain < _domain->cnt();
2226 }
2227
2228 void next() {
2229 assert(_depth != 0 || _domain->field_at(_i_domain) == _domain_cc->field_at(_i_domain_cc), "should produce same non scalarized elements");
2230 _i_sig_cc++;
2231 if (_depth == 0) {
2232 _i_domain++;
2233 }
2234 _i_domain_cc++;
2235 next_helper();
2236 }
2237
2238 uint i_domain() const {
2239 return _i_domain;
2240 }
2241
2242 uint i_domain_cc() const {
2243 return _i_domain_cc;
2244 }
2245
2246 const Type* current_domain() const {
2247 return _domain->field_at(_i_domain);
2248 }
2249
2250 const Type* current_domain_cc() const {
2251 return _domain_cc->field_at(_i_domain_cc);
2252 }
2253
2254 uint first_field_pos() const {
2255 assert(_first_field_pos >= TypeFunc::Parms, "not yet updated?");
2256 return _first_field_pos;
2257 }
2258 };
2259
2260 // Determine whether any arguments are returned.
2261 bool ConnectionGraph::returns_an_argument(CallNode* call) {
2262 ciMethod* meth = call->as_CallJava()->method();
2263 BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
2264 if (call_analyzer == nullptr) {
2265 return false;
2266 }
2267
2268 const TypeTuple* d = call->tf()->domain_sig();
2269 bool ret_arg = false;
2270 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2271 if (d->field_at(i)->isa_ptr() != nullptr &&
2272 call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
2273 if (meth->is_scalarized_arg(i - TypeFunc::Parms) && !compatible_return(call->as_CallJava(), i)) {
2274 return false;
2275 }
2276 if (call->tf()->returns_inline_type_as_fields() != meth->is_scalarized_arg(i - TypeFunc::Parms)) {
2277 return false;
2278 }
2279 ret_arg = true;
2280 }
2281 }
2282 return ret_arg;
2283 }
2284
2285 void ConnectionGraph::add_call_node(CallNode* call) {
2286 assert(call->returns_pointer() || call->tf()->returns_inline_type_as_fields(), "only for call which returns pointer");
2287 uint call_idx = call->_idx;
2288 if (call->is_Allocate()) {
2289 Node* k = call->in(AllocateNode::KlassNode);
2290 const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
2291 assert(kt != nullptr, "TypeKlassPtr required.");
2292 PointsToNode::EscapeState es = PointsToNode::NoEscape;
2293 bool scalar_replaceable = true;
2294 NOT_PRODUCT(const char* nsr_reason = "");
2295 if (call->is_AllocateArray()) {
2296 if (!kt->isa_aryklassptr()) { // StressReflectiveCode
2297 es = PointsToNode::GlobalEscape;
2298 } else {
2299 int length = call->in(AllocateNode::ALength)->find_int_con(-1);
2300 if (length < 0) {
2301 // Not scalar replaceable if the length is not constant.
2302 scalar_replaceable = false;
2303 NOT_PRODUCT(nsr_reason = "has a non-constant length");
2304 } else if (length > EliminateAllocationArraySizeLimit) {
2305 // Not scalar replaceable if the length is too big.
2306 scalar_replaceable = false;
2341 // - mapped to GlobalEscape JavaObject node if oop is returned;
2342 //
2343 // - all oop arguments are escaping globally;
2344 //
2345 // 2. CallStaticJavaNode (execute bytecode analysis if possible):
2346 //
2347 // - the same as CallDynamicJavaNode if can't do bytecode analysis;
2348 //
2349 // - mapped to GlobalEscape JavaObject node if unknown oop is returned;
2350 // - mapped to NoEscape JavaObject node if non-escaping object allocated
2351 // during call is returned;
2352 // - mapped to ArgEscape LocalVar node pointed to object arguments
2353 // which are returned and does not escape during call;
2354 //
2355 // - oop arguments escaping status is defined by bytecode analysis;
2356 //
2357 // For a static call, we know exactly what method is being called.
2358 // Use bytecode estimator to record whether the call's return value escapes.
2359 ciMethod* meth = call->as_CallJava()->method();
2360 if (meth == nullptr) {
2361 const char* name = call->as_CallStaticJava()->_name;
2362 assert(call->as_CallStaticJava()->is_call_to_multianewarray_stub() ||
2363 strncmp(name, "load_unknown_inline", 19) == 0 ||
2364 strncmp(name, "store_inline_type_fields_to_buf", 31) == 0, "TODO: add failed case check");
2365 // Returns a newly allocated non-escaped object.
2366 add_java_object(call, PointsToNode::NoEscape);
2367 set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of multinewarray"));
2368 } else if (meth->is_boxing_method()) {
2369 // Returns boxing object
2370 PointsToNode::EscapeState es;
2371 vmIntrinsics::ID intr = meth->intrinsic_id();
2372 if (intr == vmIntrinsics::_floatValue || intr == vmIntrinsics::_doubleValue) {
2373 // It does not escape if object is always allocated.
2374 es = PointsToNode::NoEscape;
2375 } else {
2376 // It escapes globally if object could be loaded from cache.
2377 es = PointsToNode::GlobalEscape;
2378 }
2379 add_java_object(call, es);
2380 if (es == PointsToNode::GlobalEscape) {
2381 set_not_scalar_replaceable(ptnode_adr(call->_idx) NOT_PRODUCT(COMMA "object can be loaded from boxing cache"));
2382 }
2383 } else {
2384 BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
2385 call_analyzer->copy_dependencies(_compile->dependencies());
2386 if (call_analyzer->is_return_allocated()) {
2387 // Returns a newly allocated non-escaped object, simply
2388 // update dependency information.
2389 // Mark it as NoEscape so that objects referenced by
2390 // it's fields will be marked as NoEscape at least.
2391 add_java_object(call, PointsToNode::NoEscape);
2392 set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of call"));
2393 } else {
2394 // For non scalarized argument/return: add_proj() adds an edge between the return projection and the call,
2395 // process_call_arguments() adds an edge between the call and the argument
2396 // For scalarized argument/return: process_call_arguments() adds an edge between a call projection for a field
2397 // and the argument input to the call for that field. An edge is added between the projection for the returned
2398 // buffer and the call.
2399 if (returns_an_argument(call) && !call->tf()->returns_inline_type_as_fields()) {
2400 // returns non scalarized argument
2401 add_local_var(call, PointsToNode::ArgEscape);
2402 } else {
2403 // Returns unknown object or scalarized argument being returned
2404 map_ideal_node(call, phantom_obj);
2405 }
2406 }
2407 }
2408 } else {
2409 // An other type of call, assume the worst case:
2410 // returned value is unknown and globally escapes.
2411 assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
2412 map_ideal_node(call, phantom_obj);
2413 }
2414 }
2415
2416 // Check that the return type is compatible with the type of the argument being returned i.e. that there's no cast that
2417 // fails in the method
2418 bool ConnectionGraph::compatible_return(CallJavaNode* call, uint k) {
2419 return call->tf()->domain_sig()->field_at(k)->is_instptr()->instance_klass() == call->tf()->range_sig()->field_at(TypeFunc::Parms)->is_instptr()->instance_klass();
2420 }
2421
2422 void ConnectionGraph::process_call_arguments(CallNode *call) {
2423 bool is_arraycopy = false;
2424 switch (call->Opcode()) {
2425 #ifdef ASSERT
2426 case Op_Allocate:
2427 case Op_AllocateArray:
2428 case Op_Lock:
2429 case Op_Unlock:
2430 assert(false, "should be done already");
2431 break;
2432 #endif
2433 case Op_ArrayCopy:
2434 case Op_CallLeafNoFP:
2435 // Most array copies are ArrayCopy nodes at this point but there
2436 // are still a few direct calls to the copy subroutines (See
2437 // PhaseStringOpts::copy_string())
2438 is_arraycopy = (call->Opcode() == Op_ArrayCopy) ||
2439 call->as_CallLeaf()->is_call_to_arraycopystub();
2440 // fall through
2441 case Op_CallLeafVector:
2442 case Op_CallLeaf: {
2443 // Stub calls, objects do not escape but they are not scale replaceable.
2444 // Adjust escape state for outgoing arguments.
2445 const TypeTuple * d = call->tf()->domain_sig();
2446 bool src_has_oops = false;
2447 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2448 const Type* at = d->field_at(i);
2449 Node *arg = call->in(i);
2450 if (arg == nullptr) {
2451 continue;
2452 }
2453 const Type *aat = _igvn->type(arg);
2454 if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr()) {
2455 continue;
2456 }
2457 if (arg->is_AddP()) {
2458 //
2459 // The inline_native_clone() case when the arraycopy stub is called
2460 // after the allocation before Initialize and CheckCastPP nodes.
2461 // Or normal arraycopy for object arrays case.
2462 //
2463 // Set AddP's base (Allocate) as not scalar replaceable since
2464 // pointer to the base (with offset) is passed as argument.
2465 //
2466 arg = get_addp_base(arg);
2467 }
2468 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2469 assert(arg_ptn != nullptr, "should be registered");
2470 PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
2471 if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
2472 assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
2473 aat->isa_ptr() != nullptr, "expecting an Ptr");
2474 bool arg_has_oops = aat->isa_oopptr() &&
2475 (aat->isa_instptr() ||
2476 (aat->isa_aryptr() && (aat->isa_aryptr()->elem() == Type::BOTTOM || aat->isa_aryptr()->elem()->make_oopptr() != nullptr)) ||
2477 (aat->isa_aryptr() && aat->isa_aryptr()->elem() != nullptr &&
2478 aat->isa_aryptr()->is_flat() &&
2479 aat->isa_aryptr()->elem()->inline_klass()->contains_oops()));
2480 if (i == TypeFunc::Parms) {
2481 src_has_oops = arg_has_oops;
2482 }
2483 //
2484 // src or dst could be j.l.Object when other is basic type array:
2485 //
2486 // arraycopy(char[],0,Object*,0,size);
2487 // arraycopy(Object*,0,char[],0,size);
2488 //
2489 // Don't add edges in such cases.
2490 //
2491 bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
2492 arg_has_oops && (i > TypeFunc::Parms);
2493 #ifdef ASSERT
2494 if (!(is_arraycopy ||
2495 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(call) ||
2496 (call->as_CallLeaf()->_name != nullptr &&
2497 (strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 ||
2498 strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32C") == 0 ||
2499 strcmp(call->as_CallLeaf()->_name, "updateBytesAdler32") == 0 ||
2524 strcmp(call->as_CallLeaf()->_name, "dilithiumDecomposePoly") == 0 ||
2525 strcmp(call->as_CallLeaf()->_name, "encodeBlock") == 0 ||
2526 strcmp(call->as_CallLeaf()->_name, "decodeBlock") == 0 ||
2527 strcmp(call->as_CallLeaf()->_name, "md5_implCompress") == 0 ||
2528 strcmp(call->as_CallLeaf()->_name, "md5_implCompressMB") == 0 ||
2529 strcmp(call->as_CallLeaf()->_name, "sha1_implCompress") == 0 ||
2530 strcmp(call->as_CallLeaf()->_name, "sha1_implCompressMB") == 0 ||
2531 strcmp(call->as_CallLeaf()->_name, "sha256_implCompress") == 0 ||
2532 strcmp(call->as_CallLeaf()->_name, "sha256_implCompressMB") == 0 ||
2533 strcmp(call->as_CallLeaf()->_name, "sha512_implCompress") == 0 ||
2534 strcmp(call->as_CallLeaf()->_name, "sha512_implCompressMB") == 0 ||
2535 strcmp(call->as_CallLeaf()->_name, "sha3_implCompress") == 0 ||
2536 strcmp(call->as_CallLeaf()->_name, "double_keccak") == 0 ||
2537 strcmp(call->as_CallLeaf()->_name, "quad_keccak") == 0 ||
2538 strcmp(call->as_CallLeaf()->_name, "sha3_implCompressMB") == 0 ||
2539 strcmp(call->as_CallLeaf()->_name, "multiplyToLen") == 0 ||
2540 strcmp(call->as_CallLeaf()->_name, "squareToLen") == 0 ||
2541 strcmp(call->as_CallLeaf()->_name, "mulAdd") == 0 ||
2542 strcmp(call->as_CallLeaf()->_name, "montgomery_multiply") == 0 ||
2543 strcmp(call->as_CallLeaf()->_name, "montgomery_square") == 0 ||
2544 strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2545 strcmp(call->as_CallLeaf()->_name, "load_unknown_inline") == 0 ||
2546 strcmp(call->as_CallLeaf()->_name, "store_unknown_inline") == 0 ||
2547 strcmp(call->as_CallLeaf()->_name, "store_inline_type_fields_to_buf") == 0 ||
2548 strcmp(call->as_CallLeaf()->_name, "bigIntegerRightShiftWorker") == 0 ||
2549 strcmp(call->as_CallLeaf()->_name, "bigIntegerLeftShiftWorker") == 0 ||
2550 strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2551 strcmp(call->as_CallLeaf()->_name, "stringIndexOf") == 0 ||
2552 strcmp(call->as_CallLeaf()->_name, "arraysort_stub") == 0 ||
2553 strcmp(call->as_CallLeaf()->_name, "array_partition_stub") == 0 ||
2554 strcmp(call->as_CallLeaf()->_name, "get_class_id_intrinsic") == 0 ||
2555 strcmp(call->as_CallLeaf()->_name, "unsafe_setmemory") == 0)
2556 ))) {
2557 call->dump();
2558 fatal("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name);
2559 }
2560 #endif
2561 // Always process arraycopy's destination object since
2562 // we need to add all possible edges to references in
2563 // source object.
2564 if (arg_esc >= PointsToNode::ArgEscape &&
2565 !arg_is_arraycopy_dest) {
2566 continue;
2567 }
2590 }
2591 }
2592 }
2593 break;
2594 }
2595 case Op_CallStaticJava: {
2596 // For a static call, we know exactly what method is being called.
2597 // Use bytecode estimator to record the call's escape affects
2598 #ifdef ASSERT
2599 const char* name = call->as_CallStaticJava()->_name;
2600 assert((name == nullptr || strcmp(name, "uncommon_trap") != 0), "normal calls only");
2601 #endif
2602 ciMethod* meth = call->as_CallJava()->method();
2603 if ((meth != nullptr) && meth->is_boxing_method()) {
2604 break; // Boxing methods do not modify any oops.
2605 }
2606 BCEscapeAnalyzer* call_analyzer = (meth !=nullptr) ? meth->get_bcea() : nullptr;
2607 // fall-through if not a Java method or no analyzer information
2608 if (call_analyzer != nullptr) {
2609 PointsToNode* call_ptn = ptnode_adr(call->_idx);
2610 bool ret_arg = returns_an_argument(call);
2611 for (DomainIterator di(call->as_CallJava()); di.has_next(); di.next()) {
2612 int k = di.i_domain() - TypeFunc::Parms;
2613 const Type* at = di.current_domain_cc();
2614 Node* arg = call->in(di.i_domain_cc());
2615 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2616 assert(!call_analyzer->is_arg_returned(k) || !meth->is_scalarized_arg(k) ||
2617 !compatible_return(call->as_CallJava(), di.i_domain()) ||
2618 call->proj_out_or_null(di.i_domain_cc() - di.first_field_pos() + TypeFunc::Parms + 1) == nullptr ||
2619 _igvn->type(call->proj_out_or_null(di.i_domain_cc() - di.first_field_pos() + TypeFunc::Parms + 1)) == at,
2620 "scalarized return and scalarized argument should match");
2621 if (at->isa_ptr() != nullptr && call_analyzer->is_arg_returned(k) && ret_arg) {
2622 // The call returns arguments.
2623 if (meth->is_scalarized_arg(k)) {
2624 ProjNode* res_proj = call->proj_out_or_null(di.i_domain_cc() - di.first_field_pos() + TypeFunc::Parms + 1);
2625 if (res_proj != nullptr) {
2626 assert(_igvn->type(res_proj)->isa_ptr(), "scalarized return and scalarized argument should match");
2627 if (res_proj->_con != TypeFunc::Parms) {
2628 // add an edge between the result projection for a field and the argument projection for the same argument field
2629 PointsToNode* proj_ptn = ptnode_adr(res_proj->_idx);
2630 add_edge(proj_ptn, arg_ptn);
2631 if (!call_analyzer->is_return_local()) {
2632 add_edge(proj_ptn, phantom_obj);
2633 }
2634 }
2635 }
2636 } else if (call_ptn != nullptr) { // Is call's result used?
2637 assert(call_ptn->is_LocalVar(), "node should be registered");
2638 assert(arg_ptn != nullptr, "node should be registered");
2639 add_edge(call_ptn, arg_ptn);
2640 }
2641 }
2642 if (at->isa_oopptr() != nullptr &&
2643 arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
2644 if (!call_analyzer->is_arg_stack(k)) {
2645 // The argument global escapes
2646 set_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2647 } else {
2648 set_escape_state(arg_ptn, PointsToNode::ArgEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2649 if (!call_analyzer->is_arg_local(k)) {
2650 // The argument itself doesn't escape, but any fields might
2651 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2652 }
2653 }
2654 }
2655 }
2656 if (call_ptn != nullptr && call_ptn->is_LocalVar()) {
2657 // The call returns arguments.
2658 assert(call_ptn->edge_count() > 0, "sanity");
2659 if (!call_analyzer->is_return_local()) {
2660 // Returns also unknown object.
2661 add_edge(call_ptn, phantom_obj);
2662 }
2663 }
2664 break;
2665 }
2666 }
2667 default: {
2668 // Fall-through here if not a Java method or no analyzer information
2669 // or some other type of call, assume the worst case: all arguments
2670 // globally escape.
2671 const TypeTuple* d = call->tf()->domain_cc();
2672 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2673 const Type* at = d->field_at(i);
2674 if (at->isa_oopptr() != nullptr) {
2675 Node* arg = call->in(i);
2676 if (arg->is_AddP()) {
2677 arg = get_addp_base(arg);
2678 }
2679 assert(ptnode_adr(arg->_idx) != nullptr, "should be defined already");
2680 set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2681 }
2682 }
2683 }
2684 }
2685 }
2686
2687
2688 // Finish Graph construction.
2689 bool ConnectionGraph::complete_connection_graph(
2690 GrowableArray<PointsToNode*>& ptnodes_worklist,
2691 GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
3069 PointsToNode* base = i.get();
3070 if (base->is_JavaObject()) {
3071 // Skip Allocate's fields which will be processed later.
3072 if (base->ideal_node()->is_Allocate()) {
3073 return 0;
3074 }
3075 assert(base == null_obj, "only null ptr base expected here");
3076 }
3077 }
3078 if (add_edge(field, phantom_obj)) {
3079 // New edge was added
3080 new_edges++;
3081 add_field_uses_to_worklist(field);
3082 }
3083 return new_edges;
3084 }
3085
3086 // Find fields initializing values for allocations.
3087 int ConnectionGraph::find_init_values_phantom(JavaObjectNode* pta) {
3088 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
3089 PointsToNode* init_val = phantom_obj;
3090 Node* alloc = pta->ideal_node();
3091
3092 // Do nothing for Allocate nodes since its fields values are
3093 // "known" unless they are initialized by arraycopy/clone.
3094 if (alloc->is_Allocate() && !pta->arraycopy_dst()) {
3095 if (alloc->as_Allocate()->in(AllocateNode::InitValue) != nullptr) {
3096 // Null-free inline type arrays are initialized with an init value instead of null
3097 init_val = ptnode_adr(alloc->as_Allocate()->in(AllocateNode::InitValue)->_idx);
3098 assert(init_val != nullptr, "init value should be registered");
3099 } else {
3100 return 0;
3101 }
3102 }
3103 // Non-escaped allocation returned from Java or runtime call has unknown values in fields.
3104 assert(pta->arraycopy_dst() || alloc->is_CallStaticJava() || init_val != phantom_obj, "sanity");
3105 #ifdef ASSERT
3106 if (alloc->is_CallStaticJava() && alloc->as_CallStaticJava()->method() == nullptr) {
3107 const char* name = alloc->as_CallStaticJava()->_name;
3108 assert(alloc->as_CallStaticJava()->is_call_to_multianewarray_stub() ||
3109 strncmp(name, "load_unknown_inline", 19) == 0 ||
3110 strncmp(name, "store_inline_type_fields_to_buf", 31) == 0, "sanity");
3111 }
3112 #endif
3113 // Non-escaped allocation returned from Java or runtime call have unknown values in fields.
3114 int new_edges = 0;
3115 for (EdgeIterator i(pta); i.has_next(); i.next()) {
3116 PointsToNode* field = i.get();
3117 if (field->is_Field() && field->as_Field()->is_oop()) {
3118 if (add_edge(field, init_val)) {
3119 // New edge was added
3120 new_edges++;
3121 add_field_uses_to_worklist(field->as_Field());
3122 }
3123 }
3124 }
3125 return new_edges;
3126 }
3127
3128 // Find fields initializing values for allocations.
3129 int ConnectionGraph::find_init_values_null(JavaObjectNode* pta, PhaseValues* phase) {
3130 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
3131 Node* alloc = pta->ideal_node();
3132 // Do nothing for Call nodes since its fields values are unknown.
3133 if (!alloc->is_Allocate() || alloc->as_Allocate()->in(AllocateNode::InitValue) != nullptr) {
3134 return 0;
3135 }
3136 InitializeNode* ini = alloc->as_Allocate()->initialization();
3137 bool visited_bottom_offset = false;
3138 GrowableArray<int> offsets_worklist;
3139 int new_edges = 0;
3140
3141 // Check if an oop field's initializing value is recorded and add
3142 // a corresponding null if field's value if it is not recorded.
3143 // Connection Graph does not record a default initialization by null
3144 // captured by Initialize node.
3145 //
3146 for (EdgeIterator i(pta); i.has_next(); i.next()) {
3147 PointsToNode* field = i.get(); // Field (AddP)
3148 if (!field->is_Field() || !field->as_Field()->is_oop()) {
3149 continue; // Not oop field
3150 }
3151 int offset = field->as_Field()->offset();
3152 if (offset == Type::OffsetBot) {
3153 if (!visited_bottom_offset) {
3199 } else {
3200 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
3201 tty->print_cr("----------init store has invalid value -----");
3202 store->dump();
3203 val->dump();
3204 assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
3205 }
3206 for (EdgeIterator j(val); j.has_next(); j.next()) {
3207 PointsToNode* obj = j.get();
3208 if (obj->is_JavaObject()) {
3209 if (!field->points_to(obj->as_JavaObject())) {
3210 missed_obj = obj;
3211 break;
3212 }
3213 }
3214 }
3215 }
3216 if (missed_obj != nullptr) {
3217 tty->print_cr("----------field---------------------------------");
3218 field->dump();
3219 tty->print_cr("----------missed reference to object------------");
3220 missed_obj->dump();
3221 tty->print_cr("----------object referenced by init store-------");
3222 store->dump();
3223 val->dump();
3224 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
3225 }
3226 }
3227 #endif
3228 } else {
3229 // There could be initializing stores which follow allocation.
3230 // For example, a volatile field store is not collected
3231 // by Initialize node.
3232 //
3233 // Need to check for dependent loads to separate such stores from
3234 // stores which follow loads. For now, add initial value null so
3235 // that compare pointers optimization works correctly.
3236 }
3237 }
3238 if (value == nullptr) {
3239 // A field's initializing value was not recorded. Add null.
3240 if (add_edge(field, null_obj)) {
3241 // New edge was added
3566 assert(field->edge_count() > 0, "sanity");
3567 }
3568 }
3569 }
3570 }
3571 #endif
3572
3573 // Optimize ideal graph.
3574 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
3575 GrowableArray<MemBarStoreStoreNode*>& storestore_worklist) {
3576 Compile* C = _compile;
3577 PhaseIterGVN* igvn = _igvn;
3578 if (EliminateLocks) {
3579 // Mark locks before changing ideal graph.
3580 int cnt = C->macro_count();
3581 for (int i = 0; i < cnt; i++) {
3582 Node *n = C->macro_node(i);
3583 if (n->is_AbstractLock()) { // Lock and Unlock nodes
3584 AbstractLockNode* alock = n->as_AbstractLock();
3585 if (!alock->is_non_esc_obj()) {
3586 const Type* obj_type = igvn->type(alock->obj_node());
3587 if (can_eliminate_lock(alock) && !obj_type->is_inlinetypeptr()) {
3588 assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
3589 // The lock could be marked eliminated by lock coarsening
3590 // code during first IGVN before EA. Replace coarsened flag
3591 // to eliminate all associated locks/unlocks.
3592 #ifdef ASSERT
3593 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc3");
3594 #endif
3595 alock->set_non_esc_obj();
3596 }
3597 }
3598 }
3599 }
3600 }
3601
3602 if (OptimizePtrCompare) {
3603 for (int i = 0; i < ptr_cmp_worklist.length(); i++) {
3604 Node *n = ptr_cmp_worklist.at(i);
3605 assert(n->Opcode() == Op_CmpN || n->Opcode() == Op_CmpP, "must be");
3606 const TypeInt* tcmp = optimize_ptr_compare(n->in(1), n->in(2));
3607 if (tcmp->singleton()) {
3609 #ifndef PRODUCT
3610 if (PrintOptimizePtrCompare) {
3611 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"));
3612 if (Verbose) {
3613 n->dump(1);
3614 }
3615 }
3616 #endif
3617 igvn->replace_node(n, cmp);
3618 }
3619 }
3620 }
3621
3622 // For MemBarStoreStore nodes added in library_call.cpp, check
3623 // escape status of associated AllocateNode and optimize out
3624 // MemBarStoreStore node if the allocated object never escapes.
3625 for (int i = 0; i < storestore_worklist.length(); i++) {
3626 Node* storestore = storestore_worklist.at(i);
3627 Node* alloc = storestore->in(MemBarNode::Precedent)->in(0);
3628 if (alloc->is_Allocate() && not_global_escape(alloc)) {
3629 if (alloc->in(AllocateNode::InlineType) != nullptr) {
3630 // Non-escaping inline type buffer allocations don't require a membar
3631 storestore->as_MemBar()->remove(_igvn);
3632 } else {
3633 MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
3634 mb->init_req(TypeFunc::Memory, storestore->in(TypeFunc::Memory));
3635 mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
3636 igvn->register_new_node_with_optimizer(mb);
3637 igvn->replace_node(storestore, mb);
3638 }
3639 }
3640 }
3641 }
3642
3643 // Atomic flat accesses on non-escaping objects can be optimized to non-atomic accesses
3644 void ConnectionGraph::optimize_flat_accesses(GrowableArray<SafePointNode*>& sfn_worklist) {
3645 PhaseIterGVN& igvn = *_igvn;
3646 bool delay = igvn.delay_transform();
3647 igvn.set_delay_transform(true);
3648 igvn.C->for_each_flat_access([&](Node* n) {
3649 Node* base = n->is_LoadFlat() ? n->as_LoadFlat()->base() : n->as_StoreFlat()->base();
3650 if (!not_global_escape(base)) {
3651 return;
3652 }
3653
3654 bool expanded;
3655 if (n->is_LoadFlat()) {
3656 expanded = n->as_LoadFlat()->expand_non_atomic(igvn);
3657 } else {
3658 expanded = n->as_StoreFlat()->expand_non_atomic(igvn);
3659 }
3660 if (expanded) {
3661 sfn_worklist.remove(n->as_SafePoint());
3662 igvn.C->remove_flat_access(n);
3663 }
3664 });
3665 igvn.set_delay_transform(delay);
3666 }
3667
3668 // Optimize objects compare.
3669 const TypeInt* ConnectionGraph::optimize_ptr_compare(Node* left, Node* right) {
3670 const TypeInt* UNKNOWN = TypeInt::CC; // [-1, 0,1]
3671 if (!OptimizePtrCompare) {
3672 return UNKNOWN;
3673 }
3674 const TypeInt* EQ = TypeInt::CC_EQ; // [0] == ZERO
3675 const TypeInt* NE = TypeInt::CC_GT; // [1] == ONE
3676
3677 PointsToNode* ptn1 = ptnode_adr(left->_idx);
3678 PointsToNode* ptn2 = ptnode_adr(right->_idx);
3679 JavaObjectNode* jobj1 = unique_java_object(left);
3680 JavaObjectNode* jobj2 = unique_java_object(right);
3681
3682 // The use of this method during allocation merge reduction may cause 'left'
3683 // or 'right' be something (e.g., a Phi) that isn't in the connection graph or
3684 // that doesn't reference an unique java object.
3685 if (ptn1 == nullptr || ptn2 == nullptr ||
3686 jobj1 == nullptr || jobj2 == nullptr) {
3687 return UNKNOWN;
3807 assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
3808 assert((src != null_obj) && (dst != null_obj), "not for ConP null");
3809 PointsToNode* ptadr = _nodes.at(n->_idx);
3810 if (ptadr != nullptr) {
3811 assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
3812 return;
3813 }
3814 Compile* C = _compile;
3815 ptadr = new (C->comp_arena()) ArraycopyNode(this, n, es);
3816 map_ideal_node(n, ptadr);
3817 // Add edge from arraycopy node to source object.
3818 (void)add_edge(ptadr, src);
3819 src->set_arraycopy_src();
3820 // Add edge from destination object to arraycopy node.
3821 (void)add_edge(dst, ptadr);
3822 dst->set_arraycopy_dst();
3823 }
3824
3825 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
3826 const Type* adr_type = n->as_AddP()->bottom_type();
3827 int field_offset = adr_type->isa_aryptr() ? adr_type->isa_aryptr()->field_offset().get() : Type::OffsetBot;
3828 BasicType bt = T_INT;
3829 if (offset == Type::OffsetBot && field_offset == Type::OffsetBot) {
3830 // Check only oop fields.
3831 if (!adr_type->isa_aryptr() ||
3832 adr_type->isa_aryptr()->elem() == Type::BOTTOM ||
3833 adr_type->isa_aryptr()->elem()->make_oopptr() != nullptr) {
3834 // OffsetBot is used to reference array's element. Ignore first AddP.
3835 if (find_second_addp(n, n->in(AddPNode::Base)) == nullptr) {
3836 bt = T_OBJECT;
3837 }
3838 }
3839 } else if (offset != oopDesc::klass_offset_in_bytes()) {
3840 if (adr_type->isa_instptr()) {
3841 ciField* field = _compile->alias_type(adr_type->is_ptr())->field();
3842 if (field != nullptr) {
3843 bt = field->layout_type();
3844 } else {
3845 // Check for unsafe oop field access
3846 if (has_oop_node_outs(n)) {
3847 bt = T_OBJECT;
3848 (*unsafe) = true;
3849 }
3850 }
3851 } else if (adr_type->isa_aryptr()) {
3852 if (offset == arrayOopDesc::length_offset_in_bytes()) {
3853 // Ignore array length load.
3854 } else if (find_second_addp(n, n->in(AddPNode::Base)) != nullptr) {
3855 // Ignore first AddP.
3856 } else {
3857 const Type* elemtype = adr_type->is_aryptr()->elem();
3858 if (adr_type->is_aryptr()->is_flat() && field_offset != Type::OffsetBot) {
3859 ciInlineKlass* vk = elemtype->inline_klass();
3860 field_offset += vk->payload_offset();
3861 ciField* field = vk->get_field_by_offset(field_offset, false);
3862 if (field != nullptr) {
3863 bt = field->layout_type();
3864 } else {
3865 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);
3866 bt = T_BOOLEAN;
3867 }
3868 } else {
3869 bt = elemtype->array_element_basic_type();
3870 }
3871 }
3872 } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
3873 // Allocation initialization, ThreadLocal field access, unsafe access
3874 if (has_oop_node_outs(n)) {
3875 bt = T_OBJECT;
3876 }
3877 }
3878 }
3879 // Note: T_NARROWOOP is not classed as a real reference type
3880 bool res = (is_reference_type(bt) || bt == T_NARROWOOP);
3881 assert(!has_oop_node_outs(n) || res, "sanity: AddP has oop outs, needs to be treated as oop field");
3882 return res;
3883 }
3884
3885 bool ConnectionGraph::has_oop_node_outs(Node* n) {
3886 return n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3887 n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3888 n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3889 BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n);
3890 }
4053 return true;
4054 }
4055 }
4056 }
4057 }
4058 }
4059 return false;
4060 }
4061
4062 int ConnectionGraph::address_offset(Node* adr, PhaseValues* phase) {
4063 const Type *adr_type = phase->type(adr);
4064 if (adr->is_AddP() && adr_type->isa_oopptr() == nullptr && is_captured_store_address(adr)) {
4065 // We are computing a raw address for a store captured by an Initialize
4066 // compute an appropriate address type. AddP cases #3 and #5 (see below).
4067 int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
4068 assert(offs != Type::OffsetBot ||
4069 adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
4070 "offset must be a constant or it is initialization of array");
4071 return offs;
4072 }
4073 return adr_type->is_ptr()->flat_offset();
4074 }
4075
4076 Node* ConnectionGraph::get_addp_base(Node *addp) {
4077 assert(addp->is_AddP(), "must be AddP");
4078 //
4079 // AddP cases for Base and Address inputs:
4080 // case #1. Direct object's field reference:
4081 // Allocate
4082 // |
4083 // Proj #5 ( oop result )
4084 // |
4085 // CheckCastPP (cast to instance type)
4086 // | |
4087 // AddP ( base == address )
4088 //
4089 // case #2. Indirect object's field reference:
4090 // Phi
4091 // |
4092 // CastPP (cast to instance type)
4093 // | |
4094 // AddP ( base == address )
4095 //
4096 // case #3. Raw object's field reference for Initialize node.
4097 // Could have an additional Phi merging multiple allocations.
4098 // Allocate
4099 // |
4100 // Proj #5 ( oop result )
4101 // top |
4102 // \ |
4103 // AddP ( base == top )
4104 //
4105 // case #4. Array's element reference:
4106 // {CheckCastPP | CastPP}
4107 // | | |
4108 // | AddP ( array's element offset )
4109 // | |
4110 // AddP ( array's offset )
4111 //
4112 // case #5. Raw object's field reference for arraycopy stub call:
4113 // The inline_native_clone() case when the arraycopy stub is called
4114 // after the allocation before Initialize and CheckCastPP nodes.
4115 // Allocate
4116 // |
4117 // Proj #5 ( oop result )
4128 // case #7. Klass's field reference.
4129 // LoadKlass
4130 // | |
4131 // AddP ( base == address )
4132 //
4133 // case #8. narrow Klass's field reference.
4134 // LoadNKlass
4135 // |
4136 // DecodeN
4137 // | |
4138 // AddP ( base == address )
4139 //
4140 // case #9. Mixed unsafe access
4141 // {instance}
4142 // |
4143 // CheckCastPP (raw)
4144 // top |
4145 // \ |
4146 // AddP ( base == top )
4147 //
4148 // case #10. Klass fetched with
4149 // LibraryCallKit::load_*_refined_array_klass()
4150 // which has en extra Phi.
4151 // LoadKlass LoadKlass
4152 // | |
4153 // CastPP CastPP
4154 // \ /
4155 // Phi
4156 // top |
4157 // \ |
4158 // AddP ( base == top )
4159 //
4160 Node *base = addp->in(AddPNode::Base);
4161 if (base->uncast()->is_top()) { // The AddP case #3, #6, #9, and #10.
4162 base = addp->in(AddPNode::Address);
4163 while (base->is_AddP()) {
4164 // Case #6 (unsafe access) may have several chained AddP nodes.
4165 assert(base->in(AddPNode::Base)->uncast()->is_top(), "expected unsafe access address only");
4166 base = base->in(AddPNode::Address);
4167 }
4168 if (base->Opcode() == Op_CheckCastPP &&
4169 base->bottom_type()->isa_rawptr() &&
4170 _igvn->type(base->in(1))->isa_oopptr()) {
4171 base = base->in(1); // Case #9
4172 } else {
4173 // Case #3, #6, and #10
4174 Node* uncast_base = base->uncast();
4175 int opcode = uncast_base->Opcode();
4176 assert(opcode == Op_ConP || opcode == Op_ThreadLocal ||
4177 opcode == Op_CastX2P || uncast_base->is_DecodeNarrowPtr() ||
4178 (_igvn->C->is_osr_compilation() && uncast_base->is_Parm() && uncast_base->as_Parm()->_con == TypeFunc::Parms)||
4179 (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_rawptr() != nullptr)) ||
4180 (uncast_base->is_Mem() && (uncast_base->bottom_type()->isa_klassptr() != nullptr)) ||
4181 is_captured_store_address(addp) ||
4182 is_load_array_klass_related(uncast_base), "sanity");
4183 }
4184 }
4185 return base;
4186 }
4187
4188 #ifdef ASSERT
4189 // Case #10
4190 bool ConnectionGraph::is_load_array_klass_related(const Node* uncast_base) {
4191 if (!uncast_base->is_Phi() || uncast_base->req() != 3) {
4192 return false;
4193 }
4194 Node* in1 = uncast_base->in(1);
4195 Node* in2 = uncast_base->in(2);
4196 return in1->uncast()->Opcode() == Op_LoadKlass &&
4197 in2->uncast()->Opcode() == Op_LoadKlass;
4198 }
4199 #endif
4200
4201 Node* ConnectionGraph::find_second_addp(Node* addp, Node* n) {
4202 assert(addp->is_AddP() && addp->outcnt() > 0, "Don't process dead nodes");
4203 Node* addp2 = addp->raw_out(0);
4204 if (addp->outcnt() == 1 && addp2->is_AddP() &&
4205 addp2->in(AddPNode::Base) == n &&
4206 addp2->in(AddPNode::Address) == addp) {
4207 assert(addp->in(AddPNode::Base) == n, "expecting the same base");
4208 //
4209 // Find array's offset to push it on worklist first and
4210 // as result process an array's element offset first (pushed second)
4211 // to avoid CastPP for the array's offset.
4212 // Otherwise the inserted CastPP (LocalVar) will point to what
4213 // the AddP (Field) points to. Which would be wrong since
4214 // the algorithm expects the CastPP has the same point as
4215 // as AddP's base CheckCastPP (LocalVar).
4216 //
4217 // ArrayAllocation
4218 // |
4219 // CheckCastPP
4220 // |
4237 }
4238 return nullptr;
4239 }
4240
4241 //
4242 // Adjust the type and inputs of an AddP which computes the
4243 // address of a field of an instance
4244 //
4245 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
4246 PhaseGVN* igvn = _igvn;
4247 const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
4248 assert(base_t != nullptr && base_t->is_known_instance(), "expecting instance oopptr");
4249 const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
4250 if (t == nullptr) {
4251 // We are computing a raw address for a store captured by an Initialize
4252 // compute an appropriate address type (cases #3 and #5).
4253 assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
4254 assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
4255 intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
4256 assert(offs != Type::OffsetBot, "offset must be a constant");
4257 if (base_t->isa_aryptr() != nullptr) {
4258 // In the case of a flat inline type array, each field has its
4259 // own slice so we need to extract the field being accessed from
4260 // the address computation
4261 t = base_t->isa_aryptr()->add_field_offset_and_offset(offs)->is_oopptr();
4262 } else {
4263 t = base_t->add_offset(offs)->is_oopptr();
4264 }
4265 }
4266 int inst_id = base_t->instance_id();
4267 assert(!t->is_known_instance() || t->instance_id() == inst_id,
4268 "old type must be non-instance or match new type");
4269
4270 // The type 't' could be subclass of 'base_t'.
4271 // As result t->offset() could be large then base_t's size and it will
4272 // cause the failure in add_offset() with narrow oops since TypeOopPtr()
4273 // constructor verifies correctness of the offset.
4274 //
4275 // It could happened on subclass's branch (from the type profiling
4276 // inlining) which was not eliminated during parsing since the exactness
4277 // of the allocation type was not propagated to the subclass type check.
4278 //
4279 // Or the type 't' could be not related to 'base_t' at all.
4280 // It could happen when CHA type is different from MDO type on a dead path
4281 // (for example, from instanceof check) which is not collapsed during parsing.
4282 //
4283 // Do nothing for such AddP node and don't process its users since
4284 // this code branch will go away.
4285 //
4286 if (!t->is_known_instance() &&
4287 !base_t->maybe_java_subtype_of(t)) {
4288 return false; // bail out
4289 }
4290 const TypePtr* tinst = base_t->add_offset(t->offset());
4291 if (tinst->isa_aryptr() && t->isa_aryptr()) {
4292 // In the case of a flat inline type array, each field has its
4293 // own slice so we need to keep track of the field being accessed.
4294 tinst = tinst->is_aryptr()->with_field_offset(t->is_aryptr()->field_offset().get());
4295 // Keep array properties (not flat/null-free)
4296 tinst = tinst->is_aryptr()->update_properties(t->is_aryptr());
4297 if (tinst == nullptr) {
4298 return false; // Skip dead path with inconsistent properties
4299 }
4300 }
4301
4302 // Do NOT remove the next line: ensure a new alias index is allocated
4303 // for the instance type. Note: C++ will not remove it since the call
4304 // has side effect.
4305 int alias_idx = _compile->get_alias_index(tinst);
4306 igvn->set_type(addp, tinst);
4307 // record the allocation in the node map
4308 set_map(addp, get_map(base->_idx));
4309 // Set addp's Base and Address to 'base'.
4310 Node *abase = addp->in(AddPNode::Base);
4311 Node *adr = addp->in(AddPNode::Address);
4312 if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
4313 adr->in(0)->_idx == (uint)inst_id) {
4314 // Skip AddP cases #3 and #5.
4315 } else {
4316 assert(!abase->is_top(), "sanity"); // AddP case #3
4317 if (abase != base) {
4318 igvn->hash_delete(addp);
4319 addp->set_req(AddPNode::Base, base);
4320 if (abase == adr) {
4321 addp->set_req(AddPNode::Address, base);
4605 } else if (C->get_alias_index(result->adr_type()) != alias_idx) {
4606 assert(C->get_general_index(alias_idx) == C->get_alias_index(result->adr_type()), "should be projection for the same field/array element");
4607 result = get_map(result->_idx);
4608 assert(result != nullptr, "new projection should have been allocated");
4609 break;
4610 }
4611 } else if (proj_in->is_MemBar()) {
4612 // Check if there is an array copy for a clone
4613 // Step over GC barrier when ReduceInitialCardMarks is disabled
4614 BarrierSetC2* bs = BarrierSet::barrier_set()->barrier_set_c2();
4615 Node* control_proj_ac = bs->step_over_gc_barrier(proj_in->in(0));
4616
4617 if (control_proj_ac->is_Proj() && control_proj_ac->in(0)->is_ArrayCopy()) {
4618 // Stop if it is a clone
4619 ArrayCopyNode* ac = control_proj_ac->in(0)->as_ArrayCopy();
4620 if (ac->may_modify(toop, igvn)) {
4621 break;
4622 }
4623 }
4624 result = proj_in->in(TypeFunc::Memory);
4625 } else if (proj_in->is_LoadFlat()) {
4626 result = proj_in->in(TypeFunc::Memory);
4627 }
4628 } else if (result->is_MergeMem()) {
4629 MergeMemNode *mmem = result->as_MergeMem();
4630 result = step_through_mergemem(mmem, alias_idx, toop);
4631 if (result == mmem->base_memory()) {
4632 // Didn't find instance memory, search through general slice recursively.
4633 result = mmem->memory_at(C->get_general_index(alias_idx));
4634 result = find_inst_mem(result, alias_idx, orig_phis, rec_depth + 1);
4635 if (C->failing()) {
4636 return nullptr;
4637 }
4638 mmem->set_memory_at(alias_idx, result);
4639 }
4640 } else if (result->is_Phi() &&
4641 C->get_alias_index(result->as_Phi()->adr_type()) != alias_idx) {
4642 Node *un = result->as_Phi()->unique_input(igvn);
4643 if (un != nullptr) {
4644 orig_phis.push(result);
4645 result = un;
4646 } else {
4892 // - not determined to be ineligible by escape analysis
4893 set_map(alloc, n);
4894 set_map(n, alloc);
4895 const TypeOopPtr* tinst = t->cast_to_instance_id(ni);
4896 igvn->hash_delete(n);
4897 igvn->set_type(n, tinst);
4898 n->raise_bottom_type(tinst);
4899 igvn->hash_insert(n);
4900 record_for_optimizer(n);
4901 // Allocate an alias index for the header fields. Accesses to
4902 // the header emitted during macro expansion wouldn't have
4903 // correct memory state otherwise.
4904 _compile->get_alias_index(tinst->add_offset(oopDesc::mark_offset_in_bytes()));
4905 _compile->get_alias_index(tinst->add_offset(oopDesc::klass_offset_in_bytes()));
4906 if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
4907 // Add a new NarrowMem projection for each existing NarrowMem projection with new adr type
4908 InitializeNode* init = alloc->as_Allocate()->initialization();
4909 assert(init != nullptr, "can't find Initialization node for this Allocate node");
4910 auto process_narrow_proj = [&](NarrowMemProjNode* proj) {
4911 const TypePtr* adr_type = proj->adr_type();
4912 const TypePtr* new_adr_type = tinst->with_offset(adr_type->offset());
4913 if (adr_type->isa_aryptr()) {
4914 // In the case of a flat inline type array, each field has its own slice so we need a
4915 // NarrowMemProj for each field of the flat array elements
4916 new_adr_type = new_adr_type->is_aryptr()->with_field_offset(adr_type->is_aryptr()->field_offset().get());
4917 }
4918 if (adr_type != new_adr_type && !init->already_has_narrow_mem_proj_with_adr_type(new_adr_type)) {
4919 // Do NOT remove the next line: ensure a new alias index is allocated for the instance type.
4920 uint alias_idx = _compile->get_alias_index(new_adr_type);
4921 assert(_compile->get_general_index(alias_idx) == _compile->get_alias_index(adr_type), "new adr type should be narrowed down from existing adr type");
4922 NarrowMemProjNode* new_proj = new NarrowMemProjNode(init, new_adr_type);
4923 igvn->set_type(new_proj, new_proj->bottom_type());
4924 record_for_optimizer(new_proj);
4925 set_map(proj, new_proj); // record it so ConnectionGraph::find_inst_mem() can find it
4926 }
4927 };
4928 init->for_each_narrow_mem_proj_with_new_uses(process_narrow_proj);
4929
4930 // First, put on the worklist all Field edges from Connection Graph
4931 // which is more accurate than putting immediate users from Ideal Graph.
4932 for (EdgeIterator e(ptn); e.has_next(); e.next()) {
4933 PointsToNode* tgt = e.get();
4934 if (tgt->is_Arraycopy()) {
4935 continue;
4936 }
4937 Node* use = tgt->ideal_node();
5015 ptnode_adr(n->_idx)->dump();
5016 assert(jobj != nullptr && jobj != phantom_obj, "escaped allocation");
5017 #endif
5018 _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
5019 return;
5020 } else {
5021 Node *val = get_map(jobj->idx()); // CheckCastPP node
5022 TypeNode *tn = n->as_Type();
5023 const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
5024 assert(tinst != nullptr && tinst->is_known_instance() &&
5025 tinst->instance_id() == jobj->idx() , "instance type expected.");
5026
5027 const Type *tn_type = igvn->type(tn);
5028 const TypeOopPtr *tn_t;
5029 if (tn_type->isa_narrowoop()) {
5030 tn_t = tn_type->make_ptr()->isa_oopptr();
5031 } else {
5032 tn_t = tn_type->isa_oopptr();
5033 }
5034 if (tn_t != nullptr && tinst->maybe_java_subtype_of(tn_t)) {
5035 if (tn_t->isa_aryptr()) {
5036 // Keep array properties (not flat/null-free)
5037 tinst = tinst->is_aryptr()->update_properties(tn_t->is_aryptr());
5038 if (tinst == nullptr) {
5039 continue; // Skip dead path with inconsistent properties
5040 }
5041 }
5042 if (tn_type->isa_narrowoop()) {
5043 tn_type = tinst->make_narrowoop();
5044 } else {
5045 tn_type = tinst;
5046 }
5047 igvn->hash_delete(tn);
5048 igvn->set_type(tn, tn_type);
5049 tn->set_type(tn_type);
5050 igvn->hash_insert(tn);
5051 record_for_optimizer(n);
5052 } else {
5053 assert(tn_type == TypePtr::NULL_PTR ||
5054 (tn_t != nullptr && !tinst->maybe_java_subtype_of(tn_t)),
5055 "unexpected type");
5056 continue; // Skip dead path with different type
5057 }
5058 }
5059 } else {
5060 DEBUG_ONLY(n->dump();)
5061 assert(false, "EA: unexpected node");
5062 continue;
5063 }
5064 // push allocation's users on appropriate worklist
5065 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5066 Node *use = n->fast_out(i);
5067 if (use->is_Mem() && use->in(MemNode::Address) == n) {
5068 // Load/store to instance's field
5069 memnode_worklist.push(use);
5070 } else if (use->is_MemBar()) {
5071 if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
5072 memnode_worklist.push(use);
5073 }
5074 } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
5075 Node* addp2 = find_second_addp(use, n);
5076 if (addp2 != nullptr) {
5077 alloc_worklist.append_if_missing(addp2);
5078 }
5079 alloc_worklist.append_if_missing(use);
5080 } else if (use->is_Phi() ||
5081 use->is_CheckCastPP() ||
5082 use->is_EncodeNarrowPtr() ||
5083 use->is_DecodeNarrowPtr() ||
5084 (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
5085 alloc_worklist.append_if_missing(use);
5086 #ifdef ASSERT
5087 } else if (use->is_Mem()) {
5088 assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
5089 } else if (use->is_MergeMem()) {
5090 assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
5091 } else if (use->is_SafePoint()) {
5092 // Look for MergeMem nodes for calls which reference unique allocation
5093 // (through CheckCastPP nodes) even for debug info.
5094 Node* m = use->in(TypeFunc::Memory);
5095 if (m->is_MergeMem()) {
5096 assert(mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
5097 }
5098 } else if (use->Opcode() == Op_EncodeISOArray) {
5099 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
5100 // EncodeISOArray overwrites destination array
5101 memnode_worklist.push(use);
5102 }
5103 } else if (use->Opcode() == Op_Return) {
5104 // Allocation is referenced by field of returned inline type
5105 assert(_compile->tf()->returns_inline_type_as_fields(), "EA: unexpected reference by ReturnNode");
5106 } else {
5107 uint op = use->Opcode();
5108 if ((op == Op_StrCompressedCopy || op == Op_StrInflatedCopy) &&
5109 (use->in(MemNode::Memory) == n)) {
5110 // They overwrite memory edge corresponding to destination array,
5111 memnode_worklist.push(use);
5112 } else if (!(op == Op_CmpP || op == Op_Conv2B ||
5113 op == Op_CastP2X ||
5114 op == Op_FastLock || op == Op_AryEq ||
5115 op == Op_StrComp || op == Op_CountPositives ||
5116 op == Op_StrCompressedCopy || op == Op_StrInflatedCopy ||
5117 op == Op_StrEquals || op == Op_VectorizedHashCode ||
5118 op == Op_StrIndexOf || op == Op_StrIndexOfChar ||
5119 op == Op_SubTypeCheck || op == Op_InlineType || op == Op_FlatArrayCheck ||
5120 op == Op_ReinterpretS2HF ||
5121 op == Op_ReachabilityFence ||
5122 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use))) {
5123 n->dump();
5124 use->dump();
5125 assert(false, "EA: missing allocation reference path");
5126 }
5127 #endif
5128 }
5129 }
5130
5131 }
5132
5133 #ifdef ASSERT
5134 if (VerifyReduceAllocationMerges) {
5135 for (uint i = 0; i < reducible_merges.size(); i++) {
5136 Node* phi = reducible_merges.at(i);
5137
5138 if (!reduced_merges.member(phi)) {
5139 phi->dump(2);
5215 n = n->as_MemBar()->proj_out_or_null(TypeFunc::Memory);
5216 if (n == nullptr) {
5217 continue;
5218 }
5219 }
5220 } else if (n->is_CallLeaf()) {
5221 // Runtime calls with narrow memory input (no MergeMem node)
5222 // get the memory projection
5223 n = n->as_Call()->proj_out_or_null(TypeFunc::Memory);
5224 if (n == nullptr) {
5225 continue;
5226 }
5227 } else if (n->Opcode() == Op_StrInflatedCopy) {
5228 // Check direct uses of StrInflatedCopy.
5229 // It is memory type Node - no special SCMemProj node.
5230 } else if (n->Opcode() == Op_StrCompressedCopy ||
5231 n->Opcode() == Op_EncodeISOArray) {
5232 // get the memory projection
5233 n = n->find_out_with(Op_SCMemProj);
5234 assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
5235 } else if (n->is_CallLeaf() && n->as_CallLeaf()->_name != nullptr &&
5236 strcmp(n->as_CallLeaf()->_name, "store_unknown_inline") == 0) {
5237 n = n->as_CallLeaf()->proj_out(TypeFunc::Memory);
5238 } else if (n->is_Proj()) {
5239 assert(n->in(0)->is_Initialize(), "we only push memory projections for Initialize");
5240 } else {
5241 #ifdef ASSERT
5242 if (!n->is_Mem()) {
5243 n->dump();
5244 }
5245 assert(n->is_Mem(), "memory node required.");
5246 #endif
5247 Node *addr = n->in(MemNode::Address);
5248 const Type *addr_t = igvn->type(addr);
5249 if (addr_t == Type::TOP) {
5250 continue;
5251 }
5252 assert (addr_t->isa_ptr() != nullptr, "pointer type required.");
5253 int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
5254 assert ((uint)alias_idx < new_index_end, "wrong alias index");
5255 Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
5256 if (_compile->failing()) {
5257 return;
5269 assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
5270 }
5271 }
5272 // push user on appropriate worklist
5273 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5274 Node *use = n->fast_out(i);
5275 if (use->is_Phi() || use->is_ClearArray()) {
5276 memnode_worklist.push(use);
5277 } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
5278 memnode_worklist.push(use);
5279 } else if (use->is_MemBar() || use->is_CallLeaf()) {
5280 if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
5281 memnode_worklist.push(use);
5282 }
5283 } else if (use->is_Proj()) {
5284 assert(n->is_Initialize(), "We only push projections of Initialize");
5285 if (use->as_Proj()->_con == TypeFunc::Memory) { // Ignore precedent edge
5286 memnode_worklist.push(use);
5287 }
5288 #ifdef ASSERT
5289 } else if (use->is_Mem()) {
5290 assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
5291 } else if (use->is_MergeMem()) {
5292 assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
5293 } else if (use->Opcode() == Op_EncodeISOArray) {
5294 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
5295 // EncodeISOArray overwrites destination array
5296 memnode_worklist.push(use);
5297 }
5298 } else if (use->is_CallLeaf() && use->as_CallLeaf()->_name != nullptr &&
5299 strcmp(use->as_CallLeaf()->_name, "store_unknown_inline") == 0) {
5300 // store_unknown_inline overwrites destination array
5301 memnode_worklist.push(use);
5302 } else {
5303 uint op = use->Opcode();
5304 if ((use->in(MemNode::Memory) == n) &&
5305 (op == Op_StrCompressedCopy || op == Op_StrInflatedCopy)) {
5306 // They overwrite memory edge corresponding to destination array,
5307 memnode_worklist.push(use);
5308 } else if (!(BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use) ||
5309 op == Op_AryEq || op == Op_StrComp || op == Op_CountPositives ||
5310 op == Op_StrCompressedCopy || op == Op_StrInflatedCopy || op == Op_VectorizedHashCode ||
5311 op == Op_StrEquals || op == Op_StrIndexOf || op == Op_StrIndexOfChar || op == Op_FlatArrayCheck)) {
5312 n->dump();
5313 use->dump();
5314 assert(false, "EA: missing memory path");
5315 }
5316 #endif
5317 }
5318 }
5319 }
5320
5321 // Phase 3: Process MergeMem nodes from mergemem_worklist.
5322 // Walk each memory slice moving the first node encountered of each
5323 // instance type to the input corresponding to its alias index.
5324 uint length = mergemem_worklist.length();
5325 for( uint next = 0; next < length; ++next ) {
5326 MergeMemNode* nmm = mergemem_worklist.at(next);
5327 assert(!visited.test_set(nmm->_idx), "should not be visited before");
5328 // Note: we don't want to use MergeMemStream here because we only want to
5329 // scan inputs which exist at the start, not ones we add during processing.
5330 // Note 2: MergeMem may already contains instance memory slices added
5331 // during find_inst_mem() call when memory nodes were processed above.
5394 _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
5395 } else if (_invocation > 0) {
5396 _compile->record_failure(C2Compiler::retry_no_iterative_escape_analysis());
5397 } else {
5398 _compile->record_failure(C2Compiler::retry_no_escape_analysis());
5399 }
5400 return;
5401 }
5402
5403 igvn->hash_insert(nmm);
5404 record_for_optimizer(nmm);
5405 }
5406
5407 _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_3, 5);
5408
5409 // Phase 4: Update the inputs of non-instance memory Phis and
5410 // the Memory input of memnodes
5411 // First update the inputs of any non-instance Phi's from
5412 // which we split out an instance Phi. Note we don't have
5413 // to recursively process Phi's encountered on the input memory
5414 // chains as is done in split_memory_phi() since they will
5415 // also be processed here.
5416 for (uint j = 0; j < orig_phis.size(); j++) {
5417 PhiNode* phi = orig_phis.at(j)->as_Phi();
5418 int alias_idx = _compile->get_alias_index(phi->adr_type());
5419 igvn->hash_delete(phi);
5420 for (uint i = 1; i < phi->req(); i++) {
5421 Node *mem = phi->in(i);
5422 Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
5423 if (_compile->failing()) {
5424 return;
5425 }
5426 if (mem != new_mem) {
5427 phi->set_req(i, new_mem);
5428 }
5429 }
5430 igvn->hash_insert(phi);
5431 record_for_optimizer(phi);
5432 }
5433
5434 // Update the memory inputs of MemNodes with the value we computed
|