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->is_InlineType() && 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->is_InlineType() && 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->is_InlineType() &&
1350 loc->bottom_type()->isa_oopptr() != nullptr &&
1351 !is_auto_boxed_primitive(loc)) { // ignore auto-boxed primitives
1352 _stress_rf_hook->add_req(loc);
1353 }
1354 }
1355 }
1356
1357 #ifdef ASSERT
1358 // Narrow receiver type when it is too broad for the method being parsed.
1359 if (!method()->is_static()) {
1360 ciInstanceKlass* callee_holder = method()->holder();
1361 const Type* holder_type = TypeInstPtr::make(TypePtr::BotPTR, callee_holder, Type::trust_interfaces);
1362
1363 Node* receiver_obj = local(0);
1364 const TypeInstPtr* receiver_type = _gvn.type(receiver_obj)->isa_instptr();
1365
1366 if (receiver_type != nullptr && !receiver_type->higher_equal(holder_type)) {
1367 // Receiver should always be a subtype of callee holder.
1368 // But, since C2 type system doesn't properly track interfaces,
1369 // the invariant can't be expressed in the type system for default methods.
1370 // Example: for unrelated C <: I and D <: I, (C `meet` D) = Object </: I.
1371 assert(callee_holder->is_interface(), "missing subtype check");
1372
1373 // Perform dynamic receiver subtype check against callee holder class w/ a halt on failure.
1374 Node* holder_klass = _gvn.makecon(TypeKlassPtr::make(callee_holder, Type::trust_interfaces));
1375 Node* not_subtype_ctrl = gen_subtype_check(receiver_obj, holder_klass);
1376 assert(!stopped(), "not a subtype");
1377
1378 halt(not_subtype_ctrl, frameptr(), "failed receiver subtype check");
1379 }
1380 }
1381 #endif // ASSERT
1382
1383 // If the method is synchronized, we need to construct a lock node, attach
1384 // it to the Start node, and pin it there.
1385 if (method()->is_synchronized()) {
1386 // Insert a FastLockNode right after the Start which takes as arguments
1387 // the current thread pointer, the "this" pointer & the address of the
1388 // stack slot pair used for the lock. The "this" pointer is a projection
1389 // off the start node, but the locking spot has to be constructed by
1390 // creating a ConLNode of 0, and boxing it with a BoxLockNode. The BoxLockNode
1391 // becomes the second argument to the FastLockNode call. The
1392 // FastLockNode becomes the new control parent to pin it to the start.
1393
1394 // Setup Object Pointer
1395 Node *lock_obj = nullptr;
1396 if (method()->is_static()) {
1397 ciInstance* mirror = _method->holder()->java_mirror();
1398 const TypeInstPtr *t_lock = TypeInstPtr::make(mirror);
1399 lock_obj = makecon(t_lock);
1400 } else { // Else pass the "this" pointer,
1401 lock_obj = local(0); // which is Parm0 from StartNode
1402 assert(!_gvn.type(lock_obj)->make_oopptr()->can_be_inline_type(), "can't be an inline type");
1403 }
1404 // Clear out dead values from the debug info.
1405 kill_dead_locals();
1406 // Build the FastLockNode
1407 _synch_lock = shared_lock(lock_obj);
1408 // Check for bailout in shared_lock
1409 if (failing()) { return; }
1410 }
1411
1412 // Feed profiling data for parameters to the type system so it can
1413 // propagate it as speculative types
1414 record_profiled_parameters_for_speculation();
1415
1416 // More argument handling
1417 int arg_size = method()->arg_size();
1418 for (int i = 0; i < arg_size; i++) {
1419 Node* parm = local(i);
1420 const Type* t = _gvn.type(parm);
1421 if (t->is_inlinetypeptr()) {
1422 // If the parameter is a value object, try to scalarize it if we know that it is unrestricted (not early larval)
1423 // Parameters are non-larval except the receiver of a constructor, which must be an early larval object.
1424 if (!(i == 0 && method()->receiver_maybe_larval())) {
1425 // Create InlineTypeNode from the oop and replace the parameter
1426 Node* vt = InlineTypeNode::make_from_oop(this, parm, t->inline_klass());
1427 replace_in_map(parm, vt);
1428 }
1429 } else if (UseTypeSpeculation && (i == (arg_size - 1)) && depth() == 1 && method()->is_varargs() && t->isa_aryptr()) {
1430 // Speculate on varargs Object array being the default array refined type. The assumption is
1431 // that a vararg method test(Object... o) is often called as test(o1, o2, o3). javac will
1432 // translate the call so that the caller will create a new default array of Object, put o1,
1433 // o2, o3 into the newly created array, then invoke the method test. This only makes sense if
1434 // the method we are parsing is the top-level method of the compilation unit. Otherwise, if
1435 // it is truly called according to our assumption, we must know the exact type of the
1436 // argument because the allocation happens inside the compilation unit.
1437 const TypePtr* spec_type = (t->speculative() != nullptr) ? t->speculative() : t->remove_speculative()->is_aryptr();
1438 ciSignature* method_signature = method()->signature();
1439 ciType* parm_citype = method_signature->type_at(method_signature->count() - 1);
1440 if (!parm_citype->is_obj_array_klass()) {
1441 continue;
1442 }
1443
1444 ciObjArrayKlass* spec_citype = ciObjArrayKlass::make(parm_citype->as_obj_array_klass()->element_klass(), true);
1445 const Type* improved_spec_type = TypeKlassPtr::make(spec_citype, Type::trust_interfaces)->as_instance_type();
1446 improved_spec_type = improved_spec_type->join(spec_type)->join(TypePtr::NOTNULL);
1447 if (improved_spec_type->empty()) {
1448 continue;
1449 }
1450
1451 const TypePtr* improved_type = TypeOopPtr::make(TypePtr::BotPTR, Type::Offset::bottom, TypeOopPtr::InstanceBot, improved_spec_type->is_ptr());
1452 improved_type = improved_type->join_speculative(t)->is_ptr();
1453 if (improved_type != t) {
1454 Node* cast = _gvn.transform(new CheckCastPPNode(control(), parm, improved_type, ConstraintCastNode::DependencyType::NonFloatingNarrowing));
1455 replace_in_map(parm, cast);
1456 }
1457 }
1458 }
1459 }
1460
1461 //------------------------------init_blocks------------------------------------
1462 // Initialize our parser map to contain the types/monitors at method entry.
1463 void Parse::init_blocks() {
1464 // Create the blocks.
1465 _block_count = flow()->block_count();
1466 _blocks = NEW_RESOURCE_ARRAY(Block, _block_count);
1467
1468 // Initialize the structs.
1469 for (int rpo = 0; rpo < block_count(); rpo++) {
1470 Block* block = rpo_at(rpo);
1471 new(block) Block(this, rpo);
1472 }
1473
1474 // Collect predecessor and successor information.
1475 for (int rpo = 0; rpo < block_count(); rpo++) {
1476 Block* block = rpo_at(rpo);
1477 block->init_graph(this);
1478 }
1479 }
1480
1481 //-------------------------------init_node-------------------------------------
1482 Parse::Block::Block(Parse* outer, int rpo) : _live_locals() {
1483 _flow = outer->flow()->rpo_at(rpo);
1484 _pred_count = 0;
1485 _preds_parsed = 0;
1486 _count = 0;
1487 _is_parsed = false;
1488 _is_handler = false;
1489 _has_merged_backedge = false;
1490 _start_map = nullptr;
1491 _has_predicates = false;
1492 _num_successors = 0;
1493 _all_successors = 0;
1494 _successors = nullptr;
1495 assert(pred_count() == 0 && preds_parsed() == 0, "sanity");
1496 assert(!(is_merged() || is_parsed() || is_handler() || has_merged_backedge()), "sanity");
1497 assert(_live_locals.size() == 0, "sanity");
1498
1499 // entry point has additional predecessor
1500 if (flow()->is_start()) _pred_count++;
1501 assert(flow()->is_start() == (this == outer->start_block()), "");
1502 }
1503
1504 //-------------------------------init_graph------------------------------------
1505 void Parse::Block::init_graph(Parse* outer) {
1506 // Create the successor list for this parser block.
1507 GrowableArray<ciTypeFlow::Block*>* tfs = flow()->successors();
1508 GrowableArray<ciTypeFlow::Block*>* tfe = flow()->exceptions();
1509 int ns = tfs->length();
1510 int ne = tfe->length();
1511 _num_successors = ns;
1512 _all_successors = ns+ne;
1513 _successors = (ns+ne == 0) ? nullptr : NEW_RESOURCE_ARRAY(Block*, ns+ne);
1514 int p = 0;
1515 for (int i = 0; i < ns+ne; i++) {
1516 ciTypeFlow::Block* tf2 = (i < ns) ? tfs->at(i) : tfe->at(i-ns);
1517 Block* block2 = outer->rpo_at(tf2->rpo());
1518 _successors[i] = block2;
1519
1520 // Accumulate pred info for the other block, too.
1521 // Note: We also need to set _pred_count for exception blocks since they could
1522 // also have normal predecessors (reached without athrow by an explicit jump).
1523 // This also means that next_path_num can be called along exception paths.
1524 block2->_pred_count++;
1525 if (i >= ns) {
1526 block2->_is_handler = true;
1527 }
1528
1529 #ifdef ASSERT
1530 // A block's successors must be distinguishable by BCI.
1531 // That is, no bytecode is allowed to branch to two different
1532 // clones of the same code location.
1533 for (int j = 0; j < i; j++) {
1534 Block* block1 = _successors[j];
1535 if (block1 == block2) continue; // duplicates are OK
1536 assert(block1->start() != block2->start(), "successors have unique bcis");
1537 }
1538 #endif
1539 }
1540 }
1541
1542 //---------------------------successor_for_bci---------------------------------
1543 Parse::Block* Parse::Block::successor_for_bci(int bci) {
1544 for (int i = 0; i < all_successors(); i++) {
1545 Block* block2 = successor_at(i);
1546 if (block2->start() == bci) return block2;
1547 }
1548 // We can actually reach here if ciTypeFlow traps out a block
1549 // due to an unloaded class, and concurrently with compilation the
1550 // class is then loaded, so that a later phase of the parser is
1551 // able to see more of the bytecode CFG. Or, the flow pass and
1552 // the parser can have a minor difference of opinion about executability
1553 // of bytecodes. For example, "obj.field = null" is executable even
1554 // if the field's type is an unloaded class; the flow pass used to
1555 // make a trap for such code.
1556 return nullptr;
1557 }
1558
1559
1560 //-----------------------------stack_type_at-----------------------------------
1561 const Type* Parse::Block::stack_type_at(int i) const {
1562 return get_type(flow()->stack_type_at(i));
1563 }
1564
1565
1566 //-----------------------------local_type_at-----------------------------------
1567 const Type* Parse::Block::local_type_at(int i) const {
1568 // Make dead locals fall to bottom.
1569 if (_live_locals.size() == 0) {
1570 MethodLivenessResult live_locals = flow()->outer()->method()->liveness_at_bci(start());
1571 // This bitmap can be zero length if we saw a breakpoint.
1572 // In such cases, pretend they are all live.
1573 ((Block*)this)->_live_locals = live_locals;
1574 }
1575 if (_live_locals.size() > 0 && !_live_locals.at(i))
1576 return Type::BOTTOM;
1577
1578 return get_type(flow()->local_type_at(i));
1579 }
1580
1581
1582 #ifndef PRODUCT
1583
1584 //----------------------------name_for_bc--------------------------------------
1585 // helper method for BytecodeParseHistogram
1586 static const char* name_for_bc(int i) {
1587 return Bytecodes::is_defined(i) ? Bytecodes::name(Bytecodes::cast(i)) : "xxxunusedxxx";
1588 }
1589
1590 //----------------------------BytecodeParseHistogram------------------------------------
1591 Parse::BytecodeParseHistogram::BytecodeParseHistogram(Parse *p, Compile *c) {
1592 _parser = p;
1593 _compiler = c;
1594 if( ! _initialized ) { _initialized = true; reset(); }
1595 }
1596
1597 //----------------------------current_count------------------------------------
1598 int Parse::BytecodeParseHistogram::current_count(BPHType bph_type) {
1599 switch( bph_type ) {
1600 case BPH_transforms: { return _parser->gvn().made_progress(); }
1601 case BPH_values: { return _parser->gvn().made_new_values(); }
1602 default: { ShouldNotReachHere(); return 0; }
1603 }
1604 }
1605
1606 //----------------------------initialized--------------------------------------
1607 bool Parse::BytecodeParseHistogram::initialized() { return _initialized; }
1608
1609 //----------------------------reset--------------------------------------------
1610 void Parse::BytecodeParseHistogram::reset() {
1611 int i = Bytecodes::number_of_codes;
1612 while (i-- > 0) { _bytecodes_parsed[i] = 0; _nodes_constructed[i] = 0; _nodes_transformed[i] = 0; _new_values[i] = 0; }
1613 }
1614
1615 //----------------------------set_initial_state--------------------------------
1616 // Record info when starting to parse one bytecode
1617 void Parse::BytecodeParseHistogram::set_initial_state( Bytecodes::Code bc ) {
1618 if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1619 _initial_bytecode = bc;
1620 _initial_node_count = _compiler->unique();
1621 _initial_transforms = current_count(BPH_transforms);
1622 _initial_values = current_count(BPH_values);
1623 }
1624 }
1625
1626 //----------------------------record_change--------------------------------
1627 // Record results of parsing one bytecode
1628 void Parse::BytecodeParseHistogram::record_change() {
1629 if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1630 ++_bytecodes_parsed[_initial_bytecode];
1631 _nodes_constructed [_initial_bytecode] += (_compiler->unique() - _initial_node_count);
1632 _nodes_transformed [_initial_bytecode] += (current_count(BPH_transforms) - _initial_transforms);
1633 _new_values [_initial_bytecode] += (current_count(BPH_values) - _initial_values);
1634 }
1635 }
1636
1637
1638 //----------------------------print--------------------------------------------
1639 void Parse::BytecodeParseHistogram::print(float cutoff) {
1640 ResourceMark rm;
1641 // print profile
1642 int total = 0;
1643 int i = 0;
1644 for( i = 0; i < Bytecodes::number_of_codes; ++i ) { total += _bytecodes_parsed[i]; }
1645 int abs_sum = 0;
1646 tty->cr(); //0123456789012345678901234567890123456789012345678901234567890123456789
1647 tty->print_cr("Histogram of %d parsed bytecodes:", total);
1648 if( total == 0 ) { return; }
1649 tty->cr();
1650 tty->print_cr("absolute: count of compiled bytecodes of this type");
1651 tty->print_cr("relative: percentage contribution to compiled nodes");
1652 tty->print_cr("nodes : Average number of nodes constructed per bytecode");
1653 tty->print_cr("rnodes : Significance towards total nodes constructed, (nodes*relative)");
1654 tty->print_cr("transforms: Average amount of transform progress per bytecode compiled");
1655 tty->print_cr("values : Average number of node values improved per bytecode");
1656 tty->print_cr("name : Bytecode name");
1657 tty->cr();
1658 tty->print_cr(" absolute relative nodes rnodes transforms values name");
1659 tty->print_cr("----------------------------------------------------------------------");
1660 while (--i > 0) {
1661 int abs = _bytecodes_parsed[i];
1662 float rel = abs * 100.0F / total;
1663 float nodes = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_constructed[i])/_bytecodes_parsed[i];
1664 float rnodes = _bytecodes_parsed[i] == 0 ? 0 : rel * nodes;
1665 float xforms = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_transformed[i])/_bytecodes_parsed[i];
1666 float values = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _new_values [i])/_bytecodes_parsed[i];
1667 if (cutoff <= rel) {
1668 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));
1669 abs_sum += abs;
1670 }
1671 }
1672 tty->print_cr("----------------------------------------------------------------------");
1673 float rel_sum = abs_sum * 100.0F / total;
1674 tty->print_cr("%10d %7.2f%% (cutoff = %.2f%%)", abs_sum, rel_sum, cutoff);
1675 tty->print_cr("----------------------------------------------------------------------");
1676 tty->cr();
1677 }
1678 #endif
1679
1680 //----------------------------load_state_from----------------------------------
1681 // Load block/map/sp. But not do not touch iter/bci.
1682 void Parse::load_state_from(Block* block) {
1683 set_block(block);
1684 // load the block's JVM state:
1685 set_map(block->start_map());
1686 set_sp( block->start_sp());
1687 }
1688
1689
1690 //-----------------------------record_state------------------------------------
1691 void Parse::Block::record_state(Parse* p) {
1692 assert(!is_merged(), "can only record state once, on 1st inflow");
1693 assert(start_sp() == p->sp(), "stack pointer must agree with ciTypeFlow");
1694 set_start_map(p->stop());
1695 }
1696
1697
1698 //------------------------------do_one_block-----------------------------------
1699 void Parse::do_one_block() {
1700 if (TraceOptoParse) {
1701 Block *b = block();
1702 int ns = b->num_successors();
1703 int nt = b->all_successors();
1704
1705 tty->print("Parsing block #%d at bci [%d,%d), successors:",
1706 block()->rpo(), block()->start(), block()->limit());
1707 for (int i = 0; i < nt; i++) {
1708 tty->print((( i < ns) ? " %d" : " %d(exception block)"), b->successor_at(i)->rpo());
1709 }
1710 if (b->is_loop_head()) {
1711 tty->print(" loop head");
1712 }
1713 if (b->is_irreducible_loop_entry()) {
1714 tty->print(" irreducible");
1715 }
1716 tty->cr();
1717 }
1718
1719 assert(block()->is_merged(), "must be merged before being parsed");
1720 block()->mark_parsed();
1721
1722 // Set iterator to start of block.
1723 iter().reset_to_bci(block()->start());
1724
1725 if (ProfileExceptionHandlers && block()->is_handler()) {
1726 ciMethodData* methodData = method()->method_data();
1727 if (methodData->is_mature()) {
1728 ciBitData data = methodData->exception_handler_bci_to_data(block()->start());
1729 if (!data.exception_handler_entered() || StressPrunedExceptionHandlers) {
1730 // dead catch block
1731 // Emit an uncommon trap instead of processing the block.
1732 set_parse_bci(block()->start());
1733 uncommon_trap(Deoptimization::Reason_unreached,
1734 Deoptimization::Action_reinterpret,
1735 nullptr, "dead catch block");
1736 return;
1737 }
1738 }
1739 }
1740
1741 CompileLog* log = C->log();
1742
1743 // Parse bytecodes
1744 while (!stopped() && !failing()) {
1745 iter().next();
1746
1747 // Learn the current bci from the iterator:
1748 set_parse_bci(iter().cur_bci());
1749
1750 if (bci() == block()->limit()) {
1751 // Do not walk into the next block until directed by do_all_blocks.
1752 merge(bci());
1753 break;
1754 }
1755 assert(bci() < block()->limit(), "bci still in block");
1756
1757 if (log != nullptr) {
1758 // Output an optional context marker, to help place actions
1759 // that occur during parsing of this BC. If there is no log
1760 // output until the next context string, this context string
1761 // will be silently ignored.
1762 log->set_context("bc code='%d' bci='%d'", (int)bc(), bci());
1763 }
1764
1765 if (block()->has_trap_at(bci())) {
1766 // We must respect the flow pass's traps, because it will refuse
1767 // to produce successors for trapping blocks.
1768 int trap_index = block()->flow()->trap_index();
1769 assert(trap_index != 0, "trap index must be valid");
1770 uncommon_trap(trap_index);
1771 break;
1772 }
1773
1774 NOT_PRODUCT( parse_histogram()->set_initial_state(bc()); );
1775
1776 #ifdef ASSERT
1777 int pre_bc_sp = sp();
1778 int inputs, depth;
1779 bool have_se = !stopped() && compute_stack_effects(inputs, depth);
1780 assert(!have_se || pre_bc_sp >= inputs, "have enough stack to execute this BC: pre_bc_sp=%d, inputs=%d", pre_bc_sp, inputs);
1781 #endif //ASSERT
1782
1783 do_one_bytecode();
1784 if (failing()) return;
1785
1786 assert(!have_se || stopped() || failing() || (sp() - pre_bc_sp) == depth,
1787 "incorrect depth prediction: sp=%d, pre_bc_sp=%d, depth=%d", sp(), pre_bc_sp, depth);
1788
1789 do_exceptions();
1790
1791 NOT_PRODUCT( parse_histogram()->record_change(); );
1792
1793 if (log != nullptr)
1794 log->clear_context(); // skip marker if nothing was printed
1795
1796 // Fall into next bytecode. Each bytecode normally has 1 sequential
1797 // successor which is typically made ready by visiting this bytecode.
1798 // If the successor has several predecessors, then it is a merge
1799 // point, starts a new basic block, and is handled like other basic blocks.
1800 }
1801 }
1802
1803
1804 //------------------------------merge------------------------------------------
1805 void Parse::set_parse_bci(int bci) {
1806 set_bci(bci);
1807 Node_Notes* nn = C->default_node_notes();
1808 if (nn == nullptr) return;
1809
1810 // Collect debug info for inlined calls unless -XX:-DebugInlinedCalls.
1811 if (!DebugInlinedCalls && depth() > 1) {
1812 return;
1813 }
1814
1815 // Update the JVMS annotation, if present.
1816 JVMState* jvms = nn->jvms();
1817 if (jvms != nullptr && jvms->bci() != bci) {
1818 // Update the JVMS.
1819 jvms = jvms->clone_shallow(C);
1820 jvms->set_bci(bci);
1821 nn->set_jvms(jvms);
1822 }
1823 }
1824
1825 //------------------------------merge------------------------------------------
1826 // Merge the current mapping into the basic block starting at bci
1827 void Parse::merge(int target_bci) {
1828 Block* target = successor_for_bci(target_bci);
1829 if (target == nullptr) { handle_missing_successor(target_bci); return; }
1830 assert(!target->is_ready(), "our arrival must be expected");
1831 int pnum = target->next_path_num();
1832 merge_common(target, pnum);
1833 }
1834
1835 //-------------------------merge_new_path--------------------------------------
1836 // Merge the current mapping into the basic block, using a new path
1837 void Parse::merge_new_path(int target_bci) {
1838 Block* target = successor_for_bci(target_bci);
1839 if (target == nullptr) { handle_missing_successor(target_bci); return; }
1840 assert(!target->is_ready(), "new path into frozen graph");
1841 int pnum = target->add_new_path();
1842 merge_common(target, pnum);
1843 }
1844
1845 //-------------------------merge_exception-------------------------------------
1846 // Push the given ex_oop onto the stack, then merge the current mapping into
1847 // the basic block starting at target_bci.
1848 void Parse::push_and_merge_exception(int target_bci, Node* ex_oop) {
1849 // Add the safepoint before trimming the stack and pushing the exception oop.
1850 // We could add the safepoint after, but then the bci would also need to be
1851 // advanced to target_bci first, so the stack state matches.
1852 maybe_add_safepoint(target_bci);
1853 push_ex_oop(ex_oop); // Push exception oop for handler
1854 #ifdef ASSERT
1855 if (target_bci <= bci()) {
1856 C->set_exception_backedge();
1857 }
1858 #endif
1859 assert(sp() == 1, "must have only the throw exception on the stack");
1860 Block* target = successor_for_bci(target_bci);
1861 if (target == nullptr) { handle_missing_successor(target_bci); return; }
1862 assert(target->is_handler(), "exceptions are handled by special blocks");
1863 int pnum = target->add_new_path();
1864 merge_common(target, pnum);
1865 }
1866
1867 //--------------------handle_missing_successor---------------------------------
1868 void Parse::handle_missing_successor(int target_bci) {
1869 #ifndef PRODUCT
1870 Block* b = block();
1871 int trap_bci = b->flow()->has_trap()? b->flow()->trap_bci(): -1;
1872 tty->print_cr("### Missing successor at bci:%d for block #%d (trap_bci:%d)", target_bci, b->rpo(), trap_bci);
1873 #endif
1874 ShouldNotReachHere();
1875 }
1876
1877 //--------------------------merge_common---------------------------------------
1878 void Parse::merge_common(Parse::Block* target, int pnum) {
1879 if (TraceOptoParse) {
1880 tty->print("Merging state at block #%d bci:%d", target->rpo(), target->start());
1881 }
1882
1883 // Zap extra stack slots to top
1884 assert(sp() == target->start_sp(), "");
1885 clean_stack(sp());
1886
1887 // Check for merge conflicts involving inline types
1888 JVMState* old_jvms = map()->jvms();
1889 int old_bci = bci();
1890 JVMState* tmp_jvms = old_jvms->clone_shallow(C);
1891 tmp_jvms->set_should_reexecute(true);
1892 tmp_jvms->bind_map(map());
1893 // Execution needs to restart a the next bytecode (entry of next
1894 // block)
1895 if (target->is_merged() ||
1896 pnum > PhiNode::Input ||
1897 target->is_handler() ||
1898 target->is_loop_head()) {
1899 set_parse_bci(target->start());
1900 for (uint j = TypeFunc::Parms; j < map()->req(); j++) {
1901 Node* n = map()->in(j); // Incoming change to target state.
1902 const Type* t = nullptr;
1903 ciType* ct = nullptr;
1904 if (tmp_jvms->is_loc(j)) {
1905 int loc_idx = j - tmp_jvms->locoff();
1906 t = target->local_type_at(loc_idx);
1907 ct = target->flow()->local_type_at(loc_idx);
1908 } else if (tmp_jvms->is_stk(j) && j < (uint)sp() + tmp_jvms->stkoff()) {
1909 int stk_idx = j - tmp_jvms->stkoff();
1910 t = target->stack_type_at(stk_idx);
1911 ct = target->flow()->stack_type_at(stk_idx);
1912 }
1913 if (t != nullptr && t != Type::BOTTOM) {
1914 // An object can appear in the JVMS as either an oop or an InlineTypeNode. If the merge is
1915 // an InlineTypeNode, we need all the merge inputs to be InlineTypeNodes. Else, if the
1916 // merge is an oop, each merge input needs to be either an oop or an buffered
1917 // InlineTypeNode.
1918 if (!t->is_inlinetypeptr()) {
1919 // The merge cannot be an InlineTypeNode, ensure the input is buffered if it is an
1920 // InlineTypeNode
1921 if (n->is_InlineType()) {
1922 map()->set_req(j, n->as_InlineType()->buffer(this));
1923 }
1924 } else {
1925 // Scalarize the value object if it is not larval
1926 if (!n->is_InlineType() && !ct->is_early_larval()) {
1927 assert(_gvn.type(n) == TypePtr::NULL_PTR, "must be a null constant");
1928 map()->set_req(j, InlineTypeNode::make_null(_gvn, t->inline_klass()));
1929 }
1930 }
1931 }
1932 }
1933 }
1934 old_jvms->bind_map(map());
1935 set_parse_bci(old_bci);
1936
1937 if (!target->is_merged()) { // No prior mapping at this bci
1938 if (TraceOptoParse) { tty->print(" with empty state"); }
1939
1940 // If this path is dead, do not bother capturing it as a merge.
1941 // It is "as if" we had 1 fewer predecessors from the beginning.
1942 if (stopped()) {
1943 if (TraceOptoParse) tty->print_cr(", but path is dead and doesn't count");
1944 return;
1945 }
1946
1947 // Make a region if we know there are multiple or unpredictable inputs.
1948 // (Also, if this is a plain fall-through, we might see another region,
1949 // which must not be allowed into this block's map.)
1950 if (pnum > PhiNode::Input // Known multiple inputs.
1951 || target->is_handler() // These have unpredictable inputs.
1952 || target->is_loop_head() // Known multiple inputs
1953 || control()->is_Region()) { // We must hide this guy.
1954
1955 int current_bci = bci();
1956 set_parse_bci(target->start()); // Set target bci
1957 if (target->is_SEL_head()) {
1958 DEBUG_ONLY( target->mark_merged_backedge(block()); )
1959 if (target->start() == 0) {
1960 // Add Parse Predicates for the special case when
1961 // there are backbranches to the method entry.
1962 add_parse_predicates();
1963 }
1964 }
1965 // Add a Region to start the new basic block. Phis will be added
1966 // later lazily.
1967 int edges = target->pred_count();
1968 if (edges < pnum) edges = pnum; // might be a new path!
1969 RegionNode *r = new RegionNode(edges+1);
1970 gvn().set_type(r, Type::CONTROL);
1971 record_for_igvn(r);
1972 // zap all inputs to null for debugging (done in Node(uint) constructor)
1973 // for (int j = 1; j < edges+1; j++) { r->init_req(j, nullptr); }
1974 r->init_req(pnum, control());
1975 set_control(r);
1976 target->copy_irreducible_status_to(r, jvms());
1977 set_parse_bci(current_bci); // Restore bci
1978 }
1979
1980 // Convert the existing Parser mapping into a mapping at this bci.
1981 store_state_to(target);
1982 assert(target->is_merged(), "do not come here twice");
1983
1984 } else { // Prior mapping at this bci
1985 if (TraceOptoParse) { tty->print(" with previous state"); }
1986 #ifdef ASSERT
1987 if (target->is_SEL_head()) {
1988 target->mark_merged_backedge(block());
1989 }
1990 #endif
1991
1992 // We must not manufacture more phis if the target is already parsed.
1993 bool nophi = target->is_parsed();
1994
1995 SafePointNode* newin = map();// Hang on to incoming mapping
1996 Block* save_block = block(); // Hang on to incoming block;
1997 load_state_from(target); // Get prior mapping
1998
1999 assert(newin->jvms()->locoff() == jvms()->locoff(), "JVMS layouts agree");
2000 assert(newin->jvms()->stkoff() == jvms()->stkoff(), "JVMS layouts agree");
2001 assert(newin->jvms()->monoff() == jvms()->monoff(), "JVMS layouts agree");
2002 assert(newin->jvms()->endoff() == jvms()->endoff(), "JVMS layouts agree");
2003
2004 // Iterate over my current mapping and the old mapping.
2005 // Where different, insert Phi functions.
2006 // Use any existing Phi functions.
2007 assert(control()->is_Region(), "must be merging to a region");
2008 RegionNode* r = control()->as_Region();
2009
2010 // Compute where to merge into
2011 // Merge incoming control path
2012 r->init_req(pnum, newin->control());
2013
2014 if (pnum == 1) { // Last merge for this Region?
2015 if (!block()->flow()->is_irreducible_loop_secondary_entry()) {
2016 Node* result = _gvn.transform(r);
2017 if (r != result && TraceOptoParse) {
2018 tty->print_cr("Block #%d replace %d with %d", block()->rpo(), r->_idx, result->_idx);
2019 }
2020 }
2021 record_for_igvn(r);
2022 }
2023
2024 // Update all the non-control inputs to map:
2025 assert(TypeFunc::Parms == newin->jvms()->locoff(), "parser map should contain only youngest jvms");
2026 bool check_elide_phi = target->is_SEL_backedge(save_block);
2027 bool last_merge = (pnum == PhiNode::Input);
2028 for (uint j = 1; j < newin->req(); j++) {
2029 Node* m = map()->in(j); // Current state of target.
2030 Node* n = newin->in(j); // Incoming change to target state.
2031 Node* phi;
2032 if (m->is_Phi() && m->as_Phi()->region() == r) {
2033 phi = m;
2034 } else if (m->is_InlineType() && m->as_InlineType()->has_phi_inputs(r)) {
2035 phi = m;
2036 } else {
2037 phi = nullptr;
2038 }
2039 if (m != n) { // Different; must merge
2040 switch (j) {
2041 // Frame pointer and Return Address never changes
2042 case TypeFunc::FramePtr:// Drop m, use the original value
2043 case TypeFunc::ReturnAdr:
2044 break;
2045 case TypeFunc::Memory: // Merge inputs to the MergeMem node
2046 assert(phi == nullptr, "the merge contains phis, not vice versa");
2047 merge_memory_edges(n->as_MergeMem(), pnum, nophi);
2048 continue;
2049 default: // All normal stuff
2050 if (phi == nullptr) {
2051 const JVMState* jvms = map()->jvms();
2052 if (EliminateNestedLocks &&
2053 jvms->is_mon(j) && jvms->is_monitor_box(j)) {
2054 // BoxLock nodes are not commoning when EliminateNestedLocks is on.
2055 // Use old BoxLock node as merged box.
2056 assert(newin->jvms()->is_monitor_box(j), "sanity");
2057 // This assert also tests that nodes are BoxLock.
2058 assert(BoxLockNode::same_slot(n, m), "sanity");
2059 BoxLockNode* old_box = m->as_BoxLock();
2060 if (n->as_BoxLock()->is_unbalanced() && !old_box->is_unbalanced()) {
2061 // Preserve Unbalanced status.
2062 //
2063 // `old_box` can have only Regular or Coarsened status
2064 // because this code is executed only during Parse phase and
2065 // Incremental Inlining before EA and Macro nodes elimination.
2066 //
2067 // Incremental Inlining is executed after IGVN optimizations
2068 // during which BoxLock can be marked as Coarsened.
2069 old_box->set_coarsened(); // Verifies state
2070 old_box->set_unbalanced();
2071 }
2072 C->gvn_replace_by(n, m);
2073 } else if (!check_elide_phi || !target->can_elide_SEL_phi(j)) {
2074 phi = ensure_phi(j, nophi);
2075 }
2076 }
2077 break;
2078 }
2079 }
2080 // At this point, n might be top if:
2081 // - there is no phi (because TypeFlow detected a conflict), or
2082 // - the corresponding control edges is top (a dead incoming path)
2083 // It is a bug if we create a phi which sees a garbage value on a live path.
2084
2085 // Merging two inline types?
2086 if (phi != nullptr && phi->is_InlineType()) {
2087 // Reload current state because it may have been updated by ensure_phi
2088 assert(phi == map()->in(j), "unexpected value in map");
2089 assert(phi->as_InlineType()->has_phi_inputs(r), "");
2090 InlineTypeNode* vtm = phi->as_InlineType(); // Current inline type
2091 InlineTypeNode* vtn = n->as_InlineType(); // Incoming inline type
2092 assert(vtm == phi, "Inline type should have Phi input");
2093
2094 #ifdef ASSERT
2095 if (TraceOptoParse) {
2096 tty->print_cr("\nMerging inline types");
2097 tty->print_cr("Current:");
2098 vtm->dump(2);
2099 tty->print_cr("Incoming:");
2100 vtn->dump(2);
2101 tty->cr();
2102 }
2103 #endif
2104 // Do the merge
2105 vtm->merge_with(&_gvn, vtn, pnum, last_merge);
2106 if (last_merge) {
2107 map()->set_req(j, _gvn.transform(vtm));
2108 record_for_igvn(vtm);
2109 }
2110 } else if (phi != nullptr) {
2111 assert(n != top() || r->in(pnum) == top(), "live value must not be garbage");
2112 assert(phi->as_Phi()->region() == r, "");
2113 phi->set_req(pnum, n); // Then add 'n' to the merge
2114 if (last_merge) {
2115 // Last merge for this Phi.
2116 // So far, Phis have had a reasonable type from ciTypeFlow.
2117 // Now _gvn will join that with the meet of current inputs.
2118 // BOTTOM is never permissible here, 'cause pessimistically
2119 // Phis of pointers cannot lose the basic pointer type.
2120 DEBUG_ONLY(const Type* bt1 = phi->bottom_type());
2121 assert(bt1 != Type::BOTTOM, "should not be building conflict phis");
2122 map()->set_req(j, _gvn.transform(phi));
2123 DEBUG_ONLY(const Type* bt2 = phi->bottom_type());
2124 assert(bt2->higher_equal_speculative(bt1), "must be consistent with type-flow");
2125 record_for_igvn(phi);
2126 }
2127 }
2128 } // End of for all values to be merged
2129
2130 if (last_merge && !r->in(0)) { // The occasional useless Region
2131 assert(control() == r, "");
2132 set_control(r->nonnull_req());
2133 }
2134
2135 map()->merge_replaced_nodes_with(newin);
2136
2137 // newin has been subsumed into the lazy merge, and is now dead.
2138 set_block(save_block);
2139
2140 stop(); // done with this guy, for now
2141 }
2142
2143 if (TraceOptoParse) {
2144 tty->print_cr(" on path %d", pnum);
2145 }
2146
2147 // Done with this parser state.
2148 assert(stopped(), "");
2149 }
2150
2151
2152 //--------------------------merge_memory_edges---------------------------------
2153 void Parse::merge_memory_edges(MergeMemNode* n, int pnum, bool nophi) {
2154 // (nophi means we must not create phis, because we already parsed here)
2155 assert(n != nullptr, "");
2156 // Merge the inputs to the MergeMems
2157 MergeMemNode* m = merged_memory();
2158
2159 assert(control()->is_Region(), "must be merging to a region");
2160 RegionNode* r = control()->as_Region();
2161
2162 PhiNode* base = nullptr;
2163 MergeMemNode* remerge = nullptr;
2164 for (MergeMemStream mms(m, n); mms.next_non_empty2(); ) {
2165 Node *p = mms.force_memory();
2166 Node *q = mms.memory2();
2167 if (mms.is_empty() && nophi) {
2168 // Trouble: No new splits allowed after a loop body is parsed.
2169 // Instead, wire the new split into a MergeMem on the backedge.
2170 // The optimizer will sort it out, slicing the phi.
2171 if (remerge == nullptr) {
2172 guarantee(base != nullptr, "");
2173 assert(base->in(0) != nullptr, "should not be xformed away");
2174 remerge = MergeMemNode::make(base->in(pnum));
2175 gvn().set_type(remerge, Type::MEMORY);
2176 base->set_req(pnum, remerge);
2177 }
2178 remerge->set_memory_at(mms.alias_idx(), q);
2179 continue;
2180 }
2181 assert(!q->is_MergeMem(), "");
2182 PhiNode* phi;
2183 if (p != q) {
2184 phi = ensure_memory_phi(mms.alias_idx(), nophi);
2185 } else {
2186 if (p->is_Phi() && p->as_Phi()->region() == r)
2187 phi = p->as_Phi();
2188 else
2189 phi = nullptr;
2190 }
2191 // Insert q into local phi
2192 if (phi != nullptr) {
2193 assert(phi->region() == r, "");
2194 p = phi;
2195 phi->set_req(pnum, q);
2196 if (mms.at_base_memory()) {
2197 base = phi; // delay transforming it
2198 } else if (pnum == 1) {
2199 record_for_igvn(phi);
2200 p = _gvn.transform(phi);
2201 }
2202 mms.set_memory(p);// store back through the iterator
2203 }
2204 }
2205 // Transform base last, in case we must fiddle with remerging.
2206 if (base != nullptr && pnum == 1) {
2207 record_for_igvn(base);
2208 m->set_base_memory(_gvn.transform(base));
2209 }
2210 }
2211
2212
2213 //------------------------ensure_phis_everywhere-------------------------------
2214 void Parse::ensure_phis_everywhere() {
2215 ensure_phi(TypeFunc::I_O);
2216
2217 // Ensure a phi on all currently known memories.
2218 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
2219 ensure_memory_phi(mms.alias_idx());
2220 DEBUG_ONLY(mms.set_memory()); // keep the iterator happy
2221 }
2222
2223 // Note: This is our only chance to create phis for memory slices.
2224 // If we miss a slice that crops up later, it will have to be
2225 // merged into the base-memory phi that we are building here.
2226 // Later, the optimizer will comb out the knot, and build separate
2227 // phi-loops for each memory slice that matters.
2228
2229 // Monitors must nest nicely and not get confused amongst themselves.
2230 // Phi-ify everything up to the monitors, though.
2231 uint monoff = map()->jvms()->monoff();
2232 uint nof_monitors = map()->jvms()->nof_monitors();
2233
2234 assert(TypeFunc::Parms == map()->jvms()->locoff(), "parser map should contain only youngest jvms");
2235 bool check_elide_phi = block()->is_SEL_head();
2236 for (uint i = TypeFunc::Parms; i < monoff; i++) {
2237 if (!check_elide_phi || !block()->can_elide_SEL_phi(i)) {
2238 ensure_phi(i);
2239 }
2240 }
2241
2242 // Even monitors need Phis, though they are well-structured.
2243 // This is true for OSR methods, and also for the rare cases where
2244 // a monitor object is the subject of a replace_in_map operation.
2245 // See bugs 4426707 and 5043395.
2246 for (uint m = 0; m < nof_monitors; m++) {
2247 ensure_phi(map()->jvms()->monitor_obj_offset(m));
2248 }
2249 }
2250
2251
2252 //-----------------------------add_new_path------------------------------------
2253 // Add a previously unaccounted predecessor to this block.
2254 int Parse::Block::add_new_path() {
2255 // If there is no map, return the lowest unused path number.
2256 if (!is_merged()) return pred_count()+1; // there will be a map shortly
2257
2258 SafePointNode* map = start_map();
2259 if (!map->control()->is_Region())
2260 return pred_count()+1; // there may be a region some day
2261 RegionNode* r = map->control()->as_Region();
2262
2263 // Add new path to the region.
2264 uint pnum = r->req();
2265 r->add_req(nullptr);
2266
2267 for (uint i = 1; i < map->req(); i++) {
2268 Node* n = map->in(i);
2269 if (i == TypeFunc::Memory) {
2270 // Ensure a phi on all currently known memories.
2271 for (MergeMemStream mms(n->as_MergeMem()); mms.next_non_empty(); ) {
2272 Node* phi = mms.memory();
2273 if (phi->is_Phi() && phi->as_Phi()->region() == r) {
2274 assert(phi->req() == pnum, "must be same size as region");
2275 phi->add_req(nullptr);
2276 }
2277 }
2278 } else {
2279 if (n->is_Phi() && n->as_Phi()->region() == r) {
2280 assert(n->req() == pnum, "must be same size as region");
2281 n->add_req(nullptr);
2282 } else if (n->is_InlineType() && n->as_InlineType()->has_phi_inputs(r)) {
2283 n->as_InlineType()->add_new_path(r);
2284 }
2285 }
2286 }
2287
2288 return pnum;
2289 }
2290
2291 //------------------------------ensure_phi-------------------------------------
2292 // Turn the idx'th entry of the current map into a Phi
2293 Node* Parse::ensure_phi(int idx, bool nocreate) {
2294 SafePointNode* map = this->map();
2295 Node* region = map->control();
2296 assert(region->is_Region(), "");
2297
2298 Node* o = map->in(idx);
2299 assert(o != nullptr, "");
2300
2301 if (o == top()) return nullptr; // TOP always merges into TOP
2302
2303 if (o->is_Phi() && o->as_Phi()->region() == region) {
2304 return o->as_Phi();
2305 }
2306 InlineTypeNode* vt = o->isa_InlineType();
2307 if (vt != nullptr && vt->has_phi_inputs(region)) {
2308 return vt;
2309 }
2310
2311 // Now use a Phi here for merging
2312 assert(!nocreate, "Cannot build a phi for a block already parsed.");
2313 const JVMState* jvms = map->jvms();
2314 const Type* t = nullptr;
2315 if (jvms->is_loc(idx)) {
2316 t = block()->local_type_at(idx - jvms->locoff());
2317 } else if (jvms->is_stk(idx)) {
2318 t = block()->stack_type_at(idx - jvms->stkoff());
2319 } else if (jvms->is_mon(idx)) {
2320 assert(!jvms->is_monitor_box(idx), "no phis for boxes");
2321 t = TypeInstPtr::BOTTOM; // this is sufficient for a lock object
2322 } else if ((uint)idx < TypeFunc::Parms) {
2323 t = o->bottom_type(); // Type::RETURN_ADDRESS or such-like.
2324 } else {
2325 assert(false, "no type information for this phi");
2326 }
2327
2328 // If the type falls to bottom, then this must be a local that
2329 // is already dead or is mixing ints and oops or some such.
2330 // Forcing it to top makes it go dead.
2331 if (t == Type::BOTTOM) {
2332 map->set_req(idx, top());
2333 return nullptr;
2334 }
2335
2336 // Do not create phis for top either.
2337 // A top on a non-null control flow must be an unused even after the.phi.
2338 if (t == Type::TOP || t == Type::HALF) {
2339 map->set_req(idx, top());
2340 return nullptr;
2341 }
2342
2343 if (vt != nullptr && t->is_inlinetypeptr()) {
2344 // Inline types are merged by merging their field values.
2345 // Create a cloned InlineTypeNode with phi inputs that
2346 // represents the merged inline type and update the map.
2347 vt = vt->clone_with_phis(&_gvn, region);
2348 map->set_req(idx, vt);
2349 return vt;
2350 } else {
2351 PhiNode* phi = PhiNode::make(region, o, t);
2352 gvn().set_type(phi, t);
2353 if (C->do_escape_analysis()) record_for_igvn(phi);
2354 map->set_req(idx, phi);
2355 return phi;
2356 }
2357 }
2358
2359 //--------------------------ensure_memory_phi----------------------------------
2360 // Turn the idx'th slice of the current memory into a Phi
2361 PhiNode *Parse::ensure_memory_phi(int idx, bool nocreate) {
2362 MergeMemNode* mem = merged_memory();
2363 Node* region = control();
2364 assert(region->is_Region(), "");
2365
2366 Node *o = (idx == Compile::AliasIdxBot)? mem->base_memory(): mem->memory_at(idx);
2367 assert(o != nullptr && o != top(), "");
2368
2369 PhiNode* phi;
2370 if (o->is_Phi() && o->as_Phi()->region() == region) {
2371 phi = o->as_Phi();
2372 if (phi == mem->base_memory() && idx >= Compile::AliasIdxRaw) {
2373 // clone the shared base memory phi to make a new memory split
2374 assert(!nocreate, "Cannot build a phi for a block already parsed.");
2375 const Type* t = phi->bottom_type();
2376 const TypePtr* adr_type = C->get_adr_type(idx);
2377 phi = phi->slice_memory(adr_type);
2378 gvn().set_type(phi, t);
2379 }
2380 return phi;
2381 }
2382
2383 // Now use a Phi here for merging
2384 assert(!nocreate, "Cannot build a phi for a block already parsed.");
2385 const Type* t = o->bottom_type();
2386 const TypePtr* adr_type = C->get_adr_type(idx);
2387 phi = PhiNode::make(region, o, t, adr_type);
2388 gvn().set_type(phi, t);
2389 if (idx == Compile::AliasIdxBot)
2390 mem->set_base_memory(phi);
2391 else
2392 mem->set_memory_at(idx, phi);
2393 return phi;
2394 }
2395
2396 //------------------------------call_register_finalizer-----------------------
2397 // Check the klass of the receiver and call register_finalizer if the
2398 // class need finalization.
2399 void Parse::call_register_finalizer() {
2400 Node* receiver = local(0);
2401 assert(receiver != nullptr && receiver->bottom_type()->isa_instptr() != nullptr,
2402 "must have non-null instance type");
2403
2404 const TypeInstPtr *tinst = receiver->bottom_type()->isa_instptr();
2405 if (tinst != nullptr && tinst->is_loaded() && !tinst->klass_is_exact()) {
2406 // The type isn't known exactly so see if CHA tells us anything.
2407 ciInstanceKlass* ik = tinst->instance_klass();
2408 if (!Dependencies::has_finalizable_subclass(ik)) {
2409 // No finalizable subclasses so skip the dynamic check.
2410 C->dependencies()->assert_has_no_finalizable_subclasses(ik);
2411 return;
2412 }
2413 }
2414
2415 // Insert a dynamic test for whether the instance needs
2416 // finalization. In general this will fold up since the concrete
2417 // class is often visible so the access flags are constant.
2418 Node* klass_addr = basic_plus_adr( receiver, receiver, oopDesc::klass_offset_in_bytes() );
2419 Node* klass = _gvn.transform(LoadKlassNode::make(_gvn, immutable_memory(), klass_addr, TypeInstPtr::KLASS));
2420
2421 Node* access_flags_addr = off_heap_plus_addr(klass, in_bytes(Klass::misc_flags_offset()));
2422 Node* access_flags = make_load(nullptr, access_flags_addr, TypeInt::UBYTE, T_BOOLEAN, MemNode::unordered);
2423
2424 Node* mask = _gvn.transform(new AndINode(access_flags, intcon(KlassFlags::_misc_has_finalizer)));
2425 Node* check = _gvn.transform(new CmpINode(mask, intcon(0)));
2426 Node* test = _gvn.transform(new BoolNode(check, BoolTest::ne));
2427
2428 IfNode* iff = create_and_map_if(control(), test, PROB_MAX, COUNT_UNKNOWN);
2429
2430 RegionNode* result_rgn = new RegionNode(3);
2431 record_for_igvn(result_rgn);
2432
2433 Node *skip_register = _gvn.transform(new IfFalseNode(iff));
2434 result_rgn->init_req(1, skip_register);
2435
2436 Node *needs_register = _gvn.transform(new IfTrueNode(iff));
2437 set_control(needs_register);
2438 if (stopped()) {
2439 // There is no slow path.
2440 result_rgn->init_req(2, top());
2441 } else {
2442 Node *call = make_runtime_call(RC_NO_LEAF,
2443 OptoRuntime::register_finalizer_Type(),
2444 OptoRuntime::register_finalizer_Java(),
2445 nullptr, TypePtr::BOTTOM,
2446 receiver);
2447 make_slow_call_ex(call, env()->Throwable_klass(), true);
2448
2449 Node* fast_io = call->in(TypeFunc::I_O);
2450 Node* fast_mem = call->in(TypeFunc::Memory);
2451 // These two phis are pre-filled with copies of of the fast IO and Memory
2452 Node* io_phi = PhiNode::make(result_rgn, fast_io, Type::ABIO);
2453 Node* mem_phi = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
2454
2455 result_rgn->init_req(2, control());
2456 io_phi ->init_req(2, i_o());
2457 mem_phi ->init_req(2, reset_memory());
2458
2459 set_all_memory( _gvn.transform(mem_phi) );
2460 set_i_o( _gvn.transform(io_phi) );
2461 }
2462
2463 set_control( _gvn.transform(result_rgn) );
2464 }
2465
2466 // Add check to deoptimize once holder klass is fully initialized.
2467 void Parse::clinit_deopt() {
2468 assert(C->has_method(), "only for normal compilations");
2469 assert(depth() == 1, "only for main compiled method");
2470 assert(is_normal_parse(), "no barrier needed on osr entry");
2471 assert(!method()->holder()->is_not_initialized(), "initialization should have been started");
2472
2473 set_parse_bci(0);
2474
2475 Node* holder = makecon(TypeKlassPtr::make(method()->holder(), Type::trust_interfaces));
2476 guard_klass_being_initialized(holder);
2477 }
2478
2479 //------------------------------return_current---------------------------------
2480 // Append current _map to _exit_return
2481 void Parse::return_current(Node* value) {
2482 if (method()->intrinsic_id() == vmIntrinsics::_Object_init) {
2483 call_register_finalizer();
2484 }
2485
2486 // frame pointer is always same, already captured
2487 if (value != nullptr) {
2488 Node* phi = _exits.argument(0);
2489 const Type* return_type = phi->bottom_type();
2490 if ((tf()->returns_inline_type_as_fields() || (_caller->has_method() && !Compile::current()->inlining_incrementally())) &&
2491 return_type->is_inlinetypeptr()) {
2492 // Inline type is returned as fields, make sure it is scalarized
2493 if (!value->is_InlineType()) {
2494 value = InlineTypeNode::make_from_oop(this, value, return_type->inline_klass());
2495 }
2496 if (!_caller->has_method() || Compile::current()->inlining_incrementally()) {
2497 // Returning from root or an incrementally inlined method. Make sure all non-flat
2498 // fields are buffered and re-execute if allocation triggers deoptimization.
2499 PreserveReexecuteState preexecs(this);
2500 assert(tf()->returns_inline_type_as_fields(), "must be returned as fields");
2501 jvms()->set_should_reexecute(true);
2502 inc_sp(1);
2503 value = value->as_InlineType()->allocate_fields(this);
2504 }
2505 } else if (value->is_InlineType()) {
2506 // Inline type is returned as oop, make sure it is buffered and re-execute
2507 // if allocation triggers deoptimization.
2508 PreserveReexecuteState preexecs(this);
2509 jvms()->set_should_reexecute(true);
2510 inc_sp(1);
2511 value = value->as_InlineType()->buffer(this);
2512 }
2513 // ...else
2514 // If returning oops to an interface-return, there is a silent free
2515 // cast from oop to interface allowed by the Verifier. Make it explicit here.
2516 phi->add_req(value);
2517 }
2518
2519 if (StressReachabilityFences) {
2520 // Insert reachability fences for all oop arguments at the end of the method.
2521 for (uint i = 1; i < _stress_rf_hook->req(); i++) {
2522 Node* referent = _stress_rf_hook->in(i);
2523 assert(referent->bottom_type()->isa_oopptr(), "%s", Type::str(referent->bottom_type()));
2524 insert_reachability_fence(referent);
2525 }
2526 }
2527
2528 // Do not set_parse_bci, so that return goo is credited to the return insn.
2529 set_bci(InvocationEntryBci);
2530 if (method()->is_synchronized()) {
2531 shared_unlock(_synch_lock->box_node(), _synch_lock->obj_node());
2532 }
2533 if (C->env()->dtrace_method_probes()) {
2534 make_dtrace_method_exit(method());
2535 }
2536
2537 SafePointNode* exit_return = _exits.map();
2538 exit_return->in( TypeFunc::Control )->add_req( control() );
2539 exit_return->in( TypeFunc::I_O )->add_req( i_o () );
2540 Node *mem = exit_return->in( TypeFunc::Memory );
2541 for (MergeMemStream mms(mem->as_MergeMem(), merged_memory()); mms.next_non_empty2(); ) {
2542 if (mms.is_empty()) {
2543 // get a copy of the base memory, and patch just this one input
2544 const TypePtr* adr_type = mms.adr_type(C);
2545 Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
2546 assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
2547 gvn().set_type_bottom(phi);
2548 phi->del_req(phi->req()-1); // prepare to re-patch
2549 mms.set_memory(phi);
2550 }
2551 mms.memory()->add_req(mms.memory2());
2552 }
2553
2554 if (_first_return) {
2555 _exits.map()->transfer_replaced_nodes_from(map(), _new_idx);
2556 _first_return = false;
2557 } else {
2558 _exits.map()->merge_replaced_nodes_with(map());
2559 }
2560
2561 stop_and_kill_map(); // This CFG path dies here
2562 }
2563
2564
2565 //------------------------------add_safepoint----------------------------------
2566 void Parse::add_safepoint() {
2567 uint parms = TypeFunc::Parms+1;
2568
2569 // Clear out dead values from the debug info.
2570 kill_dead_locals();
2571
2572 // Clone the JVM State
2573 SafePointNode *sfpnt = new SafePointNode(parms, nullptr);
2574
2575 // Capture memory state BEFORE a SafePoint. Since we can block at a
2576 // SafePoint we need our GC state to be safe; i.e. we need all our current
2577 // write barriers (card marks) to not float down after the SafePoint so we
2578 // must read raw memory. Likewise we need all oop stores to match the card
2579 // marks. If deopt can happen, we need ALL stores (we need the correct JVM
2580 // state on a deopt).
2581
2582 // We do not need to WRITE the memory state after a SafePoint. The control
2583 // edge will keep card-marks and oop-stores from floating up from below a
2584 // SafePoint and our true dependency added here will keep them from floating
2585 // down below a SafePoint.
2586
2587 // Clone the current memory state
2588 Node* mem = MergeMemNode::make(map()->memory());
2589
2590 mem = _gvn.transform(mem);
2591
2592 // Pass control through the safepoint
2593 sfpnt->init_req(TypeFunc::Control , control());
2594 // Fix edges normally used by a call
2595 sfpnt->init_req(TypeFunc::I_O , top() );
2596 sfpnt->init_req(TypeFunc::Memory , mem );
2597 sfpnt->init_req(TypeFunc::ReturnAdr, top() );
2598 sfpnt->init_req(TypeFunc::FramePtr , top() );
2599
2600 // Create a node for the polling address
2601 Node* polladr;
2602 Node* thread = _gvn.transform(new ThreadLocalNode());
2603 Node* polling_page_load_addr = _gvn.transform(off_heap_plus_addr(thread, in_bytes(JavaThread::polling_page_offset())));
2604 polladr = make_load(control(), polling_page_load_addr, TypeRawPtr::BOTTOM, T_ADDRESS, MemNode::unordered);
2605 sfpnt->init_req(TypeFunc::Parms+0, _gvn.transform(polladr));
2606
2607 // Fix up the JVM State edges
2608 add_safepoint_edges(sfpnt);
2609 Node *transformed_sfpnt = _gvn.transform(sfpnt);
2610 set_control(transformed_sfpnt);
2611
2612 // Provide an edge from root to safepoint. This makes the safepoint
2613 // appear useful until the parse has completed.
2614 if (transformed_sfpnt->is_SafePoint()) {
2615 assert(C->root() != nullptr, "Expect parse is still valid");
2616 C->root()->add_prec(transformed_sfpnt);
2617 }
2618 }
2619
2620 #ifndef PRODUCT
2621 //------------------------show_parse_info--------------------------------------
2622 void Parse::show_parse_info() {
2623 InlineTree* ilt = nullptr;
2624 if (C->ilt() != nullptr) {
2625 JVMState* caller_jvms = is_osr_parse() ? caller()->caller() : caller();
2626 ilt = InlineTree::find_subtree_from_root(C->ilt(), caller_jvms, method());
2627 }
2628 if (PrintCompilation && Verbose) {
2629 if (depth() == 1) {
2630 if( ilt->count_inlines() ) {
2631 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2632 ilt->count_inline_bcs());
2633 tty->cr();
2634 }
2635 } else {
2636 if (method()->is_synchronized()) tty->print("s");
2637 if (method()->has_exception_handlers()) tty->print("!");
2638 // Check this is not the final compiled version
2639 if (C->trap_can_recompile()) {
2640 tty->print("-");
2641 } else {
2642 tty->print(" ");
2643 }
2644 method()->print_short_name();
2645 if (is_osr_parse()) {
2646 tty->print(" @ %d", osr_bci());
2647 }
2648 tty->print(" (%d bytes)",method()->code_size());
2649 if (ilt->count_inlines()) {
2650 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2651 ilt->count_inline_bcs());
2652 }
2653 tty->cr();
2654 }
2655 }
2656 if (PrintOpto && (depth() == 1 || PrintOptoInlining)) {
2657 // Print that we succeeded; suppress this message on the first osr parse.
2658
2659 if (method()->is_synchronized()) tty->print("s");
2660 if (method()->has_exception_handlers()) tty->print("!");
2661 // Check this is not the final compiled version
2662 if (C->trap_can_recompile() && depth() == 1) {
2663 tty->print("-");
2664 } else {
2665 tty->print(" ");
2666 }
2667 if( depth() != 1 ) { tty->print(" "); } // missing compile count
2668 for (int i = 1; i < depth(); ++i) { tty->print(" "); }
2669 method()->print_short_name();
2670 if (is_osr_parse()) {
2671 tty->print(" @ %d", osr_bci());
2672 }
2673 if (ilt->caller_bci() != -1) {
2674 tty->print(" @ %d", ilt->caller_bci());
2675 }
2676 tty->print(" (%d bytes)",method()->code_size());
2677 if (ilt->count_inlines()) {
2678 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2679 ilt->count_inline_bcs());
2680 }
2681 tty->cr();
2682 }
2683 }
2684
2685
2686 //------------------------------dump-------------------------------------------
2687 // Dump information associated with the bytecodes of current _method
2688 void Parse::dump() {
2689 if( method() != nullptr ) {
2690 // Iterate over bytecodes
2691 ciBytecodeStream iter(method());
2692 for( Bytecodes::Code bc = iter.next(); bc != ciBytecodeStream::EOBC() ; bc = iter.next() ) {
2693 dump_bci( iter.cur_bci() );
2694 tty->cr();
2695 }
2696 }
2697 }
2698
2699 // Dump information associated with a byte code index, 'bci'
2700 void Parse::dump_bci(int bci) {
2701 // Output info on merge-points, cloning, and within _jsr..._ret
2702 // NYI
2703 tty->print(" bci:%d", bci);
2704 }
2705
2706 #endif