11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "ci/bcEscapeAnalyzer.hpp"
26 #include "compiler/compileLog.hpp"
27 #include "gc/shared/barrierSet.hpp"
28 #include "gc/shared/c2/barrierSetC2.hpp"
29 #include "libadt/vectset.hpp"
30 #include "memory/allocation.hpp"
31 #include "memory/resourceArea.hpp"
32 #include "opto/arraycopynode.hpp"
33 #include "opto/c2compiler.hpp"
34 #include "opto/callnode.hpp"
35 #include "opto/castnode.hpp"
36 #include "opto/cfgnode.hpp"
37 #include "opto/compile.hpp"
38 #include "opto/escape.hpp"
39 #include "opto/locknode.hpp"
40 #include "opto/macro.hpp"
41 #include "opto/movenode.hpp"
42 #include "opto/narrowptrnode.hpp"
43 #include "opto/phaseX.hpp"
44 #include "opto/rootnode.hpp"
45 #include "utilities/macros.hpp"
46
47 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn, int invocation) :
48 // If ReduceAllocationMerges is enabled we might call split_through_phi during
49 // split_unique_types and that will create additional nodes that need to be
50 // pushed to the ConnectionGraph. The code below bumps the initial capacity of
51 // _nodes by 10% to account for these additional nodes. If capacity is exceeded
52 // the array will be reallocated.
53 _nodes(C->comp_arena(), C->do_reduce_allocation_merges() ? C->unique()*1.10 : C->unique(), C->unique(), nullptr),
54 _in_worklist(C->comp_arena()),
55 _next_pidx(0),
56 _collecting(true),
57 _verify(false),
58 _compile(C),
150 GrowableArray<SafePointNode*> sfn_worklist;
151 GrowableArray<MergeMemNode*> mergemem_worklist;
152 DEBUG_ONLY( GrowableArray<Node*> addp_worklist; )
153
154 { Compile::TracePhase tp(Phase::_t_connectionGraph);
155
156 // 1. Populate Connection Graph (CG) with PointsTo nodes.
157 ideal_nodes.map(C->live_nodes(), nullptr); // preallocate space
158 // Initialize worklist
159 if (C->root() != nullptr) {
160 ideal_nodes.push(C->root());
161 }
162 // Processed ideal nodes are unique on ideal_nodes list
163 // but several ideal nodes are mapped to the phantom_obj.
164 // To avoid duplicated entries on the following worklists
165 // add the phantom_obj only once to them.
166 ptnodes_worklist.append(phantom_obj);
167 java_objects_worklist.append(phantom_obj);
168 for( uint next = 0; next < ideal_nodes.size(); ++next ) {
169 Node* n = ideal_nodes.at(next);
170 // Create PointsTo nodes and add them to Connection Graph. Called
171 // only once per ideal node since ideal_nodes is Unique_Node list.
172 add_node_to_connection_graph(n, &delayed_worklist);
173 PointsToNode* ptn = ptnode_adr(n->_idx);
174 if (ptn != nullptr && ptn != phantom_obj) {
175 ptnodes_worklist.append(ptn);
176 if (ptn->is_JavaObject()) {
177 java_objects_worklist.append(ptn->as_JavaObject());
178 if ((n->is_Allocate() || n->is_CallStaticJava()) &&
179 (ptn->escape_state() < PointsToNode::GlobalEscape)) {
180 // Only allocations and java static calls results are interesting.
181 non_escaped_allocs_worklist.append(ptn->as_JavaObject());
182 }
183 } else if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
184 oop_fields_worklist.append(ptn->as_Field());
185 }
186 }
187 // Collect some interesting nodes for further use.
188 switch (n->Opcode()) {
189 case Op_MergeMem:
407 // scalar replaceable objects.
408 split_unique_types(alloc_worklist, arraycopy_worklist, mergemem_worklist, reducible_merges);
409 if (C->failing()) {
410 NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
411 return false;
412 }
413
414 #ifdef ASSERT
415 } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
416 tty->print("=== No allocations eliminated for ");
417 C->method()->print_short_name();
418 if (!EliminateAllocations) {
419 tty->print(" since EliminateAllocations is off ===");
420 } else if(!has_scalar_replaceable_candidates) {
421 tty->print(" since there are no scalar replaceable candidates ===");
422 }
423 tty->cr();
424 #endif
425 }
426
427 _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES, 4);
428
429 // 6. Reduce allocation merges used as debug information. This is done after
430 // split_unique_types because the methods used to create SafePointScalarObject
431 // need to traverse the memory graph to find values for object fields. We also
432 // set to null the scalarized inputs of reducible Phis so that the Allocate
433 // that they point can be later scalar replaced.
434 bool delay = _igvn->delay_transform();
435 _igvn->set_delay_transform(true);
436 for (uint i = 0; i < reducible_merges.size(); i++) {
437 Node* n = reducible_merges.at(i);
438 if (n->outcnt() > 0) {
439 if (!reduce_phi_on_safepoints(n->as_Phi())) {
440 NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
441 C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
442 return false;
443 }
444
445 // Now we set the scalar replaceable inputs of ophi to null, which is
446 // the last piece that would prevent it from being scalar replaceable.
447 reset_scalar_replaceable_entries(n->as_Phi());
448 }
449 }
1283
1284 // The next two inputs are:
1285 // (1) A copy of the original pointer to NSR objects.
1286 // (2) A selector, used to decide if we need to rematerialize an object
1287 // or use the pointer to a NSR object.
1288 // See more details of these fields in the declaration of SafePointScalarMergeNode
1289 sfpt->add_req(nsr_merge_pointer);
1290 sfpt->add_req(selector);
1291
1292 for (uint i = 1; i < ophi->req(); i++) {
1293 Node* base = ophi->in(i);
1294 JavaObjectNode* ptn = unique_java_object(base);
1295
1296 // If the base is not scalar replaceable we don't need to register information about
1297 // it at this time.
1298 if (ptn == nullptr || !ptn->scalar_replaceable()) {
1299 continue;
1300 }
1301
1302 AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
1303 SafePointScalarObjectNode* sobj = mexp.create_scalarized_object_description(alloc, sfpt);
1304 if (sobj == nullptr) {
1305 return false;
1306 }
1307
1308 // Now make a pass over the debug information replacing any references
1309 // to the allocated object with "sobj"
1310 Node* ccpp = alloc->result_cast();
1311 sfpt->replace_edges_in_range(ccpp, sobj, debug_start, jvms->debug_end(), _igvn);
1312
1313 // Register the scalarized object as a candidate for reallocation
1314 smerge->add_req(sobj);
1315 }
1316
1317 // Replaces debug information references to "original_sfpt_parent" in "sfpt" with references to "smerge"
1318 sfpt->replace_edges_in_range(original_sfpt_parent, smerge, debug_start, jvms->debug_end(), _igvn);
1319
1320 // The call to 'replace_edges_in_range' above might have removed the
1321 // reference to ophi that we need at _merge_pointer_idx. The line below make
1322 // sure the reference is maintained.
1323 sfpt->set_req(smerge->merge_pointer_idx(jvms), nsr_merge_pointer);
1324 _igvn->_worklist.push(sfpt);
1325 }
1326
1327 return true;
1328 }
1329
1330 void ConnectionGraph::reduce_phi(PhiNode* ophi, GrowableArray<Node*> &alloc_worklist) {
1331 bool delay = _igvn->delay_transform();
1332 _igvn->set_delay_transform(true);
1333 _igvn->hash_delete(ophi);
1334
1497 return false;
1498 }
1499
1500 // Returns true if at least one of the arguments to the call is an object
1501 // that does not escape globally.
1502 bool ConnectionGraph::has_arg_escape(CallJavaNode* call) {
1503 if (call->method() != nullptr) {
1504 uint max_idx = TypeFunc::Parms + call->method()->arg_size();
1505 for (uint idx = TypeFunc::Parms; idx < max_idx; idx++) {
1506 Node* p = call->in(idx);
1507 if (not_global_escape(p)) {
1508 return true;
1509 }
1510 }
1511 } else {
1512 const char* name = call->as_CallStaticJava()->_name;
1513 assert(name != nullptr, "no name");
1514 // no arg escapes through uncommon traps
1515 if (strcmp(name, "uncommon_trap") != 0) {
1516 // process_call_arguments() assumes that all arguments escape globally
1517 const TypeTuple* d = call->tf()->domain();
1518 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1519 const Type* at = d->field_at(i);
1520 if (at->isa_oopptr() != nullptr) {
1521 return true;
1522 }
1523 }
1524 }
1525 }
1526 return false;
1527 }
1528
1529
1530
1531 // Utility function for nodes that load an object
1532 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1533 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1534 // ThreadLocal has RawPtr type.
1535 const Type* t = _igvn->type(n);
1536 if (t->make_ptr() != nullptr) {
1537 Node* adr = n->in(MemNode::Address);
1571 // first IGVN optimization when escape information is still available.
1572 record_for_optimizer(n);
1573 } else if (n->is_Allocate()) {
1574 add_call_node(n->as_Call());
1575 record_for_optimizer(n);
1576 } else {
1577 if (n->is_CallStaticJava()) {
1578 const char* name = n->as_CallStaticJava()->_name;
1579 if (name != nullptr && strcmp(name, "uncommon_trap") == 0) {
1580 return; // Skip uncommon traps
1581 }
1582 }
1583 // Don't mark as processed since call's arguments have to be processed.
1584 delayed_worklist->push(n);
1585 // Check if a call returns an object.
1586 if ((n->as_Call()->returns_pointer() &&
1587 n->as_Call()->proj_out_or_null(TypeFunc::Parms) != nullptr) ||
1588 (n->is_CallStaticJava() &&
1589 n->as_CallStaticJava()->is_boxing_method())) {
1590 add_call_node(n->as_Call());
1591 }
1592 }
1593 return;
1594 }
1595 // Put this check here to process call arguments since some call nodes
1596 // point to phantom_obj.
1597 if (n_ptn == phantom_obj || n_ptn == null_obj) {
1598 return; // Skip predefined nodes.
1599 }
1600 switch (opcode) {
1601 case Op_AddP: {
1602 Node* base = get_addp_base(n);
1603 PointsToNode* ptn_base = ptnode_adr(base->_idx);
1604 // Field nodes are created for all field types. They are used in
1605 // adjust_scalar_replaceable_state() and split_unique_types().
1606 // Note, non-oop fields will have only base edges in Connection
1607 // Graph because such fields are not used for oop loads and stores.
1608 int offset = address_offset(n, igvn);
1609 add_field(n, PointsToNode::NoEscape, offset);
1610 if (ptn_base == nullptr) {
1611 delayed_worklist->push(n); // Process it later.
1612 } else {
1613 n_ptn = ptnode_adr(n_idx);
1614 add_base(n_ptn->as_Field(), ptn_base);
1615 }
1616 break;
1617 }
1618 case Op_CastX2P: {
1619 map_ideal_node(n, phantom_obj);
1620 break;
1621 }
1622 case Op_CastPP:
1623 case Op_CheckCastPP:
1624 case Op_EncodeP:
1625 case Op_DecodeN:
1626 case Op_EncodePKlass:
1627 case Op_DecodeNKlass: {
1628 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1629 break;
1630 }
1631 case Op_CMoveP: {
1632 add_local_var(n, PointsToNode::NoEscape);
1633 // Do not add edges during first iteration because some could be
1634 // not defined yet.
1635 delayed_worklist->push(n);
1636 break;
1637 }
1638 case Op_ConP:
1639 case Op_ConN:
1640 case Op_ConNKlass: {
1641 // assume all oop constants globally escape except for null
1671 break;
1672 }
1673 case Op_PartialSubtypeCheck: {
1674 // Produces Null or notNull and is used in only in CmpP so
1675 // phantom_obj could be used.
1676 map_ideal_node(n, phantom_obj); // Result is unknown
1677 break;
1678 }
1679 case Op_Phi: {
1680 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1681 // ThreadLocal has RawPtr type.
1682 const Type* t = n->as_Phi()->type();
1683 if (t->make_ptr() != nullptr) {
1684 add_local_var(n, PointsToNode::NoEscape);
1685 // Do not add edges during first iteration because some could be
1686 // not defined yet.
1687 delayed_worklist->push(n);
1688 }
1689 break;
1690 }
1691 case Op_Proj: {
1692 // we are only interested in the oop result projection from a call
1693 if (n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
1694 n->in(0)->as_Call()->returns_pointer()) {
1695 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1696 }
1697 break;
1698 }
1699 case Op_Rethrow: // Exception object escapes
1700 case Op_Return: {
1701 if (n->req() > TypeFunc::Parms &&
1702 igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
1703 // Treat Return value as LocalVar with GlobalEscape escape state.
1704 add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), delayed_worklist);
1705 }
1706 break;
1707 }
1708 case Op_CompareAndExchangeP:
1709 case Op_CompareAndExchangeN:
1710 case Op_GetAndSetP:
1711 case Op_GetAndSetN: {
1712 add_objload_to_connection_graph(n, delayed_worklist);
1713 // fall-through
1714 }
1760 break;
1761 }
1762 default:
1763 ; // Do nothing for nodes not related to EA.
1764 }
1765 return;
1766 }
1767
1768 // Add final simple edges to graph.
1769 void ConnectionGraph::add_final_edges(Node *n) {
1770 PointsToNode* n_ptn = ptnode_adr(n->_idx);
1771 #ifdef ASSERT
1772 if (_verify && n_ptn->is_JavaObject())
1773 return; // This method does not change graph for JavaObject.
1774 #endif
1775
1776 if (n->is_Call()) {
1777 process_call_arguments(n->as_Call());
1778 return;
1779 }
1780 assert(n->is_Store() || n->is_LoadStore() ||
1781 ((n_ptn != nullptr) && (n_ptn->ideal_node() != nullptr)),
1782 "node should be registered already");
1783 int opcode = n->Opcode();
1784 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_final_edges(this, _igvn, n, opcode);
1785 if (gc_handled) {
1786 return; // Ignore node if already handled by GC.
1787 }
1788 switch (opcode) {
1789 case Op_AddP: {
1790 Node* base = get_addp_base(n);
1791 PointsToNode* ptn_base = ptnode_adr(base->_idx);
1792 assert(ptn_base != nullptr, "field's base should be registered");
1793 add_base(n_ptn->as_Field(), ptn_base);
1794 break;
1795 }
1796 case Op_CastPP:
1797 case Op_CheckCastPP:
1798 case Op_EncodeP:
1799 case Op_DecodeN:
1800 case Op_EncodePKlass:
1801 case Op_DecodeNKlass: {
1802 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), nullptr);
1803 break;
1804 }
1805 case Op_CMoveP: {
1806 for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
1807 Node* in = n->in(i);
1808 if (in == nullptr) {
1809 continue; // ignore null
1810 }
1811 Node* uncast_in = in->uncast();
1812 if (uncast_in->is_top() || uncast_in == n) {
1813 continue; // ignore top or inputs which go back this node
1814 }
1815 PointsToNode* ptn = ptnode_adr(in->_idx);
1828 }
1829 case Op_Phi: {
1830 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1831 // ThreadLocal has RawPtr type.
1832 assert(n->as_Phi()->type()->make_ptr() != nullptr, "Unexpected node type");
1833 for (uint i = 1; i < n->req(); i++) {
1834 Node* in = n->in(i);
1835 if (in == nullptr) {
1836 continue; // ignore null
1837 }
1838 Node* uncast_in = in->uncast();
1839 if (uncast_in->is_top() || uncast_in == n) {
1840 continue; // ignore top or inputs which go back this node
1841 }
1842 PointsToNode* ptn = ptnode_adr(in->_idx);
1843 assert(ptn != nullptr, "node should be registered");
1844 add_edge(n_ptn, ptn);
1845 }
1846 break;
1847 }
1848 case Op_Proj: {
1849 // we are only interested in the oop result projection from a call
1850 assert(n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->is_Call() &&
1851 n->in(0)->as_Call()->returns_pointer(), "Unexpected node type");
1852 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), nullptr);
1853 break;
1854 }
1855 case Op_Rethrow: // Exception object escapes
1856 case Op_Return: {
1857 assert(n->req() > TypeFunc::Parms && _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr(),
1858 "Unexpected node type");
1859 // Treat Return value as LocalVar with GlobalEscape escape state.
1860 add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), nullptr);
1861 break;
1862 }
1863 case Op_CompareAndExchangeP:
1864 case Op_CompareAndExchangeN:
1865 case Op_GetAndSetP:
1866 case Op_GetAndSetN:{
1867 assert(_igvn->type(n)->make_ptr() != nullptr, "Unexpected node type");
1868 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), nullptr);
1869 // fall-through
1870 }
1871 case Op_CompareAndSwapP:
1872 case Op_CompareAndSwapN:
2007 PointsToNode* ptn = ptnode_adr(val->_idx);
2008 assert(ptn != nullptr, "node should be registered");
2009 set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "stored at raw address"));
2010 // Add edge to object for unsafe access with offset.
2011 PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
2012 assert(adr_ptn != nullptr, "node should be registered");
2013 if (adr_ptn->is_Field()) {
2014 assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
2015 add_edge(adr_ptn, ptn);
2016 }
2017 return true;
2018 }
2019 #ifdef ASSERT
2020 n->dump(1);
2021 assert(false, "not unsafe");
2022 #endif
2023 return false;
2024 }
2025
2026 void ConnectionGraph::add_call_node(CallNode* call) {
2027 assert(call->returns_pointer(), "only for call which returns pointer");
2028 uint call_idx = call->_idx;
2029 if (call->is_Allocate()) {
2030 Node* k = call->in(AllocateNode::KlassNode);
2031 const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
2032 assert(kt != nullptr, "TypeKlassPtr required.");
2033 PointsToNode::EscapeState es = PointsToNode::NoEscape;
2034 bool scalar_replaceable = true;
2035 NOT_PRODUCT(const char* nsr_reason = "");
2036 if (call->is_AllocateArray()) {
2037 if (!kt->isa_aryklassptr()) { // StressReflectiveCode
2038 es = PointsToNode::GlobalEscape;
2039 } else {
2040 int length = call->in(AllocateNode::ALength)->find_int_con(-1);
2041 if (length < 0) {
2042 // Not scalar replaceable if the length is not constant.
2043 scalar_replaceable = false;
2044 NOT_PRODUCT(nsr_reason = "has a non-constant length");
2045 } else if (length > EliminateAllocationArraySizeLimit) {
2046 // Not scalar replaceable if the length is too big.
2047 scalar_replaceable = false;
2082 // - mapped to GlobalEscape JavaObject node if oop is returned;
2083 //
2084 // - all oop arguments are escaping globally;
2085 //
2086 // 2. CallStaticJavaNode (execute bytecode analysis if possible):
2087 //
2088 // - the same as CallDynamicJavaNode if can't do bytecode analysis;
2089 //
2090 // - mapped to GlobalEscape JavaObject node if unknown oop is returned;
2091 // - mapped to NoEscape JavaObject node if non-escaping object allocated
2092 // during call is returned;
2093 // - mapped to ArgEscape LocalVar node pointed to object arguments
2094 // which are returned and does not escape during call;
2095 //
2096 // - oop arguments escaping status is defined by bytecode analysis;
2097 //
2098 // For a static call, we know exactly what method is being called.
2099 // Use bytecode estimator to record whether the call's return value escapes.
2100 ciMethod* meth = call->as_CallJava()->method();
2101 if (meth == nullptr) {
2102 assert(call->as_CallStaticJava()->is_call_to_multianewarray_stub(), "TODO: add failed case check");
2103 // Returns a newly allocated non-escaped object.
2104 add_java_object(call, PointsToNode::NoEscape);
2105 set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of multinewarray"));
2106 } else if (meth->is_boxing_method()) {
2107 // Returns boxing object
2108 PointsToNode::EscapeState es;
2109 vmIntrinsics::ID intr = meth->intrinsic_id();
2110 if (intr == vmIntrinsics::_floatValue || intr == vmIntrinsics::_doubleValue) {
2111 // It does not escape if object is always allocated.
2112 es = PointsToNode::NoEscape;
2113 } else {
2114 // It escapes globally if object could be loaded from cache.
2115 es = PointsToNode::GlobalEscape;
2116 }
2117 add_java_object(call, es);
2118 if (es == PointsToNode::GlobalEscape) {
2119 set_not_scalar_replaceable(ptnode_adr(call->_idx) NOT_PRODUCT(COMMA "object can be loaded from boxing cache"));
2120 }
2121 } else {
2122 BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
2123 call_analyzer->copy_dependencies(_compile->dependencies());
2124 if (call_analyzer->is_return_allocated()) {
2125 // Returns a newly allocated non-escaped object, simply
2126 // update dependency information.
2127 // Mark it as NoEscape so that objects referenced by
2128 // it's fields will be marked as NoEscape at least.
2129 add_java_object(call, PointsToNode::NoEscape);
2130 set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of call"));
2131 } else {
2132 // Determine whether any arguments are returned.
2133 const TypeTuple* d = call->tf()->domain();
2134 bool ret_arg = false;
2135 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2136 if (d->field_at(i)->isa_ptr() != nullptr &&
2137 call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
2138 ret_arg = true;
2139 break;
2140 }
2141 }
2142 if (ret_arg) {
2143 add_local_var(call, PointsToNode::ArgEscape);
2144 } else {
2145 // Returns unknown object.
2146 map_ideal_node(call, phantom_obj);
2147 }
2148 }
2149 }
2150 } else {
2151 // An other type of call, assume the worst case:
2152 // returned value is unknown and globally escapes.
2153 assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
2161 #ifdef ASSERT
2162 case Op_Allocate:
2163 case Op_AllocateArray:
2164 case Op_Lock:
2165 case Op_Unlock:
2166 assert(false, "should be done already");
2167 break;
2168 #endif
2169 case Op_ArrayCopy:
2170 case Op_CallLeafNoFP:
2171 // Most array copies are ArrayCopy nodes at this point but there
2172 // are still a few direct calls to the copy subroutines (See
2173 // PhaseStringOpts::copy_string())
2174 is_arraycopy = (call->Opcode() == Op_ArrayCopy) ||
2175 call->as_CallLeaf()->is_call_to_arraycopystub();
2176 // fall through
2177 case Op_CallLeafVector:
2178 case Op_CallLeaf: {
2179 // Stub calls, objects do not escape but they are not scale replaceable.
2180 // Adjust escape state for outgoing arguments.
2181 const TypeTuple * d = call->tf()->domain();
2182 bool src_has_oops = false;
2183 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2184 const Type* at = d->field_at(i);
2185 Node *arg = call->in(i);
2186 if (arg == nullptr) {
2187 continue;
2188 }
2189 const Type *aat = _igvn->type(arg);
2190 if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr()) {
2191 continue;
2192 }
2193 if (arg->is_AddP()) {
2194 //
2195 // The inline_native_clone() case when the arraycopy stub is called
2196 // after the allocation before Initialize and CheckCastPP nodes.
2197 // Or normal arraycopy for object arrays case.
2198 //
2199 // Set AddP's base (Allocate) as not scalar replaceable since
2200 // pointer to the base (with offset) is passed as argument.
2201 //
2202 arg = get_addp_base(arg);
2203 }
2204 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2205 assert(arg_ptn != nullptr, "should be registered");
2206 PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
2207 if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
2208 assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
2209 aat->isa_ptr() != nullptr, "expecting an Ptr");
2210 bool arg_has_oops = aat->isa_oopptr() &&
2211 (aat->isa_instptr() ||
2212 (aat->isa_aryptr() && (aat->isa_aryptr()->elem() == Type::BOTTOM || aat->isa_aryptr()->elem()->make_oopptr() != nullptr)));
2213 if (i == TypeFunc::Parms) {
2214 src_has_oops = arg_has_oops;
2215 }
2216 //
2217 // src or dst could be j.l.Object when other is basic type array:
2218 //
2219 // arraycopy(char[],0,Object*,0,size);
2220 // arraycopy(Object*,0,char[],0,size);
2221 //
2222 // Don't add edges in such cases.
2223 //
2224 bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
2225 arg_has_oops && (i > TypeFunc::Parms);
2226 #ifdef ASSERT
2227 if (!(is_arraycopy ||
2228 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(call) ||
2229 (call->as_CallLeaf()->_name != nullptr &&
2230 (strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 ||
2231 strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32C") == 0 ||
2232 strcmp(call->as_CallLeaf()->_name, "updateBytesAdler32") == 0 ||
2256 strcmp(call->as_CallLeaf()->_name, "dilithiumMontMulByConstant") == 0 ||
2257 strcmp(call->as_CallLeaf()->_name, "dilithiumDecomposePoly") == 0 ||
2258 strcmp(call->as_CallLeaf()->_name, "encodeBlock") == 0 ||
2259 strcmp(call->as_CallLeaf()->_name, "decodeBlock") == 0 ||
2260 strcmp(call->as_CallLeaf()->_name, "md5_implCompress") == 0 ||
2261 strcmp(call->as_CallLeaf()->_name, "md5_implCompressMB") == 0 ||
2262 strcmp(call->as_CallLeaf()->_name, "sha1_implCompress") == 0 ||
2263 strcmp(call->as_CallLeaf()->_name, "sha1_implCompressMB") == 0 ||
2264 strcmp(call->as_CallLeaf()->_name, "sha256_implCompress") == 0 ||
2265 strcmp(call->as_CallLeaf()->_name, "sha256_implCompressMB") == 0 ||
2266 strcmp(call->as_CallLeaf()->_name, "sha512_implCompress") == 0 ||
2267 strcmp(call->as_CallLeaf()->_name, "sha512_implCompressMB") == 0 ||
2268 strcmp(call->as_CallLeaf()->_name, "sha3_implCompress") == 0 ||
2269 strcmp(call->as_CallLeaf()->_name, "double_keccak") == 0 ||
2270 strcmp(call->as_CallLeaf()->_name, "sha3_implCompressMB") == 0 ||
2271 strcmp(call->as_CallLeaf()->_name, "multiplyToLen") == 0 ||
2272 strcmp(call->as_CallLeaf()->_name, "squareToLen") == 0 ||
2273 strcmp(call->as_CallLeaf()->_name, "mulAdd") == 0 ||
2274 strcmp(call->as_CallLeaf()->_name, "montgomery_multiply") == 0 ||
2275 strcmp(call->as_CallLeaf()->_name, "montgomery_square") == 0 ||
2276 strcmp(call->as_CallLeaf()->_name, "bigIntegerRightShiftWorker") == 0 ||
2277 strcmp(call->as_CallLeaf()->_name, "bigIntegerLeftShiftWorker") == 0 ||
2278 strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2279 strcmp(call->as_CallLeaf()->_name, "stringIndexOf") == 0 ||
2280 strcmp(call->as_CallLeaf()->_name, "arraysort_stub") == 0 ||
2281 strcmp(call->as_CallLeaf()->_name, "array_partition_stub") == 0 ||
2282 strcmp(call->as_CallLeaf()->_name, "get_class_id_intrinsic") == 0 ||
2283 strcmp(call->as_CallLeaf()->_name, "unsafe_setmemory") == 0)
2284 ))) {
2285 call->dump();
2286 fatal("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name);
2287 }
2288 #endif
2289 // Always process arraycopy's destination object since
2290 // we need to add all possible edges to references in
2291 // source object.
2292 if (arg_esc >= PointsToNode::ArgEscape &&
2293 !arg_is_arraycopy_dest) {
2294 continue;
2295 }
2318 }
2319 }
2320 }
2321 break;
2322 }
2323 case Op_CallStaticJava: {
2324 // For a static call, we know exactly what method is being called.
2325 // Use bytecode estimator to record the call's escape affects
2326 #ifdef ASSERT
2327 const char* name = call->as_CallStaticJava()->_name;
2328 assert((name == nullptr || strcmp(name, "uncommon_trap") != 0), "normal calls only");
2329 #endif
2330 ciMethod* meth = call->as_CallJava()->method();
2331 if ((meth != nullptr) && meth->is_boxing_method()) {
2332 break; // Boxing methods do not modify any oops.
2333 }
2334 BCEscapeAnalyzer* call_analyzer = (meth !=nullptr) ? meth->get_bcea() : nullptr;
2335 // fall-through if not a Java method or no analyzer information
2336 if (call_analyzer != nullptr) {
2337 PointsToNode* call_ptn = ptnode_adr(call->_idx);
2338 const TypeTuple* d = call->tf()->domain();
2339 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2340 const Type* at = d->field_at(i);
2341 int k = i - TypeFunc::Parms;
2342 Node* arg = call->in(i);
2343 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2344 if (at->isa_ptr() != nullptr &&
2345 call_analyzer->is_arg_returned(k)) {
2346 // The call returns arguments.
2347 if (call_ptn != nullptr) { // Is call's result used?
2348 assert(call_ptn->is_LocalVar(), "node should be registered");
2349 assert(arg_ptn != nullptr, "node should be registered");
2350 add_edge(call_ptn, arg_ptn);
2351 }
2352 }
2353 if (at->isa_oopptr() != nullptr &&
2354 arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
2355 if (!call_analyzer->is_arg_stack(k)) {
2356 // The argument global escapes
2357 set_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2358 } else {
2362 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2363 }
2364 }
2365 }
2366 }
2367 if (call_ptn != nullptr && call_ptn->is_LocalVar()) {
2368 // The call returns arguments.
2369 assert(call_ptn->edge_count() > 0, "sanity");
2370 if (!call_analyzer->is_return_local()) {
2371 // Returns also unknown object.
2372 add_edge(call_ptn, phantom_obj);
2373 }
2374 }
2375 break;
2376 }
2377 }
2378 default: {
2379 // Fall-through here if not a Java method or no analyzer information
2380 // or some other type of call, assume the worst case: all arguments
2381 // globally escape.
2382 const TypeTuple* d = call->tf()->domain();
2383 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2384 const Type* at = d->field_at(i);
2385 if (at->isa_oopptr() != nullptr) {
2386 Node* arg = call->in(i);
2387 if (arg->is_AddP()) {
2388 arg = get_addp_base(arg);
2389 }
2390 assert(ptnode_adr(arg->_idx) != nullptr, "should be defined already");
2391 set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2392 }
2393 }
2394 }
2395 }
2396 }
2397
2398
2399 // Finish Graph construction.
2400 bool ConnectionGraph::complete_connection_graph(
2401 GrowableArray<PointsToNode*>& ptnodes_worklist,
2402 GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
2780 PointsToNode* base = i.get();
2781 if (base->is_JavaObject()) {
2782 // Skip Allocate's fields which will be processed later.
2783 if (base->ideal_node()->is_Allocate()) {
2784 return 0;
2785 }
2786 assert(base == null_obj, "only null ptr base expected here");
2787 }
2788 }
2789 if (add_edge(field, phantom_obj)) {
2790 // New edge was added
2791 new_edges++;
2792 add_field_uses_to_worklist(field);
2793 }
2794 return new_edges;
2795 }
2796
2797 // Find fields initializing values for allocations.
2798 int ConnectionGraph::find_init_values_phantom(JavaObjectNode* pta) {
2799 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2800 Node* alloc = pta->ideal_node();
2801
2802 // Do nothing for Allocate nodes since its fields values are
2803 // "known" unless they are initialized by arraycopy/clone.
2804 if (alloc->is_Allocate() && !pta->arraycopy_dst()) {
2805 return 0;
2806 }
2807 assert(pta->arraycopy_dst() || alloc->as_CallStaticJava(), "sanity");
2808 #ifdef ASSERT
2809 if (!pta->arraycopy_dst() && alloc->as_CallStaticJava()->method() == nullptr) {
2810 assert(alloc->as_CallStaticJava()->is_call_to_multianewarray_stub(), "sanity");
2811 }
2812 #endif
2813 // Non-escaped allocation returned from Java or runtime call have unknown values in fields.
2814 int new_edges = 0;
2815 for (EdgeIterator i(pta); i.has_next(); i.next()) {
2816 PointsToNode* field = i.get();
2817 if (field->is_Field() && field->as_Field()->is_oop()) {
2818 if (add_edge(field, phantom_obj)) {
2819 // New edge was added
2820 new_edges++;
2821 add_field_uses_to_worklist(field->as_Field());
2822 }
2823 }
2824 }
2825 return new_edges;
2826 }
2827
2828 // Find fields initializing values for allocations.
2829 int ConnectionGraph::find_init_values_null(JavaObjectNode* pta, PhaseValues* phase) {
2830 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2831 Node* alloc = pta->ideal_node();
2832 // Do nothing for Call nodes since its fields values are unknown.
2833 if (!alloc->is_Allocate()) {
2834 return 0;
2835 }
2836 InitializeNode* ini = alloc->as_Allocate()->initialization();
2837 bool visited_bottom_offset = false;
2838 GrowableArray<int> offsets_worklist;
2839 int new_edges = 0;
2840
2841 // Check if an oop field's initializing value is recorded and add
2842 // a corresponding null if field's value if it is not recorded.
2843 // Connection Graph does not record a default initialization by null
2844 // captured by Initialize node.
2845 //
2846 for (EdgeIterator i(pta); i.has_next(); i.next()) {
2847 PointsToNode* field = i.get(); // Field (AddP)
2848 if (!field->is_Field() || !field->as_Field()->is_oop()) {
2849 continue; // Not oop field
2850 }
2851 int offset = field->as_Field()->offset();
2852 if (offset == Type::OffsetBot) {
2853 if (!visited_bottom_offset) {
2899 } else {
2900 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
2901 tty->print_cr("----------init store has invalid value -----");
2902 store->dump();
2903 val->dump();
2904 assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
2905 }
2906 for (EdgeIterator j(val); j.has_next(); j.next()) {
2907 PointsToNode* obj = j.get();
2908 if (obj->is_JavaObject()) {
2909 if (!field->points_to(obj->as_JavaObject())) {
2910 missed_obj = obj;
2911 break;
2912 }
2913 }
2914 }
2915 }
2916 if (missed_obj != nullptr) {
2917 tty->print_cr("----------field---------------------------------");
2918 field->dump();
2919 tty->print_cr("----------missed referernce to object-----------");
2920 missed_obj->dump();
2921 tty->print_cr("----------object referernced by init store -----");
2922 store->dump();
2923 val->dump();
2924 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
2925 }
2926 }
2927 #endif
2928 } else {
2929 // There could be initializing stores which follow allocation.
2930 // For example, a volatile field store is not collected
2931 // by Initialize node.
2932 //
2933 // Need to check for dependent loads to separate such stores from
2934 // stores which follow loads. For now, add initial value null so
2935 // that compare pointers optimization works correctly.
2936 }
2937 }
2938 if (value == nullptr) {
2939 // A field's initializing value was not recorded. Add null.
2940 if (add_edge(field, null_obj)) {
2941 // New edge was added
3266 assert(field->edge_count() > 0, "sanity");
3267 }
3268 }
3269 }
3270 }
3271 #endif
3272
3273 // Optimize ideal graph.
3274 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
3275 GrowableArray<MemBarStoreStoreNode*>& storestore_worklist) {
3276 Compile* C = _compile;
3277 PhaseIterGVN* igvn = _igvn;
3278 if (EliminateLocks) {
3279 // Mark locks before changing ideal graph.
3280 int cnt = C->macro_count();
3281 for (int i = 0; i < cnt; i++) {
3282 Node *n = C->macro_node(i);
3283 if (n->is_AbstractLock()) { // Lock and Unlock nodes
3284 AbstractLockNode* alock = n->as_AbstractLock();
3285 if (!alock->is_non_esc_obj()) {
3286 if (can_eliminate_lock(alock)) {
3287 assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
3288 // The lock could be marked eliminated by lock coarsening
3289 // code during first IGVN before EA. Replace coarsened flag
3290 // to eliminate all associated locks/unlocks.
3291 #ifdef ASSERT
3292 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc3");
3293 #endif
3294 alock->set_non_esc_obj();
3295 }
3296 }
3297 }
3298 }
3299 }
3300
3301 if (OptimizePtrCompare) {
3302 for (int i = 0; i < ptr_cmp_worklist.length(); i++) {
3303 Node *n = ptr_cmp_worklist.at(i);
3304 assert(n->Opcode() == Op_CmpN || n->Opcode() == Op_CmpP, "must be");
3305 const TypeInt* tcmp = optimize_ptr_compare(n->in(1), n->in(2));
3306 if (tcmp->singleton()) {
3308 #ifndef PRODUCT
3309 if (PrintOptimizePtrCompare) {
3310 tty->print_cr("++++ Replaced: %d %s(%d,%d) --> %s", n->_idx, (n->Opcode() == Op_CmpP ? "CmpP" : "CmpN"), n->in(1)->_idx, n->in(2)->_idx, (tcmp == TypeInt::CC_EQ ? "EQ" : "NotEQ"));
3311 if (Verbose) {
3312 n->dump(1);
3313 }
3314 }
3315 #endif
3316 igvn->replace_node(n, cmp);
3317 }
3318 }
3319 }
3320
3321 // For MemBarStoreStore nodes added in library_call.cpp, check
3322 // escape status of associated AllocateNode and optimize out
3323 // MemBarStoreStore node if the allocated object never escapes.
3324 for (int i = 0; i < storestore_worklist.length(); i++) {
3325 Node* storestore = storestore_worklist.at(i);
3326 Node* alloc = storestore->in(MemBarNode::Precedent)->in(0);
3327 if (alloc->is_Allocate() && not_global_escape(alloc)) {
3328 MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
3329 mb->init_req(TypeFunc::Memory, storestore->in(TypeFunc::Memory));
3330 mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
3331 igvn->register_new_node_with_optimizer(mb);
3332 igvn->replace_node(storestore, mb);
3333 }
3334 }
3335 }
3336
3337 // Optimize objects compare.
3338 const TypeInt* ConnectionGraph::optimize_ptr_compare(Node* left, Node* right) {
3339 const TypeInt* UNKNOWN = TypeInt::CC; // [-1, 0,1]
3340 if (!OptimizePtrCompare) {
3341 return UNKNOWN;
3342 }
3343 const TypeInt* EQ = TypeInt::CC_EQ; // [0] == ZERO
3344 const TypeInt* NE = TypeInt::CC_GT; // [1] == ONE
3345
3346 PointsToNode* ptn1 = ptnode_adr(left->_idx);
3347 PointsToNode* ptn2 = ptnode_adr(right->_idx);
3348 JavaObjectNode* jobj1 = unique_java_object(left);
3349 JavaObjectNode* jobj2 = unique_java_object(right);
3350
3351 // The use of this method during allocation merge reduction may cause 'left'
3352 // or 'right' be something (e.g., a Phi) that isn't in the connection graph or
3353 // that doesn't reference an unique java object.
3354 if (ptn1 == nullptr || ptn2 == nullptr ||
3355 jobj1 == nullptr || jobj2 == nullptr) {
3356 return UNKNOWN;
3476 assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
3477 assert((src != null_obj) && (dst != null_obj), "not for ConP null");
3478 PointsToNode* ptadr = _nodes.at(n->_idx);
3479 if (ptadr != nullptr) {
3480 assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
3481 return;
3482 }
3483 Compile* C = _compile;
3484 ptadr = new (C->comp_arena()) ArraycopyNode(this, n, es);
3485 map_ideal_node(n, ptadr);
3486 // Add edge from arraycopy node to source object.
3487 (void)add_edge(ptadr, src);
3488 src->set_arraycopy_src();
3489 // Add edge from destination object to arraycopy node.
3490 (void)add_edge(dst, ptadr);
3491 dst->set_arraycopy_dst();
3492 }
3493
3494 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
3495 const Type* adr_type = n->as_AddP()->bottom_type();
3496 BasicType bt = T_INT;
3497 if (offset == Type::OffsetBot) {
3498 // Check only oop fields.
3499 if (!adr_type->isa_aryptr() ||
3500 adr_type->isa_aryptr()->elem() == Type::BOTTOM ||
3501 adr_type->isa_aryptr()->elem()->make_oopptr() != nullptr) {
3502 // OffsetBot is used to reference array's element. Ignore first AddP.
3503 if (find_second_addp(n, n->in(AddPNode::Base)) == nullptr) {
3504 bt = T_OBJECT;
3505 }
3506 }
3507 } else if (offset != oopDesc::klass_offset_in_bytes()) {
3508 if (adr_type->isa_instptr()) {
3509 ciField* field = _compile->alias_type(adr_type->isa_instptr())->field();
3510 if (field != nullptr) {
3511 bt = field->layout_type();
3512 } else {
3513 // Check for unsafe oop field access
3514 if (n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3515 n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3516 n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3517 BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n)) {
3518 bt = T_OBJECT;
3519 (*unsafe) = true;
3520 }
3521 }
3522 } else if (adr_type->isa_aryptr()) {
3523 if (offset == arrayOopDesc::length_offset_in_bytes()) {
3524 // Ignore array length load.
3525 } else if (find_second_addp(n, n->in(AddPNode::Base)) != nullptr) {
3526 // Ignore first AddP.
3527 } else {
3528 const Type* elemtype = adr_type->isa_aryptr()->elem();
3529 bt = elemtype->array_element_basic_type();
3530 }
3531 } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
3532 // Allocation initialization, ThreadLocal field access, unsafe access
3533 if (n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3534 n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3535 n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3536 BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n)) {
3537 bt = T_OBJECT;
3538 }
3539 }
3540 }
3541 // Note: T_NARROWOOP is not classed as a real reference type
3542 return (is_reference_type(bt) || bt == T_NARROWOOP);
3543 }
3544
3545 // Returns unique pointed java object or null.
3546 JavaObjectNode* ConnectionGraph::unique_java_object(Node *n) const {
3547 // If the node was created after the escape computation we can't answer.
3548 uint idx = n->_idx;
3549 if (idx >= nodes_size()) {
3706 return true;
3707 }
3708 }
3709 }
3710 }
3711 }
3712 return false;
3713 }
3714
3715 int ConnectionGraph::address_offset(Node* adr, PhaseValues* phase) {
3716 const Type *adr_type = phase->type(adr);
3717 if (adr->is_AddP() && adr_type->isa_oopptr() == nullptr && is_captured_store_address(adr)) {
3718 // We are computing a raw address for a store captured by an Initialize
3719 // compute an appropriate address type. AddP cases #3 and #5 (see below).
3720 int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
3721 assert(offs != Type::OffsetBot ||
3722 adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
3723 "offset must be a constant or it is initialization of array");
3724 return offs;
3725 }
3726 const TypePtr *t_ptr = adr_type->isa_ptr();
3727 assert(t_ptr != nullptr, "must be a pointer type");
3728 return t_ptr->offset();
3729 }
3730
3731 Node* ConnectionGraph::get_addp_base(Node *addp) {
3732 assert(addp->is_AddP(), "must be AddP");
3733 //
3734 // AddP cases for Base and Address inputs:
3735 // case #1. Direct object's field reference:
3736 // Allocate
3737 // |
3738 // Proj #5 ( oop result )
3739 // |
3740 // CheckCastPP (cast to instance type)
3741 // | |
3742 // AddP ( base == address )
3743 //
3744 // case #2. Indirect object's field reference:
3745 // Phi
3746 // |
3747 // CastPP (cast to instance type)
3748 // | |
3862 }
3863 return nullptr;
3864 }
3865
3866 //
3867 // Adjust the type and inputs of an AddP which computes the
3868 // address of a field of an instance
3869 //
3870 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
3871 PhaseGVN* igvn = _igvn;
3872 const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
3873 assert(base_t != nullptr && base_t->is_known_instance(), "expecting instance oopptr");
3874 const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
3875 if (t == nullptr) {
3876 // We are computing a raw address for a store captured by an Initialize
3877 // compute an appropriate address type (cases #3 and #5).
3878 assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
3879 assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
3880 intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
3881 assert(offs != Type::OffsetBot, "offset must be a constant");
3882 t = base_t->add_offset(offs)->is_oopptr();
3883 }
3884 int inst_id = base_t->instance_id();
3885 assert(!t->is_known_instance() || t->instance_id() == inst_id,
3886 "old type must be non-instance or match new type");
3887
3888 // The type 't' could be subclass of 'base_t'.
3889 // As result t->offset() could be large then base_t's size and it will
3890 // cause the failure in add_offset() with narrow oops since TypeOopPtr()
3891 // constructor verifies correctness of the offset.
3892 //
3893 // It could happened on subclass's branch (from the type profiling
3894 // inlining) which was not eliminated during parsing since the exactness
3895 // of the allocation type was not propagated to the subclass type check.
3896 //
3897 // Or the type 't' could be not related to 'base_t' at all.
3898 // It could happened when CHA type is different from MDO type on a dead path
3899 // (for example, from instanceof check) which is not collapsed during parsing.
3900 //
3901 // Do nothing for such AddP node and don't process its users since
3902 // this code branch will go away.
3903 //
3904 if (!t->is_known_instance() &&
3905 !base_t->maybe_java_subtype_of(t)) {
3906 return false; // bail out
3907 }
3908 const TypeOopPtr *tinst = base_t->add_offset(t->offset())->is_oopptr();
3909 // Do NOT remove the next line: ensure a new alias index is allocated
3910 // for the instance type. Note: C++ will not remove it since the call
3911 // has side effect.
3912 int alias_idx = _compile->get_alias_index(tinst);
3913 igvn->set_type(addp, tinst);
3914 // record the allocation in the node map
3915 set_map(addp, get_map(base->_idx));
3916 // Set addp's Base and Address to 'base'.
3917 Node *abase = addp->in(AddPNode::Base);
3918 Node *adr = addp->in(AddPNode::Address);
3919 if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
3920 adr->in(0)->_idx == (uint)inst_id) {
3921 // Skip AddP cases #3 and #5.
3922 } else {
3923 assert(!abase->is_top(), "sanity"); // AddP case #3
3924 if (abase != base) {
3925 igvn->hash_delete(addp);
3926 addp->set_req(AddPNode::Base, base);
3927 if (abase == adr) {
3928 addp->set_req(AddPNode::Address, base);
4498 // - not determined to be ineligible by escape analysis
4499 set_map(alloc, n);
4500 set_map(n, alloc);
4501 const TypeOopPtr* tinst = t->cast_to_instance_id(ni);
4502 igvn->hash_delete(n);
4503 igvn->set_type(n, tinst);
4504 n->raise_bottom_type(tinst);
4505 igvn->hash_insert(n);
4506 record_for_optimizer(n);
4507 // Allocate an alias index for the header fields. Accesses to
4508 // the header emitted during macro expansion wouldn't have
4509 // correct memory state otherwise.
4510 _compile->get_alias_index(tinst->add_offset(oopDesc::mark_offset_in_bytes()));
4511 _compile->get_alias_index(tinst->add_offset(oopDesc::klass_offset_in_bytes()));
4512 if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
4513 // Add a new NarrowMem projection for each existing NarrowMem projection with new adr type
4514 InitializeNode* init = alloc->as_Allocate()->initialization();
4515 assert(init != nullptr, "can't find Initialization node for this Allocate node");
4516 auto process_narrow_proj = [&](NarrowMemProjNode* proj) {
4517 const TypePtr* adr_type = proj->adr_type();
4518 const TypePtr* new_adr_type = tinst->add_offset(adr_type->offset());
4519 if (adr_type != new_adr_type && !init->already_has_narrow_mem_proj_with_adr_type(new_adr_type)) {
4520 DEBUG_ONLY( uint alias_idx = _compile->get_alias_index(new_adr_type); )
4521 assert(_compile->get_general_index(alias_idx) == _compile->get_alias_index(adr_type), "new adr type should be narrowed down from existing adr type");
4522 NarrowMemProjNode* new_proj = new NarrowMemProjNode(init, new_adr_type);
4523 igvn->set_type(new_proj, new_proj->bottom_type());
4524 record_for_optimizer(new_proj);
4525 set_map(proj, new_proj); // record it so ConnectionGraph::find_inst_mem() can find it
4526 }
4527 };
4528 init->for_each_narrow_mem_proj_with_new_uses(process_narrow_proj);
4529
4530 // First, put on the worklist all Field edges from Connection Graph
4531 // which is more accurate than putting immediate users from Ideal Graph.
4532 for (EdgeIterator e(ptn); e.has_next(); e.next()) {
4533 PointsToNode* tgt = e.get();
4534 if (tgt->is_Arraycopy()) {
4535 continue;
4536 }
4537 Node* use = tgt->ideal_node();
4538 assert(tgt->is_Field() && use->is_AddP(),
4615 ptnode_adr(n->_idx)->dump();
4616 assert(jobj != nullptr && jobj != phantom_obj, "escaped allocation");
4617 #endif
4618 _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4619 return;
4620 } else {
4621 Node *val = get_map(jobj->idx()); // CheckCastPP node
4622 TypeNode *tn = n->as_Type();
4623 const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
4624 assert(tinst != nullptr && tinst->is_known_instance() &&
4625 tinst->instance_id() == jobj->idx() , "instance type expected.");
4626
4627 const Type *tn_type = igvn->type(tn);
4628 const TypeOopPtr *tn_t;
4629 if (tn_type->isa_narrowoop()) {
4630 tn_t = tn_type->make_ptr()->isa_oopptr();
4631 } else {
4632 tn_t = tn_type->isa_oopptr();
4633 }
4634 if (tn_t != nullptr && tinst->maybe_java_subtype_of(tn_t)) {
4635 if (tn_type->isa_narrowoop()) {
4636 tn_type = tinst->make_narrowoop();
4637 } else {
4638 tn_type = tinst;
4639 }
4640 igvn->hash_delete(tn);
4641 igvn->set_type(tn, tn_type);
4642 tn->set_type(tn_type);
4643 igvn->hash_insert(tn);
4644 record_for_optimizer(n);
4645 } else {
4646 assert(tn_type == TypePtr::NULL_PTR ||
4647 (tn_t != nullptr && !tinst->maybe_java_subtype_of(tn_t)),
4648 "unexpected type");
4649 continue; // Skip dead path with different type
4650 }
4651 }
4652 } else {
4653 DEBUG_ONLY(n->dump();)
4654 assert(false, "EA: unexpected node");
4655 continue;
4656 }
4657 // push allocation's users on appropriate worklist
4658 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4659 Node *use = n->fast_out(i);
4660 if(use->is_Mem() && use->in(MemNode::Address) == n) {
4661 // Load/store to instance's field
4662 memnode_worklist.append_if_missing(use);
4663 } else if (use->is_MemBar()) {
4664 if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4665 memnode_worklist.append_if_missing(use);
4666 }
4667 } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
4668 Node* addp2 = find_second_addp(use, n);
4669 if (addp2 != nullptr) {
4670 alloc_worklist.append_if_missing(addp2);
4671 }
4672 alloc_worklist.append_if_missing(use);
4673 } else if (use->is_Phi() ||
4674 use->is_CheckCastPP() ||
4675 use->is_EncodeNarrowPtr() ||
4676 use->is_DecodeNarrowPtr() ||
4677 (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
4678 alloc_worklist.append_if_missing(use);
4679 #ifdef ASSERT
4680 } else if (use->is_Mem()) {
4681 assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
4682 } else if (use->is_MergeMem()) {
4683 assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4684 } else if (use->is_SafePoint()) {
4685 // Look for MergeMem nodes for calls which reference unique allocation
4686 // (through CheckCastPP nodes) even for debug info.
4687 Node* m = use->in(TypeFunc::Memory);
4688 if (m->is_MergeMem()) {
4689 assert(mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4690 }
4691 } else if (use->Opcode() == Op_EncodeISOArray) {
4692 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4693 // EncodeISOArray overwrites destination array
4694 memnode_worklist.append_if_missing(use);
4695 }
4696 } else {
4697 uint op = use->Opcode();
4698 if ((op == Op_StrCompressedCopy || op == Op_StrInflatedCopy) &&
4699 (use->in(MemNode::Memory) == n)) {
4700 // They overwrite memory edge corresponding to destination array,
4701 memnode_worklist.append_if_missing(use);
4702 } else if (!(op == Op_CmpP || op == Op_Conv2B ||
4703 op == Op_CastP2X ||
4704 op == Op_FastLock || op == Op_AryEq ||
4705 op == Op_StrComp || op == Op_CountPositives ||
4706 op == Op_StrCompressedCopy || op == Op_StrInflatedCopy ||
4707 op == Op_StrEquals || op == Op_VectorizedHashCode ||
4708 op == Op_StrIndexOf || op == Op_StrIndexOfChar ||
4709 op == Op_SubTypeCheck ||
4710 op == Op_ReinterpretS2HF ||
4711 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use))) {
4712 n->dump();
4713 use->dump();
4714 assert(false, "EA: missing allocation reference path");
4715 }
4716 #endif
4717 }
4718 }
4719
4720 }
4721
4722 #ifdef ASSERT
4723 if (VerifyReduceAllocationMerges) {
4724 for (uint i = 0; i < reducible_merges.size(); i++) {
4725 Node* phi = reducible_merges.at(i);
4726
4727 if (!reduced_merges.member(phi)) {
4728 phi->dump(2);
4729 phi->dump(-2);
4797 n = n->as_MemBar()->proj_out_or_null(TypeFunc::Memory);
4798 if (n == nullptr) {
4799 continue;
4800 }
4801 }
4802 } else if (n->is_CallLeaf()) {
4803 // Runtime calls with narrow memory input (no MergeMem node)
4804 // get the memory projection
4805 n = n->as_Call()->proj_out_or_null(TypeFunc::Memory);
4806 if (n == nullptr) {
4807 continue;
4808 }
4809 } else if (n->Opcode() == Op_StrInflatedCopy) {
4810 // Check direct uses of StrInflatedCopy.
4811 // It is memory type Node - no special SCMemProj node.
4812 } else if (n->Opcode() == Op_StrCompressedCopy ||
4813 n->Opcode() == Op_EncodeISOArray) {
4814 // get the memory projection
4815 n = n->find_out_with(Op_SCMemProj);
4816 assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
4817 } else if (n->is_Proj()) {
4818 assert(n->in(0)->is_Initialize(), "we only push memory projections for Initialize");
4819 } else {
4820 #ifdef ASSERT
4821 if (!n->is_Mem()) {
4822 n->dump();
4823 }
4824 assert(n->is_Mem(), "memory node required.");
4825 #endif
4826 Node *addr = n->in(MemNode::Address);
4827 const Type *addr_t = igvn->type(addr);
4828 if (addr_t == Type::TOP) {
4829 continue;
4830 }
4831 assert (addr_t->isa_ptr() != nullptr, "pointer type required.");
4832 int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
4833 assert ((uint)alias_idx < new_index_end, "wrong alias index");
4834 Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
4835 if (_compile->failing()) {
4836 return;
4848 assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
4849 }
4850 }
4851 // push user on appropriate worklist
4852 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4853 Node *use = n->fast_out(i);
4854 if (use->is_Phi() || use->is_ClearArray()) {
4855 memnode_worklist.append_if_missing(use);
4856 } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
4857 memnode_worklist.append_if_missing(use);
4858 } else if (use->is_MemBar() || use->is_CallLeaf()) {
4859 if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4860 memnode_worklist.append_if_missing(use);
4861 }
4862 } else if (use->is_Proj()) {
4863 assert(n->is_Initialize(), "We only push projections of Initialize");
4864 if (use->as_Proj()->_con == TypeFunc::Memory) { // Ignore precedent edge
4865 memnode_worklist.append_if_missing(use);
4866 }
4867 #ifdef ASSERT
4868 } else if(use->is_Mem()) {
4869 assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
4870 } else if (use->is_MergeMem()) {
4871 assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4872 } else if (use->Opcode() == Op_EncodeISOArray) {
4873 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4874 // EncodeISOArray overwrites destination array
4875 memnode_worklist.append_if_missing(use);
4876 }
4877 } else {
4878 uint op = use->Opcode();
4879 if ((use->in(MemNode::Memory) == n) &&
4880 (op == Op_StrCompressedCopy || op == Op_StrInflatedCopy)) {
4881 // They overwrite memory edge corresponding to destination array,
4882 memnode_worklist.append_if_missing(use);
4883 } else if (!(BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use) ||
4884 op == Op_AryEq || op == Op_StrComp || op == Op_CountPositives ||
4885 op == Op_StrCompressedCopy || op == Op_StrInflatedCopy || op == Op_VectorizedHashCode ||
4886 op == Op_StrEquals || op == Op_StrIndexOf || op == Op_StrIndexOfChar)) {
4887 n->dump();
4888 use->dump();
4889 assert(false, "EA: missing memory path");
4890 }
4891 #endif
4892 }
4893 }
4894 }
4895
4896 // Phase 3: Process MergeMem nodes from mergemem_worklist.
4897 // Walk each memory slice moving the first node encountered of each
4898 // instance type to the input corresponding to its alias index.
4899 uint length = mergemem_worklist.length();
4900 for( uint next = 0; next < length; ++next ) {
4901 MergeMemNode* nmm = mergemem_worklist.at(next);
4902 assert(!visited.test_set(nmm->_idx), "should not be visited before");
4903 // Note: we don't want to use MergeMemStream here because we only want to
4904 // scan inputs which exist at the start, not ones we add during processing.
4905 // Note 2: MergeMem may already contains instance memory slices added
4906 // during find_inst_mem() call when memory nodes were processed above.
4969 _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
4970 } else if (_invocation > 0) {
4971 _compile->record_failure(C2Compiler::retry_no_iterative_escape_analysis());
4972 } else {
4973 _compile->record_failure(C2Compiler::retry_no_escape_analysis());
4974 }
4975 return;
4976 }
4977
4978 igvn->hash_insert(nmm);
4979 record_for_optimizer(nmm);
4980 }
4981
4982 _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_3, 5);
4983
4984 // Phase 4: Update the inputs of non-instance memory Phis and
4985 // the Memory input of memnodes
4986 // First update the inputs of any non-instance Phi's from
4987 // which we split out an instance Phi. Note we don't have
4988 // to recursively process Phi's encountered on the input memory
4989 // chains as is done in split_memory_phi() since they will
4990 // also be processed here.
4991 for (int j = 0; j < orig_phis.length(); j++) {
4992 PhiNode *phi = orig_phis.at(j);
4993 int alias_idx = _compile->get_alias_index(phi->adr_type());
4994 igvn->hash_delete(phi);
4995 for (uint i = 1; i < phi->req(); i++) {
4996 Node *mem = phi->in(i);
4997 Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
4998 if (_compile->failing()) {
4999 return;
5000 }
5001 if (mem != new_mem) {
5002 phi->set_req(i, new_mem);
5003 }
5004 }
5005 igvn->hash_insert(phi);
5006 record_for_optimizer(phi);
5007 }
5008
5009 // Update the memory inputs of MemNodes with the value we computed
|
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "ci/bcEscapeAnalyzer.hpp"
26 #include "compiler/compileLog.hpp"
27 #include "gc/shared/barrierSet.hpp"
28 #include "gc/shared/c2/barrierSetC2.hpp"
29 #include "libadt/vectset.hpp"
30 #include "memory/allocation.hpp"
31 #include "memory/metaspace.hpp"
32 #include "memory/resourceArea.hpp"
33 #include "opto/arraycopynode.hpp"
34 #include "opto/c2compiler.hpp"
35 #include "opto/callnode.hpp"
36 #include "opto/castnode.hpp"
37 #include "opto/cfgnode.hpp"
38 #include "opto/compile.hpp"
39 #include "opto/escape.hpp"
40 #include "opto/inlinetypenode.hpp"
41 #include "opto/locknode.hpp"
42 #include "opto/macro.hpp"
43 #include "opto/movenode.hpp"
44 #include "opto/narrowptrnode.hpp"
45 #include "opto/phaseX.hpp"
46 #include "opto/rootnode.hpp"
47 #include "utilities/macros.hpp"
48
49 ConnectionGraph::ConnectionGraph(Compile * C, PhaseIterGVN *igvn, int invocation) :
50 // If ReduceAllocationMerges is enabled we might call split_through_phi during
51 // split_unique_types and that will create additional nodes that need to be
52 // pushed to the ConnectionGraph. The code below bumps the initial capacity of
53 // _nodes by 10% to account for these additional nodes. If capacity is exceeded
54 // the array will be reallocated.
55 _nodes(C->comp_arena(), C->do_reduce_allocation_merges() ? C->unique()*1.10 : C->unique(), C->unique(), nullptr),
56 _in_worklist(C->comp_arena()),
57 _next_pidx(0),
58 _collecting(true),
59 _verify(false),
60 _compile(C),
152 GrowableArray<SafePointNode*> sfn_worklist;
153 GrowableArray<MergeMemNode*> mergemem_worklist;
154 DEBUG_ONLY( GrowableArray<Node*> addp_worklist; )
155
156 { Compile::TracePhase tp(Phase::_t_connectionGraph);
157
158 // 1. Populate Connection Graph (CG) with PointsTo nodes.
159 ideal_nodes.map(C->live_nodes(), nullptr); // preallocate space
160 // Initialize worklist
161 if (C->root() != nullptr) {
162 ideal_nodes.push(C->root());
163 }
164 // Processed ideal nodes are unique on ideal_nodes list
165 // but several ideal nodes are mapped to the phantom_obj.
166 // To avoid duplicated entries on the following worklists
167 // add the phantom_obj only once to them.
168 ptnodes_worklist.append(phantom_obj);
169 java_objects_worklist.append(phantom_obj);
170 for( uint next = 0; next < ideal_nodes.size(); ++next ) {
171 Node* n = ideal_nodes.at(next);
172 if ((n->Opcode() == Op_LoadX || n->Opcode() == Op_StoreX) &&
173 !n->in(MemNode::Address)->is_AddP() &&
174 _igvn->type(n->in(MemNode::Address))->isa_oopptr()) {
175 // Load/Store at mark work address is at offset 0 so has no AddP which confuses EA
176 Node* addp = new AddPNode(n->in(MemNode::Address), n->in(MemNode::Address), _igvn->MakeConX(0));
177 _igvn->register_new_node_with_optimizer(addp);
178 _igvn->replace_input_of(n, MemNode::Address, addp);
179 ideal_nodes.push(addp);
180 _nodes.at_put_grow(addp->_idx, nullptr, nullptr);
181 }
182 // Create PointsTo nodes and add them to Connection Graph. Called
183 // only once per ideal node since ideal_nodes is Unique_Node list.
184 add_node_to_connection_graph(n, &delayed_worklist);
185 PointsToNode* ptn = ptnode_adr(n->_idx);
186 if (ptn != nullptr && ptn != phantom_obj) {
187 ptnodes_worklist.append(ptn);
188 if (ptn->is_JavaObject()) {
189 java_objects_worklist.append(ptn->as_JavaObject());
190 if ((n->is_Allocate() || n->is_CallStaticJava()) &&
191 (ptn->escape_state() < PointsToNode::GlobalEscape)) {
192 // Only allocations and java static calls results are interesting.
193 non_escaped_allocs_worklist.append(ptn->as_JavaObject());
194 }
195 } else if (ptn->is_Field() && ptn->as_Field()->is_oop()) {
196 oop_fields_worklist.append(ptn->as_Field());
197 }
198 }
199 // Collect some interesting nodes for further use.
200 switch (n->Opcode()) {
201 case Op_MergeMem:
419 // scalar replaceable objects.
420 split_unique_types(alloc_worklist, arraycopy_worklist, mergemem_worklist, reducible_merges);
421 if (C->failing()) {
422 NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
423 return false;
424 }
425
426 #ifdef ASSERT
427 } else if (Verbose && (PrintEscapeAnalysis || PrintEliminateAllocations)) {
428 tty->print("=== No allocations eliminated for ");
429 C->method()->print_short_name();
430 if (!EliminateAllocations) {
431 tty->print(" since EliminateAllocations is off ===");
432 } else if(!has_scalar_replaceable_candidates) {
433 tty->print(" since there are no scalar replaceable candidates ===");
434 }
435 tty->cr();
436 #endif
437 }
438
439 // 6. Expand flat accesses if the object does not escape. This adds nodes to
440 // the graph, so it has to be after split_unique_types. This expands atomic
441 // mismatched accesses (though encapsulated in LoadFlats and StoreFlats) into
442 // non-mismatched accesses, so it is better before reduce allocation merges.
443 if (has_non_escaping_obj) {
444 optimize_flat_accesses(sfn_worklist);
445 }
446
447 _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES, 4);
448
449 // 7. Reduce allocation merges used as debug information. This is done after
450 // split_unique_types because the methods used to create SafePointScalarObject
451 // need to traverse the memory graph to find values for object fields. We also
452 // set to null the scalarized inputs of reducible Phis so that the Allocate
453 // that they point can be later scalar replaced.
454 bool delay = _igvn->delay_transform();
455 _igvn->set_delay_transform(true);
456 for (uint i = 0; i < reducible_merges.size(); i++) {
457 Node* n = reducible_merges.at(i);
458 if (n->outcnt() > 0) {
459 if (!reduce_phi_on_safepoints(n->as_Phi())) {
460 NOT_PRODUCT(escape_state_statistics(java_objects_worklist);)
461 C->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
462 return false;
463 }
464
465 // Now we set the scalar replaceable inputs of ophi to null, which is
466 // the last piece that would prevent it from being scalar replaceable.
467 reset_scalar_replaceable_entries(n->as_Phi());
468 }
469 }
1303
1304 // The next two inputs are:
1305 // (1) A copy of the original pointer to NSR objects.
1306 // (2) A selector, used to decide if we need to rematerialize an object
1307 // or use the pointer to a NSR object.
1308 // See more details of these fields in the declaration of SafePointScalarMergeNode
1309 sfpt->add_req(nsr_merge_pointer);
1310 sfpt->add_req(selector);
1311
1312 for (uint i = 1; i < ophi->req(); i++) {
1313 Node* base = ophi->in(i);
1314 JavaObjectNode* ptn = unique_java_object(base);
1315
1316 // If the base is not scalar replaceable we don't need to register information about
1317 // it at this time.
1318 if (ptn == nullptr || !ptn->scalar_replaceable()) {
1319 continue;
1320 }
1321
1322 AllocateNode* alloc = ptn->ideal_node()->as_Allocate();
1323 Unique_Node_List value_worklist;
1324 #ifdef ASSERT
1325 const Type* res_type = alloc->result_cast()->bottom_type();
1326 if (res_type->is_inlinetypeptr() && !Compile::current()->has_circular_inline_type()) {
1327 PhiNode* phi = ophi->as_Phi();
1328 assert(!ophi->as_Phi()->can_push_inline_types_down(_igvn), "missed earlier scalarization opportunity");
1329 }
1330 #endif
1331 SafePointScalarObjectNode* sobj = mexp.create_scalarized_object_description(alloc, sfpt, &value_worklist);
1332 if (sobj == nullptr) {
1333 _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
1334 return false;
1335 }
1336
1337 // Now make a pass over the debug information replacing any references
1338 // to the allocated object with "sobj"
1339 Node* ccpp = alloc->result_cast();
1340 sfpt->replace_edges_in_range(ccpp, sobj, debug_start, jvms->debug_end(), _igvn);
1341
1342 // Register the scalarized object as a candidate for reallocation
1343 smerge->add_req(sobj);
1344
1345 // Scalarize inline types that were added to the safepoint.
1346 // Don't allow linking a constant oop (if available) for flat array elements
1347 // because Deoptimization::reassign_flat_array_elements needs field values.
1348 const bool allow_oop = !merge_t->is_flat();
1349 for (uint j = 0; j < value_worklist.size(); ++j) {
1350 InlineTypeNode* vt = value_worklist.at(j)->as_InlineType();
1351 vt->make_scalar_in_safepoints(_igvn, allow_oop);
1352 }
1353 }
1354
1355 // Replaces debug information references to "original_sfpt_parent" in "sfpt" with references to "smerge"
1356 sfpt->replace_edges_in_range(original_sfpt_parent, smerge, debug_start, jvms->debug_end(), _igvn);
1357
1358 // The call to 'replace_edges_in_range' above might have removed the
1359 // reference to ophi that we need at _merge_pointer_idx. The line below make
1360 // sure the reference is maintained.
1361 sfpt->set_req(smerge->merge_pointer_idx(jvms), nsr_merge_pointer);
1362 _igvn->_worklist.push(sfpt);
1363 }
1364
1365 return true;
1366 }
1367
1368 void ConnectionGraph::reduce_phi(PhiNode* ophi, GrowableArray<Node*> &alloc_worklist) {
1369 bool delay = _igvn->delay_transform();
1370 _igvn->set_delay_transform(true);
1371 _igvn->hash_delete(ophi);
1372
1535 return false;
1536 }
1537
1538 // Returns true if at least one of the arguments to the call is an object
1539 // that does not escape globally.
1540 bool ConnectionGraph::has_arg_escape(CallJavaNode* call) {
1541 if (call->method() != nullptr) {
1542 uint max_idx = TypeFunc::Parms + call->method()->arg_size();
1543 for (uint idx = TypeFunc::Parms; idx < max_idx; idx++) {
1544 Node* p = call->in(idx);
1545 if (not_global_escape(p)) {
1546 return true;
1547 }
1548 }
1549 } else {
1550 const char* name = call->as_CallStaticJava()->_name;
1551 assert(name != nullptr, "no name");
1552 // no arg escapes through uncommon traps
1553 if (strcmp(name, "uncommon_trap") != 0) {
1554 // process_call_arguments() assumes that all arguments escape globally
1555 const TypeTuple* d = call->tf()->domain_sig();
1556 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
1557 const Type* at = d->field_at(i);
1558 if (at->isa_oopptr() != nullptr) {
1559 return true;
1560 }
1561 }
1562 }
1563 }
1564 return false;
1565 }
1566
1567
1568
1569 // Utility function for nodes that load an object
1570 void ConnectionGraph::add_objload_to_connection_graph(Node *n, Unique_Node_List *delayed_worklist) {
1571 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1572 // ThreadLocal has RawPtr type.
1573 const Type* t = _igvn->type(n);
1574 if (t->make_ptr() != nullptr) {
1575 Node* adr = n->in(MemNode::Address);
1609 // first IGVN optimization when escape information is still available.
1610 record_for_optimizer(n);
1611 } else if (n->is_Allocate()) {
1612 add_call_node(n->as_Call());
1613 record_for_optimizer(n);
1614 } else {
1615 if (n->is_CallStaticJava()) {
1616 const char* name = n->as_CallStaticJava()->_name;
1617 if (name != nullptr && strcmp(name, "uncommon_trap") == 0) {
1618 return; // Skip uncommon traps
1619 }
1620 }
1621 // Don't mark as processed since call's arguments have to be processed.
1622 delayed_worklist->push(n);
1623 // Check if a call returns an object.
1624 if ((n->as_Call()->returns_pointer() &&
1625 n->as_Call()->proj_out_or_null(TypeFunc::Parms) != nullptr) ||
1626 (n->is_CallStaticJava() &&
1627 n->as_CallStaticJava()->is_boxing_method())) {
1628 add_call_node(n->as_Call());
1629 } else if (n->as_Call()->tf()->returns_inline_type_as_fields()) {
1630 bool returns_oop = false;
1631 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax && !returns_oop; i++) {
1632 ProjNode* pn = n->fast_out(i)->as_Proj();
1633 if (pn->_con >= TypeFunc::Parms && pn->bottom_type()->isa_ptr()) {
1634 returns_oop = true;
1635 }
1636 }
1637 if (returns_oop) {
1638 add_call_node(n->as_Call());
1639 }
1640 }
1641 }
1642 return;
1643 }
1644 // Put this check here to process call arguments since some call nodes
1645 // point to phantom_obj.
1646 if (n_ptn == phantom_obj || n_ptn == null_obj) {
1647 return; // Skip predefined nodes.
1648 }
1649 switch (opcode) {
1650 case Op_AddP: {
1651 Node* base = get_addp_base(n);
1652 PointsToNode* ptn_base = ptnode_adr(base->_idx);
1653 // Field nodes are created for all field types. They are used in
1654 // adjust_scalar_replaceable_state() and split_unique_types().
1655 // Note, non-oop fields will have only base edges in Connection
1656 // Graph because such fields are not used for oop loads and stores.
1657 int offset = address_offset(n, igvn);
1658 add_field(n, PointsToNode::NoEscape, offset);
1659 if (ptn_base == nullptr) {
1660 delayed_worklist->push(n); // Process it later.
1661 } else {
1662 n_ptn = ptnode_adr(n_idx);
1663 add_base(n_ptn->as_Field(), ptn_base);
1664 }
1665 break;
1666 }
1667 case Op_CastX2P:
1668 case Op_CastI2N: {
1669 map_ideal_node(n, phantom_obj);
1670 break;
1671 }
1672 case Op_InlineType:
1673 case Op_CastPP:
1674 case Op_CheckCastPP:
1675 case Op_EncodeP:
1676 case Op_DecodeN:
1677 case Op_EncodePKlass:
1678 case Op_DecodeNKlass: {
1679 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), delayed_worklist);
1680 break;
1681 }
1682 case Op_CMoveP: {
1683 add_local_var(n, PointsToNode::NoEscape);
1684 // Do not add edges during first iteration because some could be
1685 // not defined yet.
1686 delayed_worklist->push(n);
1687 break;
1688 }
1689 case Op_ConP:
1690 case Op_ConN:
1691 case Op_ConNKlass: {
1692 // assume all oop constants globally escape except for null
1722 break;
1723 }
1724 case Op_PartialSubtypeCheck: {
1725 // Produces Null or notNull and is used in only in CmpP so
1726 // phantom_obj could be used.
1727 map_ideal_node(n, phantom_obj); // Result is unknown
1728 break;
1729 }
1730 case Op_Phi: {
1731 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1732 // ThreadLocal has RawPtr type.
1733 const Type* t = n->as_Phi()->type();
1734 if (t->make_ptr() != nullptr) {
1735 add_local_var(n, PointsToNode::NoEscape);
1736 // Do not add edges during first iteration because some could be
1737 // not defined yet.
1738 delayed_worklist->push(n);
1739 }
1740 break;
1741 }
1742 case Op_LoadFlat:
1743 // Treat LoadFlat similar to an unknown call that receives nothing and produces its results
1744 map_ideal_node(n, phantom_obj);
1745 break;
1746 case Op_StoreFlat:
1747 // Treat StoreFlat similar to a call that escapes the stored flattened fields
1748 delayed_worklist->push(n);
1749 break;
1750 case Op_Proj: {
1751 // we are only interested in the oop result projection from a call
1752 if (n->as_Proj()->_con >= TypeFunc::Parms && n->in(0)->is_Call() &&
1753 (n->in(0)->as_Call()->returns_pointer() || n->bottom_type()->isa_ptr())) {
1754 assert((n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->as_Call()->returns_pointer()) ||
1755 n->in(0)->as_Call()->tf()->returns_inline_type_as_fields(), "what kind of oop return is it?");
1756 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1757 } else if (n->as_Proj()->_con >= TypeFunc::Parms && n->in(0)->is_LoadFlat() && igvn->type(n)->isa_ptr()) {
1758 // Treat LoadFlat outputs similar to a call return value
1759 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), delayed_worklist);
1760 }
1761 break;
1762 }
1763 case Op_Rethrow: // Exception object escapes
1764 case Op_Return: {
1765 if (n->req() > TypeFunc::Parms &&
1766 igvn->type(n->in(TypeFunc::Parms))->isa_oopptr()) {
1767 // Treat Return value as LocalVar with GlobalEscape escape state.
1768 add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), delayed_worklist);
1769 }
1770 break;
1771 }
1772 case Op_CompareAndExchangeP:
1773 case Op_CompareAndExchangeN:
1774 case Op_GetAndSetP:
1775 case Op_GetAndSetN: {
1776 add_objload_to_connection_graph(n, delayed_worklist);
1777 // fall-through
1778 }
1824 break;
1825 }
1826 default:
1827 ; // Do nothing for nodes not related to EA.
1828 }
1829 return;
1830 }
1831
1832 // Add final simple edges to graph.
1833 void ConnectionGraph::add_final_edges(Node *n) {
1834 PointsToNode* n_ptn = ptnode_adr(n->_idx);
1835 #ifdef ASSERT
1836 if (_verify && n_ptn->is_JavaObject())
1837 return; // This method does not change graph for JavaObject.
1838 #endif
1839
1840 if (n->is_Call()) {
1841 process_call_arguments(n->as_Call());
1842 return;
1843 }
1844 assert(n->is_Store() || n->is_LoadStore() || n->is_StoreFlat() ||
1845 ((n_ptn != nullptr) && (n_ptn->ideal_node() != nullptr)),
1846 "node should be registered already");
1847 int opcode = n->Opcode();
1848 bool gc_handled = BarrierSet::barrier_set()->barrier_set_c2()->escape_add_final_edges(this, _igvn, n, opcode);
1849 if (gc_handled) {
1850 return; // Ignore node if already handled by GC.
1851 }
1852 switch (opcode) {
1853 case Op_AddP: {
1854 Node* base = get_addp_base(n);
1855 PointsToNode* ptn_base = ptnode_adr(base->_idx);
1856 assert(ptn_base != nullptr, "field's base should be registered");
1857 add_base(n_ptn->as_Field(), ptn_base);
1858 break;
1859 }
1860 case Op_InlineType:
1861 case Op_CastPP:
1862 case Op_CheckCastPP:
1863 case Op_EncodeP:
1864 case Op_DecodeN:
1865 case Op_EncodePKlass:
1866 case Op_DecodeNKlass: {
1867 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(1), nullptr);
1868 break;
1869 }
1870 case Op_CMoveP: {
1871 for (uint i = CMoveNode::IfFalse; i < n->req(); i++) {
1872 Node* in = n->in(i);
1873 if (in == nullptr) {
1874 continue; // ignore null
1875 }
1876 Node* uncast_in = in->uncast();
1877 if (uncast_in->is_top() || uncast_in == n) {
1878 continue; // ignore top or inputs which go back this node
1879 }
1880 PointsToNode* ptn = ptnode_adr(in->_idx);
1893 }
1894 case Op_Phi: {
1895 // Using isa_ptr() instead of isa_oopptr() for LoadP and Phi because
1896 // ThreadLocal has RawPtr type.
1897 assert(n->as_Phi()->type()->make_ptr() != nullptr, "Unexpected node type");
1898 for (uint i = 1; i < n->req(); i++) {
1899 Node* in = n->in(i);
1900 if (in == nullptr) {
1901 continue; // ignore null
1902 }
1903 Node* uncast_in = in->uncast();
1904 if (uncast_in->is_top() || uncast_in == n) {
1905 continue; // ignore top or inputs which go back this node
1906 }
1907 PointsToNode* ptn = ptnode_adr(in->_idx);
1908 assert(ptn != nullptr, "node should be registered");
1909 add_edge(n_ptn, ptn);
1910 }
1911 break;
1912 }
1913 case Op_StoreFlat: {
1914 // StoreFlat globally escapes its stored flattened fields
1915 InlineTypeNode* value = n->as_StoreFlat()->value();
1916 ciInlineKlass* vk = _igvn->type(value)->inline_klass();
1917 for (int i = 0; i < vk->nof_nonstatic_fields(); i++) {
1918 ciField* field = vk->nonstatic_field_at(i);
1919 if (field->type()->is_primitive_type()) {
1920 continue;
1921 }
1922
1923 Node* field_value = value->field_value_by_offset(field->offset_in_bytes(), true);
1924 PointsToNode* field_value_ptn = ptnode_adr(field_value->_idx);
1925 set_escape_state(field_value_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "store into a flat field"));
1926 }
1927 break;
1928 }
1929 case Op_Proj: {
1930 if (n->in(0)->is_Call()) {
1931 // we are only interested in the oop result projection from a call
1932 assert((n->as_Proj()->_con == TypeFunc::Parms && n->in(0)->as_Call()->returns_pointer()) ||
1933 n->in(0)->as_Call()->tf()->returns_inline_type_as_fields(), "what kind of oop return is it?");
1934 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), nullptr);
1935 } else if (n->in(0)->is_LoadFlat()) {
1936 // Treat LoadFlat outputs similar to a call return value
1937 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(0), nullptr);
1938 }
1939 break;
1940 }
1941 case Op_Rethrow: // Exception object escapes
1942 case Op_Return: {
1943 assert(n->req() > TypeFunc::Parms && _igvn->type(n->in(TypeFunc::Parms))->isa_oopptr(),
1944 "Unexpected node type");
1945 // Treat Return value as LocalVar with GlobalEscape escape state.
1946 add_local_var_and_edge(n, PointsToNode::GlobalEscape, n->in(TypeFunc::Parms), nullptr);
1947 break;
1948 }
1949 case Op_CompareAndExchangeP:
1950 case Op_CompareAndExchangeN:
1951 case Op_GetAndSetP:
1952 case Op_GetAndSetN:{
1953 assert(_igvn->type(n)->make_ptr() != nullptr, "Unexpected node type");
1954 add_local_var_and_edge(n, PointsToNode::NoEscape, n->in(MemNode::Address), nullptr);
1955 // fall-through
1956 }
1957 case Op_CompareAndSwapP:
1958 case Op_CompareAndSwapN:
2093 PointsToNode* ptn = ptnode_adr(val->_idx);
2094 assert(ptn != nullptr, "node should be registered");
2095 set_escape_state(ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA "stored at raw address"));
2096 // Add edge to object for unsafe access with offset.
2097 PointsToNode* adr_ptn = ptnode_adr(adr->_idx);
2098 assert(adr_ptn != nullptr, "node should be registered");
2099 if (adr_ptn->is_Field()) {
2100 assert(adr_ptn->as_Field()->is_oop(), "should be oop field");
2101 add_edge(adr_ptn, ptn);
2102 }
2103 return true;
2104 }
2105 #ifdef ASSERT
2106 n->dump(1);
2107 assert(false, "not unsafe");
2108 #endif
2109 return false;
2110 }
2111
2112 void ConnectionGraph::add_call_node(CallNode* call) {
2113 assert(call->returns_pointer() || call->tf()->returns_inline_type_as_fields(), "only for call which returns pointer");
2114 uint call_idx = call->_idx;
2115 if (call->is_Allocate()) {
2116 Node* k = call->in(AllocateNode::KlassNode);
2117 const TypeKlassPtr* kt = k->bottom_type()->isa_klassptr();
2118 assert(kt != nullptr, "TypeKlassPtr required.");
2119 PointsToNode::EscapeState es = PointsToNode::NoEscape;
2120 bool scalar_replaceable = true;
2121 NOT_PRODUCT(const char* nsr_reason = "");
2122 if (call->is_AllocateArray()) {
2123 if (!kt->isa_aryklassptr()) { // StressReflectiveCode
2124 es = PointsToNode::GlobalEscape;
2125 } else {
2126 int length = call->in(AllocateNode::ALength)->find_int_con(-1);
2127 if (length < 0) {
2128 // Not scalar replaceable if the length is not constant.
2129 scalar_replaceable = false;
2130 NOT_PRODUCT(nsr_reason = "has a non-constant length");
2131 } else if (length > EliminateAllocationArraySizeLimit) {
2132 // Not scalar replaceable if the length is too big.
2133 scalar_replaceable = false;
2168 // - mapped to GlobalEscape JavaObject node if oop is returned;
2169 //
2170 // - all oop arguments are escaping globally;
2171 //
2172 // 2. CallStaticJavaNode (execute bytecode analysis if possible):
2173 //
2174 // - the same as CallDynamicJavaNode if can't do bytecode analysis;
2175 //
2176 // - mapped to GlobalEscape JavaObject node if unknown oop is returned;
2177 // - mapped to NoEscape JavaObject node if non-escaping object allocated
2178 // during call is returned;
2179 // - mapped to ArgEscape LocalVar node pointed to object arguments
2180 // which are returned and does not escape during call;
2181 //
2182 // - oop arguments escaping status is defined by bytecode analysis;
2183 //
2184 // For a static call, we know exactly what method is being called.
2185 // Use bytecode estimator to record whether the call's return value escapes.
2186 ciMethod* meth = call->as_CallJava()->method();
2187 if (meth == nullptr) {
2188 const char* name = call->as_CallStaticJava()->_name;
2189 assert(call->as_CallStaticJava()->is_call_to_multianewarray_stub() ||
2190 strncmp(name, "load_unknown_inline", 19) == 0 ||
2191 strncmp(name, "store_inline_type_fields_to_buf", 31) == 0, "TODO: add failed case check");
2192 // Returns a newly allocated non-escaped object.
2193 add_java_object(call, PointsToNode::NoEscape);
2194 set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of multinewarray"));
2195 } else if (meth->is_boxing_method()) {
2196 // Returns boxing object
2197 PointsToNode::EscapeState es;
2198 vmIntrinsics::ID intr = meth->intrinsic_id();
2199 if (intr == vmIntrinsics::_floatValue || intr == vmIntrinsics::_doubleValue) {
2200 // It does not escape if object is always allocated.
2201 es = PointsToNode::NoEscape;
2202 } else {
2203 // It escapes globally if object could be loaded from cache.
2204 es = PointsToNode::GlobalEscape;
2205 }
2206 add_java_object(call, es);
2207 if (es == PointsToNode::GlobalEscape) {
2208 set_not_scalar_replaceable(ptnode_adr(call->_idx) NOT_PRODUCT(COMMA "object can be loaded from boxing cache"));
2209 }
2210 } else {
2211 BCEscapeAnalyzer* call_analyzer = meth->get_bcea();
2212 call_analyzer->copy_dependencies(_compile->dependencies());
2213 if (call_analyzer->is_return_allocated()) {
2214 // Returns a newly allocated non-escaped object, simply
2215 // update dependency information.
2216 // Mark it as NoEscape so that objects referenced by
2217 // it's fields will be marked as NoEscape at least.
2218 add_java_object(call, PointsToNode::NoEscape);
2219 set_not_scalar_replaceable(ptnode_adr(call_idx) NOT_PRODUCT(COMMA "is result of call"));
2220 } else {
2221 // Determine whether any arguments are returned.
2222 const TypeTuple* d = call->tf()->domain_cc();
2223 bool ret_arg = false;
2224 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2225 if (d->field_at(i)->isa_ptr() != nullptr &&
2226 call_analyzer->is_arg_returned(i - TypeFunc::Parms)) {
2227 ret_arg = true;
2228 break;
2229 }
2230 }
2231 if (ret_arg) {
2232 add_local_var(call, PointsToNode::ArgEscape);
2233 } else {
2234 // Returns unknown object.
2235 map_ideal_node(call, phantom_obj);
2236 }
2237 }
2238 }
2239 } else {
2240 // An other type of call, assume the worst case:
2241 // returned value is unknown and globally escapes.
2242 assert(call->Opcode() == Op_CallDynamicJava, "add failed case check");
2250 #ifdef ASSERT
2251 case Op_Allocate:
2252 case Op_AllocateArray:
2253 case Op_Lock:
2254 case Op_Unlock:
2255 assert(false, "should be done already");
2256 break;
2257 #endif
2258 case Op_ArrayCopy:
2259 case Op_CallLeafNoFP:
2260 // Most array copies are ArrayCopy nodes at this point but there
2261 // are still a few direct calls to the copy subroutines (See
2262 // PhaseStringOpts::copy_string())
2263 is_arraycopy = (call->Opcode() == Op_ArrayCopy) ||
2264 call->as_CallLeaf()->is_call_to_arraycopystub();
2265 // fall through
2266 case Op_CallLeafVector:
2267 case Op_CallLeaf: {
2268 // Stub calls, objects do not escape but they are not scale replaceable.
2269 // Adjust escape state for outgoing arguments.
2270 const TypeTuple * d = call->tf()->domain_sig();
2271 bool src_has_oops = false;
2272 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2273 const Type* at = d->field_at(i);
2274 Node *arg = call->in(i);
2275 if (arg == nullptr) {
2276 continue;
2277 }
2278 const Type *aat = _igvn->type(arg);
2279 if (arg->is_top() || !at->isa_ptr() || !aat->isa_ptr()) {
2280 continue;
2281 }
2282 if (arg->is_AddP()) {
2283 //
2284 // The inline_native_clone() case when the arraycopy stub is called
2285 // after the allocation before Initialize and CheckCastPP nodes.
2286 // Or normal arraycopy for object arrays case.
2287 //
2288 // Set AddP's base (Allocate) as not scalar replaceable since
2289 // pointer to the base (with offset) is passed as argument.
2290 //
2291 arg = get_addp_base(arg);
2292 }
2293 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2294 assert(arg_ptn != nullptr, "should be registered");
2295 PointsToNode::EscapeState arg_esc = arg_ptn->escape_state();
2296 if (is_arraycopy || arg_esc < PointsToNode::ArgEscape) {
2297 assert(aat == Type::TOP || aat == TypePtr::NULL_PTR ||
2298 aat->isa_ptr() != nullptr, "expecting an Ptr");
2299 bool arg_has_oops = aat->isa_oopptr() &&
2300 (aat->isa_instptr() ||
2301 (aat->isa_aryptr() && (aat->isa_aryptr()->elem() == Type::BOTTOM || aat->isa_aryptr()->elem()->make_oopptr() != nullptr)) ||
2302 (aat->isa_aryptr() && aat->isa_aryptr()->elem() != nullptr &&
2303 aat->isa_aryptr()->is_flat() &&
2304 aat->isa_aryptr()->elem()->inline_klass()->contains_oops()));
2305 if (i == TypeFunc::Parms) {
2306 src_has_oops = arg_has_oops;
2307 }
2308 //
2309 // src or dst could be j.l.Object when other is basic type array:
2310 //
2311 // arraycopy(char[],0,Object*,0,size);
2312 // arraycopy(Object*,0,char[],0,size);
2313 //
2314 // Don't add edges in such cases.
2315 //
2316 bool arg_is_arraycopy_dest = src_has_oops && is_arraycopy &&
2317 arg_has_oops && (i > TypeFunc::Parms);
2318 #ifdef ASSERT
2319 if (!(is_arraycopy ||
2320 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(call) ||
2321 (call->as_CallLeaf()->_name != nullptr &&
2322 (strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 ||
2323 strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32C") == 0 ||
2324 strcmp(call->as_CallLeaf()->_name, "updateBytesAdler32") == 0 ||
2348 strcmp(call->as_CallLeaf()->_name, "dilithiumMontMulByConstant") == 0 ||
2349 strcmp(call->as_CallLeaf()->_name, "dilithiumDecomposePoly") == 0 ||
2350 strcmp(call->as_CallLeaf()->_name, "encodeBlock") == 0 ||
2351 strcmp(call->as_CallLeaf()->_name, "decodeBlock") == 0 ||
2352 strcmp(call->as_CallLeaf()->_name, "md5_implCompress") == 0 ||
2353 strcmp(call->as_CallLeaf()->_name, "md5_implCompressMB") == 0 ||
2354 strcmp(call->as_CallLeaf()->_name, "sha1_implCompress") == 0 ||
2355 strcmp(call->as_CallLeaf()->_name, "sha1_implCompressMB") == 0 ||
2356 strcmp(call->as_CallLeaf()->_name, "sha256_implCompress") == 0 ||
2357 strcmp(call->as_CallLeaf()->_name, "sha256_implCompressMB") == 0 ||
2358 strcmp(call->as_CallLeaf()->_name, "sha512_implCompress") == 0 ||
2359 strcmp(call->as_CallLeaf()->_name, "sha512_implCompressMB") == 0 ||
2360 strcmp(call->as_CallLeaf()->_name, "sha3_implCompress") == 0 ||
2361 strcmp(call->as_CallLeaf()->_name, "double_keccak") == 0 ||
2362 strcmp(call->as_CallLeaf()->_name, "sha3_implCompressMB") == 0 ||
2363 strcmp(call->as_CallLeaf()->_name, "multiplyToLen") == 0 ||
2364 strcmp(call->as_CallLeaf()->_name, "squareToLen") == 0 ||
2365 strcmp(call->as_CallLeaf()->_name, "mulAdd") == 0 ||
2366 strcmp(call->as_CallLeaf()->_name, "montgomery_multiply") == 0 ||
2367 strcmp(call->as_CallLeaf()->_name, "montgomery_square") == 0 ||
2368 strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2369 strcmp(call->as_CallLeaf()->_name, "load_unknown_inline") == 0 ||
2370 strcmp(call->as_CallLeaf()->_name, "store_unknown_inline") == 0 ||
2371 strcmp(call->as_CallLeaf()->_name, "store_inline_type_fields_to_buf") == 0 ||
2372 strcmp(call->as_CallLeaf()->_name, "bigIntegerRightShiftWorker") == 0 ||
2373 strcmp(call->as_CallLeaf()->_name, "bigIntegerLeftShiftWorker") == 0 ||
2374 strcmp(call->as_CallLeaf()->_name, "vectorizedMismatch") == 0 ||
2375 strcmp(call->as_CallLeaf()->_name, "stringIndexOf") == 0 ||
2376 strcmp(call->as_CallLeaf()->_name, "arraysort_stub") == 0 ||
2377 strcmp(call->as_CallLeaf()->_name, "array_partition_stub") == 0 ||
2378 strcmp(call->as_CallLeaf()->_name, "get_class_id_intrinsic") == 0 ||
2379 strcmp(call->as_CallLeaf()->_name, "unsafe_setmemory") == 0)
2380 ))) {
2381 call->dump();
2382 fatal("EA unexpected CallLeaf %s", call->as_CallLeaf()->_name);
2383 }
2384 #endif
2385 // Always process arraycopy's destination object since
2386 // we need to add all possible edges to references in
2387 // source object.
2388 if (arg_esc >= PointsToNode::ArgEscape &&
2389 !arg_is_arraycopy_dest) {
2390 continue;
2391 }
2414 }
2415 }
2416 }
2417 break;
2418 }
2419 case Op_CallStaticJava: {
2420 // For a static call, we know exactly what method is being called.
2421 // Use bytecode estimator to record the call's escape affects
2422 #ifdef ASSERT
2423 const char* name = call->as_CallStaticJava()->_name;
2424 assert((name == nullptr || strcmp(name, "uncommon_trap") != 0), "normal calls only");
2425 #endif
2426 ciMethod* meth = call->as_CallJava()->method();
2427 if ((meth != nullptr) && meth->is_boxing_method()) {
2428 break; // Boxing methods do not modify any oops.
2429 }
2430 BCEscapeAnalyzer* call_analyzer = (meth !=nullptr) ? meth->get_bcea() : nullptr;
2431 // fall-through if not a Java method or no analyzer information
2432 if (call_analyzer != nullptr) {
2433 PointsToNode* call_ptn = ptnode_adr(call->_idx);
2434 const TypeTuple* d = call->tf()->domain_cc();
2435 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2436 const Type* at = d->field_at(i);
2437 int k = i - TypeFunc::Parms;
2438 Node* arg = call->in(i);
2439 PointsToNode* arg_ptn = ptnode_adr(arg->_idx);
2440 if (at->isa_ptr() != nullptr &&
2441 call_analyzer->is_arg_returned(k)) {
2442 // The call returns arguments.
2443 if (call_ptn != nullptr) { // Is call's result used?
2444 assert(call_ptn->is_LocalVar(), "node should be registered");
2445 assert(arg_ptn != nullptr, "node should be registered");
2446 add_edge(call_ptn, arg_ptn);
2447 }
2448 }
2449 if (at->isa_oopptr() != nullptr &&
2450 arg_ptn->escape_state() < PointsToNode::GlobalEscape) {
2451 if (!call_analyzer->is_arg_stack(k)) {
2452 // The argument global escapes
2453 set_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2454 } else {
2458 set_fields_escape_state(arg_ptn, PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2459 }
2460 }
2461 }
2462 }
2463 if (call_ptn != nullptr && call_ptn->is_LocalVar()) {
2464 // The call returns arguments.
2465 assert(call_ptn->edge_count() > 0, "sanity");
2466 if (!call_analyzer->is_return_local()) {
2467 // Returns also unknown object.
2468 add_edge(call_ptn, phantom_obj);
2469 }
2470 }
2471 break;
2472 }
2473 }
2474 default: {
2475 // Fall-through here if not a Java method or no analyzer information
2476 // or some other type of call, assume the worst case: all arguments
2477 // globally escape.
2478 const TypeTuple* d = call->tf()->domain_cc();
2479 for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {
2480 const Type* at = d->field_at(i);
2481 if (at->isa_oopptr() != nullptr) {
2482 Node* arg = call->in(i);
2483 if (arg->is_AddP()) {
2484 arg = get_addp_base(arg);
2485 }
2486 assert(ptnode_adr(arg->_idx) != nullptr, "should be defined already");
2487 set_escape_state(ptnode_adr(arg->_idx), PointsToNode::GlobalEscape NOT_PRODUCT(COMMA trace_arg_escape_message(call)));
2488 }
2489 }
2490 }
2491 }
2492 }
2493
2494
2495 // Finish Graph construction.
2496 bool ConnectionGraph::complete_connection_graph(
2497 GrowableArray<PointsToNode*>& ptnodes_worklist,
2498 GrowableArray<JavaObjectNode*>& non_escaped_allocs_worklist,
2876 PointsToNode* base = i.get();
2877 if (base->is_JavaObject()) {
2878 // Skip Allocate's fields which will be processed later.
2879 if (base->ideal_node()->is_Allocate()) {
2880 return 0;
2881 }
2882 assert(base == null_obj, "only null ptr base expected here");
2883 }
2884 }
2885 if (add_edge(field, phantom_obj)) {
2886 // New edge was added
2887 new_edges++;
2888 add_field_uses_to_worklist(field);
2889 }
2890 return new_edges;
2891 }
2892
2893 // Find fields initializing values for allocations.
2894 int ConnectionGraph::find_init_values_phantom(JavaObjectNode* pta) {
2895 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2896 PointsToNode* init_val = phantom_obj;
2897 Node* alloc = pta->ideal_node();
2898
2899 // Do nothing for Allocate nodes since its fields values are
2900 // "known" unless they are initialized by arraycopy/clone.
2901 if (alloc->is_Allocate() && !pta->arraycopy_dst()) {
2902 if (alloc->as_Allocate()->in(AllocateNode::InitValue) != nullptr) {
2903 // Null-free inline type arrays are initialized with an init value instead of null
2904 init_val = ptnode_adr(alloc->as_Allocate()->in(AllocateNode::InitValue)->_idx);
2905 assert(init_val != nullptr, "init value should be registered");
2906 } else {
2907 return 0;
2908 }
2909 }
2910 // Non-escaped allocation returned from Java or runtime call has unknown values in fields.
2911 assert(pta->arraycopy_dst() || alloc->is_CallStaticJava() || init_val != phantom_obj, "sanity");
2912 #ifdef ASSERT
2913 if (alloc->is_CallStaticJava() && alloc->as_CallStaticJava()->method() == nullptr) {
2914 const char* name = alloc->as_CallStaticJava()->_name;
2915 assert(alloc->as_CallStaticJava()->is_call_to_multianewarray_stub() ||
2916 strncmp(name, "load_unknown_inline", 19) == 0 ||
2917 strncmp(name, "store_inline_type_fields_to_buf", 31) == 0, "sanity");
2918 }
2919 #endif
2920 // Non-escaped allocation returned from Java or runtime call have unknown values in fields.
2921 int new_edges = 0;
2922 for (EdgeIterator i(pta); i.has_next(); i.next()) {
2923 PointsToNode* field = i.get();
2924 if (field->is_Field() && field->as_Field()->is_oop()) {
2925 if (add_edge(field, init_val)) {
2926 // New edge was added
2927 new_edges++;
2928 add_field_uses_to_worklist(field->as_Field());
2929 }
2930 }
2931 }
2932 return new_edges;
2933 }
2934
2935 // Find fields initializing values for allocations.
2936 int ConnectionGraph::find_init_values_null(JavaObjectNode* pta, PhaseValues* phase) {
2937 assert(pta->escape_state() == PointsToNode::NoEscape, "Not escaped Allocate nodes only");
2938 Node* alloc = pta->ideal_node();
2939 // Do nothing for Call nodes since its fields values are unknown.
2940 if (!alloc->is_Allocate() || alloc->as_Allocate()->in(AllocateNode::InitValue) != nullptr) {
2941 return 0;
2942 }
2943 InitializeNode* ini = alloc->as_Allocate()->initialization();
2944 bool visited_bottom_offset = false;
2945 GrowableArray<int> offsets_worklist;
2946 int new_edges = 0;
2947
2948 // Check if an oop field's initializing value is recorded and add
2949 // a corresponding null if field's value if it is not recorded.
2950 // Connection Graph does not record a default initialization by null
2951 // captured by Initialize node.
2952 //
2953 for (EdgeIterator i(pta); i.has_next(); i.next()) {
2954 PointsToNode* field = i.get(); // Field (AddP)
2955 if (!field->is_Field() || !field->as_Field()->is_oop()) {
2956 continue; // Not oop field
2957 }
2958 int offset = field->as_Field()->offset();
2959 if (offset == Type::OffsetBot) {
2960 if (!visited_bottom_offset) {
3006 } else {
3007 if (!val->is_LocalVar() || (val->edge_count() == 0)) {
3008 tty->print_cr("----------init store has invalid value -----");
3009 store->dump();
3010 val->dump();
3011 assert(val->is_LocalVar() && (val->edge_count() > 0), "should be processed already");
3012 }
3013 for (EdgeIterator j(val); j.has_next(); j.next()) {
3014 PointsToNode* obj = j.get();
3015 if (obj->is_JavaObject()) {
3016 if (!field->points_to(obj->as_JavaObject())) {
3017 missed_obj = obj;
3018 break;
3019 }
3020 }
3021 }
3022 }
3023 if (missed_obj != nullptr) {
3024 tty->print_cr("----------field---------------------------------");
3025 field->dump();
3026 tty->print_cr("----------missed reference to object------------");
3027 missed_obj->dump();
3028 tty->print_cr("----------object referenced by init store-------");
3029 store->dump();
3030 val->dump();
3031 assert(!field->points_to(missed_obj->as_JavaObject()), "missed JavaObject reference");
3032 }
3033 }
3034 #endif
3035 } else {
3036 // There could be initializing stores which follow allocation.
3037 // For example, a volatile field store is not collected
3038 // by Initialize node.
3039 //
3040 // Need to check for dependent loads to separate such stores from
3041 // stores which follow loads. For now, add initial value null so
3042 // that compare pointers optimization works correctly.
3043 }
3044 }
3045 if (value == nullptr) {
3046 // A field's initializing value was not recorded. Add null.
3047 if (add_edge(field, null_obj)) {
3048 // New edge was added
3373 assert(field->edge_count() > 0, "sanity");
3374 }
3375 }
3376 }
3377 }
3378 #endif
3379
3380 // Optimize ideal graph.
3381 void ConnectionGraph::optimize_ideal_graph(GrowableArray<Node*>& ptr_cmp_worklist,
3382 GrowableArray<MemBarStoreStoreNode*>& storestore_worklist) {
3383 Compile* C = _compile;
3384 PhaseIterGVN* igvn = _igvn;
3385 if (EliminateLocks) {
3386 // Mark locks before changing ideal graph.
3387 int cnt = C->macro_count();
3388 for (int i = 0; i < cnt; i++) {
3389 Node *n = C->macro_node(i);
3390 if (n->is_AbstractLock()) { // Lock and Unlock nodes
3391 AbstractLockNode* alock = n->as_AbstractLock();
3392 if (!alock->is_non_esc_obj()) {
3393 const Type* obj_type = igvn->type(alock->obj_node());
3394 if (can_eliminate_lock(alock) && !obj_type->is_inlinetypeptr()) {
3395 assert(!alock->is_eliminated() || alock->is_coarsened(), "sanity");
3396 // The lock could be marked eliminated by lock coarsening
3397 // code during first IGVN before EA. Replace coarsened flag
3398 // to eliminate all associated locks/unlocks.
3399 #ifdef ASSERT
3400 alock->log_lock_optimization(C, "eliminate_lock_set_non_esc3");
3401 #endif
3402 alock->set_non_esc_obj();
3403 }
3404 }
3405 }
3406 }
3407 }
3408
3409 if (OptimizePtrCompare) {
3410 for (int i = 0; i < ptr_cmp_worklist.length(); i++) {
3411 Node *n = ptr_cmp_worklist.at(i);
3412 assert(n->Opcode() == Op_CmpN || n->Opcode() == Op_CmpP, "must be");
3413 const TypeInt* tcmp = optimize_ptr_compare(n->in(1), n->in(2));
3414 if (tcmp->singleton()) {
3416 #ifndef PRODUCT
3417 if (PrintOptimizePtrCompare) {
3418 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"));
3419 if (Verbose) {
3420 n->dump(1);
3421 }
3422 }
3423 #endif
3424 igvn->replace_node(n, cmp);
3425 }
3426 }
3427 }
3428
3429 // For MemBarStoreStore nodes added in library_call.cpp, check
3430 // escape status of associated AllocateNode and optimize out
3431 // MemBarStoreStore node if the allocated object never escapes.
3432 for (int i = 0; i < storestore_worklist.length(); i++) {
3433 Node* storestore = storestore_worklist.at(i);
3434 Node* alloc = storestore->in(MemBarNode::Precedent)->in(0);
3435 if (alloc->is_Allocate() && not_global_escape(alloc)) {
3436 if (alloc->in(AllocateNode::InlineType) != nullptr) {
3437 // Non-escaping inline type buffer allocations don't require a membar
3438 storestore->as_MemBar()->remove(_igvn);
3439 } else {
3440 MemBarNode* mb = MemBarNode::make(C, Op_MemBarCPUOrder, Compile::AliasIdxBot);
3441 mb->init_req(TypeFunc::Memory, storestore->in(TypeFunc::Memory));
3442 mb->init_req(TypeFunc::Control, storestore->in(TypeFunc::Control));
3443 igvn->register_new_node_with_optimizer(mb);
3444 igvn->replace_node(storestore, mb);
3445 }
3446 }
3447 }
3448 }
3449
3450 // Atomic flat accesses on non-escaping objects can be optimized to non-atomic accesses
3451 void ConnectionGraph::optimize_flat_accesses(GrowableArray<SafePointNode*>& sfn_worklist) {
3452 PhaseIterGVN& igvn = *_igvn;
3453 bool delay = igvn.delay_transform();
3454 igvn.set_delay_transform(true);
3455 igvn.C->for_each_flat_access([&](Node* n) {
3456 Node* base = n->is_LoadFlat() ? n->as_LoadFlat()->base() : n->as_StoreFlat()->base();
3457 if (!not_global_escape(base)) {
3458 return;
3459 }
3460
3461 bool expanded;
3462 if (n->is_LoadFlat()) {
3463 expanded = n->as_LoadFlat()->expand_non_atomic(igvn);
3464 } else {
3465 expanded = n->as_StoreFlat()->expand_non_atomic(igvn);
3466 }
3467 if (expanded) {
3468 sfn_worklist.remove(n->as_SafePoint());
3469 igvn.C->remove_flat_access(n);
3470 }
3471 });
3472 igvn.set_delay_transform(delay);
3473 }
3474
3475 // Optimize objects compare.
3476 const TypeInt* ConnectionGraph::optimize_ptr_compare(Node* left, Node* right) {
3477 const TypeInt* UNKNOWN = TypeInt::CC; // [-1, 0,1]
3478 if (!OptimizePtrCompare) {
3479 return UNKNOWN;
3480 }
3481 const TypeInt* EQ = TypeInt::CC_EQ; // [0] == ZERO
3482 const TypeInt* NE = TypeInt::CC_GT; // [1] == ONE
3483
3484 PointsToNode* ptn1 = ptnode_adr(left->_idx);
3485 PointsToNode* ptn2 = ptnode_adr(right->_idx);
3486 JavaObjectNode* jobj1 = unique_java_object(left);
3487 JavaObjectNode* jobj2 = unique_java_object(right);
3488
3489 // The use of this method during allocation merge reduction may cause 'left'
3490 // or 'right' be something (e.g., a Phi) that isn't in the connection graph or
3491 // that doesn't reference an unique java object.
3492 if (ptn1 == nullptr || ptn2 == nullptr ||
3493 jobj1 == nullptr || jobj2 == nullptr) {
3494 return UNKNOWN;
3614 assert(!src->is_Field() && !dst->is_Field(), "only for JavaObject and LocalVar");
3615 assert((src != null_obj) && (dst != null_obj), "not for ConP null");
3616 PointsToNode* ptadr = _nodes.at(n->_idx);
3617 if (ptadr != nullptr) {
3618 assert(ptadr->is_Arraycopy() && ptadr->ideal_node() == n, "sanity");
3619 return;
3620 }
3621 Compile* C = _compile;
3622 ptadr = new (C->comp_arena()) ArraycopyNode(this, n, es);
3623 map_ideal_node(n, ptadr);
3624 // Add edge from arraycopy node to source object.
3625 (void)add_edge(ptadr, src);
3626 src->set_arraycopy_src();
3627 // Add edge from destination object to arraycopy node.
3628 (void)add_edge(dst, ptadr);
3629 dst->set_arraycopy_dst();
3630 }
3631
3632 bool ConnectionGraph::is_oop_field(Node* n, int offset, bool* unsafe) {
3633 const Type* adr_type = n->as_AddP()->bottom_type();
3634 int field_offset = adr_type->isa_aryptr() ? adr_type->isa_aryptr()->field_offset().get() : Type::OffsetBot;
3635 BasicType bt = T_INT;
3636 if (offset == Type::OffsetBot && field_offset == Type::OffsetBot) {
3637 // Check only oop fields.
3638 if (!adr_type->isa_aryptr() ||
3639 adr_type->isa_aryptr()->elem() == Type::BOTTOM ||
3640 adr_type->isa_aryptr()->elem()->make_oopptr() != nullptr) {
3641 // OffsetBot is used to reference array's element. Ignore first AddP.
3642 if (find_second_addp(n, n->in(AddPNode::Base)) == nullptr) {
3643 bt = T_OBJECT;
3644 }
3645 }
3646 } else if (offset != oopDesc::klass_offset_in_bytes()) {
3647 if (adr_type->isa_instptr()) {
3648 ciField* field = _compile->alias_type(adr_type->is_ptr())->field();
3649 if (field != nullptr) {
3650 bt = field->layout_type();
3651 } else {
3652 // Check for unsafe oop field access
3653 if (n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3654 n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3655 n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3656 BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n)) {
3657 bt = T_OBJECT;
3658 (*unsafe) = true;
3659 }
3660 }
3661 } else if (adr_type->isa_aryptr()) {
3662 if (offset == arrayOopDesc::length_offset_in_bytes()) {
3663 // Ignore array length load.
3664 } else if (find_second_addp(n, n->in(AddPNode::Base)) != nullptr) {
3665 // Ignore first AddP.
3666 } else {
3667 const Type* elemtype = adr_type->is_aryptr()->elem();
3668 if (adr_type->is_aryptr()->is_flat() && field_offset != Type::OffsetBot) {
3669 ciInlineKlass* vk = elemtype->inline_klass();
3670 field_offset += vk->payload_offset();
3671 ciField* field = vk->get_field_by_offset(field_offset, false);
3672 if (field != nullptr) {
3673 bt = field->layout_type();
3674 } else {
3675 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);
3676 bt = T_BOOLEAN;
3677 }
3678 } else {
3679 bt = elemtype->array_element_basic_type();
3680 }
3681 }
3682 } else if (adr_type->isa_rawptr() || adr_type->isa_klassptr()) {
3683 // Allocation initialization, ThreadLocal field access, unsafe access
3684 if (n->has_out_with(Op_StoreP, Op_LoadP, Op_StoreN, Op_LoadN) ||
3685 n->has_out_with(Op_GetAndSetP, Op_GetAndSetN, Op_CompareAndExchangeP, Op_CompareAndExchangeN) ||
3686 n->has_out_with(Op_CompareAndSwapP, Op_CompareAndSwapN, Op_WeakCompareAndSwapP, Op_WeakCompareAndSwapN) ||
3687 BarrierSet::barrier_set()->barrier_set_c2()->escape_has_out_with_unsafe_object(n)) {
3688 bt = T_OBJECT;
3689 }
3690 }
3691 }
3692 // Note: T_NARROWOOP is not classed as a real reference type
3693 return (is_reference_type(bt) || bt == T_NARROWOOP);
3694 }
3695
3696 // Returns unique pointed java object or null.
3697 JavaObjectNode* ConnectionGraph::unique_java_object(Node *n) const {
3698 // If the node was created after the escape computation we can't answer.
3699 uint idx = n->_idx;
3700 if (idx >= nodes_size()) {
3857 return true;
3858 }
3859 }
3860 }
3861 }
3862 }
3863 return false;
3864 }
3865
3866 int ConnectionGraph::address_offset(Node* adr, PhaseValues* phase) {
3867 const Type *adr_type = phase->type(adr);
3868 if (adr->is_AddP() && adr_type->isa_oopptr() == nullptr && is_captured_store_address(adr)) {
3869 // We are computing a raw address for a store captured by an Initialize
3870 // compute an appropriate address type. AddP cases #3 and #5 (see below).
3871 int offs = (int)phase->find_intptr_t_con(adr->in(AddPNode::Offset), Type::OffsetBot);
3872 assert(offs != Type::OffsetBot ||
3873 adr->in(AddPNode::Address)->in(0)->is_AllocateArray(),
3874 "offset must be a constant or it is initialization of array");
3875 return offs;
3876 }
3877 return adr_type->is_ptr()->flat_offset();
3878 }
3879
3880 Node* ConnectionGraph::get_addp_base(Node *addp) {
3881 assert(addp->is_AddP(), "must be AddP");
3882 //
3883 // AddP cases for Base and Address inputs:
3884 // case #1. Direct object's field reference:
3885 // Allocate
3886 // |
3887 // Proj #5 ( oop result )
3888 // |
3889 // CheckCastPP (cast to instance type)
3890 // | |
3891 // AddP ( base == address )
3892 //
3893 // case #2. Indirect object's field reference:
3894 // Phi
3895 // |
3896 // CastPP (cast to instance type)
3897 // | |
4011 }
4012 return nullptr;
4013 }
4014
4015 //
4016 // Adjust the type and inputs of an AddP which computes the
4017 // address of a field of an instance
4018 //
4019 bool ConnectionGraph::split_AddP(Node *addp, Node *base) {
4020 PhaseGVN* igvn = _igvn;
4021 const TypeOopPtr *base_t = igvn->type(base)->isa_oopptr();
4022 assert(base_t != nullptr && base_t->is_known_instance(), "expecting instance oopptr");
4023 const TypeOopPtr *t = igvn->type(addp)->isa_oopptr();
4024 if (t == nullptr) {
4025 // We are computing a raw address for a store captured by an Initialize
4026 // compute an appropriate address type (cases #3 and #5).
4027 assert(igvn->type(addp) == TypeRawPtr::NOTNULL, "must be raw pointer");
4028 assert(addp->in(AddPNode::Address)->is_Proj(), "base of raw address must be result projection from allocation");
4029 intptr_t offs = (int)igvn->find_intptr_t_con(addp->in(AddPNode::Offset), Type::OffsetBot);
4030 assert(offs != Type::OffsetBot, "offset must be a constant");
4031 if (base_t->isa_aryptr() != nullptr) {
4032 // In the case of a flat inline type array, each field has its
4033 // own slice so we need to extract the field being accessed from
4034 // the address computation
4035 t = base_t->isa_aryptr()->add_field_offset_and_offset(offs)->is_oopptr();
4036 } else {
4037 t = base_t->add_offset(offs)->is_oopptr();
4038 }
4039 }
4040 int inst_id = base_t->instance_id();
4041 assert(!t->is_known_instance() || t->instance_id() == inst_id,
4042 "old type must be non-instance or match new type");
4043
4044 // The type 't' could be subclass of 'base_t'.
4045 // As result t->offset() could be large then base_t's size and it will
4046 // cause the failure in add_offset() with narrow oops since TypeOopPtr()
4047 // constructor verifies correctness of the offset.
4048 //
4049 // It could happened on subclass's branch (from the type profiling
4050 // inlining) which was not eliminated during parsing since the exactness
4051 // of the allocation type was not propagated to the subclass type check.
4052 //
4053 // Or the type 't' could be not related to 'base_t' at all.
4054 // It could happen when CHA type is different from MDO type on a dead path
4055 // (for example, from instanceof check) which is not collapsed during parsing.
4056 //
4057 // Do nothing for such AddP node and don't process its users since
4058 // this code branch will go away.
4059 //
4060 if (!t->is_known_instance() &&
4061 !base_t->maybe_java_subtype_of(t)) {
4062 return false; // bail out
4063 }
4064 const TypePtr* tinst = base_t->add_offset(t->offset());
4065 if (tinst->isa_aryptr() && t->isa_aryptr()) {
4066 // In the case of a flat inline type array, each field has its
4067 // own slice so we need to keep track of the field being accessed.
4068 tinst = tinst->is_aryptr()->with_field_offset(t->is_aryptr()->field_offset().get());
4069 // Keep array properties (not flat/null-free)
4070 tinst = tinst->is_aryptr()->update_properties(t->is_aryptr());
4071 if (tinst == nullptr) {
4072 return false; // Skip dead path with inconsistent properties
4073 }
4074 }
4075
4076 // Do NOT remove the next line: ensure a new alias index is allocated
4077 // for the instance type. Note: C++ will not remove it since the call
4078 // has side effect.
4079 int alias_idx = _compile->get_alias_index(tinst);
4080 igvn->set_type(addp, tinst);
4081 // record the allocation in the node map
4082 set_map(addp, get_map(base->_idx));
4083 // Set addp's Base and Address to 'base'.
4084 Node *abase = addp->in(AddPNode::Base);
4085 Node *adr = addp->in(AddPNode::Address);
4086 if (adr->is_Proj() && adr->in(0)->is_Allocate() &&
4087 adr->in(0)->_idx == (uint)inst_id) {
4088 // Skip AddP cases #3 and #5.
4089 } else {
4090 assert(!abase->is_top(), "sanity"); // AddP case #3
4091 if (abase != base) {
4092 igvn->hash_delete(addp);
4093 addp->set_req(AddPNode::Base, base);
4094 if (abase == adr) {
4095 addp->set_req(AddPNode::Address, base);
4665 // - not determined to be ineligible by escape analysis
4666 set_map(alloc, n);
4667 set_map(n, alloc);
4668 const TypeOopPtr* tinst = t->cast_to_instance_id(ni);
4669 igvn->hash_delete(n);
4670 igvn->set_type(n, tinst);
4671 n->raise_bottom_type(tinst);
4672 igvn->hash_insert(n);
4673 record_for_optimizer(n);
4674 // Allocate an alias index for the header fields. Accesses to
4675 // the header emitted during macro expansion wouldn't have
4676 // correct memory state otherwise.
4677 _compile->get_alias_index(tinst->add_offset(oopDesc::mark_offset_in_bytes()));
4678 _compile->get_alias_index(tinst->add_offset(oopDesc::klass_offset_in_bytes()));
4679 if (alloc->is_Allocate() && (t->isa_instptr() || t->isa_aryptr())) {
4680 // Add a new NarrowMem projection for each existing NarrowMem projection with new adr type
4681 InitializeNode* init = alloc->as_Allocate()->initialization();
4682 assert(init != nullptr, "can't find Initialization node for this Allocate node");
4683 auto process_narrow_proj = [&](NarrowMemProjNode* proj) {
4684 const TypePtr* adr_type = proj->adr_type();
4685 const TypePtr* new_adr_type = tinst->with_offset(adr_type->offset());
4686 if (adr_type->isa_aryptr()) {
4687 // In the case of a flat inline type array, each field has its own slice so we need a
4688 // NarrowMemProj for each field of the flat array elements
4689 new_adr_type = new_adr_type->is_aryptr()->with_field_offset(adr_type->is_aryptr()->field_offset().get());
4690 }
4691 if (adr_type != new_adr_type && !init->already_has_narrow_mem_proj_with_adr_type(new_adr_type)) {
4692 DEBUG_ONLY( uint alias_idx = _compile->get_alias_index(new_adr_type); )
4693 assert(_compile->get_general_index(alias_idx) == _compile->get_alias_index(adr_type), "new adr type should be narrowed down from existing adr type");
4694 NarrowMemProjNode* new_proj = new NarrowMemProjNode(init, new_adr_type);
4695 igvn->set_type(new_proj, new_proj->bottom_type());
4696 record_for_optimizer(new_proj);
4697 set_map(proj, new_proj); // record it so ConnectionGraph::find_inst_mem() can find it
4698 }
4699 };
4700 init->for_each_narrow_mem_proj_with_new_uses(process_narrow_proj);
4701
4702 // First, put on the worklist all Field edges from Connection Graph
4703 // which is more accurate than putting immediate users from Ideal Graph.
4704 for (EdgeIterator e(ptn); e.has_next(); e.next()) {
4705 PointsToNode* tgt = e.get();
4706 if (tgt->is_Arraycopy()) {
4707 continue;
4708 }
4709 Node* use = tgt->ideal_node();
4710 assert(tgt->is_Field() && use->is_AddP(),
4787 ptnode_adr(n->_idx)->dump();
4788 assert(jobj != nullptr && jobj != phantom_obj, "escaped allocation");
4789 #endif
4790 _compile->record_failure(_invocation > 0 ? C2Compiler::retry_no_iterative_escape_analysis() : C2Compiler::retry_no_escape_analysis());
4791 return;
4792 } else {
4793 Node *val = get_map(jobj->idx()); // CheckCastPP node
4794 TypeNode *tn = n->as_Type();
4795 const TypeOopPtr* tinst = igvn->type(val)->isa_oopptr();
4796 assert(tinst != nullptr && tinst->is_known_instance() &&
4797 tinst->instance_id() == jobj->idx() , "instance type expected.");
4798
4799 const Type *tn_type = igvn->type(tn);
4800 const TypeOopPtr *tn_t;
4801 if (tn_type->isa_narrowoop()) {
4802 tn_t = tn_type->make_ptr()->isa_oopptr();
4803 } else {
4804 tn_t = tn_type->isa_oopptr();
4805 }
4806 if (tn_t != nullptr && tinst->maybe_java_subtype_of(tn_t)) {
4807 if (tn_t->isa_aryptr()) {
4808 // Keep array properties (not flat/null-free)
4809 tinst = tinst->is_aryptr()->update_properties(tn_t->is_aryptr());
4810 if (tinst == nullptr) {
4811 continue; // Skip dead path with inconsistent properties
4812 }
4813 }
4814 if (tn_type->isa_narrowoop()) {
4815 tn_type = tinst->make_narrowoop();
4816 } else {
4817 tn_type = tinst;
4818 }
4819 igvn->hash_delete(tn);
4820 igvn->set_type(tn, tn_type);
4821 tn->set_type(tn_type);
4822 igvn->hash_insert(tn);
4823 record_for_optimizer(n);
4824 } else {
4825 assert(tn_type == TypePtr::NULL_PTR ||
4826 (tn_t != nullptr && !tinst->maybe_java_subtype_of(tn_t)),
4827 "unexpected type");
4828 continue; // Skip dead path with different type
4829 }
4830 }
4831 } else {
4832 DEBUG_ONLY(n->dump();)
4833 assert(false, "EA: unexpected node");
4834 continue;
4835 }
4836 // push allocation's users on appropriate worklist
4837 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
4838 Node *use = n->fast_out(i);
4839 if (use->is_Mem() && use->in(MemNode::Address) == n) {
4840 // Load/store to instance's field
4841 memnode_worklist.append_if_missing(use);
4842 } else if (use->is_MemBar()) {
4843 if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
4844 memnode_worklist.append_if_missing(use);
4845 }
4846 } else if (use->is_AddP() && use->outcnt() > 0) { // No dead nodes
4847 Node* addp2 = find_second_addp(use, n);
4848 if (addp2 != nullptr) {
4849 alloc_worklist.append_if_missing(addp2);
4850 }
4851 alloc_worklist.append_if_missing(use);
4852 } else if (use->is_Phi() ||
4853 use->is_CheckCastPP() ||
4854 use->is_EncodeNarrowPtr() ||
4855 use->is_DecodeNarrowPtr() ||
4856 (use->is_ConstraintCast() && use->Opcode() == Op_CastPP)) {
4857 alloc_worklist.append_if_missing(use);
4858 #ifdef ASSERT
4859 } else if (use->is_Mem()) {
4860 assert(use->in(MemNode::Address) != n, "EA: missing allocation reference path");
4861 } else if (use->is_MergeMem()) {
4862 assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4863 } else if (use->is_SafePoint()) {
4864 // Look for MergeMem nodes for calls which reference unique allocation
4865 // (through CheckCastPP nodes) even for debug info.
4866 Node* m = use->in(TypeFunc::Memory);
4867 if (m->is_MergeMem()) {
4868 assert(mergemem_worklist.contains(m->as_MergeMem()), "EA: missing MergeMem node in the worklist");
4869 }
4870 } else if (use->Opcode() == Op_EncodeISOArray) {
4871 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
4872 // EncodeISOArray overwrites destination array
4873 memnode_worklist.append_if_missing(use);
4874 }
4875 } else if (use->Opcode() == Op_Return) {
4876 // Allocation is referenced by field of returned inline type
4877 assert(_compile->tf()->returns_inline_type_as_fields(), "EA: unexpected reference by ReturnNode");
4878 } else {
4879 uint op = use->Opcode();
4880 if ((op == Op_StrCompressedCopy || op == Op_StrInflatedCopy) &&
4881 (use->in(MemNode::Memory) == n)) {
4882 // They overwrite memory edge corresponding to destination array,
4883 memnode_worklist.append_if_missing(use);
4884 } else if (!(op == Op_CmpP || op == Op_Conv2B ||
4885 op == Op_CastP2X ||
4886 op == Op_FastLock || op == Op_AryEq ||
4887 op == Op_StrComp || op == Op_CountPositives ||
4888 op == Op_StrCompressedCopy || op == Op_StrInflatedCopy ||
4889 op == Op_StrEquals || op == Op_VectorizedHashCode ||
4890 op == Op_StrIndexOf || op == Op_StrIndexOfChar ||
4891 op == Op_SubTypeCheck || op == Op_InlineType || op == Op_FlatArrayCheck ||
4892 op == Op_ReinterpretS2HF ||
4893 BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use))) {
4894 n->dump();
4895 use->dump();
4896 assert(false, "EA: missing allocation reference path");
4897 }
4898 #endif
4899 }
4900 }
4901
4902 }
4903
4904 #ifdef ASSERT
4905 if (VerifyReduceAllocationMerges) {
4906 for (uint i = 0; i < reducible_merges.size(); i++) {
4907 Node* phi = reducible_merges.at(i);
4908
4909 if (!reduced_merges.member(phi)) {
4910 phi->dump(2);
4911 phi->dump(-2);
4979 n = n->as_MemBar()->proj_out_or_null(TypeFunc::Memory);
4980 if (n == nullptr) {
4981 continue;
4982 }
4983 }
4984 } else if (n->is_CallLeaf()) {
4985 // Runtime calls with narrow memory input (no MergeMem node)
4986 // get the memory projection
4987 n = n->as_Call()->proj_out_or_null(TypeFunc::Memory);
4988 if (n == nullptr) {
4989 continue;
4990 }
4991 } else if (n->Opcode() == Op_StrInflatedCopy) {
4992 // Check direct uses of StrInflatedCopy.
4993 // It is memory type Node - no special SCMemProj node.
4994 } else if (n->Opcode() == Op_StrCompressedCopy ||
4995 n->Opcode() == Op_EncodeISOArray) {
4996 // get the memory projection
4997 n = n->find_out_with(Op_SCMemProj);
4998 assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
4999 } else if (n->is_CallLeaf() && n->as_CallLeaf()->_name != nullptr &&
5000 strcmp(n->as_CallLeaf()->_name, "store_unknown_inline") == 0) {
5001 n = n->as_CallLeaf()->proj_out(TypeFunc::Memory);
5002 } else if (n->is_Proj()) {
5003 assert(n->in(0)->is_Initialize(), "we only push memory projections for Initialize");
5004 } else {
5005 #ifdef ASSERT
5006 if (!n->is_Mem()) {
5007 n->dump();
5008 }
5009 assert(n->is_Mem(), "memory node required.");
5010 #endif
5011 Node *addr = n->in(MemNode::Address);
5012 const Type *addr_t = igvn->type(addr);
5013 if (addr_t == Type::TOP) {
5014 continue;
5015 }
5016 assert (addr_t->isa_ptr() != nullptr, "pointer type required.");
5017 int alias_idx = _compile->get_alias_index(addr_t->is_ptr());
5018 assert ((uint)alias_idx < new_index_end, "wrong alias index");
5019 Node *mem = find_inst_mem(n->in(MemNode::Memory), alias_idx, orig_phis);
5020 if (_compile->failing()) {
5021 return;
5033 assert(n != nullptr && n->Opcode() == Op_SCMemProj, "memory projection required");
5034 }
5035 }
5036 // push user on appropriate worklist
5037 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
5038 Node *use = n->fast_out(i);
5039 if (use->is_Phi() || use->is_ClearArray()) {
5040 memnode_worklist.append_if_missing(use);
5041 } else if (use->is_Mem() && use->in(MemNode::Memory) == n) {
5042 memnode_worklist.append_if_missing(use);
5043 } else if (use->is_MemBar() || use->is_CallLeaf()) {
5044 if (use->in(TypeFunc::Memory) == n) { // Ignore precedent edge
5045 memnode_worklist.append_if_missing(use);
5046 }
5047 } else if (use->is_Proj()) {
5048 assert(n->is_Initialize(), "We only push projections of Initialize");
5049 if (use->as_Proj()->_con == TypeFunc::Memory) { // Ignore precedent edge
5050 memnode_worklist.append_if_missing(use);
5051 }
5052 #ifdef ASSERT
5053 } else if (use->is_Mem()) {
5054 assert(use->in(MemNode::Memory) != n, "EA: missing memory path");
5055 } else if (use->is_MergeMem()) {
5056 assert(mergemem_worklist.contains(use->as_MergeMem()), "EA: missing MergeMem node in the worklist");
5057 } else if (use->Opcode() == Op_EncodeISOArray) {
5058 if (use->in(MemNode::Memory) == n || use->in(3) == n) {
5059 // EncodeISOArray overwrites destination array
5060 memnode_worklist.append_if_missing(use);
5061 }
5062 } else if (use->is_CallLeaf() && use->as_CallLeaf()->_name != nullptr &&
5063 strcmp(use->as_CallLeaf()->_name, "store_unknown_inline") == 0) {
5064 // store_unknown_inline overwrites destination array
5065 memnode_worklist.append_if_missing(use);
5066 } else {
5067 uint op = use->Opcode();
5068 if ((use->in(MemNode::Memory) == n) &&
5069 (op == Op_StrCompressedCopy || op == Op_StrInflatedCopy)) {
5070 // They overwrite memory edge corresponding to destination array,
5071 memnode_worklist.append_if_missing(use);
5072 } else if (!(BarrierSet::barrier_set()->barrier_set_c2()->is_gc_barrier_node(use) ||
5073 op == Op_AryEq || op == Op_StrComp || op == Op_CountPositives ||
5074 op == Op_StrCompressedCopy || op == Op_StrInflatedCopy || op == Op_VectorizedHashCode ||
5075 op == Op_StrEquals || op == Op_StrIndexOf || op == Op_StrIndexOfChar || op == Op_FlatArrayCheck)) {
5076 n->dump();
5077 use->dump();
5078 assert(false, "EA: missing memory path");
5079 }
5080 #endif
5081 }
5082 }
5083 }
5084
5085 // Phase 3: Process MergeMem nodes from mergemem_worklist.
5086 // Walk each memory slice moving the first node encountered of each
5087 // instance type to the input corresponding to its alias index.
5088 uint length = mergemem_worklist.length();
5089 for( uint next = 0; next < length; ++next ) {
5090 MergeMemNode* nmm = mergemem_worklist.at(next);
5091 assert(!visited.test_set(nmm->_idx), "should not be visited before");
5092 // Note: we don't want to use MergeMemStream here because we only want to
5093 // scan inputs which exist at the start, not ones we add during processing.
5094 // Note 2: MergeMem may already contains instance memory slices added
5095 // during find_inst_mem() call when memory nodes were processed above.
5158 _compile->record_failure(C2Compiler::retry_no_reduce_allocation_merges());
5159 } else if (_invocation > 0) {
5160 _compile->record_failure(C2Compiler::retry_no_iterative_escape_analysis());
5161 } else {
5162 _compile->record_failure(C2Compiler::retry_no_escape_analysis());
5163 }
5164 return;
5165 }
5166
5167 igvn->hash_insert(nmm);
5168 record_for_optimizer(nmm);
5169 }
5170
5171 _compile->print_method(PHASE_EA_AFTER_SPLIT_UNIQUE_TYPES_3, 5);
5172
5173 // Phase 4: Update the inputs of non-instance memory Phis and
5174 // the Memory input of memnodes
5175 // First update the inputs of any non-instance Phi's from
5176 // which we split out an instance Phi. Note we don't have
5177 // to recursively process Phi's encountered on the input memory
5178 // chains as is done in split_memory_phi() since they will
5179 // also be processed here.
5180 for (int j = 0; j < orig_phis.length(); j++) {
5181 PhiNode *phi = orig_phis.at(j);
5182 int alias_idx = _compile->get_alias_index(phi->adr_type());
5183 igvn->hash_delete(phi);
5184 for (uint i = 1; i < phi->req(); i++) {
5185 Node *mem = phi->in(i);
5186 Node *new_mem = find_inst_mem(mem, alias_idx, orig_phis);
5187 if (_compile->failing()) {
5188 return;
5189 }
5190 if (mem != new_mem) {
5191 phi->set_req(i, new_mem);
5192 }
5193 }
5194 igvn->hash_insert(phi);
5195 record_for_optimizer(phi);
5196 }
5197
5198 // Update the memory inputs of MemNodes with the value we computed
|