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