1 /*
2 * Copyright (c) 1997, 2026, 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/ciObjArrayKlass.hpp"
26 #include "ci/ciSignature.hpp"
27 #include "ci/ciTypeFlow.hpp"
28 #include "compiler/compileLog.hpp"
29 #include "interpreter/linkResolver.hpp"
30 #include "memory/resourceArea.hpp"
31 #include "oops/method.hpp"
32 #include "opto/addnode.hpp"
33 #include "opto/c2compiler.hpp"
34 #include "opto/castnode.hpp"
35 #include "opto/convertnode.hpp"
36 #include "opto/idealGraphPrinter.hpp"
37 #include "opto/inlinetypenode.hpp"
38 #include "opto/locknode.hpp"
39 #include "opto/memnode.hpp"
40 #include "opto/opaquenode.hpp"
41 #include "opto/parse.hpp"
42 #include "opto/rootnode.hpp"
43 #include "opto/runtime.hpp"
44 #include "opto/type.hpp"
45 #include "runtime/arguments.hpp"
46 #include "runtime/handles.inline.hpp"
47 #include "runtime/safepointMechanism.hpp"
48 #include "runtime/sharedRuntime.hpp"
49 #include "utilities/bitMap.inline.hpp"
50 #include "utilities/copy.hpp"
51
52 // Static array so we can figure out which bytecodes stop us from compiling
53 // the most. Some of the non-static variables are needed in bytecodeInfo.cpp
54 // and eventually should be encapsulated in a proper class (gri 8/18/98).
55
56 #ifndef PRODUCT
57 uint nodes_created = 0;
58 uint methods_parsed = 0;
59 uint methods_seen = 0;
60 uint blocks_parsed = 0;
61 uint blocks_seen = 0;
62
63 uint explicit_null_checks_inserted = 0;
64 uint explicit_null_checks_elided = 0;
65 uint all_null_checks_found = 0;
66 uint implicit_null_checks = 0;
67
68 bool Parse::BytecodeParseHistogram::_initialized = false;
69 uint Parse::BytecodeParseHistogram::_bytecodes_parsed [Bytecodes::number_of_codes];
70 uint Parse::BytecodeParseHistogram::_nodes_constructed[Bytecodes::number_of_codes];
71 uint Parse::BytecodeParseHistogram::_nodes_transformed[Bytecodes::number_of_codes];
72 uint Parse::BytecodeParseHistogram::_new_values [Bytecodes::number_of_codes];
73
74 //------------------------------print_statistics-------------------------------
75 void Parse::print_statistics() {
76 tty->print_cr("--- Compiler Statistics ---");
77 tty->print("Methods seen: %u Methods parsed: %u", methods_seen, methods_parsed);
78 tty->print(" Nodes created: %u", nodes_created);
79 tty->cr();
80 if (methods_seen != methods_parsed) {
81 tty->print_cr("Reasons for parse failures (NOT cumulative):");
82 }
83 tty->print_cr("Blocks parsed: %u Blocks seen: %u", blocks_parsed, blocks_seen);
84
85 if (explicit_null_checks_inserted) {
86 tty->print_cr("%u original null checks - %u elided (%2u%%); optimizer leaves %u,",
87 explicit_null_checks_inserted, explicit_null_checks_elided,
88 (100*explicit_null_checks_elided)/explicit_null_checks_inserted,
89 all_null_checks_found);
90 }
91 if (all_null_checks_found) {
92 tty->print_cr("%u made implicit (%2u%%)", implicit_null_checks,
93 (100*implicit_null_checks)/all_null_checks_found);
94 }
95 if (SharedRuntime::_implicit_null_throws) {
96 tty->print_cr("%u implicit null exceptions at runtime",
97 SharedRuntime::_implicit_null_throws);
98 }
99
100 if (PrintParseStatistics && BytecodeParseHistogram::initialized()) {
101 BytecodeParseHistogram::print();
102 }
103 }
104 #endif
105
106 //------------------------------ON STACK REPLACEMENT---------------------------
107
108 // Construct a node which can be used to get incoming state for
109 // on stack replacement.
110 Node* Parse::fetch_interpreter_state(int index,
111 const Type* type,
112 Node* local_addrs) {
113 BasicType bt = type->basic_type();
114 if (type == TypePtr::NULL_PTR) {
115 // Ptr types are mixed together with T_ADDRESS but nullptr is
116 // really for T_OBJECT types so correct it.
117 bt = T_OBJECT;
118 }
119 Node* mem = memory(Compile::AliasIdxRaw);
120 Node* adr = off_heap_plus_addr(local_addrs, -index*wordSize);
121 Node* ctl = control();
122
123 // Very similar to LoadNode::make, except we handle un-aligned longs and
124 // doubles on Sparc. Intel can handle them just fine directly.
125 Node *l = nullptr;
126 switch (bt) { // Signature is flattened
127 case T_INT: l = new LoadINode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeInt::INT, MemNode::unordered); break;
128 case T_FLOAT: l = new LoadFNode(ctl, mem, adr, TypeRawPtr::BOTTOM, Type::FLOAT, MemNode::unordered); break;
129 case T_ADDRESS: l = new LoadPNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM, MemNode::unordered); break;
130 case T_OBJECT: l = new LoadPNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeInstPtr::BOTTOM, MemNode::unordered); break;
131 case T_LONG:
132 case T_DOUBLE: {
133 // Since arguments are in reverse order, the argument address 'adr'
134 // refers to the back half of the long/double. Recompute adr.
135 adr = off_heap_plus_addr(local_addrs, -(index+1)*wordSize);
136 if (Matcher::misaligned_doubles_ok) {
137 l = (bt == T_DOUBLE)
138 ? (Node*)new LoadDNode(ctl, mem, adr, TypeRawPtr::BOTTOM, Type::DOUBLE, MemNode::unordered)
139 : (Node*)new LoadLNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeLong::LONG, MemNode::unordered);
140 } else {
141 l = (bt == T_DOUBLE)
142 ? (Node*)new LoadD_unalignedNode(ctl, mem, adr, TypeRawPtr::BOTTOM, MemNode::unordered)
143 : (Node*)new LoadL_unalignedNode(ctl, mem, adr, TypeRawPtr::BOTTOM, MemNode::unordered);
144 }
145 break;
146 }
147 default: ShouldNotReachHere();
148 }
149 return _gvn.transform(l);
150 }
151
152 // Helper routine to prevent the interpreter from handing
153 // unexpected typestate to an OSR method.
154 // The Node l is a value newly dug out of the interpreter frame.
155 // The type is the type predicted by ciTypeFlow. Note that it is
156 // not a general type, but can only come from Type::get_typeflow_type.
157 // The safepoint is a map which will feed an uncommon trap.
158 Node* Parse::check_interpreter_type(Node* l, ciType* ci_type, SafePointNode* &bad_type_exit) {
159 ciType* unwrapped_ci_type = ci_type->unwrap();
160
161 // TypeFlow may assert null-ness if a type appears unloaded.
162 if (int(unwrapped_ci_type->basic_type()) == int(ciTypeFlow::StateVector::T_NULL) ||
163 !unwrapped_ci_type->is_loaded()) {
164 // Value must be null, not a real oop.
165 Node* chk = _gvn.transform(new CmpPNode(l, null()));
166 Node* tst = _gvn.transform(new BoolNode(chk, BoolTest::eq));
167 IfNode* iff = create_and_map_if(control(), tst, PROB_MAX, COUNT_UNKNOWN);
168 set_control(_gvn.transform(new IfTrueNode(iff)));
169 Node* bad_type = _gvn.transform(new IfFalseNode(iff));
170 bad_type_exit->control()->add_req(bad_type);
171 l = null();
172 }
173
174 // Typeflow can also cut off paths from the CFG, based on
175 // types which appear unloaded, or call sites which appear unlinked.
176 // When paths are cut off, values at later merge points can rise
177 // toward more specific classes. Make sure these specific classes
178 // are still in effect.
179 if (unwrapped_ci_type->is_klass()) {
180 // TypeFlow asserted a specific object type. Value must have that type.
181 assert(_gvn.type(l) == TypePtr::NULL_PTR || _gvn.type(l)->isa_oopptr(), "must be an oop");
182 if (ci_type->is_null_free()) {
183 // Check inline types for null here to prevent checkcast from adding an
184 // exception state before the bytecode entry (use 'bad_type_ctrl' instead).
185 Node* bad_type_ctrl = nullptr;
186 l = null_check_oop(l, &bad_type_ctrl);
187 bad_type_exit->control()->add_req(bad_type_ctrl);
188 }
189
190 const TypeKlassPtr* klass_type = TypeKlassPtr::make(unwrapped_ci_type->as_klass(), Type::ignore_interfaces);
191 klass_type = klass_type->try_improve();
192 bool is_early_larval = ci_type->is_early_larval();
193 Node* bad_type_ctrl = nullptr;
194 l = gen_checkcast(l, makecon(klass_type), &bad_type_ctrl, nullptr, false, is_early_larval);
195 bad_type_exit->control()->add_req(bad_type_ctrl);
196 } else {
197 const Type* type = Type::get_typeflow_type(ci_type);
198 assert(_gvn.type(l)->higher_equal(type), "must match");
199 }
200
201 return l;
202 }
203
204 // Helper routine which sets up elements of the initial parser map when
205 // performing a parse for on stack replacement. Add values into map.
206 // The only parameter contains the address of a interpreter arguments.
207 void Parse::load_interpreter_state(Node* osr_buf) {
208 int index;
209 int max_locals = jvms()->loc_size();
210 int max_stack = jvms()->stk_size();
211
212 // Mismatch between method and jvms can occur since map briefly held
213 // an OSR entry state (which takes up one RawPtr word).
214 assert(max_locals == method()->max_locals(), "sanity");
215 assert(max_stack >= method()->max_stack(), "sanity");
216 assert((int)jvms()->endoff() == TypeFunc::Parms + max_locals + max_stack, "sanity");
217 assert((int)jvms()->endoff() == (int)map()->req(), "sanity");
218
219 // Find the start block.
220 Block* osr_block = start_block();
221 assert(osr_block->start() == osr_bci(), "sanity");
222
223 // Set initial BCI.
224 set_parse_bci(osr_block->start());
225
226 // Set initial stack depth.
227 set_sp(osr_block->start_sp());
228
229 // Check bailouts. We currently do not perform on stack replacement
230 // of loops in catch blocks or loops which branch with a non-empty stack.
231 if (sp() != 0) {
232 C->record_method_not_compilable("OSR starts with non-empty stack");
233 return;
234 }
235 // Do not OSR inside finally clauses:
236 if (osr_block->has_trap_at(osr_block->start())) {
237 assert(false, "OSR starts with an immediate trap");
238 C->record_method_not_compilable("OSR starts with an immediate trap");
239 return;
240 }
241
242 // Commute monitors from interpreter frame to compiler frame.
243 assert(jvms()->monitor_depth() == 0, "should be no active locks at beginning of osr");
244 int mcnt = osr_block->flow()->monitor_count();
245 Node* monitors_addr = off_heap_plus_addr(osr_buf, (max_locals+mcnt*2-1)*wordSize);
246 for (index = 0; index < mcnt; index++) {
247 // Make a BoxLockNode for the monitor.
248 BoxLockNode* osr_box = new BoxLockNode(next_monitor());
249 // Check for bailout after new BoxLockNode
250 if (failing()) { return; }
251
252 // This OSR locking region is unbalanced because it does not have Lock node:
253 // locking was done in Interpreter.
254 // This is similar to Coarsened case when Lock node is eliminated
255 // and as result the region is marked as Unbalanced.
256
257 // Emulate Coarsened state transition from Regular to Unbalanced.
258 osr_box->set_coarsened();
259 osr_box->set_unbalanced();
260
261 Node* box = _gvn.transform(osr_box);
262
263 // Displaced headers and locked objects are interleaved in the
264 // temp OSR buffer. We only copy the locked objects out here.
265 // Fetch the locked object from the OSR temp buffer and copy to our fastlock node.
266 Node* lock_object = fetch_interpreter_state(index*2, Type::get_const_basic_type(T_OBJECT), monitors_addr);
267 // Try and copy the displaced header to the BoxNode
268 Node* displaced_hdr = fetch_interpreter_state((index*2) + 1, Type::get_const_basic_type(T_ADDRESS), monitors_addr);
269
270 store_to_memory(control(), box, displaced_hdr, T_ADDRESS, MemNode::unordered);
271
272 // Build a bogus FastLockNode (no code will be generated) and push the
273 // monitor into our debug info.
274 const FastLockNode *flock = _gvn.transform(new FastLockNode( nullptr, lock_object, box ))->as_FastLock();
275 map()->push_monitor(flock);
276
277 // If the lock is our method synchronization lock, tuck it away in
278 // _sync_lock for return and rethrow exit paths.
279 if (index == 0 && method()->is_synchronized()) {
280 _synch_lock = flock;
281 }
282 }
283
284 // Use the raw liveness computation to make sure that unexpected
285 // values don't propagate into the OSR frame.
286 MethodLivenessResult live_locals = method()->liveness_at_bci(osr_bci());
287 if (!live_locals.is_valid()) {
288 // Degenerate or breakpointed method.
289 assert(false, "OSR in empty or breakpointed method");
290 C->record_method_not_compilable("OSR in empty or breakpointed method");
291 return;
292 }
293
294 // Extract the needed locals from the interpreter frame.
295 Node* locals_addr = off_heap_plus_addr(osr_buf, (max_locals-1)*wordSize);
296
297 // find all the locals that the interpreter thinks contain live oops
298 const ResourceBitMap live_oops = method()->live_local_oops_at_bci(osr_bci());
299 for (index = 0; index < max_locals; index++) {
300
301 if (!live_locals.at(index)) {
302 continue;
303 }
304
305 const Type *type = osr_block->local_type_at(index);
306
307 if (type->isa_oopptr() != nullptr) {
308
309 // 6403625: Verify that the interpreter oopMap thinks that the oop is live
310 // else we might load a stale oop if the MethodLiveness disagrees with the
311 // result of the interpreter. If the interpreter says it is dead we agree
312 // by making the value go to top.
313 //
314
315 if (!live_oops.at(index)) {
316 if (C->log() != nullptr) {
317 C->log()->elem("OSR_mismatch local_index='%d'",index);
318 }
319 set_local(index, null());
320 // and ignore it for the loads
321 continue;
322 }
323 }
324
325 // Filter out TOP, HALF, and BOTTOM. (Cf. ensure_phi.)
326 if (type == Type::TOP || type == Type::HALF) {
327 continue;
328 }
329 // If the type falls to bottom, then this must be a local that
330 // is mixing ints and oops or some such. Forcing it to top
331 // makes it go dead.
332 if (type == Type::BOTTOM) {
333 continue;
334 }
335 // Construct code to access the appropriate local.
336 Node* value = fetch_interpreter_state(index, type, locals_addr);
337 set_local(index, value);
338 }
339
340 // Extract the needed stack entries from the interpreter frame.
341 for (index = 0; index < sp(); index++) {
342 const Type *type = osr_block->stack_type_at(index);
343 if (type != Type::TOP) {
344 // Currently the compiler bails out when attempting to on stack replace
345 // at a bci with a non-empty stack. We should not reach here.
346 ShouldNotReachHere();
347 }
348 }
349
350 // End the OSR migration
351 make_runtime_call(RC_LEAF, OptoRuntime::osr_end_Type(),
352 CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_end),
353 "OSR_migration_end", TypeRawPtr::BOTTOM,
354 osr_buf);
355
356 // Now that the interpreter state is loaded, make sure it will match
357 // at execution time what the compiler is expecting now:
358 SafePointNode* bad_type_exit = clone_map();
359 bad_type_exit->set_control(new RegionNode(1));
360
361 assert(osr_block->flow()->jsrs()->size() == 0, "should be no jsrs live at osr point");
362 for (index = 0; index < max_locals; index++) {
363 if (stopped()) {
364 break;
365 }
366 const Type *type = osr_block->local_type_at(index);
367 Node* l = local(index);
368 if (l->is_top()) {
369 continue;
370 }
371
372 ciType* ci_type = osr_block->flow()->local_type_at(index);
373 if (ci_type->unwrap()->is_klass() && !live_oops.at(index)) {
374 // skip type check for dead oops
375 continue;
376 }
377
378 if (ci_type->is_return_address()) {
379 // In our current system it's illegal for jsr addresses to be
380 // live into an OSR entry point because the compiler performs
381 // inlining of jsrs. ciTypeFlow has a bailout that detect this
382 // case and aborts the compile if addresses are live into an OSR
383 // entry point. Because of that we can assume that any address
384 // locals at the OSR entry point are dead. Method liveness
385 // isn't precise enough to figure out that they are dead in all
386 // cases so simply skip checking address locals all
387 // together. Any type check is guaranteed to fail since the
388 // interpreter type is the result of a load which might have any
389 // value and the expected type is a constant.
390 continue;
391 }
392 if (StressReachabilityFences && type->isa_oopptr() != nullptr) {
393 // Keep all oop locals alive until the method returns as if there are
394 // reachability fences for them at the end of the method.
395 Node* loc = local(index);
396 if (loc->bottom_type() != TypePtr::NULL_PTR) {
397 assert(loc->bottom_type()->isa_oopptr() != nullptr, "%s", Type::str(loc->bottom_type()));
398 _stress_rf_hook->add_req(loc);
399 }
400 }
401 set_local(index, check_interpreter_type(l, ci_type, bad_type_exit));
402 }
403
404 for (index = 0; index < sp(); index++) {
405 if (stopped()) {
406 break;
407 }
408 const Type *type = osr_block->local_type_at(index);
409 if (StressReachabilityFences && type->isa_oopptr() != nullptr) {
410 // Keep all oops on stack alive until the method returns as if there are
411 // reachability fences for them at the end of the method.
412 Node* stk = stack(index);
413 if (stk->bottom_type() != TypePtr::NULL_PTR) {
414 assert(stk->bottom_type()->isa_oopptr() != nullptr, "%s", Type::str(stk->bottom_type()));
415 _stress_rf_hook->add_req(stk);
416 }
417 }
418
419 Node* l = stack(index);
420 if (l->is_top()) {
421 continue;
422 }
423
424 ciType* ci_type = osr_block->flow()->stack_type_at(index);
425 set_stack(index, check_interpreter_type(l, ci_type, bad_type_exit));
426 }
427
428 if (bad_type_exit->control()->req() > 1) {
429 // Build an uncommon trap here, if any inputs can be unexpected.
430 bad_type_exit->set_control(_gvn.transform( bad_type_exit->control() ));
431 record_for_igvn(bad_type_exit->control());
432 SafePointNode* types_are_good = map();
433 set_map(bad_type_exit);
434 // The unexpected type happens because a new edge is active
435 // in the CFG, which typeflow had previously ignored.
436 // E.g., Object x = coldAtFirst() && notReached()? "str": new Integer(123).
437 // This x will be typed as Integer if notReached is not yet linked.
438 // It could also happen due to a problem in ciTypeFlow analysis.
439 uncommon_trap(Deoptimization::Reason_constraint,
440 Deoptimization::Action_reinterpret);
441 set_map(types_are_good);
442 }
443 }
444
445 //------------------------------Parse------------------------------------------
446 // Main parser constructor.
447 Parse::Parse(JVMState* caller, ciMethod* parse_method, float expected_uses)
448 : _exits(caller)
449 {
450 // Init some variables
451 _caller = caller;
452 _method = parse_method;
453 _expected_uses = expected_uses;
454 _depth = 1 + (caller->has_method() ? caller->depth() : 0);
455 _wrote_non_strict_final = false;
456 _wrote_volatile = false;
457 _wrote_stable = false;
458 _wrote_fields = false;
459 _alloc_with_final_or_stable = nullptr;
460 _stress_rf_hook = (StressReachabilityFences ? new Node(1) : nullptr);
461 _block = nullptr;
462 _first_return = true;
463 _replaced_nodes_for_exceptions = false;
464 _new_idx = C->unique();
465 DEBUG_ONLY(_entry_bci = UnknownBci);
466 DEBUG_ONLY(_block_count = -1);
467 DEBUG_ONLY(_blocks = (Block*)-1);
468 #ifndef PRODUCT
469 if (PrintCompilation || PrintOpto) {
470 // Make sure I have an inline tree, so I can print messages about it.
471 InlineTree::find_subtree_from_root(C->ilt(), caller, parse_method);
472 }
473 _max_switch_depth = 0;
474 _est_switch_depth = 0;
475 #endif
476
477 if (parse_method->has_reserved_stack_access()) {
478 C->set_has_reserved_stack_access(true);
479 }
480
481 if (parse_method->is_synchronized() || parse_method->has_monitor_bytecodes()) {
482 C->set_has_monitors(true);
483 }
484
485 if (parse_method->is_scoped()) {
486 C->set_has_scoped_access(true);
487 }
488
489 _iter.reset_to_method(method());
490 C->set_has_loops(C->has_loops() || method()->has_loops());
491
492 if (_expected_uses <= 0) {
493 _prof_factor = 1;
494 } else {
495 float prof_total = parse_method->interpreter_invocation_count();
496 if (prof_total <= _expected_uses) {
497 _prof_factor = 1;
498 } else {
499 _prof_factor = _expected_uses / prof_total;
500 }
501 }
502
503 CompileLog* log = C->log();
504 if (log != nullptr) {
505 log->begin_head("parse method='%d' uses='%f'",
506 log->identify(parse_method), expected_uses);
507 if (depth() == 1 && C->is_osr_compilation()) {
508 log->print(" osr_bci='%d'", C->entry_bci());
509 }
510 log->stamp();
511 log->end_head();
512 }
513
514 // Accumulate deoptimization counts.
515 // (The range_check and store_check counts are checked elsewhere.)
516 ciMethodData* md = method()->method_data();
517 for (uint reason = 0; reason < md->trap_reason_limit(); reason++) {
518 uint md_count = md->trap_count(reason);
519 if (md_count != 0) {
520 if (md_count >= md->trap_count_limit()) {
521 md_count = md->trap_count_limit() + md->overflow_trap_count();
522 }
523 uint total_count = C->trap_count(reason);
524 uint old_count = total_count;
525 total_count += md_count;
526 // Saturate the add if it overflows.
527 if (total_count < old_count || total_count < md_count)
528 total_count = (uint)-1;
529 C->set_trap_count(reason, total_count);
530 if (log != nullptr)
531 log->elem("observe trap='%s' count='%d' total='%d'",
532 Deoptimization::trap_reason_name(reason),
533 md_count, total_count);
534 }
535 }
536 // Accumulate total sum of decompilations, also.
537 C->set_decompile_count(C->decompile_count() + md->decompile_count());
538
539 if (log != nullptr && method()->has_exception_handlers()) {
540 log->elem("observe that='has_exception_handlers'");
541 }
542
543 assert(InlineTree::check_can_parse(method()) == nullptr, "Can not parse this method, cutout earlier");
544 assert(method()->has_balanced_monitors(), "Can not parse unbalanced monitors, cutout earlier");
545
546 // Always register dependence if JVMTI is enabled, because
547 // either breakpoint setting or hotswapping of methods may
548 // cause deoptimization.
549 if (C->env()->jvmti_can_hotswap_or_post_breakpoint()) {
550 C->dependencies()->assert_evol_method(method());
551 }
552
553 NOT_PRODUCT(methods_seen++);
554
555 // Do some special top-level things.
556 if (depth() == 1 && C->is_osr_compilation()) {
557 _tf = C->tf(); // the OSR entry type is different
558 _entry_bci = C->entry_bci();
559 _flow = method()->get_osr_flow_analysis(osr_bci());
560 } else {
561 _tf = TypeFunc::make(method(), false);
562 _entry_bci = InvocationEntryBci;
563 _flow = method()->get_flow_analysis();
564 }
565
566 if (_flow->failing()) {
567 assert(false, "type flow analysis failed during parsing");
568 C->record_method_not_compilable(_flow->failure_reason());
569 #ifndef PRODUCT
570 if (PrintOpto && (Verbose || WizardMode)) {
571 if (is_osr_parse()) {
572 tty->print_cr("OSR @%d type flow bailout: %s", _entry_bci, _flow->failure_reason());
573 } else {
574 tty->print_cr("type flow bailout: %s", _flow->failure_reason());
575 }
576 if (Verbose) {
577 method()->print();
578 method()->print_codes();
579 _flow->print();
580 }
581 }
582 #endif
583 }
584
585 #ifdef ASSERT
586 if (depth() == 1) {
587 assert(C->is_osr_compilation() == this->is_osr_parse(), "OSR in sync");
588 } else {
589 assert(!this->is_osr_parse(), "no recursive OSR");
590 }
591 #endif
592
593 #ifndef PRODUCT
594 if (_flow->has_irreducible_entry()) {
595 C->set_parsed_irreducible_loop(true);
596 }
597
598 methods_parsed++;
599 // add method size here to guarantee that inlined methods are added too
600 if (CITime)
601 _total_bytes_compiled += method()->code_size();
602
603 show_parse_info();
604 #endif
605
606 if (failing()) {
607 if (log) log->done("parse");
608 return;
609 }
610
611 gvn().transform(top());
612
613 // Import the results of the ciTypeFlow.
614 init_blocks();
615
616 // Merge point for all normal exits
617 build_exits();
618
619 // Setup the initial JVM state map.
620 SafePointNode* entry_map = create_entry_map();
621
622 // Check for bailouts during map initialization
623 if (failing() || entry_map == nullptr) {
624 if (log) log->done("parse");
625 return;
626 }
627
628 Node_Notes* caller_nn = C->default_node_notes();
629 // Collect debug info for inlined calls unless -XX:-DebugInlinedCalls.
630 if (DebugInlinedCalls || depth() == 1) {
631 C->set_default_node_notes(make_node_notes(caller_nn));
632 }
633
634 if (is_osr_parse()) {
635 Node* osr_buf = entry_map->in(TypeFunc::Parms+0);
636 entry_map->set_req(TypeFunc::Parms+0, top());
637 set_map(entry_map);
638 load_interpreter_state(osr_buf);
639 } else {
640 set_map(entry_map);
641 do_method_entry();
642 }
643
644 if (depth() == 1 && !failing()) {
645 if (C->clinit_barrier_on_entry()) {
646 // Add check to deoptimize the nmethod once the holder class is fully initialized
647 clinit_deopt();
648 }
649 }
650
651 // Check for bailouts during method entry.
652 if (failing()) {
653 if (log) log->done("parse");
654 C->set_default_node_notes(caller_nn);
655 return;
656 }
657
658 entry_map = map(); // capture any changes performed by method setup code
659 assert(jvms()->endoff() == map()->req(), "map matches JVMS layout");
660
661 // We begin parsing as if we have just encountered a jump to the
662 // method entry.
663 Block* entry_block = start_block();
664 assert(entry_block->start() == (is_osr_parse() ? osr_bci() : 0), "");
665 set_map_clone(entry_map);
666 merge_common(entry_block, entry_block->next_path_num());
667
668 #ifndef PRODUCT
669 BytecodeParseHistogram *parse_histogram_obj = new (C->env()->arena()) BytecodeParseHistogram(this, C);
670 set_parse_histogram( parse_histogram_obj );
671 #endif
672
673 // Parse all the basic blocks.
674 do_all_blocks();
675
676 // Check for bailouts during conversion to graph
677 if (failing()) {
678 if (log) log->done("parse");
679 return;
680 }
681
682 // Fix up all exiting control flow.
683 set_map(entry_map);
684 do_exits();
685
686 // Only reset this now, to make sure that debug information emitted
687 // for exiting control flow still refers to the inlined method.
688 C->set_default_node_notes(caller_nn);
689
690 if (log) log->done("parse nodes='%d' live='%d' memory='%zu'",
691 C->unique(), C->live_nodes(), C->node_arena()->used());
692
693 if (StressReachabilityFences) {
694 _stress_rf_hook->destruct(&_gvn);
695 _stress_rf_hook = nullptr;
696 }
697 }
698
699 //---------------------------do_all_blocks-------------------------------------
700 void Parse::do_all_blocks() {
701 bool has_irreducible = flow()->has_irreducible_entry();
702
703 // Walk over all blocks in Reverse Post-Order.
704 while (true) {
705 bool progress = false;
706 for (int rpo = 0; rpo < block_count(); rpo++) {
707 Block* block = rpo_at(rpo);
708
709 if (block->is_parsed()) continue;
710
711 if (!block->is_merged()) {
712 // Dead block, no state reaches this block
713 continue;
714 }
715
716 // Prepare to parse this block.
717 load_state_from(block);
718
719 if (stopped()) {
720 // Block is dead.
721 continue;
722 }
723
724 NOT_PRODUCT(blocks_parsed++);
725
726 progress = true;
727 if (block->is_loop_head() || block->is_handler() || (has_irreducible && !block->is_ready())) {
728 // Not all preds have been parsed. We must build phis everywhere.
729 // (Note that dead locals do not get phis built, ever.)
730 ensure_phis_everywhere();
731
732 if (block->is_SEL_head()) {
733 // Add predicate to single entry (not irreducible) loop head.
734 assert(!block->has_merged_backedge(), "only entry paths should be merged for now");
735 // Predicates may have been added after a dominating if
736 if (!block->has_predicates()) {
737 // Need correct bci for predicate.
738 // It is fine to set it here since do_one_block() will set it anyway.
739 set_parse_bci(block->start());
740 add_parse_predicates();
741 }
742 // Add new region for back branches.
743 int edges = block->pred_count() - block->preds_parsed() + 1; // +1 for original region
744 RegionNode *r = new RegionNode(edges+1);
745 _gvn.set_type(r, Type::CONTROL);
746 record_for_igvn(r);
747 r->init_req(edges, control());
748 set_control(r);
749 block->copy_irreducible_status_to(r, jvms());
750 // Add new phis.
751 ensure_phis_everywhere();
752 }
753
754 // Leave behind an undisturbed copy of the map, for future merges.
755 set_map(clone_map());
756 }
757
758 if (control()->is_Region() && !block->is_loop_head() && !has_irreducible && !block->is_handler()) {
759 // In the absence of irreducible loops, the Region and Phis
760 // associated with a merge that doesn't involve a backedge can
761 // be simplified now since the RPO parsing order guarantees
762 // that any path which was supposed to reach here has already
763 // been parsed or must be dead.
764 Node* c = control();
765 Node* result = _gvn.transform(control());
766 if (c != result && TraceOptoParse) {
767 tty->print_cr("Block #%d replace %d with %d", block->rpo(), c->_idx, result->_idx);
768 }
769 if (result != top()) {
770 record_for_igvn(result);
771 }
772 }
773
774 // Parse the block.
775 do_one_block();
776
777 // Check for bailouts.
778 if (failing()) return;
779 }
780
781 // with irreducible loops multiple passes might be necessary to parse everything
782 if (!has_irreducible || !progress) {
783 break;
784 }
785 }
786
787 #ifndef PRODUCT
788 blocks_seen += block_count();
789
790 // Make sure there are no half-processed blocks remaining.
791 // Every remaining unprocessed block is dead and may be ignored now.
792 for (int rpo = 0; rpo < block_count(); rpo++) {
793 Block* block = rpo_at(rpo);
794 if (!block->is_parsed()) {
795 if (TraceOptoParse) {
796 tty->print_cr("Skipped dead block %d at bci:%d", rpo, block->start());
797 }
798 assert(!block->is_merged(), "no half-processed blocks");
799 }
800 }
801 #endif
802 }
803
804 static Node* mask_int_value(Node* v, BasicType bt, PhaseGVN* gvn) {
805 switch (bt) {
806 case T_BYTE:
807 v = gvn->transform(new LShiftINode(v, gvn->intcon(24)));
808 v = gvn->transform(new RShiftINode(v, gvn->intcon(24)));
809 break;
810 case T_SHORT:
811 v = gvn->transform(new LShiftINode(v, gvn->intcon(16)));
812 v = gvn->transform(new RShiftINode(v, gvn->intcon(16)));
813 break;
814 case T_CHAR:
815 v = gvn->transform(new AndINode(v, gvn->intcon(0xFFFF)));
816 break;
817 case T_BOOLEAN:
818 v = gvn->transform(new AndINode(v, gvn->intcon(0x1)));
819 break;
820 default:
821 break;
822 }
823 return v;
824 }
825
826 //-------------------------------build_exits----------------------------------
827 // Build normal and exceptional exit merge points.
828 void Parse::build_exits() {
829 // make a clone of caller to prevent sharing of side-effects
830 _exits.set_map(_exits.clone_map());
831 _exits.clean_stack(_exits.sp());
832 _exits.sync_jvms();
833
834 RegionNode* region = new RegionNode(1);
835 record_for_igvn(region);
836 gvn().set_type_bottom(region);
837 _exits.set_control(region);
838
839 // Note: iophi and memphi are not transformed until do_exits.
840 Node* iophi = new PhiNode(region, Type::ABIO);
841 Node* memphi = new PhiNode(region, Type::MEMORY, TypePtr::BOTTOM);
842 gvn().set_type_bottom(iophi);
843 gvn().set_type_bottom(memphi);
844 _exits.set_i_o(iophi);
845 _exits.set_all_memory(memphi);
846
847 // Add a return value to the exit state. (Do not push it yet.)
848 if (tf()->range_sig()->cnt() > TypeFunc::Parms) {
849 const Type* ret_type = tf()->range_sig()->field_at(TypeFunc::Parms);
850 if (ret_type->isa_int()) {
851 BasicType ret_bt = method()->return_type()->basic_type();
852 if (ret_bt == T_BOOLEAN ||
853 ret_bt == T_CHAR ||
854 ret_bt == T_BYTE ||
855 ret_bt == T_SHORT) {
856 ret_type = TypeInt::INT;
857 }
858 }
859
860 // Don't "bind" an unloaded return klass to the ret_phi. If the klass
861 // becomes loaded during the subsequent parsing, the loaded and unloaded
862 // types will not join when we transform and push in do_exits().
863 const TypeOopPtr* ret_oop_type = ret_type->isa_oopptr();
864 if (ret_oop_type && !ret_oop_type->is_loaded()) {
865 ret_type = TypeOopPtr::BOTTOM;
866 }
867 int ret_size = type2size[ret_type->basic_type()];
868 Node* ret_phi = new PhiNode(region, ret_type);
869 gvn().set_type_bottom(ret_phi);
870 _exits.ensure_stack(ret_size);
871 assert((int)(tf()->range_sig()->cnt() - TypeFunc::Parms) == ret_size, "good tf range");
872 assert(method()->return_type()->size() == ret_size, "tf agrees w/ method");
873 _exits.set_argument(0, ret_phi); // here is where the parser finds it
874 // Note: ret_phi is not yet pushed, until do_exits.
875 }
876 }
877
878 //----------------------------build_start_state-------------------------------
879 // Construct a state which contains only the incoming arguments from an
880 // unknown caller. The method & bci will be null & InvocationEntryBci.
881 JVMState* Compile::build_start_state(StartNode* start, const TypeFunc* tf) {
882 int arg_size = tf->domain_sig()->cnt();
883 int max_size = MAX2(arg_size, (int)tf->range_cc()->cnt());
884 JVMState* jvms = new (this) JVMState(max_size - TypeFunc::Parms);
885 SafePointNode* map = new SafePointNode(max_size, jvms);
886 jvms->set_map(map);
887 record_for_igvn(map);
888 assert(arg_size == TypeFunc::Parms + (is_osr_compilation() ? 1 : method()->arg_size()), "correct arg_size");
889 Node_Notes* old_nn = default_node_notes();
890 if (old_nn != nullptr && has_method()) {
891 Node_Notes* entry_nn = old_nn->clone(this);
892 JVMState* entry_jvms = new(this) JVMState(method(), old_nn->jvms());
893 entry_jvms->set_offsets(0);
894 entry_jvms->set_bci(entry_bci());
895 entry_nn->set_jvms(entry_jvms);
896 set_default_node_notes(entry_nn);
897 }
898 PhaseGVN& gvn = *initial_gvn();
899 uint i = 0;
900 int arg_num = 0;
901 for (uint j = 0; i < (uint)arg_size; i++) {
902 const Type* t = tf->domain_sig()->field_at(i);
903 Node* parm = nullptr;
904 if (t->is_inlinetypeptr() && method()->is_scalarized_arg(arg_num)) {
905 // Inline type arguments are not passed by reference: we get an argument per
906 // field of the inline type. Build InlineTypeNodes from the inline type arguments.
907 GraphKit kit(jvms, &gvn);
908 kit.set_control(map->control());
909 Node* old_mem = map->memory();
910 // Use immutable memory for inline type loads and restore it below
911 kit.set_all_memory(C->immutable_memory());
912 parm = InlineTypeNode::make_from_multi(&kit, start, t->inline_klass(), j, /* in= */ true, /* null_free= */ !t->maybe_null());
913 assert(map == kit.map(), "broken if map changes");
914 map->set_control(kit.control());
915 map->set_memory(old_mem);
916 } else {
917 parm = gvn.transform(new ParmNode(start, j++));
918 }
919 map->init_req(i, parm);
920 // Record all these guys for later GVN.
921 record_for_igvn(parm);
922 if (i >= TypeFunc::Parms && t != Type::HALF) {
923 arg_num++;
924 }
925 }
926 for (; i < map->req(); i++) {
927 map->init_req(i, top());
928 }
929 assert(jvms->argoff() == TypeFunc::Parms, "parser gets arguments here");
930 set_default_node_notes(old_nn);
931 return jvms;
932 }
933
934 //-----------------------------make_node_notes---------------------------------
935 Node_Notes* Parse::make_node_notes(Node_Notes* caller_nn) {
936 if (caller_nn == nullptr) return nullptr;
937 Node_Notes* nn = caller_nn->clone(C);
938 JVMState* caller_jvms = nn->jvms();
939 JVMState* jvms = new (C) JVMState(method(), caller_jvms);
940 jvms->set_offsets(0);
941 jvms->set_bci(_entry_bci);
942 nn->set_jvms(jvms);
943 return nn;
944 }
945
946
947 //--------------------------return_values--------------------------------------
948 void Compile::return_values(JVMState* jvms) {
949 GraphKit kit(jvms);
950 Node* ret = new ReturnNode(TypeFunc::Parms,
951 kit.control(),
952 kit.i_o(),
953 kit.reset_memory(),
954 kit.frameptr(),
955 kit.returnadr());
956 // Add zero or 1 return values
957 int ret_size = tf()->range_sig()->cnt() - TypeFunc::Parms;
958 if (ret_size > 0) {
959 kit.inc_sp(-ret_size); // pop the return value(s)
960 kit.sync_jvms();
961 Node* res = kit.argument(0);
962 if (tf()->returns_inline_type_as_fields()) {
963 // Multiple return values (inline type fields): add as many edges
964 // to the Return node as returned values.
965 InlineTypeNode* vt = res->as_InlineType();
966 ret->add_req_batch(nullptr, tf()->range_cc()->cnt() - TypeFunc::Parms);
967 if (vt->is_allocated(&kit.gvn()) && !StressCallingConvention) {
968 ret->init_req(TypeFunc::Parms, vt);
969 } else {
970 // Return the tagged klass pointer to signal scalarization to the caller
971 Node* tagged_klass = vt->tagged_klass(kit.gvn());
972 // Return null if the inline type is null (null marker field is not set)
973 Node* conv = kit.gvn().transform(new ConvI2LNode(vt->get_null_marker()));
974 Node* shl = kit.gvn().transform(new LShiftLNode(conv, kit.intcon(63)));
975 Node* shr = kit.gvn().transform(new RShiftLNode(shl, kit.intcon(63)));
976 tagged_klass = kit.gvn().transform(new AndLNode(tagged_klass, shr));
977 ret->init_req(TypeFunc::Parms, tagged_klass);
978 }
979 uint idx = TypeFunc::Parms + 1;
980 vt->pass_fields(&kit, ret, idx, false, false);
981 } else {
982 ret->add_req(res);
983 // Note: The second dummy edge is not needed by a ReturnNode.
984 }
985 }
986 // bind it to root
987 root()->add_req(ret);
988 record_for_igvn(ret);
989 initial_gvn()->transform(ret);
990 }
991
992 //------------------------rethrow_exceptions-----------------------------------
993 // Bind all exception states in the list into a single RethrowNode.
994 void Compile::rethrow_exceptions(JVMState* jvms) {
995 GraphKit kit(jvms);
996 if (!kit.has_exceptions()) return; // nothing to generate
997 // Load my combined exception state into the kit, with all phis transformed:
998 SafePointNode* ex_map = kit.combine_and_pop_all_exception_states();
999 Node* ex_oop = kit.use_exception_state(ex_map);
1000 RethrowNode* exit = new RethrowNode(kit.control(),
1001 kit.i_o(), kit.reset_memory(),
1002 kit.frameptr(), kit.returnadr(),
1003 // like a return but with exception input
1004 ex_oop);
1005 // bind to root
1006 root()->add_req(exit);
1007 record_for_igvn(exit);
1008 initial_gvn()->transform(exit);
1009 }
1010
1011 //---------------------------do_exceptions-------------------------------------
1012 // Process exceptions arising from the current bytecode.
1013 // Send caught exceptions to the proper handler within this method.
1014 // Unhandled exceptions feed into _exit.
1015 void Parse::do_exceptions() {
1016 if (!has_exceptions()) return;
1017
1018 if (failing()) {
1019 // Pop them all off and throw them away.
1020 while (pop_exception_state() != nullptr) ;
1021 return;
1022 }
1023
1024 PreserveJVMState pjvms(this, false);
1025
1026 SafePointNode* ex_map;
1027 while ((ex_map = pop_exception_state()) != nullptr) {
1028 if (!method()->has_exception_handlers()) {
1029 // Common case: Transfer control outward.
1030 // Doing it this early allows the exceptions to common up
1031 // even between adjacent method calls.
1032 throw_to_exit(ex_map);
1033 } else {
1034 // Have to look at the exception first.
1035 assert(stopped(), "catch_inline_exceptions trashes the map");
1036 catch_inline_exceptions(ex_map);
1037 stop_and_kill_map(); // we used up this exception state; kill it
1038 }
1039 }
1040
1041 // We now return to our regularly scheduled program:
1042 }
1043
1044 //---------------------------throw_to_exit-------------------------------------
1045 // Merge the given map into an exception exit from this method.
1046 // The exception exit will handle any unlocking of receiver.
1047 // The ex_oop must be saved within the ex_map, unlike merge_exception.
1048 void Parse::throw_to_exit(SafePointNode* ex_map) {
1049 // Pop the JVMS to (a copy of) the caller.
1050 GraphKit caller;
1051 caller.set_map_clone(_caller->map());
1052 caller.set_bci(_caller->bci());
1053 caller.set_sp(_caller->sp());
1054 // Copy out the standard machine state:
1055 for (uint i = 0; i < TypeFunc::Parms; i++) {
1056 caller.map()->set_req(i, ex_map->in(i));
1057 }
1058 if (ex_map->has_replaced_nodes()) {
1059 _replaced_nodes_for_exceptions = true;
1060 }
1061 caller.map()->transfer_replaced_nodes_from(ex_map, _new_idx);
1062 // ...and the exception:
1063 Node* ex_oop = saved_ex_oop(ex_map);
1064 SafePointNode* caller_ex_map = caller.make_exception_state(ex_oop);
1065 // Finally, collect the new exception state in my exits:
1066 _exits.add_exception_state(caller_ex_map);
1067 }
1068
1069 //------------------------------do_exits---------------------------------------
1070 void Parse::do_exits() {
1071 set_parse_bci(InvocationEntryBci);
1072
1073 // Now peephole on the return bits
1074 Node* region = _exits.control();
1075 _exits.set_control(gvn().transform(region));
1076
1077 Node* iophi = _exits.i_o();
1078 _exits.set_i_o(gvn().transform(iophi));
1079
1080 // Figure out if we need to emit the trailing barrier. The barrier is only
1081 // needed in the constructors, and only in three cases:
1082 //
1083 // 1. The constructor wrote a final or a @Stable field. All these
1084 // initializations must be ordered before any code after the constructor
1085 // publishes the reference to the newly constructed object. Rather
1086 // than wait for the publication, we simply block the writes here.
1087 // Rather than put a barrier on only those writes which are required
1088 // to complete, we force all writes to complete.
1089 //
1090 // 2. Experimental VM option is used to force the barrier if any field
1091 // was written out in the constructor.
1092 //
1093 // 3. On processors which are not CPU_MULTI_COPY_ATOMIC (e.g. PPC64),
1094 // support_IRIW_for_not_multiple_copy_atomic_cpu selects that
1095 // MemBarVolatile is used before volatile load instead of after volatile
1096 // store, so there's no barrier after the store.
1097 // We want to guarantee the same behavior as on platforms with total store
1098 // order, although this is not required by the Java memory model.
1099 // In this case, we want to enforce visibility of volatile field
1100 // initializations which are performed in constructors.
1101 // So as with finals, we add a barrier here.
1102 //
1103 // "All bets are off" unless the first publication occurs after a
1104 // normal return from the constructor. We do not attempt to detect
1105 // such unusual early publications. But no barrier is needed on
1106 // exceptional returns, since they cannot publish normally.
1107 //
1108 if ((method()->is_object_constructor() || method()->is_class_initializer()) &&
1109 (wrote_non_strict_final() || wrote_stable() ||
1110 (AlwaysSafeConstructors && wrote_fields()) ||
1111 (support_IRIW_for_not_multiple_copy_atomic_cpu && wrote_volatile()))) {
1112 Node* recorded_alloc = alloc_with_final_or_stable();
1113 _exits.insert_mem_bar(UseStoreStoreForCtor ? Op_MemBarStoreStore : Op_MemBarRelease,
1114 recorded_alloc);
1115
1116 // If Memory barrier is created for final fields write
1117 // and allocation node does not escape the initialize method,
1118 // then barrier introduced by allocation node can be removed.
1119 if (DoEscapeAnalysis && (recorded_alloc != nullptr)) {
1120 AllocateNode* alloc = AllocateNode::Ideal_allocation(recorded_alloc);
1121 alloc->compute_MemBar_redundancy(method());
1122 }
1123 if (PrintOpto && (Verbose || WizardMode)) {
1124 method()->print_name();
1125 tty->print_cr(" writes finals/@Stable and needs a memory barrier");
1126 }
1127 }
1128
1129 for (MergeMemStream mms(_exits.merged_memory()); mms.next_non_empty(); ) {
1130 // transform each slice of the original memphi:
1131 mms.set_memory(_gvn.transform(mms.memory()));
1132 }
1133 // Clean up input MergeMems created by transforming the slices
1134 _gvn.transform(_exits.merged_memory());
1135
1136 if (tf()->range_sig()->cnt() > TypeFunc::Parms) {
1137 const Type* ret_type = tf()->range_sig()->field_at(TypeFunc::Parms);
1138 Node* ret_phi = _gvn.transform( _exits.argument(0) );
1139 if (!_exits.control()->is_top() && _gvn.type(ret_phi)->empty()) {
1140 // If the type we set for the ret_phi in build_exits() is too optimistic and
1141 // the ret_phi is top now, there's an extremely small chance that it may be due to class
1142 // loading. It could also be due to an error, so mark this method as not compilable because
1143 // otherwise this could lead to an infinite compile loop.
1144 // In any case, this code path is rarely (and never in my testing) reached.
1145 C->record_method_not_compilable("Can't determine return type.");
1146 return;
1147 }
1148 if (ret_type->isa_int()) {
1149 BasicType ret_bt = method()->return_type()->basic_type();
1150 ret_phi = mask_int_value(ret_phi, ret_bt, &_gvn);
1151 }
1152 _exits.push_node(ret_type->basic_type(), ret_phi);
1153 }
1154
1155 // Note: Logic for creating and optimizing the ReturnNode is in Compile.
1156
1157 // Unlock along the exceptional paths.
1158 // This is done late so that we can common up equivalent exceptions
1159 // (e.g., null checks) arising from multiple points within this method.
1160 // See GraphKit::add_exception_state, which performs the commoning.
1161 bool do_synch = method()->is_synchronized();
1162
1163 // record exit from a method if compiled while Dtrace is turned on.
1164 if (do_synch || C->env()->dtrace_method_probes() || _replaced_nodes_for_exceptions) {
1165 // First move the exception list out of _exits:
1166 GraphKit kit(_exits.transfer_exceptions_into_jvms());
1167 SafePointNode* normal_map = kit.map(); // keep this guy safe
1168 // Now re-collect the exceptions into _exits:
1169 SafePointNode* ex_map;
1170 while ((ex_map = kit.pop_exception_state()) != nullptr) {
1171 Node* ex_oop = kit.use_exception_state(ex_map);
1172 // Force the exiting JVM state to have this method at InvocationEntryBci.
1173 // The exiting JVM state is otherwise a copy of the calling JVMS.
1174 JVMState* caller = kit.jvms();
1175 JVMState* ex_jvms = caller->clone_shallow(C);
1176 ex_jvms->bind_map(kit.clone_map());
1177 ex_jvms->set_bci( InvocationEntryBci);
1178 kit.set_jvms(ex_jvms);
1179 if (do_synch) {
1180 // Add on the synchronized-method box/object combo
1181 kit.map()->push_monitor(_synch_lock);
1182 // Unlock!
1183 kit.shared_unlock(_synch_lock->box_node(), _synch_lock->obj_node());
1184 }
1185 if (C->env()->dtrace_method_probes()) {
1186 kit.make_dtrace_method_exit(method());
1187 }
1188 if (_replaced_nodes_for_exceptions) {
1189 kit.map()->apply_replaced_nodes(_new_idx);
1190 }
1191 // Done with exception-path processing.
1192 ex_map = kit.make_exception_state(ex_oop);
1193 assert(ex_jvms->same_calls_as(ex_map->jvms()), "sanity");
1194 // Pop the last vestige of this method:
1195 caller->clone_shallow(C)->bind_map(ex_map);
1196 _exits.push_exception_state(ex_map);
1197 }
1198 assert(_exits.map() == normal_map, "keep the same return state");
1199 }
1200
1201 {
1202 // Capture very early exceptions (receiver null checks) from caller JVMS
1203 GraphKit caller(_caller);
1204 SafePointNode* ex_map;
1205 while ((ex_map = caller.pop_exception_state()) != nullptr) {
1206 _exits.add_exception_state(ex_map);
1207 }
1208 }
1209 _exits.map()->apply_replaced_nodes(_new_idx);
1210 }
1211
1212 //-----------------------------create_entry_map-------------------------------
1213 // Initialize our parser map to contain the types at method entry.
1214 // For OSR, the map contains a single RawPtr parameter.
1215 // Initial monitor locking for sync. methods is performed by do_method_entry.
1216 SafePointNode* Parse::create_entry_map() {
1217 // Check for really stupid bail-out cases.
1218 uint len = TypeFunc::Parms + method()->max_locals() + method()->max_stack();
1219 if (len >= 32760) {
1220 // Bailout expected, this is a very rare edge case.
1221 C->record_method_not_compilable("too many local variables");
1222 return nullptr;
1223 }
1224
1225 // clear current replaced nodes that are of no use from here on (map was cloned in build_exits).
1226 _caller->map()->delete_replaced_nodes();
1227
1228 // If this is an inlined method, we may have to do a receiver null check.
1229 if (_caller->has_method() && is_normal_parse() && !method()->is_static()) {
1230 GraphKit kit(_caller);
1231 kit.null_check_receiver_before_call(method());
1232 _caller = kit.transfer_exceptions_into_jvms();
1233
1234 if (kit.stopped()) {
1235 _exits.add_exception_states_from(_caller);
1236 _exits.set_jvms(_caller);
1237 return nullptr;
1238 }
1239 }
1240
1241 assert(method() != nullptr, "parser must have a method");
1242
1243 // Create an initial safepoint to hold JVM state during parsing
1244 JVMState* jvms = new (C) JVMState(method(), _caller->has_method() ? _caller : nullptr);
1245 set_map(new SafePointNode(len, jvms));
1246
1247 // Capture receiver info for compiled lambda forms.
1248 if (method()->is_compiled_lambda_form()) {
1249 ciInstance* recv_info = _caller->compute_receiver_info(method());
1250 jvms->set_receiver_info(recv_info);
1251 }
1252
1253 jvms->set_map(map());
1254 record_for_igvn(map());
1255 assert(jvms->endoff() == len, "correct jvms sizing");
1256
1257 SafePointNode* inmap = _caller->map();
1258 assert(inmap != nullptr, "must have inmap");
1259 // In case of null check on receiver above
1260 map()->transfer_replaced_nodes_from(inmap, _new_idx);
1261
1262 uint i;
1263
1264 // Pass thru the predefined input parameters.
1265 for (i = 0; i < TypeFunc::Parms; i++) {
1266 map()->init_req(i, inmap->in(i));
1267 }
1268
1269 if (depth() == 1) {
1270 assert(map()->memory()->Opcode() == Op_Parm, "");
1271 // Insert the memory aliasing node
1272 set_all_memory(reset_memory());
1273 }
1274 assert(merged_memory(), "");
1275
1276 // Now add the locals which are initially bound to arguments:
1277 uint arg_size = tf()->domain_sig()->cnt();
1278 ensure_stack(arg_size - TypeFunc::Parms); // OSR methods have funny args
1279 for (i = TypeFunc::Parms; i < arg_size; i++) {
1280 map()->init_req(i, inmap->argument(_caller, i - TypeFunc::Parms));
1281 }
1282
1283 // Clear out the rest of the map (locals and stack)
1284 for (i = arg_size; i < len; i++) {
1285 map()->init_req(i, top());
1286 }
1287
1288 SafePointNode* entry_map = stop();
1289 return entry_map;
1290 }
1291
1292 //-----------------------is_auto_boxed_primitive------------------------------
1293 // Helper method to detect auto-boxed primitives (result of valueOf() call).
1294 static bool is_auto_boxed_primitive(Node* n) {
1295 return (n->is_Proj() && n->as_Proj()->_con == TypeFunc::Parms &&
1296 n->in(0)->is_CallJava() &&
1297 n->in(0)->as_CallJava()->method()->is_boxing_method());
1298 }
1299
1300 //-----------------------------do_method_entry--------------------------------
1301 // Emit any code needed in the pseudo-block before BCI zero.
1302 // The main thing to do is lock the receiver of a synchronized method.
1303 void Parse::do_method_entry() {
1304 set_parse_bci(InvocationEntryBci); // Pseudo-BCP
1305 set_sp(0); // Java Stack Pointer
1306
1307 NOT_PRODUCT( count_compiled_calls(true/*at_method_entry*/, false/*is_inline*/); )
1308
1309 // Check if we need a membar at the beginning of the java.lang.Object
1310 // constructor to satisfy the memory model for strict fields.
1311 if (Arguments::is_valhalla_enabled() && method()->intrinsic_id() == vmIntrinsics::_Object_init) {
1312 Node* receiver_obj = local(0);
1313 const TypeInstPtr* receiver_type = _gvn.type(receiver_obj)->isa_instptr();
1314 // If there's no exact type, check if the declared type has no implementors and add a dependency
1315 const TypeKlassPtr* klass_ptr = receiver_type->as_klass_type(/* try_for_exact= */ true);
1316 ciType* klass = klass_ptr->klass_is_exact() ? klass_ptr->exact_klass() : nullptr;
1317 if (klass != nullptr && klass->is_instance_klass()) {
1318 // Exact receiver type, check if there is a strict field
1319 ciInstanceKlass* holder = klass->as_instance_klass();
1320 for (int i = 0; i < holder->nof_nonstatic_fields(); i++) {
1321 ciField* field = holder->nonstatic_field_at(i);
1322 if (field->is_strict()) {
1323 // Found a strict field, a membar is needed
1324 AllocateNode* alloc = AllocateNode::Ideal_allocation(receiver_obj);
1325 insert_mem_bar(UseStoreStoreForCtor ? Op_MemBarStoreStore : Op_MemBarRelease, receiver_obj);
1326 if (DoEscapeAnalysis && (alloc != nullptr)) {
1327 alloc->compute_MemBar_redundancy(method());
1328 }
1329 break;
1330 }
1331 }
1332 } else if (klass == nullptr) {
1333 // We can't statically determine the type of the receiver and therefore need
1334 // to put a membar here because it could have a strict field.
1335 insert_mem_bar(UseStoreStoreForCtor ? Op_MemBarStoreStore : Op_MemBarRelease);
1336 }
1337 }
1338
1339 if (C->env()->dtrace_method_probes()) {
1340 make_dtrace_method_entry(method());
1341 }
1342
1343 if (StressReachabilityFences) {
1344 // Keep all oop arguments alive until the method returns as if there are
1345 // reachability fences for them at the end of the method.
1346 int max_locals = jvms()->loc_size();
1347 for (int idx = 0; idx < max_locals; idx++) {
1348 Node* loc = local(idx);
1349 if (loc->bottom_type()->isa_oopptr() != nullptr &&
1350 !is_auto_boxed_primitive(loc)) { // ignore auto-boxed primitives
1351 _stress_rf_hook->add_req(loc);
1352 }
1353 }
1354 }
1355
1356 #ifdef ASSERT
1357 // Narrow receiver type when it is too broad for the method being parsed.
1358 if (!method()->is_static()) {
1359 ciInstanceKlass* callee_holder = method()->holder();
1360 const Type* holder_type = TypeInstPtr::make(TypePtr::BotPTR, callee_holder, Type::trust_interfaces);
1361
1362 Node* receiver_obj = local(0);
1363 const TypeInstPtr* receiver_type = _gvn.type(receiver_obj)->isa_instptr();
1364
1365 if (receiver_type != nullptr && !receiver_type->higher_equal(holder_type)) {
1366 // Receiver should always be a subtype of callee holder.
1367 // But, since C2 type system doesn't properly track interfaces,
1368 // the invariant can't be expressed in the type system for default methods.
1369 // Example: for unrelated C <: I and D <: I, (C `meet` D) = Object </: I.
1370 assert(callee_holder->is_interface(), "missing subtype check");
1371
1372 // Perform dynamic receiver subtype check against callee holder class w/ a halt on failure.
1373 Node* holder_klass = _gvn.makecon(TypeKlassPtr::make(callee_holder, Type::trust_interfaces));
1374 Node* not_subtype_ctrl = gen_subtype_check(receiver_obj, holder_klass);
1375 assert(!stopped(), "not a subtype");
1376
1377 halt(not_subtype_ctrl, frameptr(), "failed receiver subtype check");
1378 }
1379 }
1380 #endif // ASSERT
1381
1382 // If the method is synchronized, we need to construct a lock node, attach
1383 // it to the Start node, and pin it there.
1384 if (method()->is_synchronized()) {
1385 // Insert a FastLockNode right after the Start which takes as arguments
1386 // the current thread pointer, the "this" pointer & the address of the
1387 // stack slot pair used for the lock. The "this" pointer is a projection
1388 // off the start node, but the locking spot has to be constructed by
1389 // creating a ConLNode of 0, and boxing it with a BoxLockNode. The BoxLockNode
1390 // becomes the second argument to the FastLockNode call. The
1391 // FastLockNode becomes the new control parent to pin it to the start.
1392
1393 // Setup Object Pointer
1394 Node *lock_obj = nullptr;
1395 if (method()->is_static()) {
1396 ciInstance* mirror = _method->holder()->java_mirror();
1397 const TypeInstPtr *t_lock = TypeInstPtr::make(mirror);
1398 lock_obj = makecon(t_lock);
1399 } else { // Else pass the "this" pointer,
1400 lock_obj = local(0); // which is Parm0 from StartNode
1401 assert(!_gvn.type(lock_obj)->make_oopptr()->can_be_inline_type(), "can't be an inline type");
1402 }
1403 // Clear out dead values from the debug info.
1404 kill_dead_locals();
1405 // Build the FastLockNode
1406 _synch_lock = shared_lock(lock_obj);
1407 // Check for bailout in shared_lock
1408 if (failing()) { return; }
1409 }
1410
1411 // Feed profiling data for parameters to the type system so it can
1412 // propagate it as speculative types
1413 record_profiled_parameters_for_speculation();
1414
1415 // More argument handling
1416 int arg_size = method()->arg_size();
1417 for (int i = 0; i < arg_size; i++) {
1418 Node* parm = local(i);
1419 const Type* t = _gvn.type(parm);
1420 if (t->is_inlinetypeptr()) {
1421 // If the parameter is a value object, try to scalarize it if we know that it is unrestricted (not early larval)
1422 // Parameters are non-larval except the receiver of a constructor, which must be an early larval object.
1423 if (!(i == 0 && method()->receiver_maybe_larval())) {
1424 // Create InlineTypeNode from the oop and replace the parameter
1425 Node* vt = InlineTypeNode::make_from_oop(this, parm, t->inline_klass());
1426 replace_in_map(parm, vt);
1427 }
1428 } else if (UseTypeSpeculation && (i == (arg_size - 1)) && depth() == 1 && method()->has_vararg() && t->isa_aryptr()) {
1429 // Speculate on varargs Object array being the default array refined type. The assumption is
1430 // that a vararg method test(Object... o) is often called as test(o1, o2, o3). javac will
1431 // translate the call so that the caller will create a new default array of Object, put o1,
1432 // o2, o3 into the newly created array, then invoke the method test. This only makes sense if
1433 // the method we are parsing is the top-level method of the compilation unit. Otherwise, if
1434 // it is truly called according to our assumption, we must know the exact type of the
1435 // argument because the allocation happens inside the compilation unit.
1436 const TypePtr* spec_type = (t->speculative() != nullptr) ? t->speculative() : t->remove_speculative()->is_aryptr();
1437 ciSignature* method_signature = method()->signature();
1438 ciType* parm_citype = method_signature->type_at(method_signature->count() - 1);
1439 if (!parm_citype->is_obj_array_klass()) {
1440 continue;
1441 }
1442
1443 ciObjArrayKlass* spec_citype = ciObjArrayKlass::make(parm_citype->as_obj_array_klass()->element_klass(), true);
1444 const Type* improved_spec_type = TypeKlassPtr::make(spec_citype, Type::trust_interfaces)->as_instance_type();
1445 improved_spec_type = improved_spec_type->join(spec_type)->join(TypePtr::NOTNULL);
1446 if (improved_spec_type->empty()) {
1447 continue;
1448 }
1449
1450 const TypePtr* improved_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, improved_spec_type->is_ptr());
1451 improved_type = improved_type->join_speculative(t)->is_ptr();
1452 if (improved_type != t) {
1453 Node* cast = _gvn.transform(new CheckCastPPNode(control(), parm, improved_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
1454 replace_in_map(parm, cast);
1455 }
1456 }
1457 }
1458 }
1459
1460 //------------------------------init_blocks------------------------------------
1461 // Initialize our parser map to contain the types/monitors at method entry.
1462 void Parse::init_blocks() {
1463 // Create the blocks.
1464 _block_count = flow()->block_count();
1465 _blocks = NEW_RESOURCE_ARRAY(Block, _block_count);
1466
1467 // Initialize the structs.
1468 for (int rpo = 0; rpo < block_count(); rpo++) {
1469 Block* block = rpo_at(rpo);
1470 new(block) Block(this, rpo);
1471 }
1472
1473 // Collect predecessor and successor information.
1474 for (int rpo = 0; rpo < block_count(); rpo++) {
1475 Block* block = rpo_at(rpo);
1476 block->init_graph(this);
1477 }
1478 }
1479
1480 //-------------------------------init_node-------------------------------------
1481 Parse::Block::Block(Parse* outer, int rpo) : _live_locals() {
1482 _flow = outer->flow()->rpo_at(rpo);
1483 _pred_count = 0;
1484 _preds_parsed = 0;
1485 _count = 0;
1486 _is_parsed = false;
1487 _is_handler = false;
1488 _has_merged_backedge = false;
1489 _start_map = nullptr;
1490 _has_predicates = false;
1491 _num_successors = 0;
1492 _all_successors = 0;
1493 _successors = nullptr;
1494 assert(pred_count() == 0 && preds_parsed() == 0, "sanity");
1495 assert(!(is_merged() || is_parsed() || is_handler() || has_merged_backedge()), "sanity");
1496 assert(_live_locals.size() == 0, "sanity");
1497
1498 // entry point has additional predecessor
1499 if (flow()->is_start()) _pred_count++;
1500 assert(flow()->is_start() == (this == outer->start_block()), "");
1501 }
1502
1503 //-------------------------------init_graph------------------------------------
1504 void Parse::Block::init_graph(Parse* outer) {
1505 // Create the successor list for this parser block.
1506 GrowableArray<ciTypeFlow::Block*>* tfs = flow()->successors();
1507 GrowableArray<ciTypeFlow::Block*>* tfe = flow()->exceptions();
1508 int ns = tfs->length();
1509 int ne = tfe->length();
1510 _num_successors = ns;
1511 _all_successors = ns+ne;
1512 _successors = (ns+ne == 0) ? nullptr : NEW_RESOURCE_ARRAY(Block*, ns+ne);
1513 int p = 0;
1514 for (int i = 0; i < ns+ne; i++) {
1515 ciTypeFlow::Block* tf2 = (i < ns) ? tfs->at(i) : tfe->at(i-ns);
1516 Block* block2 = outer->rpo_at(tf2->rpo());
1517 _successors[i] = block2;
1518
1519 // Accumulate pred info for the other block, too.
1520 // Note: We also need to set _pred_count for exception blocks since they could
1521 // also have normal predecessors (reached without athrow by an explicit jump).
1522 // This also means that next_path_num can be called along exception paths.
1523 block2->_pred_count++;
1524 if (i >= ns) {
1525 block2->_is_handler = true;
1526 }
1527
1528 #ifdef ASSERT
1529 // A block's successors must be distinguishable by BCI.
1530 // That is, no bytecode is allowed to branch to two different
1531 // clones of the same code location.
1532 for (int j = 0; j < i; j++) {
1533 Block* block1 = _successors[j];
1534 if (block1 == block2) continue; // duplicates are OK
1535 assert(block1->start() != block2->start(), "successors have unique bcis");
1536 }
1537 #endif
1538 }
1539 }
1540
1541 //---------------------------successor_for_bci---------------------------------
1542 Parse::Block* Parse::Block::successor_for_bci(int bci) {
1543 for (int i = 0; i < all_successors(); i++) {
1544 Block* block2 = successor_at(i);
1545 if (block2->start() == bci) return block2;
1546 }
1547 // We can actually reach here if ciTypeFlow traps out a block
1548 // due to an unloaded class, and concurrently with compilation the
1549 // class is then loaded, so that a later phase of the parser is
1550 // able to see more of the bytecode CFG. Or, the flow pass and
1551 // the parser can have a minor difference of opinion about executability
1552 // of bytecodes. For example, "obj.field = null" is executable even
1553 // if the field's type is an unloaded class; the flow pass used to
1554 // make a trap for such code.
1555 return nullptr;
1556 }
1557
1558
1559 //-----------------------------stack_type_at-----------------------------------
1560 const Type* Parse::Block::stack_type_at(int i) const {
1561 return get_type(flow()->stack_type_at(i));
1562 }
1563
1564
1565 //-----------------------------local_type_at-----------------------------------
1566 const Type* Parse::Block::local_type_at(int i) const {
1567 // Make dead locals fall to bottom.
1568 if (_live_locals.size() == 0) {
1569 MethodLivenessResult live_locals = flow()->outer()->method()->liveness_at_bci(start());
1570 // This bitmap can be zero length if we saw a breakpoint.
1571 // In such cases, pretend they are all live.
1572 ((Block*)this)->_live_locals = live_locals;
1573 }
1574 if (_live_locals.size() > 0 && !_live_locals.at(i))
1575 return Type::BOTTOM;
1576
1577 return get_type(flow()->local_type_at(i));
1578 }
1579
1580
1581 #ifndef PRODUCT
1582
1583 //----------------------------name_for_bc--------------------------------------
1584 // helper method for BytecodeParseHistogram
1585 static const char* name_for_bc(int i) {
1586 return Bytecodes::is_defined(i) ? Bytecodes::name(Bytecodes::cast(i)) : "xxxunusedxxx";
1587 }
1588
1589 //----------------------------BytecodeParseHistogram------------------------------------
1590 Parse::BytecodeParseHistogram::BytecodeParseHistogram(Parse *p, Compile *c) {
1591 _parser = p;
1592 _compiler = c;
1593 if( ! _initialized ) { _initialized = true; reset(); }
1594 }
1595
1596 //----------------------------current_count------------------------------------
1597 int Parse::BytecodeParseHistogram::current_count(BPHType bph_type) {
1598 switch( bph_type ) {
1599 case BPH_transforms: { return _parser->gvn().made_progress(); }
1600 case BPH_values: { return _parser->gvn().made_new_values(); }
1601 default: { ShouldNotReachHere(); return 0; }
1602 }
1603 }
1604
1605 //----------------------------initialized--------------------------------------
1606 bool Parse::BytecodeParseHistogram::initialized() { return _initialized; }
1607
1608 //----------------------------reset--------------------------------------------
1609 void Parse::BytecodeParseHistogram::reset() {
1610 int i = Bytecodes::number_of_codes;
1611 while (i-- > 0) { _bytecodes_parsed[i] = 0; _nodes_constructed[i] = 0; _nodes_transformed[i] = 0; _new_values[i] = 0; }
1612 }
1613
1614 //----------------------------set_initial_state--------------------------------
1615 // Record info when starting to parse one bytecode
1616 void Parse::BytecodeParseHistogram::set_initial_state( Bytecodes::Code bc ) {
1617 if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1618 _initial_bytecode = bc;
1619 _initial_node_count = _compiler->unique();
1620 _initial_transforms = current_count(BPH_transforms);
1621 _initial_values = current_count(BPH_values);
1622 }
1623 }
1624
1625 //----------------------------record_change--------------------------------
1626 // Record results of parsing one bytecode
1627 void Parse::BytecodeParseHistogram::record_change() {
1628 if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1629 ++_bytecodes_parsed[_initial_bytecode];
1630 _nodes_constructed [_initial_bytecode] += (_compiler->unique() - _initial_node_count);
1631 _nodes_transformed [_initial_bytecode] += (current_count(BPH_transforms) - _initial_transforms);
1632 _new_values [_initial_bytecode] += (current_count(BPH_values) - _initial_values);
1633 }
1634 }
1635
1636
1637 //----------------------------print--------------------------------------------
1638 void Parse::BytecodeParseHistogram::print(float cutoff) {
1639 ResourceMark rm;
1640 // print profile
1641 int total = 0;
1642 int i = 0;
1643 for( i = 0; i < Bytecodes::number_of_codes; ++i ) { total += _bytecodes_parsed[i]; }
1644 int abs_sum = 0;
1645 tty->cr(); //0123456789012345678901234567890123456789012345678901234567890123456789
1646 tty->print_cr("Histogram of %d parsed bytecodes:", total);
1647 if( total == 0 ) { return; }
1648 tty->cr();
1649 tty->print_cr("absolute: count of compiled bytecodes of this type");
1650 tty->print_cr("relative: percentage contribution to compiled nodes");
1651 tty->print_cr("nodes : Average number of nodes constructed per bytecode");
1652 tty->print_cr("rnodes : Significance towards total nodes constructed, (nodes*relative)");
1653 tty->print_cr("transforms: Average amount of transform progress per bytecode compiled");
1654 tty->print_cr("values : Average number of node values improved per bytecode");
1655 tty->print_cr("name : Bytecode name");
1656 tty->cr();
1657 tty->print_cr(" absolute relative nodes rnodes transforms values name");
1658 tty->print_cr("----------------------------------------------------------------------");
1659 while (--i > 0) {
1660 int abs = _bytecodes_parsed[i];
1661 float rel = abs * 100.0F / total;
1662 float nodes = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_constructed[i])/_bytecodes_parsed[i];
1663 float rnodes = _bytecodes_parsed[i] == 0 ? 0 : rel * nodes;
1664 float xforms = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_transformed[i])/_bytecodes_parsed[i];
1665 float values = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _new_values [i])/_bytecodes_parsed[i];
1666 if (cutoff <= rel) {
1667 tty->print_cr("%10d %7.2f%% %6.1f %6.2f %6.1f %6.1f %s", abs, rel, nodes, rnodes, xforms, values, name_for_bc(i));
1668 abs_sum += abs;
1669 }
1670 }
1671 tty->print_cr("----------------------------------------------------------------------");
1672 float rel_sum = abs_sum * 100.0F / total;
1673 tty->print_cr("%10d %7.2f%% (cutoff = %.2f%%)", abs_sum, rel_sum, cutoff);
1674 tty->print_cr("----------------------------------------------------------------------");
1675 tty->cr();
1676 }
1677 #endif
1678
1679 //----------------------------load_state_from----------------------------------
1680 // Load block/map/sp. But not do not touch iter/bci.
1681 void Parse::load_state_from(Block* block) {
1682 set_block(block);
1683 // load the block's JVM state:
1684 set_map(block->start_map());
1685 set_sp( block->start_sp());
1686 }
1687
1688
1689 //-----------------------------record_state------------------------------------
1690 void Parse::Block::record_state(Parse* p) {
1691 assert(!is_merged(), "can only record state once, on 1st inflow");
1692 assert(start_sp() == p->sp(), "stack pointer must agree with ciTypeFlow");
1693 set_start_map(p->stop());
1694 }
1695
1696
1697 //------------------------------do_one_block-----------------------------------
1698 void Parse::do_one_block() {
1699 if (TraceOptoParse) {
1700 Block *b = block();
1701 int ns = b->num_successors();
1702 int nt = b->all_successors();
1703
1704 tty->print("Parsing block #%d at bci [%d,%d), successors:",
1705 block()->rpo(), block()->start(), block()->limit());
1706 for (int i = 0; i < nt; i++) {
1707 tty->print((( i < ns) ? " %d" : " %d(exception block)"), b->successor_at(i)->rpo());
1708 }
1709 if (b->is_loop_head()) {
1710 tty->print(" loop head");
1711 }
1712 if (b->is_irreducible_loop_entry()) {
1713 tty->print(" irreducible");
1714 }
1715 tty->cr();
1716 }
1717
1718 assert(block()->is_merged(), "must be merged before being parsed");
1719 block()->mark_parsed();
1720
1721 // Set iterator to start of block.
1722 iter().reset_to_bci(block()->start());
1723
1724 if (ProfileExceptionHandlers && block()->is_handler()) {
1725 ciMethodData* methodData = method()->method_data();
1726 if (methodData->is_mature()) {
1727 ciBitData data = methodData->exception_handler_bci_to_data(block()->start());
1728 if (!data.exception_handler_entered() || StressPrunedExceptionHandlers) {
1729 // dead catch block
1730 // Emit an uncommon trap instead of processing the block.
1731 set_parse_bci(block()->start());
1732 uncommon_trap(Deoptimization::Reason_unreached,
1733 Deoptimization::Action_reinterpret,
1734 nullptr, "dead catch block");
1735 return;
1736 }
1737 }
1738 }
1739
1740 CompileLog* log = C->log();
1741
1742 // Parse bytecodes
1743 while (!stopped() && !failing()) {
1744 iter().next();
1745
1746 // Learn the current bci from the iterator:
1747 set_parse_bci(iter().cur_bci());
1748
1749 if (bci() == block()->limit()) {
1750 // Do not walk into the next block until directed by do_all_blocks.
1751 merge(bci());
1752 break;
1753 }
1754 assert(bci() < block()->limit(), "bci still in block");
1755
1756 if (log != nullptr) {
1757 // Output an optional context marker, to help place actions
1758 // that occur during parsing of this BC. If there is no log
1759 // output until the next context string, this context string
1760 // will be silently ignored.
1761 log->set_context("bc code='%d' bci='%d'", (int)bc(), bci());
1762 }
1763
1764 if (block()->has_trap_at(bci())) {
1765 // We must respect the flow pass's traps, because it will refuse
1766 // to produce successors for trapping blocks.
1767 int trap_index = block()->flow()->trap_index();
1768 assert(trap_index != 0, "trap index must be valid");
1769 uncommon_trap(trap_index);
1770 break;
1771 }
1772
1773 NOT_PRODUCT( parse_histogram()->set_initial_state(bc()); );
1774
1775 #ifdef ASSERT
1776 int pre_bc_sp = sp();
1777 int inputs, depth;
1778 bool have_se = !stopped() && compute_stack_effects(inputs, depth);
1779 assert(!have_se || pre_bc_sp >= inputs, "have enough stack to execute this BC: pre_bc_sp=%d, inputs=%d", pre_bc_sp, inputs);
1780 #endif //ASSERT
1781
1782 do_one_bytecode();
1783 if (failing()) return;
1784
1785 assert(!have_se || stopped() || failing() || (sp() - pre_bc_sp) == depth,
1786 "incorrect depth prediction: sp=%d, pre_bc_sp=%d, depth=%d", sp(), pre_bc_sp, depth);
1787
1788 do_exceptions();
1789
1790 NOT_PRODUCT( parse_histogram()->record_change(); );
1791
1792 if (log != nullptr)
1793 log->clear_context(); // skip marker if nothing was printed
1794
1795 // Fall into next bytecode. Each bytecode normally has 1 sequential
1796 // successor which is typically made ready by visiting this bytecode.
1797 // If the successor has several predecessors, then it is a merge
1798 // point, starts a new basic block, and is handled like other basic blocks.
1799 }
1800 }
1801
1802
1803 //------------------------------merge------------------------------------------
1804 void Parse::set_parse_bci(int bci) {
1805 set_bci(bci);
1806 Node_Notes* nn = C->default_node_notes();
1807 if (nn == nullptr) return;
1808
1809 // Collect debug info for inlined calls unless -XX:-DebugInlinedCalls.
1810 if (!DebugInlinedCalls && depth() > 1) {
1811 return;
1812 }
1813
1814 // Update the JVMS annotation, if present.
1815 JVMState* jvms = nn->jvms();
1816 if (jvms != nullptr && jvms->bci() != bci) {
1817 // Update the JVMS.
1818 jvms = jvms->clone_shallow(C);
1819 jvms->set_bci(bci);
1820 nn->set_jvms(jvms);
1821 }
1822 }
1823
1824 //------------------------------merge------------------------------------------
1825 // Merge the current mapping into the basic block starting at bci
1826 void Parse::merge(int target_bci) {
1827 Block* target = successor_for_bci(target_bci);
1828 if (target == nullptr) { handle_missing_successor(target_bci); return; }
1829 assert(!target->is_ready(), "our arrival must be expected");
1830 int pnum = target->next_path_num();
1831 merge_common(target, pnum);
1832 }
1833
1834 //-------------------------merge_new_path--------------------------------------
1835 // Merge the current mapping into the basic block, using a new path
1836 void Parse::merge_new_path(int target_bci) {
1837 Block* target = successor_for_bci(target_bci);
1838 if (target == nullptr) { handle_missing_successor(target_bci); return; }
1839 assert(!target->is_ready(), "new path into frozen graph");
1840 int pnum = target->add_new_path();
1841 merge_common(target, pnum);
1842 }
1843
1844 //-------------------------merge_exception-------------------------------------
1845 // Push the given ex_oop onto the stack, then merge the current mapping into
1846 // the basic block starting at target_bci.
1847 void Parse::push_and_merge_exception(int target_bci, Node* ex_oop) {
1848 // Add the safepoint before trimming the stack and pushing the exception oop.
1849 // We could add the safepoint after, but then the bci would also need to be
1850 // advanced to target_bci first, so the stack state matches.
1851 maybe_add_safepoint(target_bci);
1852 push_ex_oop(ex_oop); // Push exception oop for handler
1853 #ifdef ASSERT
1854 if (target_bci <= bci()) {
1855 C->set_exception_backedge();
1856 }
1857 #endif
1858 assert(sp() == 1, "must have only the throw exception on the stack");
1859 Block* target = successor_for_bci(target_bci);
1860 if (target == nullptr) { handle_missing_successor(target_bci); return; }
1861 assert(target->is_handler(), "exceptions are handled by special blocks");
1862 int pnum = target->add_new_path();
1863 merge_common(target, pnum);
1864 }
1865
1866 //--------------------handle_missing_successor---------------------------------
1867 void Parse::handle_missing_successor(int target_bci) {
1868 #ifndef PRODUCT
1869 Block* b = block();
1870 int trap_bci = b->flow()->has_trap()? b->flow()->trap_bci(): -1;
1871 tty->print_cr("### Missing successor at bci:%d for block #%d (trap_bci:%d)", target_bci, b->rpo(), trap_bci);
1872 #endif
1873 ShouldNotReachHere();
1874 }
1875
1876 //--------------------------merge_common---------------------------------------
1877 void Parse::merge_common(Parse::Block* target, int pnum) {
1878 if (TraceOptoParse) {
1879 tty->print("Merging state at block #%d bci:%d", target->rpo(), target->start());
1880 }
1881
1882 // Zap extra stack slots to top
1883 assert(sp() == target->start_sp(), "");
1884 clean_stack(sp());
1885
1886 // Check for merge conflicts involving inline types
1887 JVMState* old_jvms = map()->jvms();
1888 int old_bci = bci();
1889 JVMState* tmp_jvms = old_jvms->clone_shallow(C);
1890 tmp_jvms->set_should_reexecute(true);
1891 tmp_jvms->bind_map(map());
1892 // Execution needs to restart a the next bytecode (entry of next
1893 // block)
1894 if (target->is_merged() ||
1895 pnum > PhiNode::Input ||
1896 target->is_handler() ||
1897 target->is_loop_head()) {
1898 set_parse_bci(target->start());
1899 for (uint j = TypeFunc::Parms; j < map()->req(); j++) {
1900 Node* n = map()->in(j); // Incoming change to target state.
1901 const Type* t = nullptr;
1902 ciType* ct = nullptr;
1903 if (tmp_jvms->is_loc(j)) {
1904 int loc_idx = j - tmp_jvms->locoff();
1905 t = target->local_type_at(loc_idx);
1906 ct = target->flow()->local_type_at(loc_idx);
1907 } else if (tmp_jvms->is_stk(j) && j < (uint)sp() + tmp_jvms->stkoff()) {
1908 int stk_idx = j - tmp_jvms->stkoff();
1909 t = target->stack_type_at(stk_idx);
1910 ct = target->flow()->stack_type_at(stk_idx);
1911 }
1912 if (t != nullptr && t != Type::BOTTOM) {
1913 // An object can appear in the JVMS as either an oop or an InlineTypeNode. If the merge is
1914 // an InlineTypeNode, we need all the merge inputs to be InlineTypeNodes. Else, if the
1915 // merge is an oop, each merge input needs to be either an oop or an buffered
1916 // InlineTypeNode.
1917 if (!t->is_inlinetypeptr()) {
1918 // The merge cannot be an InlineTypeNode, ensure the input is buffered if it is an
1919 // InlineTypeNode
1920 if (n->is_InlineType()) {
1921 map()->set_req(j, n->as_InlineType()->buffer(this));
1922 }
1923 } else {
1924 // Scalarize the value object if it is not larval
1925 if (!n->is_InlineType() && !ct->is_early_larval()) {
1926 assert(_gvn.type(n) == TypePtr::NULL_PTR, "must be a null constant");
1927 map()->set_req(j, InlineTypeNode::make_null(_gvn, t->inline_klass()));
1928 }
1929 }
1930 }
1931 }
1932 }
1933 old_jvms->bind_map(map());
1934 set_parse_bci(old_bci);
1935
1936 if (!target->is_merged()) { // No prior mapping at this bci
1937 if (TraceOptoParse) { tty->print(" with empty state"); }
1938
1939 // If this path is dead, do not bother capturing it as a merge.
1940 // It is "as if" we had 1 fewer predecessors from the beginning.
1941 if (stopped()) {
1942 if (TraceOptoParse) tty->print_cr(", but path is dead and doesn't count");
1943 return;
1944 }
1945
1946 // Make a region if we know there are multiple or unpredictable inputs.
1947 // (Also, if this is a plain fall-through, we might see another region,
1948 // which must not be allowed into this block's map.)
1949 if (pnum > PhiNode::Input // Known multiple inputs.
1950 || target->is_handler() // These have unpredictable inputs.
1951 || target->is_loop_head() // Known multiple inputs
1952 || control()->is_Region()) { // We must hide this guy.
1953
1954 int current_bci = bci();
1955 set_parse_bci(target->start()); // Set target bci
1956 if (target->is_SEL_head()) {
1957 DEBUG_ONLY( target->mark_merged_backedge(block()); )
1958 if (target->start() == 0) {
1959 // Add Parse Predicates for the special case when
1960 // there are backbranches to the method entry.
1961 add_parse_predicates();
1962 }
1963 }
1964 // Add a Region to start the new basic block. Phis will be added
1965 // later lazily.
1966 int edges = target->pred_count();
1967 if (edges < pnum) edges = pnum; // might be a new path!
1968 RegionNode *r = new RegionNode(edges+1);
1969 gvn().set_type(r, Type::CONTROL);
1970 record_for_igvn(r);
1971 // zap all inputs to null for debugging (done in Node(uint) constructor)
1972 // for (int j = 1; j < edges+1; j++) { r->init_req(j, nullptr); }
1973 r->init_req(pnum, control());
1974 set_control(r);
1975 target->copy_irreducible_status_to(r, jvms());
1976 set_parse_bci(current_bci); // Restore bci
1977 }
1978
1979 // Convert the existing Parser mapping into a mapping at this bci.
1980 store_state_to(target);
1981 assert(target->is_merged(), "do not come here twice");
1982
1983 } else { // Prior mapping at this bci
1984 if (TraceOptoParse) { tty->print(" with previous state"); }
1985 #ifdef ASSERT
1986 if (target->is_SEL_head()) {
1987 target->mark_merged_backedge(block());
1988 }
1989 #endif
1990
1991 // We must not manufacture more phis if the target is already parsed.
1992 bool nophi = target->is_parsed();
1993
1994 SafePointNode* newin = map();// Hang on to incoming mapping
1995 Block* save_block = block(); // Hang on to incoming block;
1996 load_state_from(target); // Get prior mapping
1997
1998 assert(newin->jvms()->locoff() == jvms()->locoff(), "JVMS layouts agree");
1999 assert(newin->jvms()->stkoff() == jvms()->stkoff(), "JVMS layouts agree");
2000 assert(newin->jvms()->monoff() == jvms()->monoff(), "JVMS layouts agree");
2001 assert(newin->jvms()->endoff() == jvms()->endoff(), "JVMS layouts agree");
2002
2003 // Iterate over my current mapping and the old mapping.
2004 // Where different, insert Phi functions.
2005 // Use any existing Phi functions.
2006 assert(control()->is_Region(), "must be merging to a region");
2007 RegionNode* r = control()->as_Region();
2008
2009 // Compute where to merge into
2010 // Merge incoming control path
2011 r->init_req(pnum, newin->control());
2012
2013 if (pnum == 1) { // Last merge for this Region?
2014 if (!block()->flow()->is_irreducible_loop_secondary_entry()) {
2015 Node* result = _gvn.transform(r);
2016 if (r != result && TraceOptoParse) {
2017 tty->print_cr("Block #%d replace %d with %d", block()->rpo(), r->_idx, result->_idx);
2018 }
2019 }
2020 record_for_igvn(r);
2021 }
2022
2023 // Update all the non-control inputs to map:
2024 assert(TypeFunc::Parms == newin->jvms()->locoff(), "parser map should contain only youngest jvms");
2025 bool check_elide_phi = target->is_SEL_backedge(save_block);
2026 bool last_merge = (pnum == PhiNode::Input);
2027 for (uint j = 1; j < newin->req(); j++) {
2028 Node* m = map()->in(j); // Current state of target.
2029 Node* n = newin->in(j); // Incoming change to target state.
2030 Node* phi;
2031 if (m->is_Phi() && m->as_Phi()->region() == r) {
2032 phi = m;
2033 } else if (m->is_InlineType() && m->as_InlineType()->has_phi_inputs(r)) {
2034 phi = m;
2035 } else {
2036 phi = nullptr;
2037 }
2038 if (m != n) { // Different; must merge
2039 switch (j) {
2040 // Frame pointer and Return Address never changes
2041 case TypeFunc::FramePtr:// Drop m, use the original value
2042 case TypeFunc::ReturnAdr:
2043 break;
2044 case TypeFunc::Memory: // Merge inputs to the MergeMem node
2045 assert(phi == nullptr, "the merge contains phis, not vice versa");
2046 merge_memory_edges(n->as_MergeMem(), pnum, nophi);
2047 continue;
2048 default: // All normal stuff
2049 if (phi == nullptr) {
2050 const JVMState* jvms = map()->jvms();
2051 if (EliminateNestedLocks &&
2052 jvms->is_mon(j) && jvms->is_monitor_box(j)) {
2053 // BoxLock nodes are not commoning when EliminateNestedLocks is on.
2054 // Use old BoxLock node as merged box.
2055 assert(newin->jvms()->is_monitor_box(j), "sanity");
2056 // This assert also tests that nodes are BoxLock.
2057 assert(BoxLockNode::same_slot(n, m), "sanity");
2058 BoxLockNode* old_box = m->as_BoxLock();
2059 if (n->as_BoxLock()->is_unbalanced() && !old_box->is_unbalanced()) {
2060 // Preserve Unbalanced status.
2061 //
2062 // `old_box` can have only Regular or Coarsened status
2063 // because this code is executed only during Parse phase and
2064 // Incremental Inlining before EA and Macro nodes elimination.
2065 //
2066 // Incremental Inlining is executed after IGVN optimizations
2067 // during which BoxLock can be marked as Coarsened.
2068 old_box->set_coarsened(); // Verifies state
2069 old_box->set_unbalanced();
2070 }
2071 C->gvn_replace_by(n, m);
2072 } else if (!check_elide_phi || !target->can_elide_SEL_phi(j)) {
2073 phi = ensure_phi(j, nophi);
2074 }
2075 }
2076 break;
2077 }
2078 }
2079 // At this point, n might be top if:
2080 // - there is no phi (because TypeFlow detected a conflict), or
2081 // - the corresponding control edges is top (a dead incoming path)
2082 // It is a bug if we create a phi which sees a garbage value on a live path.
2083
2084 // Merging two inline types?
2085 if (phi != nullptr && phi->is_InlineType()) {
2086 // Reload current state because it may have been updated by ensure_phi
2087 assert(phi == map()->in(j), "unexpected value in map");
2088 assert(phi->as_InlineType()->has_phi_inputs(r), "");
2089 InlineTypeNode* vtm = phi->as_InlineType(); // Current inline type
2090 InlineTypeNode* vtn = n->as_InlineType(); // Incoming inline type
2091 assert(vtm == phi, "Inline type should have Phi input");
2092
2093 #ifdef ASSERT
2094 if (TraceOptoParse) {
2095 tty->print_cr("\nMerging inline types");
2096 tty->print_cr("Current:");
2097 vtm->dump(2);
2098 tty->print_cr("Incoming:");
2099 vtn->dump(2);
2100 tty->cr();
2101 }
2102 #endif
2103 // Do the merge
2104 vtm->merge_with(&_gvn, vtn, pnum, last_merge);
2105 if (last_merge) {
2106 map()->set_req(j, _gvn.transform(vtm));
2107 record_for_igvn(vtm);
2108 }
2109 } else if (phi != nullptr) {
2110 assert(n != top() || r->in(pnum) == top(), "live value must not be garbage");
2111 assert(phi->as_Phi()->region() == r, "");
2112 phi->set_req(pnum, n); // Then add 'n' to the merge
2113 if (last_merge) {
2114 // Last merge for this Phi.
2115 // So far, Phis have had a reasonable type from ciTypeFlow.
2116 // Now _gvn will join that with the meet of current inputs.
2117 // BOTTOM is never permissible here, 'cause pessimistically
2118 // Phis of pointers cannot lose the basic pointer type.
2119 DEBUG_ONLY(const Type* bt1 = phi->bottom_type());
2120 assert(bt1 != Type::BOTTOM, "should not be building conflict phis");
2121 map()->set_req(j, _gvn.transform(phi));
2122 DEBUG_ONLY(const Type* bt2 = phi->bottom_type());
2123 assert(bt2->higher_equal_speculative(bt1), "must be consistent with type-flow");
2124 record_for_igvn(phi);
2125 }
2126 }
2127 } // End of for all values to be merged
2128
2129 if (last_merge && !r->in(0)) { // The occasional useless Region
2130 assert(control() == r, "");
2131 set_control(r->nonnull_req());
2132 }
2133
2134 map()->merge_replaced_nodes_with(newin);
2135
2136 // newin has been subsumed into the lazy merge, and is now dead.
2137 set_block(save_block);
2138
2139 stop(); // done with this guy, for now
2140 }
2141
2142 if (TraceOptoParse) {
2143 tty->print_cr(" on path %d", pnum);
2144 }
2145
2146 // Done with this parser state.
2147 assert(stopped(), "");
2148 }
2149
2150
2151 //--------------------------merge_memory_edges---------------------------------
2152 void Parse::merge_memory_edges(MergeMemNode* n, int pnum, bool nophi) {
2153 // (nophi means we must not create phis, because we already parsed here)
2154 assert(n != nullptr, "");
2155 // Merge the inputs to the MergeMems
2156 MergeMemNode* m = merged_memory();
2157
2158 assert(control()->is_Region(), "must be merging to a region");
2159 RegionNode* r = control()->as_Region();
2160
2161 PhiNode* base = nullptr;
2162 MergeMemNode* remerge = nullptr;
2163 for (MergeMemStream mms(m, n); mms.next_non_empty2(); ) {
2164 Node *p = mms.force_memory();
2165 Node *q = mms.memory2();
2166 if (mms.is_empty() && nophi) {
2167 // Trouble: No new splits allowed after a loop body is parsed.
2168 // Instead, wire the new split into a MergeMem on the backedge.
2169 // The optimizer will sort it out, slicing the phi.
2170 if (remerge == nullptr) {
2171 guarantee(base != nullptr, "");
2172 assert(base->in(0) != nullptr, "should not be xformed away");
2173 remerge = MergeMemNode::make(base->in(pnum));
2174 gvn().set_type(remerge, Type::MEMORY);
2175 base->set_req(pnum, remerge);
2176 }
2177 remerge->set_memory_at(mms.alias_idx(), q);
2178 continue;
2179 }
2180 assert(!q->is_MergeMem(), "");
2181 PhiNode* phi;
2182 if (p != q) {
2183 phi = ensure_memory_phi(mms.alias_idx(), nophi);
2184 } else {
2185 if (p->is_Phi() && p->as_Phi()->region() == r)
2186 phi = p->as_Phi();
2187 else
2188 phi = nullptr;
2189 }
2190 // Insert q into local phi
2191 if (phi != nullptr) {
2192 assert(phi->region() == r, "");
2193 p = phi;
2194 phi->set_req(pnum, q);
2195 if (mms.at_base_memory()) {
2196 base = phi; // delay transforming it
2197 } else if (pnum == 1) {
2198 record_for_igvn(phi);
2199 p = _gvn.transform(phi);
2200 }
2201 mms.set_memory(p);// store back through the iterator
2202 }
2203 }
2204 // Transform base last, in case we must fiddle with remerging.
2205 if (base != nullptr && pnum == 1) {
2206 record_for_igvn(base);
2207 m->set_base_memory(_gvn.transform(base));
2208 }
2209 }
2210
2211
2212 //------------------------ensure_phis_everywhere-------------------------------
2213 void Parse::ensure_phis_everywhere() {
2214 ensure_phi(TypeFunc::I_O);
2215
2216 // Ensure a phi on all currently known memories.
2217 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
2218 ensure_memory_phi(mms.alias_idx());
2219 DEBUG_ONLY(mms.set_memory()); // keep the iterator happy
2220 }
2221
2222 // Note: This is our only chance to create phis for memory slices.
2223 // If we miss a slice that crops up later, it will have to be
2224 // merged into the base-memory phi that we are building here.
2225 // Later, the optimizer will comb out the knot, and build separate
2226 // phi-loops for each memory slice that matters.
2227
2228 // Monitors must nest nicely and not get confused amongst themselves.
2229 // Phi-ify everything up to the monitors, though.
2230 uint monoff = map()->jvms()->monoff();
2231 uint nof_monitors = map()->jvms()->nof_monitors();
2232
2233 assert(TypeFunc::Parms == map()->jvms()->locoff(), "parser map should contain only youngest jvms");
2234 bool check_elide_phi = block()->is_SEL_head();
2235 for (uint i = TypeFunc::Parms; i < monoff; i++) {
2236 if (!check_elide_phi || !block()->can_elide_SEL_phi(i)) {
2237 ensure_phi(i);
2238 }
2239 }
2240
2241 // Even monitors need Phis, though they are well-structured.
2242 // This is true for OSR methods, and also for the rare cases where
2243 // a monitor object is the subject of a replace_in_map operation.
2244 // See bugs 4426707 and 5043395.
2245 for (uint m = 0; m < nof_monitors; m++) {
2246 ensure_phi(map()->jvms()->monitor_obj_offset(m));
2247 }
2248 }
2249
2250
2251 //-----------------------------add_new_path------------------------------------
2252 // Add a previously unaccounted predecessor to this block.
2253 int Parse::Block::add_new_path() {
2254 // If there is no map, return the lowest unused path number.
2255 if (!is_merged()) return pred_count()+1; // there will be a map shortly
2256
2257 SafePointNode* map = start_map();
2258 if (!map->control()->is_Region())
2259 return pred_count()+1; // there may be a region some day
2260 RegionNode* r = map->control()->as_Region();
2261
2262 // Add new path to the region.
2263 uint pnum = r->req();
2264 r->add_req(nullptr);
2265
2266 for (uint i = 1; i < map->req(); i++) {
2267 Node* n = map->in(i);
2268 if (i == TypeFunc::Memory) {
2269 // Ensure a phi on all currently known memories.
2270 for (MergeMemStream mms(n->as_MergeMem()); mms.next_non_empty(); ) {
2271 Node* phi = mms.memory();
2272 if (phi->is_Phi() && phi->as_Phi()->region() == r) {
2273 assert(phi->req() == pnum, "must be same size as region");
2274 phi->add_req(nullptr);
2275 }
2276 }
2277 } else {
2278 if (n->is_Phi() && n->as_Phi()->region() == r) {
2279 assert(n->req() == pnum, "must be same size as region");
2280 n->add_req(nullptr);
2281 } else if (n->is_InlineType() && n->as_InlineType()->has_phi_inputs(r)) {
2282 n->as_InlineType()->add_new_path(r);
2283 }
2284 }
2285 }
2286
2287 return pnum;
2288 }
2289
2290 //------------------------------ensure_phi-------------------------------------
2291 // Turn the idx'th entry of the current map into a Phi
2292 Node* Parse::ensure_phi(int idx, bool nocreate) {
2293 SafePointNode* map = this->map();
2294 Node* region = map->control();
2295 assert(region->is_Region(), "");
2296
2297 Node* o = map->in(idx);
2298 assert(o != nullptr, "");
2299
2300 if (o == top()) return nullptr; // TOP always merges into TOP
2301
2302 if (o->is_Phi() && o->as_Phi()->region() == region) {
2303 return o->as_Phi();
2304 }
2305 InlineTypeNode* vt = o->isa_InlineType();
2306 if (vt != nullptr && vt->has_phi_inputs(region)) {
2307 return vt;
2308 }
2309
2310 // Now use a Phi here for merging
2311 assert(!nocreate, "Cannot build a phi for a block already parsed.");
2312 const JVMState* jvms = map->jvms();
2313 const Type* t = nullptr;
2314 if (jvms->is_loc(idx)) {
2315 t = block()->local_type_at(idx - jvms->locoff());
2316 } else if (jvms->is_stk(idx)) {
2317 t = block()->stack_type_at(idx - jvms->stkoff());
2318 } else if (jvms->is_mon(idx)) {
2319 assert(!jvms->is_monitor_box(idx), "no phis for boxes");
2320 t = TypeInstPtr::BOTTOM; // this is sufficient for a lock object
2321 } else if ((uint)idx < TypeFunc::Parms) {
2322 t = o->bottom_type(); // Type::RETURN_ADDRESS or such-like.
2323 } else {
2324 assert(false, "no type information for this phi");
2325 }
2326
2327 // If the type falls to bottom, then this must be a local that
2328 // is already dead or is mixing ints and oops or some such.
2329 // Forcing it to top makes it go dead.
2330 if (t == Type::BOTTOM) {
2331 map->set_req(idx, top());
2332 return nullptr;
2333 }
2334
2335 // Do not create phis for top either.
2336 // A top on a non-null control flow must be an unused even after the.phi.
2337 if (t == Type::TOP || t == Type::HALF) {
2338 map->set_req(idx, top());
2339 return nullptr;
2340 }
2341
2342 if (vt != nullptr && t->is_inlinetypeptr()) {
2343 // Inline types are merged by merging their field values.
2344 // Create a cloned InlineTypeNode with phi inputs that
2345 // represents the merged inline type and update the map.
2346 vt = vt->clone_with_phis(&_gvn, region);
2347 map->set_req(idx, vt);
2348 return vt;
2349 } else {
2350 PhiNode* phi = PhiNode::make(region, o, t);
2351 gvn().set_type(phi, t);
2352 if (C->do_escape_analysis()) record_for_igvn(phi);
2353 map->set_req(idx, phi);
2354 return phi;
2355 }
2356 }
2357
2358 //--------------------------ensure_memory_phi----------------------------------
2359 // Turn the idx'th slice of the current memory into a Phi
2360 PhiNode *Parse::ensure_memory_phi(int idx, bool nocreate) {
2361 MergeMemNode* mem = merged_memory();
2362 Node* region = control();
2363 assert(region->is_Region(), "");
2364
2365 Node *o = (idx == Compile::AliasIdxBot)? mem->base_memory(): mem->memory_at(idx);
2366 assert(o != nullptr && o != top(), "");
2367
2368 PhiNode* phi;
2369 if (o->is_Phi() && o->as_Phi()->region() == region) {
2370 phi = o->as_Phi();
2371 if (phi == mem->base_memory() && idx >= Compile::AliasIdxRaw) {
2372 // clone the shared base memory phi to make a new memory split
2373 assert(!nocreate, "Cannot build a phi for a block already parsed.");
2374 const Type* t = phi->bottom_type();
2375 const TypePtr* adr_type = C->get_adr_type(idx);
2376 phi = phi->slice_memory(adr_type);
2377 gvn().set_type(phi, t);
2378 }
2379 return phi;
2380 }
2381
2382 // Now use a Phi here for merging
2383 assert(!nocreate, "Cannot build a phi for a block already parsed.");
2384 const Type* t = o->bottom_type();
2385 const TypePtr* adr_type = C->get_adr_type(idx);
2386 phi = PhiNode::make(region, o, t, adr_type);
2387 gvn().set_type(phi, t);
2388 if (idx == Compile::AliasIdxBot)
2389 mem->set_base_memory(phi);
2390 else
2391 mem->set_memory_at(idx, phi);
2392 return phi;
2393 }
2394
2395 //------------------------------call_register_finalizer-----------------------
2396 // Check the klass of the receiver and call register_finalizer if the
2397 // class need finalization.
2398 void Parse::call_register_finalizer() {
2399 Node* receiver = local(0);
2400 assert(receiver != nullptr && receiver->bottom_type()->isa_instptr() != nullptr,
2401 "must have non-null instance type");
2402
2403 const TypeInstPtr *tinst = receiver->bottom_type()->isa_instptr();
2404 if (tinst != nullptr && tinst->is_loaded() && !tinst->klass_is_exact()) {
2405 // The type isn't known exactly so see if CHA tells us anything.
2406 ciInstanceKlass* ik = tinst->instance_klass();
2407 if (!Dependencies::has_finalizable_subclass(ik)) {
2408 // No finalizable subclasses so skip the dynamic check.
2409 C->dependencies()->assert_has_no_finalizable_subclasses(ik);
2410 return;
2411 }
2412 }
2413
2414 // Insert a dynamic test for whether the instance needs
2415 // finalization. In general this will fold up since the concrete
2416 // class is often visible so the access flags are constant.
2417 Node* klass_addr = basic_plus_adr( receiver, receiver, oopDesc::klass_offset_in_bytes() );
2418 Node* klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), klass_addr, TypeInstPtr::KLASS));
2419
2420 Node* access_flags_addr = off_heap_plus_addr(klass, in_bytes(Klass::misc_flags_offset()));
2421 Node* access_flags = make_load(nullptr, access_flags_addr, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
2422
2423 Node* mask = _gvn.transform(new AndINode(access_flags, intcon(KlassFlags::_misc_has_finalizer)));
2424 Node* check = _gvn.transform(new CmpINode(mask, intcon(0)));
2425 Node* test = _gvn.transform(new BoolNode(check, BoolTest::ne));
2426
2427 IfNode* iff = create_and_map_if(control(), test, PROB_MAX, COUNT_UNKNOWN);
2428
2429 RegionNode* result_rgn = new RegionNode(3);
2430 record_for_igvn(result_rgn);
2431
2432 Node *skip_register = _gvn.transform(new IfFalseNode(iff));
2433 result_rgn->init_req(1, skip_register);
2434
2435 Node *needs_register = _gvn.transform(new IfTrueNode(iff));
2436 set_control(needs_register);
2437 if (stopped()) {
2438 // There is no slow path.
2439 result_rgn->init_req(2, top());
2440 } else {
2441 Node *call = make_runtime_call(RC_NO_LEAF,
2442 OptoRuntime::register_finalizer_Type(),
2443 OptoRuntime::register_finalizer_Java(),
2444 nullptr, TypePtr::BOTTOM,
2445 receiver);
2446 make_slow_call_ex(call, env()->Throwable_klass(), true);
2447
2448 Node* fast_io = call->in(TypeFunc::I_O);
2449 Node* fast_mem = call->in(TypeFunc::Memory);
2450 // These two phis are pre-filled with copies of of the fast IO and Memory
2451 Node* io_phi = PhiNode::make(result_rgn, fast_io, Type::ABIO);
2452 Node* mem_phi = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
2453
2454 result_rgn->init_req(2, control());
2455 io_phi ->init_req(2, i_o());
2456 mem_phi ->init_req(2, reset_memory());
2457
2458 set_all_memory( _gvn.transform(mem_phi) );
2459 set_i_o( _gvn.transform(io_phi) );
2460 }
2461
2462 set_control( _gvn.transform(result_rgn) );
2463 }
2464
2465 // Add check to deoptimize once holder klass is fully initialized.
2466 void Parse::clinit_deopt() {
2467 assert(C->has_method(), "only for normal compilations");
2468 assert(depth() == 1, "only for main compiled method");
2469 assert(is_normal_parse(), "no barrier needed on osr entry");
2470 assert(!method()->holder()->is_not_initialized(), "initialization should have been started");
2471
2472 set_parse_bci(0);
2473
2474 Node* holder = makecon(TypeKlassPtr::make(method()->holder(), Type::trust_interfaces));
2475 guard_klass_being_initialized(holder);
2476 }
2477
2478 //------------------------------return_current---------------------------------
2479 // Append current _map to _exit_return
2480 void Parse::return_current(Node* value) {
2481 if (method()->intrinsic_id() == vmIntrinsics::_Object_init) {
2482 call_register_finalizer();
2483 }
2484
2485 // frame pointer is always same, already captured
2486 if (value != nullptr) {
2487 Node* phi = _exits.argument(0);
2488 const Type* return_type = phi->bottom_type();
2489 if ((tf()->returns_inline_type_as_fields() || (_caller->has_method() && !Compile::current()->inlining_incrementally())) &&
2490 return_type->is_inlinetypeptr()) {
2491 // Inline type is returned as fields, make sure it is scalarized
2492 if (!value->is_InlineType()) {
2493 value = InlineTypeNode::make_from_oop(this, value, return_type->inline_klass());
2494 }
2495 if (!_caller->has_method() || Compile::current()->inlining_incrementally()) {
2496 // Returning from root or an incrementally inlined method. Make sure all non-flat
2497 // fields are buffered and re-execute if allocation triggers deoptimization.
2498 PreserveReexecuteState preexecs(this);
2499 assert(tf()->returns_inline_type_as_fields(), "must be returned as fields");
2500 jvms()->set_should_reexecute(true);
2501 inc_sp(1);
2502 value = value->as_InlineType()->allocate_fields(this);
2503 }
2504 } else if (value->is_InlineType()) {
2505 // Inline type is returned as oop, make sure it is buffered and re-execute
2506 // if allocation triggers deoptimization.
2507 PreserveReexecuteState preexecs(this);
2508 jvms()->set_should_reexecute(true);
2509 inc_sp(1);
2510 value = value->as_InlineType()->buffer(this);
2511 }
2512 // ...else
2513 // If returning oops to an interface-return, there is a silent free
2514 // cast from oop to interface allowed by the Verifier. Make it explicit here.
2515 phi->add_req(value);
2516 }
2517
2518 if (StressReachabilityFences) {
2519 // Insert reachability fences for all oop arguments at the end of the method.
2520 for (uint i = 1; i < _stress_rf_hook->req(); i++) {
2521 Node* referent = _stress_rf_hook->in(i);
2522 assert(referent->bottom_type()->isa_oopptr(), "%s", Type::str(referent->bottom_type()));
2523 insert_reachability_fence(referent);
2524 }
2525 }
2526
2527 // Do not set_parse_bci, so that return goo is credited to the return insn.
2528 set_bci(InvocationEntryBci);
2529 if (method()->is_synchronized()) {
2530 shared_unlock(_synch_lock->box_node(), _synch_lock->obj_node());
2531 }
2532 if (C->env()->dtrace_method_probes()) {
2533 make_dtrace_method_exit(method());
2534 }
2535
2536 SafePointNode* exit_return = _exits.map();
2537 exit_return->in( TypeFunc::Control )->add_req( control() );
2538 exit_return->in( TypeFunc::I_O )->add_req( i_o () );
2539 Node *mem = exit_return->in( TypeFunc::Memory );
2540 for (MergeMemStream mms(mem->as_MergeMem(), merged_memory()); mms.next_non_empty2(); ) {
2541 if (mms.is_empty()) {
2542 // get a copy of the base memory, and patch just this one input
2543 const TypePtr* adr_type = mms.adr_type(C);
2544 Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
2545 assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
2546 gvn().set_type_bottom(phi);
2547 phi->del_req(phi->req()-1); // prepare to re-patch
2548 mms.set_memory(phi);
2549 }
2550 mms.memory()->add_req(mms.memory2());
2551 }
2552
2553 if (_first_return) {
2554 _exits.map()->transfer_replaced_nodes_from(map(), _new_idx);
2555 _first_return = false;
2556 } else {
2557 _exits.map()->merge_replaced_nodes_with(map());
2558 }
2559
2560 stop_and_kill_map(); // This CFG path dies here
2561 }
2562
2563
2564 //------------------------------add_safepoint----------------------------------
2565 void Parse::add_safepoint() {
2566 uint parms = TypeFunc::Parms+1;
2567
2568 // Clear out dead values from the debug info.
2569 kill_dead_locals();
2570
2571 // Clone the JVM State
2572 SafePointNode *sfpnt = new SafePointNode(parms, nullptr);
2573
2574 // Capture memory state BEFORE a SafePoint. Since we can block at a
2575 // SafePoint we need our GC state to be safe; i.e. we need all our current
2576 // write barriers (card marks) to not float down after the SafePoint so we
2577 // must read raw memory. Likewise we need all oop stores to match the card
2578 // marks. If deopt can happen, we need ALL stores (we need the correct JVM
2579 // state on a deopt).
2580
2581 // We do not need to WRITE the memory state after a SafePoint. The control
2582 // edge will keep card-marks and oop-stores from floating up from below a
2583 // SafePoint and our true dependency added here will keep them from floating
2584 // down below a SafePoint.
2585
2586 // Clone the current memory state
2587 Node* mem = MergeMemNode::make(map()->memory());
2588
2589 mem = _gvn.transform(mem);
2590
2591 // Pass control through the safepoint
2592 sfpnt->init_req(TypeFunc::Control , control());
2593 // Fix edges normally used by a call
2594 sfpnt->init_req(TypeFunc::I_O , top() );
2595 sfpnt->init_req(TypeFunc::Memory , mem );
2596 sfpnt->init_req(TypeFunc::ReturnAdr, top() );
2597 sfpnt->init_req(TypeFunc::FramePtr , top() );
2598
2599 // Create a node for the polling address
2600 Node* polladr;
2601 Node* thread = _gvn.transform(new ThreadLocalNode());
2602 Node* polling_page_load_addr = _gvn.transform(off_heap_plus_addr(thread, in_bytes(JavaThread::polling_page_offset())));
2603 polladr = make_load(control(), polling_page_load_addr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
2604 sfpnt->init_req(TypeFunc::Parms+0, _gvn.transform(polladr));
2605
2606 // Fix up the JVM State edges
2607 add_safepoint_edges(sfpnt);
2608 Node *transformed_sfpnt = _gvn.transform(sfpnt);
2609 set_control(transformed_sfpnt);
2610
2611 // Provide an edge from root to safepoint. This makes the safepoint
2612 // appear useful until the parse has completed.
2613 if (transformed_sfpnt->is_SafePoint()) {
2614 assert(C->root() != nullptr, "Expect parse is still valid");
2615 C->root()->add_prec(transformed_sfpnt);
2616 }
2617 }
2618
2619 #ifndef PRODUCT
2620 //------------------------show_parse_info--------------------------------------
2621 void Parse::show_parse_info() {
2622 InlineTree* ilt = nullptr;
2623 if (C->ilt() != nullptr) {
2624 JVMState* caller_jvms = is_osr_parse() ? caller()->caller() : caller();
2625 ilt = InlineTree::find_subtree_from_root(C->ilt(), caller_jvms, method());
2626 }
2627 if (PrintCompilation && Verbose) {
2628 if (depth() == 1) {
2629 if( ilt->count_inlines() ) {
2630 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2631 ilt->count_inline_bcs());
2632 tty->cr();
2633 }
2634 } else {
2635 if (method()->is_synchronized()) tty->print("s");
2636 if (method()->has_exception_handlers()) tty->print("!");
2637 // Check this is not the final compiled version
2638 if (C->trap_can_recompile()) {
2639 tty->print("-");
2640 } else {
2641 tty->print(" ");
2642 }
2643 method()->print_short_name();
2644 if (is_osr_parse()) {
2645 tty->print(" @ %d", osr_bci());
2646 }
2647 tty->print(" (%d bytes)",method()->code_size());
2648 if (ilt->count_inlines()) {
2649 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2650 ilt->count_inline_bcs());
2651 }
2652 tty->cr();
2653 }
2654 }
2655 if (PrintOpto && (depth() == 1 || PrintOptoInlining)) {
2656 // Print that we succeeded; suppress this message on the first osr parse.
2657
2658 if (method()->is_synchronized()) tty->print("s");
2659 if (method()->has_exception_handlers()) tty->print("!");
2660 // Check this is not the final compiled version
2661 if (C->trap_can_recompile() && depth() == 1) {
2662 tty->print("-");
2663 } else {
2664 tty->print(" ");
2665 }
2666 if( depth() != 1 ) { tty->print(" "); } // missing compile count
2667 for (int i = 1; i < depth(); ++i) { tty->print(" "); }
2668 method()->print_short_name();
2669 if (is_osr_parse()) {
2670 tty->print(" @ %d", osr_bci());
2671 }
2672 if (ilt->caller_bci() != -1) {
2673 tty->print(" @ %d", ilt->caller_bci());
2674 }
2675 tty->print(" (%d bytes)",method()->code_size());
2676 if (ilt->count_inlines()) {
2677 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2678 ilt->count_inline_bcs());
2679 }
2680 tty->cr();
2681 }
2682 }
2683
2684
2685 //------------------------------dump-------------------------------------------
2686 // Dump information associated with the bytecodes of current _method
2687 void Parse::dump() {
2688 if( method() != nullptr ) {
2689 // Iterate over bytecodes
2690 ciBytecodeStream iter(method());
2691 for( Bytecodes::Code bc = iter.next(); bc != ciBytecodeStream::EOBC() ; bc = iter.next() ) {
2692 dump_bci( iter.cur_bci() );
2693 tty->cr();
2694 }
2695 }
2696 }
2697
2698 // Dump information associated with a byte code index, 'bci'
2699 void Parse::dump_bci(int bci) {
2700 // Output info on merge-points, cloning, and within _jsr..._ret
2701 // NYI
2702 tty->print(" bci:%d", bci);
2703 }
2704
2705 #endif