Thu, 24 May 2018 19:26:50 +0800
#7046 C2 supports long branch
Contributed-by: fujie
1 /*
2 * Copyright (c) 1997, 2016, 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 */
25 #include "precompiled.hpp"
26 #include "compiler/compileLog.hpp"
27 #include "interpreter/linkResolver.hpp"
28 #include "oops/method.hpp"
29 #include "opto/addnode.hpp"
30 #include "opto/c2compiler.hpp"
31 #include "opto/idealGraphPrinter.hpp"
32 #include "opto/locknode.hpp"
33 #include "opto/memnode.hpp"
34 #include "opto/parse.hpp"
35 #include "opto/rootnode.hpp"
36 #include "opto/runtime.hpp"
37 #include "runtime/arguments.hpp"
38 #include "runtime/handles.inline.hpp"
39 #include "runtime/sharedRuntime.hpp"
40 #include "utilities/copy.hpp"
42 // Static array so we can figure out which bytecodes stop us from compiling
43 // the most. Some of the non-static variables are needed in bytecodeInfo.cpp
44 // and eventually should be encapsulated in a proper class (gri 8/18/98).
46 int nodes_created = 0;
47 int methods_parsed = 0;
48 int methods_seen = 0;
49 int blocks_parsed = 0;
50 int blocks_seen = 0;
52 int explicit_null_checks_inserted = 0;
53 int explicit_null_checks_elided = 0;
54 int all_null_checks_found = 0, implicit_null_checks = 0;
55 int implicit_null_throws = 0;
57 int reclaim_idx = 0;
58 int reclaim_in = 0;
59 int reclaim_node = 0;
61 #ifndef PRODUCT
62 bool Parse::BytecodeParseHistogram::_initialized = false;
63 uint Parse::BytecodeParseHistogram::_bytecodes_parsed [Bytecodes::number_of_codes];
64 uint Parse::BytecodeParseHistogram::_nodes_constructed[Bytecodes::number_of_codes];
65 uint Parse::BytecodeParseHistogram::_nodes_transformed[Bytecodes::number_of_codes];
66 uint Parse::BytecodeParseHistogram::_new_values [Bytecodes::number_of_codes];
67 #endif
69 //------------------------------print_statistics-------------------------------
70 #ifndef PRODUCT
71 void Parse::print_statistics() {
72 tty->print_cr("--- Compiler Statistics ---");
73 tty->print("Methods seen: %d Methods parsed: %d", methods_seen, methods_parsed);
74 tty->print(" Nodes created: %d", nodes_created);
75 tty->cr();
76 if (methods_seen != methods_parsed)
77 tty->print_cr("Reasons for parse failures (NOT cumulative):");
78 tty->print_cr("Blocks parsed: %d Blocks seen: %d", blocks_parsed, blocks_seen);
80 if( explicit_null_checks_inserted )
81 tty->print_cr("%d original NULL checks - %d elided (%2d%%); optimizer leaves %d,", explicit_null_checks_inserted, explicit_null_checks_elided, (100*explicit_null_checks_elided)/explicit_null_checks_inserted, all_null_checks_found);
82 if( all_null_checks_found )
83 tty->print_cr("%d made implicit (%2d%%)", implicit_null_checks,
84 (100*implicit_null_checks)/all_null_checks_found);
85 if( implicit_null_throws )
86 tty->print_cr("%d implicit null exceptions at runtime",
87 implicit_null_throws);
89 if( PrintParseStatistics && BytecodeParseHistogram::initialized() ) {
90 BytecodeParseHistogram::print();
91 }
92 }
93 #endif
95 //------------------------------ON STACK REPLACEMENT---------------------------
97 // Construct a node which can be used to get incoming state for
98 // on stack replacement.
99 Node *Parse::fetch_interpreter_state(int index,
100 BasicType bt,
101 Node *local_addrs,
102 Node *local_addrs_base) {
103 Node *mem = memory(Compile::AliasIdxRaw);
104 Node *adr = basic_plus_adr( local_addrs_base, local_addrs, -index*wordSize );
105 Node *ctl = control();
107 // Very similar to LoadNode::make, except we handle un-aligned longs and
108 // doubles on Sparc. Intel can handle them just fine directly.
109 Node *l = NULL;
110 switch (bt) { // Signature is flattened
111 case T_INT: l = new (C) LoadINode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeInt::INT, MemNode::unordered); break;
112 case T_FLOAT: l = new (C) LoadFNode(ctl, mem, adr, TypeRawPtr::BOTTOM, Type::FLOAT, MemNode::unordered); break;
113 case T_ADDRESS: l = new (C) LoadPNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeRawPtr::BOTTOM, MemNode::unordered); break;
114 case T_OBJECT: l = new (C) LoadPNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeInstPtr::BOTTOM, MemNode::unordered); break;
115 case T_LONG:
116 case T_DOUBLE: {
117 // Since arguments are in reverse order, the argument address 'adr'
118 // refers to the back half of the long/double. Recompute adr.
119 adr = basic_plus_adr(local_addrs_base, local_addrs, -(index+1)*wordSize);
120 if (Matcher::misaligned_doubles_ok) {
121 l = (bt == T_DOUBLE)
122 ? (Node*)new (C) LoadDNode(ctl, mem, adr, TypeRawPtr::BOTTOM, Type::DOUBLE, MemNode::unordered)
123 : (Node*)new (C) LoadLNode(ctl, mem, adr, TypeRawPtr::BOTTOM, TypeLong::LONG, MemNode::unordered);
124 } else {
125 l = (bt == T_DOUBLE)
126 ? (Node*)new (C) LoadD_unalignedNode(ctl, mem, adr, TypeRawPtr::BOTTOM, MemNode::unordered)
127 : (Node*)new (C) LoadL_unalignedNode(ctl, mem, adr, TypeRawPtr::BOTTOM, MemNode::unordered);
128 }
129 break;
130 }
131 default: ShouldNotReachHere();
132 }
133 return _gvn.transform(l);
134 }
136 // Helper routine to prevent the interpreter from handing
137 // unexpected typestate to an OSR method.
138 // The Node l is a value newly dug out of the interpreter frame.
139 // The type is the type predicted by ciTypeFlow. Note that it is
140 // not a general type, but can only come from Type::get_typeflow_type.
141 // The safepoint is a map which will feed an uncommon trap.
142 Node* Parse::check_interpreter_type(Node* l, const Type* type,
143 SafePointNode* &bad_type_exit) {
145 const TypeOopPtr* tp = type->isa_oopptr();
147 // TypeFlow may assert null-ness if a type appears unloaded.
148 if (type == TypePtr::NULL_PTR ||
149 (tp != NULL && !tp->klass()->is_loaded())) {
150 // Value must be null, not a real oop.
151 Node* chk = _gvn.transform( new (C) CmpPNode(l, null()) );
152 Node* tst = _gvn.transform( new (C) BoolNode(chk, BoolTest::eq) );
153 IfNode* iff = create_and_map_if(control(), tst, PROB_MAX, COUNT_UNKNOWN);
154 set_control(_gvn.transform( new (C) IfTrueNode(iff) ));
155 Node* bad_type = _gvn.transform( new (C) IfFalseNode(iff) );
156 bad_type_exit->control()->add_req(bad_type);
157 l = null();
158 }
160 // Typeflow can also cut off paths from the CFG, based on
161 // types which appear unloaded, or call sites which appear unlinked.
162 // When paths are cut off, values at later merge points can rise
163 // toward more specific classes. Make sure these specific classes
164 // are still in effect.
165 if (tp != NULL && tp->klass() != C->env()->Object_klass()) {
166 // TypeFlow asserted a specific object type. Value must have that type.
167 Node* bad_type_ctrl = NULL;
168 l = gen_checkcast(l, makecon(TypeKlassPtr::make(tp->klass())), &bad_type_ctrl);
169 bad_type_exit->control()->add_req(bad_type_ctrl);
170 }
172 BasicType bt_l = _gvn.type(l)->basic_type();
173 BasicType bt_t = type->basic_type();
174 assert(_gvn.type(l)->higher_equal(type), "must constrain OSR typestate");
175 return l;
176 }
178 // Helper routine which sets up elements of the initial parser map when
179 // performing a parse for on stack replacement. Add values into map.
180 // The only parameter contains the address of a interpreter arguments.
181 void Parse::load_interpreter_state(Node* osr_buf) {
182 int index;
183 int max_locals = jvms()->loc_size();
184 int max_stack = jvms()->stk_size();
187 // Mismatch between method and jvms can occur since map briefly held
188 // an OSR entry state (which takes up one RawPtr word).
189 assert(max_locals == method()->max_locals(), "sanity");
190 assert(max_stack >= method()->max_stack(), "sanity");
191 assert((int)jvms()->endoff() == TypeFunc::Parms + max_locals + max_stack, "sanity");
192 assert((int)jvms()->endoff() == (int)map()->req(), "sanity");
194 // Find the start block.
195 Block* osr_block = start_block();
196 assert(osr_block->start() == osr_bci(), "sanity");
198 // Set initial BCI.
199 set_parse_bci(osr_block->start());
201 // Set initial stack depth.
202 set_sp(osr_block->start_sp());
204 // Check bailouts. We currently do not perform on stack replacement
205 // of loops in catch blocks or loops which branch with a non-empty stack.
206 if (sp() != 0) {
207 C->record_method_not_compilable("OSR starts with non-empty stack");
208 return;
209 }
210 // Do not OSR inside finally clauses:
211 if (osr_block->has_trap_at(osr_block->start())) {
212 C->record_method_not_compilable("OSR starts with an immediate trap");
213 return;
214 }
216 // Commute monitors from interpreter frame to compiler frame.
217 assert(jvms()->monitor_depth() == 0, "should be no active locks at beginning of osr");
218 int mcnt = osr_block->flow()->monitor_count();
219 Node *monitors_addr = basic_plus_adr(osr_buf, osr_buf, (max_locals+mcnt*2-1)*wordSize);
220 for (index = 0; index < mcnt; index++) {
221 // Make a BoxLockNode for the monitor.
222 Node *box = _gvn.transform(new (C) BoxLockNode(next_monitor()));
225 // Displaced headers and locked objects are interleaved in the
226 // temp OSR buffer. We only copy the locked objects out here.
227 // Fetch the locked object from the OSR temp buffer and copy to our fastlock node.
228 Node *lock_object = fetch_interpreter_state(index*2, T_OBJECT, monitors_addr, osr_buf);
229 // Try and copy the displaced header to the BoxNode
230 Node *displaced_hdr = fetch_interpreter_state((index*2) + 1, T_ADDRESS, monitors_addr, osr_buf);
233 store_to_memory(control(), box, displaced_hdr, T_ADDRESS, Compile::AliasIdxRaw, MemNode::unordered);
235 // Build a bogus FastLockNode (no code will be generated) and push the
236 // monitor into our debug info.
237 const FastLockNode *flock = _gvn.transform(new (C) FastLockNode( 0, lock_object, box ))->as_FastLock();
238 map()->push_monitor(flock);
240 // If the lock is our method synchronization lock, tuck it away in
241 // _sync_lock for return and rethrow exit paths.
242 if (index == 0 && method()->is_synchronized()) {
243 _synch_lock = flock;
244 }
245 }
247 // Use the raw liveness computation to make sure that unexpected
248 // values don't propagate into the OSR frame.
249 MethodLivenessResult live_locals = method()->liveness_at_bci(osr_bci());
250 if (!live_locals.is_valid()) {
251 // Degenerate or breakpointed method.
252 C->record_method_not_compilable("OSR in empty or breakpointed method");
253 return;
254 }
256 // Extract the needed locals from the interpreter frame.
257 Node *locals_addr = basic_plus_adr(osr_buf, osr_buf, (max_locals-1)*wordSize);
259 // find all the locals that the interpreter thinks contain live oops
260 const BitMap live_oops = method()->live_local_oops_at_bci(osr_bci());
261 for (index = 0; index < max_locals; index++) {
263 if (!live_locals.at(index)) {
264 continue;
265 }
267 const Type *type = osr_block->local_type_at(index);
269 if (type->isa_oopptr() != NULL) {
271 // 6403625: Verify that the interpreter oopMap thinks that the oop is live
272 // else we might load a stale oop if the MethodLiveness disagrees with the
273 // result of the interpreter. If the interpreter says it is dead we agree
274 // by making the value go to top.
275 //
277 if (!live_oops.at(index)) {
278 if (C->log() != NULL) {
279 C->log()->elem("OSR_mismatch local_index='%d'",index);
280 }
281 set_local(index, null());
282 // and ignore it for the loads
283 continue;
284 }
285 }
287 // Filter out TOP, HALF, and BOTTOM. (Cf. ensure_phi.)
288 if (type == Type::TOP || type == Type::HALF) {
289 continue;
290 }
291 // If the type falls to bottom, then this must be a local that
292 // is mixing ints and oops or some such. Forcing it to top
293 // makes it go dead.
294 if (type == Type::BOTTOM) {
295 continue;
296 }
297 // Construct code to access the appropriate local.
298 BasicType bt = type->basic_type();
299 if (type == TypePtr::NULL_PTR) {
300 // Ptr types are mixed together with T_ADDRESS but NULL is
301 // really for T_OBJECT types so correct it.
302 bt = T_OBJECT;
303 }
304 Node *value = fetch_interpreter_state(index, bt, locals_addr, osr_buf);
305 set_local(index, value);
306 }
308 // Extract the needed stack entries from the interpreter frame.
309 for (index = 0; index < sp(); index++) {
310 const Type *type = osr_block->stack_type_at(index);
311 if (type != Type::TOP) {
312 // Currently the compiler bails out when attempting to on stack replace
313 // at a bci with a non-empty stack. We should not reach here.
314 ShouldNotReachHere();
315 }
316 }
318 // End the OSR migration
319 make_runtime_call(RC_LEAF, OptoRuntime::osr_end_Type(),
320 CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_end),
321 "OSR_migration_end", TypeRawPtr::BOTTOM,
322 osr_buf);
324 // Now that the interpreter state is loaded, make sure it will match
325 // at execution time what the compiler is expecting now:
326 SafePointNode* bad_type_exit = clone_map();
327 bad_type_exit->set_control(new (C) RegionNode(1));
329 assert(osr_block->flow()->jsrs()->size() == 0, "should be no jsrs live at osr point");
330 for (index = 0; index < max_locals; index++) {
331 if (stopped()) break;
332 Node* l = local(index);
333 if (l->is_top()) continue; // nothing here
334 const Type *type = osr_block->local_type_at(index);
335 if (type->isa_oopptr() != NULL) {
336 if (!live_oops.at(index)) {
337 // skip type check for dead oops
338 continue;
339 }
340 }
341 if (osr_block->flow()->local_type_at(index)->is_return_address()) {
342 // In our current system it's illegal for jsr addresses to be
343 // live into an OSR entry point because the compiler performs
344 // inlining of jsrs. ciTypeFlow has a bailout that detect this
345 // case and aborts the compile if addresses are live into an OSR
346 // entry point. Because of that we can assume that any address
347 // locals at the OSR entry point are dead. Method liveness
348 // isn't precise enought to figure out that they are dead in all
349 // cases so simply skip checking address locals all
350 // together. Any type check is guaranteed to fail since the
351 // interpreter type is the result of a load which might have any
352 // value and the expected type is a constant.
353 continue;
354 }
355 set_local(index, check_interpreter_type(l, type, bad_type_exit));
356 }
358 for (index = 0; index < sp(); index++) {
359 if (stopped()) break;
360 Node* l = stack(index);
361 if (l->is_top()) continue; // nothing here
362 const Type *type = osr_block->stack_type_at(index);
363 set_stack(index, check_interpreter_type(l, type, bad_type_exit));
364 }
366 if (bad_type_exit->control()->req() > 1) {
367 // Build an uncommon trap here, if any inputs can be unexpected.
368 bad_type_exit->set_control(_gvn.transform( bad_type_exit->control() ));
369 record_for_igvn(bad_type_exit->control());
370 SafePointNode* types_are_good = map();
371 set_map(bad_type_exit);
372 // The unexpected type happens because a new edge is active
373 // in the CFG, which typeflow had previously ignored.
374 // E.g., Object x = coldAtFirst() && notReached()? "str": new Integer(123).
375 // This x will be typed as Integer if notReached is not yet linked.
376 // It could also happen due to a problem in ciTypeFlow analysis.
377 uncommon_trap(Deoptimization::Reason_constraint,
378 Deoptimization::Action_reinterpret);
379 set_map(types_are_good);
380 }
381 }
383 //------------------------------Parse------------------------------------------
384 // Main parser constructor.
385 Parse::Parse(JVMState* caller, ciMethod* parse_method, float expected_uses)
386 : _exits(caller)
387 {
388 // Init some variables
389 _caller = caller;
390 _method = parse_method;
391 _expected_uses = expected_uses;
392 _depth = 1 + (caller->has_method() ? caller->depth() : 0);
393 _wrote_final = false;
394 _wrote_volatile = false;
395 _alloc_with_final = NULL;
396 _entry_bci = InvocationEntryBci;
397 _tf = NULL;
398 _block = NULL;
399 _first_return = true;
400 _replaced_nodes_for_exceptions = false;
401 _new_idx = C->unique();
402 debug_only(_block_count = -1);
403 debug_only(_blocks = (Block*)-1);
404 #ifndef PRODUCT
405 if (PrintCompilation || PrintOpto) {
406 // Make sure I have an inline tree, so I can print messages about it.
407 JVMState* ilt_caller = is_osr_parse() ? caller->caller() : caller;
408 InlineTree::find_subtree_from_root(C->ilt(), ilt_caller, parse_method);
409 }
410 _max_switch_depth = 0;
411 _est_switch_depth = 0;
412 #endif
414 _tf = TypeFunc::make(method());
415 _iter.reset_to_method(method());
416 _flow = method()->get_flow_analysis();
417 if (_flow->failing()) {
418 C->record_method_not_compilable_all_tiers(_flow->failure_reason());
419 }
421 #ifndef PRODUCT
422 if (_flow->has_irreducible_entry()) {
423 C->set_parsed_irreducible_loop(true);
424 }
425 #endif
427 if (_expected_uses <= 0) {
428 _prof_factor = 1;
429 } else {
430 float prof_total = parse_method->interpreter_invocation_count();
431 if (prof_total <= _expected_uses) {
432 _prof_factor = 1;
433 } else {
434 _prof_factor = _expected_uses / prof_total;
435 }
436 }
438 CompileLog* log = C->log();
439 if (log != NULL) {
440 log->begin_head("parse method='%d' uses='%g'",
441 log->identify(parse_method), expected_uses);
442 if (depth() == 1 && C->is_osr_compilation()) {
443 log->print(" osr_bci='%d'", C->entry_bci());
444 }
445 log->stamp();
446 log->end_head();
447 }
449 // Accumulate deoptimization counts.
450 // (The range_check and store_check counts are checked elsewhere.)
451 ciMethodData* md = method()->method_data();
452 for (uint reason = 0; reason < md->trap_reason_limit(); reason++) {
453 uint md_count = md->trap_count(reason);
454 if (md_count != 0) {
455 if (md_count == md->trap_count_limit())
456 md_count += md->overflow_trap_count();
457 uint total_count = C->trap_count(reason);
458 uint old_count = total_count;
459 total_count += md_count;
460 // Saturate the add if it overflows.
461 if (total_count < old_count || total_count < md_count)
462 total_count = (uint)-1;
463 C->set_trap_count(reason, total_count);
464 if (log != NULL)
465 log->elem("observe trap='%s' count='%d' total='%d'",
466 Deoptimization::trap_reason_name(reason),
467 md_count, total_count);
468 }
469 }
470 // Accumulate total sum of decompilations, also.
471 C->set_decompile_count(C->decompile_count() + md->decompile_count());
473 _count_invocations = C->do_count_invocations();
474 _method_data_update = C->do_method_data_update();
476 if (log != NULL && method()->has_exception_handlers()) {
477 log->elem("observe that='has_exception_handlers'");
478 }
480 assert(method()->can_be_compiled(), "Can not parse this method, cutout earlier");
481 assert(method()->has_balanced_monitors(), "Can not parse unbalanced monitors, cutout earlier");
483 // Always register dependence if JVMTI is enabled, because
484 // either breakpoint setting or hotswapping of methods may
485 // cause deoptimization.
486 if (C->env()->jvmti_can_hotswap_or_post_breakpoint()) {
487 C->dependencies()->assert_evol_method(method());
488 }
490 methods_seen++;
492 // Do some special top-level things.
493 if (depth() == 1 && C->is_osr_compilation()) {
494 _entry_bci = C->entry_bci();
495 _flow = method()->get_osr_flow_analysis(osr_bci());
496 if (_flow->failing()) {
497 C->record_method_not_compilable(_flow->failure_reason());
498 #ifndef PRODUCT
499 if (PrintOpto && (Verbose || WizardMode)) {
500 tty->print_cr("OSR @%d type flow bailout: %s", _entry_bci, _flow->failure_reason());
501 if (Verbose) {
502 method()->print();
503 method()->print_codes();
504 _flow->print();
505 }
506 }
507 #endif
508 }
509 _tf = C->tf(); // the OSR entry type is different
510 }
512 #ifdef ASSERT
513 if (depth() == 1) {
514 assert(C->is_osr_compilation() == this->is_osr_parse(), "OSR in sync");
515 if (C->tf() != tf()) {
516 MutexLockerEx ml(Compile_lock, Mutex::_no_safepoint_check_flag);
517 assert(C->env()->system_dictionary_modification_counter_changed(),
518 "Must invalidate if TypeFuncs differ");
519 }
520 } else {
521 assert(!this->is_osr_parse(), "no recursive OSR");
522 }
523 #endif
525 methods_parsed++;
526 #ifndef PRODUCT
527 // add method size here to guarantee that inlined methods are added too
528 if (TimeCompiler)
529 _total_bytes_compiled += method()->code_size();
531 show_parse_info();
532 #endif
534 if (failing()) {
535 if (log) log->done("parse");
536 return;
537 }
539 gvn().set_type(root(), root()->bottom_type());
540 gvn().transform(top());
542 // Import the results of the ciTypeFlow.
543 init_blocks();
545 // Merge point for all normal exits
546 build_exits();
548 // Setup the initial JVM state map.
549 SafePointNode* entry_map = create_entry_map();
551 // Check for bailouts during map initialization
552 if (failing() || entry_map == NULL) {
553 if (log) log->done("parse");
554 return;
555 }
557 Node_Notes* caller_nn = C->default_node_notes();
558 // Collect debug info for inlined calls unless -XX:-DebugInlinedCalls.
559 if (DebugInlinedCalls || depth() == 1) {
560 C->set_default_node_notes(make_node_notes(caller_nn));
561 }
563 if (is_osr_parse()) {
564 Node* osr_buf = entry_map->in(TypeFunc::Parms+0);
565 entry_map->set_req(TypeFunc::Parms+0, top());
566 set_map(entry_map);
567 load_interpreter_state(osr_buf);
568 } else {
569 set_map(entry_map);
570 do_method_entry();
571 }
573 if (depth() == 1 && !failing()) {
574 // Add check to deoptimize the nmethod if RTM state was changed
575 rtm_deopt();
576 }
578 // Check for bailouts during method entry or RTM state check setup.
579 if (failing()) {
580 if (log) log->done("parse");
581 C->set_default_node_notes(caller_nn);
582 return;
583 }
585 entry_map = map(); // capture any changes performed by method setup code
586 assert(jvms()->endoff() == map()->req(), "map matches JVMS layout");
588 // We begin parsing as if we have just encountered a jump to the
589 // method entry.
590 Block* entry_block = start_block();
591 assert(entry_block->start() == (is_osr_parse() ? osr_bci() : 0), "");
592 set_map_clone(entry_map);
593 merge_common(entry_block, entry_block->next_path_num());
595 #ifndef PRODUCT
596 BytecodeParseHistogram *parse_histogram_obj = new (C->env()->arena()) BytecodeParseHistogram(this, C);
597 set_parse_histogram( parse_histogram_obj );
598 #endif
600 // Parse all the basic blocks.
601 do_all_blocks();
603 C->set_default_node_notes(caller_nn);
605 // Check for bailouts during conversion to graph
606 if (failing()) {
607 if (log) log->done("parse");
608 return;
609 }
611 // Fix up all exiting control flow.
612 set_map(entry_map);
613 do_exits();
615 if (log) log->done("parse nodes='%d' live='%d' memory='" SIZE_FORMAT "'",
616 C->unique(), C->live_nodes(), C->node_arena()->used());
617 }
619 //---------------------------do_all_blocks-------------------------------------
620 void Parse::do_all_blocks() {
621 bool has_irreducible = flow()->has_irreducible_entry();
623 // Walk over all blocks in Reverse Post-Order.
624 while (true) {
625 bool progress = false;
626 for (int rpo = 0; rpo < block_count(); rpo++) {
627 Block* block = rpo_at(rpo);
629 if (block->is_parsed()) continue;
631 if (!block->is_merged()) {
632 // Dead block, no state reaches this block
633 continue;
634 }
636 // Prepare to parse this block.
637 load_state_from(block);
639 if (stopped()) {
640 // Block is dead.
641 continue;
642 }
644 blocks_parsed++;
646 progress = true;
647 if (block->is_loop_head() || block->is_handler() || has_irreducible && !block->is_ready()) {
648 // Not all preds have been parsed. We must build phis everywhere.
649 // (Note that dead locals do not get phis built, ever.)
650 ensure_phis_everywhere();
652 if (block->is_SEL_head() &&
653 (UseLoopPredicate || LoopLimitCheck)) {
654 // Add predicate to single entry (not irreducible) loop head.
655 assert(!block->has_merged_backedge(), "only entry paths should be merged for now");
656 // Need correct bci for predicate.
657 // It is fine to set it here since do_one_block() will set it anyway.
658 set_parse_bci(block->start());
659 add_predicate();
660 // Add new region for back branches.
661 int edges = block->pred_count() - block->preds_parsed() + 1; // +1 for original region
662 RegionNode *r = new (C) RegionNode(edges+1);
663 _gvn.set_type(r, Type::CONTROL);
664 record_for_igvn(r);
665 r->init_req(edges, control());
666 set_control(r);
667 // Add new phis.
668 ensure_phis_everywhere();
669 }
671 // Leave behind an undisturbed copy of the map, for future merges.
672 set_map(clone_map());
673 }
675 if (control()->is_Region() && !block->is_loop_head() && !has_irreducible && !block->is_handler()) {
676 // In the absence of irreducible loops, the Region and Phis
677 // associated with a merge that doesn't involve a backedge can
678 // be simplified now since the RPO parsing order guarantees
679 // that any path which was supposed to reach here has already
680 // been parsed or must be dead.
681 Node* c = control();
682 Node* result = _gvn.transform_no_reclaim(control());
683 if (c != result && TraceOptoParse) {
684 tty->print_cr("Block #%d replace %d with %d", block->rpo(), c->_idx, result->_idx);
685 }
686 if (result != top()) {
687 record_for_igvn(result);
688 }
689 }
691 // Parse the block.
692 do_one_block();
694 // Check for bailouts.
695 if (failing()) return;
696 }
698 // with irreducible loops multiple passes might be necessary to parse everything
699 if (!has_irreducible || !progress) {
700 break;
701 }
702 }
704 blocks_seen += block_count();
706 #ifndef PRODUCT
707 // Make sure there are no half-processed blocks remaining.
708 // Every remaining unprocessed block is dead and may be ignored now.
709 for (int rpo = 0; rpo < block_count(); rpo++) {
710 Block* block = rpo_at(rpo);
711 if (!block->is_parsed()) {
712 if (TraceOptoParse) {
713 tty->print_cr("Skipped dead block %d at bci:%d", rpo, block->start());
714 }
715 assert(!block->is_merged(), "no half-processed blocks");
716 }
717 }
718 #endif
719 }
721 static Node* mask_int_value(Node* v, BasicType bt, PhaseGVN* gvn) {
722 Compile* C = gvn->C;
723 switch (bt) {
724 case T_BYTE:
725 v = gvn->transform(new (C) LShiftINode(v, gvn->intcon(24)));
726 v = gvn->transform(new (C) RShiftINode(v, gvn->intcon(24)));
727 break;
728 case T_SHORT:
729 v = gvn->transform(new (C) LShiftINode(v, gvn->intcon(16)));
730 v = gvn->transform(new (C) RShiftINode(v, gvn->intcon(16)));
731 break;
732 case T_CHAR:
733 v = gvn->transform(new (C) AndINode(v, gvn->intcon(0xFFFF)));
734 break;
735 case T_BOOLEAN:
736 v = gvn->transform(new (C) AndINode(v, gvn->intcon(0x1)));
737 break;
738 }
739 return v;
740 }
742 //-------------------------------build_exits----------------------------------
743 // Build normal and exceptional exit merge points.
744 void Parse::build_exits() {
745 // make a clone of caller to prevent sharing of side-effects
746 _exits.set_map(_exits.clone_map());
747 _exits.clean_stack(_exits.sp());
748 _exits.sync_jvms();
750 RegionNode* region = new (C) RegionNode(1);
751 record_for_igvn(region);
752 gvn().set_type_bottom(region);
753 _exits.set_control(region);
755 // Note: iophi and memphi are not transformed until do_exits.
756 Node* iophi = new (C) PhiNode(region, Type::ABIO);
757 Node* memphi = new (C) PhiNode(region, Type::MEMORY, TypePtr::BOTTOM);
758 gvn().set_type_bottom(iophi);
759 gvn().set_type_bottom(memphi);
760 _exits.set_i_o(iophi);
761 _exits.set_all_memory(memphi);
763 // Add a return value to the exit state. (Do not push it yet.)
764 if (tf()->range()->cnt() > TypeFunc::Parms) {
765 const Type* ret_type = tf()->range()->field_at(TypeFunc::Parms);
766 if (ret_type->isa_int()) {
767 BasicType ret_bt = method()->return_type()->basic_type();
768 if (ret_bt == T_BOOLEAN ||
769 ret_bt == T_CHAR ||
770 ret_bt == T_BYTE ||
771 ret_bt == T_SHORT) {
772 ret_type = TypeInt::INT;
773 }
774 }
776 // Don't "bind" an unloaded return klass to the ret_phi. If the klass
777 // becomes loaded during the subsequent parsing, the loaded and unloaded
778 // types will not join when we transform and push in do_exits().
779 const TypeOopPtr* ret_oop_type = ret_type->isa_oopptr();
780 if (ret_oop_type && !ret_oop_type->klass()->is_loaded()) {
781 ret_type = TypeOopPtr::BOTTOM;
782 }
783 int ret_size = type2size[ret_type->basic_type()];
784 Node* ret_phi = new (C) PhiNode(region, ret_type);
785 gvn().set_type_bottom(ret_phi);
786 _exits.ensure_stack(ret_size);
787 assert((int)(tf()->range()->cnt() - TypeFunc::Parms) == ret_size, "good tf range");
788 assert(method()->return_type()->size() == ret_size, "tf agrees w/ method");
789 _exits.set_argument(0, ret_phi); // here is where the parser finds it
790 // Note: ret_phi is not yet pushed, until do_exits.
791 }
792 }
795 //----------------------------build_start_state-------------------------------
796 // Construct a state which contains only the incoming arguments from an
797 // unknown caller. The method & bci will be NULL & InvocationEntryBci.
798 JVMState* Compile::build_start_state(StartNode* start, const TypeFunc* tf) {
799 int arg_size = tf->domain()->cnt();
800 int max_size = MAX2(arg_size, (int)tf->range()->cnt());
801 JVMState* jvms = new (this) JVMState(max_size - TypeFunc::Parms);
802 SafePointNode* map = new (this) SafePointNode(max_size, NULL);
803 record_for_igvn(map);
804 assert(arg_size == TypeFunc::Parms + (is_osr_compilation() ? 1 : method()->arg_size()), "correct arg_size");
805 Node_Notes* old_nn = default_node_notes();
806 if (old_nn != NULL && has_method()) {
807 Node_Notes* entry_nn = old_nn->clone(this);
808 JVMState* entry_jvms = new(this) JVMState(method(), old_nn->jvms());
809 entry_jvms->set_offsets(0);
810 entry_jvms->set_bci(entry_bci());
811 entry_nn->set_jvms(entry_jvms);
812 set_default_node_notes(entry_nn);
813 }
814 uint i;
815 for (i = 0; i < (uint)arg_size; i++) {
816 Node* parm = initial_gvn()->transform(new (this) ParmNode(start, i));
817 map->init_req(i, parm);
818 // Record all these guys for later GVN.
819 record_for_igvn(parm);
820 }
821 for (; i < map->req(); i++) {
822 map->init_req(i, top());
823 }
824 assert(jvms->argoff() == TypeFunc::Parms, "parser gets arguments here");
825 set_default_node_notes(old_nn);
826 map->set_jvms(jvms);
827 jvms->set_map(map);
828 return jvms;
829 }
831 //-----------------------------make_node_notes---------------------------------
832 Node_Notes* Parse::make_node_notes(Node_Notes* caller_nn) {
833 if (caller_nn == NULL) return NULL;
834 Node_Notes* nn = caller_nn->clone(C);
835 JVMState* caller_jvms = nn->jvms();
836 JVMState* jvms = new (C) JVMState(method(), caller_jvms);
837 jvms->set_offsets(0);
838 jvms->set_bci(_entry_bci);
839 nn->set_jvms(jvms);
840 return nn;
841 }
844 //--------------------------return_values--------------------------------------
845 void Compile::return_values(JVMState* jvms) {
846 GraphKit kit(jvms);
847 Node* ret = new (this) ReturnNode(TypeFunc::Parms,
848 kit.control(),
849 kit.i_o(),
850 kit.reset_memory(),
851 kit.frameptr(),
852 kit.returnadr());
853 // Add zero or 1 return values
854 int ret_size = tf()->range()->cnt() - TypeFunc::Parms;
855 if (ret_size > 0) {
856 kit.inc_sp(-ret_size); // pop the return value(s)
857 kit.sync_jvms();
858 ret->add_req(kit.argument(0));
859 // Note: The second dummy edge is not needed by a ReturnNode.
860 }
861 // bind it to root
862 root()->add_req(ret);
863 record_for_igvn(ret);
864 initial_gvn()->transform_no_reclaim(ret);
865 }
867 //------------------------rethrow_exceptions-----------------------------------
868 // Bind all exception states in the list into a single RethrowNode.
869 void Compile::rethrow_exceptions(JVMState* jvms) {
870 GraphKit kit(jvms);
871 if (!kit.has_exceptions()) return; // nothing to generate
872 // Load my combined exception state into the kit, with all phis transformed:
873 SafePointNode* ex_map = kit.combine_and_pop_all_exception_states();
874 Node* ex_oop = kit.use_exception_state(ex_map);
875 RethrowNode* exit = new (this) RethrowNode(kit.control(),
876 kit.i_o(), kit.reset_memory(),
877 kit.frameptr(), kit.returnadr(),
878 // like a return but with exception input
879 ex_oop);
880 // bind to root
881 root()->add_req(exit);
882 record_for_igvn(exit);
883 initial_gvn()->transform_no_reclaim(exit);
884 }
886 //---------------------------do_exceptions-------------------------------------
887 // Process exceptions arising from the current bytecode.
888 // Send caught exceptions to the proper handler within this method.
889 // Unhandled exceptions feed into _exit.
890 void Parse::do_exceptions() {
891 if (!has_exceptions()) return;
893 if (failing()) {
894 // Pop them all off and throw them away.
895 while (pop_exception_state() != NULL) ;
896 return;
897 }
899 PreserveJVMState pjvms(this, false);
901 SafePointNode* ex_map;
902 while ((ex_map = pop_exception_state()) != NULL) {
903 if (!method()->has_exception_handlers()) {
904 // Common case: Transfer control outward.
905 // Doing it this early allows the exceptions to common up
906 // even between adjacent method calls.
907 throw_to_exit(ex_map);
908 } else {
909 // Have to look at the exception first.
910 assert(stopped(), "catch_inline_exceptions trashes the map");
911 catch_inline_exceptions(ex_map);
912 stop_and_kill_map(); // we used up this exception state; kill it
913 }
914 }
916 // We now return to our regularly scheduled program:
917 }
919 //---------------------------throw_to_exit-------------------------------------
920 // Merge the given map into an exception exit from this method.
921 // The exception exit will handle any unlocking of receiver.
922 // The ex_oop must be saved within the ex_map, unlike merge_exception.
923 void Parse::throw_to_exit(SafePointNode* ex_map) {
924 // Pop the JVMS to (a copy of) the caller.
925 GraphKit caller;
926 caller.set_map_clone(_caller->map());
927 caller.set_bci(_caller->bci());
928 caller.set_sp(_caller->sp());
929 // Copy out the standard machine state:
930 for (uint i = 0; i < TypeFunc::Parms; i++) {
931 caller.map()->set_req(i, ex_map->in(i));
932 }
933 if (ex_map->has_replaced_nodes()) {
934 _replaced_nodes_for_exceptions = true;
935 }
936 caller.map()->transfer_replaced_nodes_from(ex_map, _new_idx);
937 // ...and the exception:
938 Node* ex_oop = saved_ex_oop(ex_map);
939 SafePointNode* caller_ex_map = caller.make_exception_state(ex_oop);
940 // Finally, collect the new exception state in my exits:
941 _exits.add_exception_state(caller_ex_map);
942 }
944 //------------------------------do_exits---------------------------------------
945 void Parse::do_exits() {
946 set_parse_bci(InvocationEntryBci);
948 // Now peephole on the return bits
949 Node* region = _exits.control();
950 _exits.set_control(gvn().transform(region));
952 Node* iophi = _exits.i_o();
953 _exits.set_i_o(gvn().transform(iophi));
955 // On PPC64, also add MemBarRelease for constructors which write
956 // volatile fields. As support_IRIW_for_not_multiple_copy_atomic_cpu
957 // is set on PPC64, no sync instruction is issued after volatile
958 // stores. We want to quarantee the same behaviour as on platforms
959 // with total store order, although this is not required by the Java
960 // memory model. So as with finals, we add a barrier here.
961 if (wrote_final() PPC64_ONLY(|| (wrote_volatile() && method()->is_initializer()))) {
962 // This method (which must be a constructor by the rules of Java)
963 // wrote a final. The effects of all initializations must be
964 // committed to memory before any code after the constructor
965 // publishes the reference to the newly constructor object.
966 // Rather than wait for the publication, we simply block the
967 // writes here. Rather than put a barrier on only those writes
968 // which are required to complete, we force all writes to complete.
969 //
970 // "All bets are off" unless the first publication occurs after a
971 // normal return from the constructor. We do not attempt to detect
972 // such unusual early publications. But no barrier is needed on
973 // exceptional returns, since they cannot publish normally.
974 //
975 _exits.insert_mem_bar(Op_MemBarRelease, alloc_with_final());
976 #ifndef PRODUCT
977 if (PrintOpto && (Verbose || WizardMode)) {
978 method()->print_name();
979 tty->print_cr(" writes finals and needs a memory barrier");
980 }
981 #endif
982 }
984 for (MergeMemStream mms(_exits.merged_memory()); mms.next_non_empty(); ) {
985 // transform each slice of the original memphi:
986 mms.set_memory(_gvn.transform(mms.memory()));
987 }
989 if (tf()->range()->cnt() > TypeFunc::Parms) {
990 const Type* ret_type = tf()->range()->field_at(TypeFunc::Parms);
991 Node* ret_phi = _gvn.transform( _exits.argument(0) );
992 if (!_exits.control()->is_top() && _gvn.type(ret_phi)->empty()) {
993 // In case of concurrent class loading, the type we set for the
994 // ret_phi in build_exits() may have been too optimistic and the
995 // ret_phi may be top now.
996 // Otherwise, we've encountered an error and have to mark the method as
997 // not compilable. Just using an assertion instead would be dangerous
998 // as this could lead to an infinite compile loop in non-debug builds.
999 {
1000 MutexLockerEx ml(Compile_lock, Mutex::_no_safepoint_check_flag);
1001 if (C->env()->system_dictionary_modification_counter_changed()) {
1002 C->record_failure(C2Compiler::retry_class_loading_during_parsing());
1003 } else {
1004 C->record_method_not_compilable("Can't determine return type.");
1005 }
1006 }
1007 return;
1008 }
1009 if (ret_type->isa_int()) {
1010 BasicType ret_bt = method()->return_type()->basic_type();
1011 ret_phi = mask_int_value(ret_phi, ret_bt, &_gvn);
1012 }
1013 _exits.push_node(ret_type->basic_type(), ret_phi);
1014 }
1016 // Note: Logic for creating and optimizing the ReturnNode is in Compile.
1018 // Unlock along the exceptional paths.
1019 // This is done late so that we can common up equivalent exceptions
1020 // (e.g., null checks) arising from multiple points within this method.
1021 // See GraphKit::add_exception_state, which performs the commoning.
1022 bool do_synch = method()->is_synchronized() && GenerateSynchronizationCode;
1024 // record exit from a method if compiled while Dtrace is turned on.
1025 if (do_synch || C->env()->dtrace_method_probes() || _replaced_nodes_for_exceptions) {
1026 // First move the exception list out of _exits:
1027 GraphKit kit(_exits.transfer_exceptions_into_jvms());
1028 SafePointNode* normal_map = kit.map(); // keep this guy safe
1029 // Now re-collect the exceptions into _exits:
1030 SafePointNode* ex_map;
1031 while ((ex_map = kit.pop_exception_state()) != NULL) {
1032 Node* ex_oop = kit.use_exception_state(ex_map);
1033 // Force the exiting JVM state to have this method at InvocationEntryBci.
1034 // The exiting JVM state is otherwise a copy of the calling JVMS.
1035 JVMState* caller = kit.jvms();
1036 JVMState* ex_jvms = caller->clone_shallow(C);
1037 ex_jvms->set_map(kit.clone_map());
1038 ex_jvms->map()->set_jvms(ex_jvms);
1039 ex_jvms->set_bci( InvocationEntryBci);
1040 kit.set_jvms(ex_jvms);
1041 if (do_synch) {
1042 // Add on the synchronized-method box/object combo
1043 kit.map()->push_monitor(_synch_lock);
1044 // Unlock!
1045 kit.shared_unlock(_synch_lock->box_node(), _synch_lock->obj_node());
1046 }
1047 if (C->env()->dtrace_method_probes()) {
1048 kit.make_dtrace_method_exit(method());
1049 }
1050 if (_replaced_nodes_for_exceptions) {
1051 kit.map()->apply_replaced_nodes(_new_idx);
1052 }
1053 // Done with exception-path processing.
1054 ex_map = kit.make_exception_state(ex_oop);
1055 assert(ex_jvms->same_calls_as(ex_map->jvms()), "sanity");
1056 // Pop the last vestige of this method:
1057 ex_map->set_jvms(caller->clone_shallow(C));
1058 ex_map->jvms()->set_map(ex_map);
1059 _exits.push_exception_state(ex_map);
1060 }
1061 assert(_exits.map() == normal_map, "keep the same return state");
1062 }
1064 {
1065 // Capture very early exceptions (receiver null checks) from caller JVMS
1066 GraphKit caller(_caller);
1067 SafePointNode* ex_map;
1068 while ((ex_map = caller.pop_exception_state()) != NULL) {
1069 _exits.add_exception_state(ex_map);
1070 }
1071 }
1072 _exits.map()->apply_replaced_nodes(_new_idx);
1073 }
1075 //-----------------------------create_entry_map-------------------------------
1076 // Initialize our parser map to contain the types at method entry.
1077 // For OSR, the map contains a single RawPtr parameter.
1078 // Initial monitor locking for sync. methods is performed by do_method_entry.
1079 SafePointNode* Parse::create_entry_map() {
1080 // Check for really stupid bail-out cases.
1081 uint len = TypeFunc::Parms + method()->max_locals() + method()->max_stack();
1082 if (len >= 32760) {
1083 C->record_method_not_compilable_all_tiers("too many local variables");
1084 return NULL;
1085 }
1087 // clear current replaced nodes that are of no use from here on (map was cloned in build_exits).
1088 _caller->map()->delete_replaced_nodes();
1090 // If this is an inlined method, we may have to do a receiver null check.
1091 if (_caller->has_method() && is_normal_parse() && !method()->is_static()) {
1092 GraphKit kit(_caller);
1093 kit.null_check_receiver_before_call(method());
1094 _caller = kit.transfer_exceptions_into_jvms();
1095 if (kit.stopped()) {
1096 _exits.add_exception_states_from(_caller);
1097 _exits.set_jvms(_caller);
1098 return NULL;
1099 }
1100 }
1102 assert(method() != NULL, "parser must have a method");
1104 // Create an initial safepoint to hold JVM state during parsing
1105 JVMState* jvms = new (C) JVMState(method(), _caller->has_method() ? _caller : NULL);
1106 set_map(new (C) SafePointNode(len, jvms));
1107 jvms->set_map(map());
1108 record_for_igvn(map());
1109 assert(jvms->endoff() == len, "correct jvms sizing");
1111 SafePointNode* inmap = _caller->map();
1112 assert(inmap != NULL, "must have inmap");
1113 // In case of null check on receiver above
1114 map()->transfer_replaced_nodes_from(inmap, _new_idx);
1116 uint i;
1118 // Pass thru the predefined input parameters.
1119 for (i = 0; i < TypeFunc::Parms; i++) {
1120 map()->init_req(i, inmap->in(i));
1121 }
1123 if (depth() == 1) {
1124 assert(map()->memory()->Opcode() == Op_Parm, "");
1125 // Insert the memory aliasing node
1126 set_all_memory(reset_memory());
1127 }
1128 assert(merged_memory(), "");
1130 // Now add the locals which are initially bound to arguments:
1131 uint arg_size = tf()->domain()->cnt();
1132 ensure_stack(arg_size - TypeFunc::Parms); // OSR methods have funny args
1133 for (i = TypeFunc::Parms; i < arg_size; i++) {
1134 map()->init_req(i, inmap->argument(_caller, i - TypeFunc::Parms));
1135 }
1137 // Clear out the rest of the map (locals and stack)
1138 for (i = arg_size; i < len; i++) {
1139 map()->init_req(i, top());
1140 }
1142 SafePointNode* entry_map = stop();
1143 return entry_map;
1144 }
1146 //-----------------------------do_method_entry--------------------------------
1147 // Emit any code needed in the pseudo-block before BCI zero.
1148 // The main thing to do is lock the receiver of a synchronized method.
1149 void Parse::do_method_entry() {
1150 set_parse_bci(InvocationEntryBci); // Pseudo-BCP
1151 set_sp(0); // Java Stack Pointer
1153 NOT_PRODUCT( count_compiled_calls(true/*at_method_entry*/, false/*is_inline*/); )
1155 if (C->env()->dtrace_method_probes()) {
1156 make_dtrace_method_entry(method());
1157 }
1159 // If the method is synchronized, we need to construct a lock node, attach
1160 // it to the Start node, and pin it there.
1161 if (method()->is_synchronized()) {
1162 // Insert a FastLockNode right after the Start which takes as arguments
1163 // the current thread pointer, the "this" pointer & the address of the
1164 // stack slot pair used for the lock. The "this" pointer is a projection
1165 // off the start node, but the locking spot has to be constructed by
1166 // creating a ConLNode of 0, and boxing it with a BoxLockNode. The BoxLockNode
1167 // becomes the second argument to the FastLockNode call. The
1168 // FastLockNode becomes the new control parent to pin it to the start.
1170 // Setup Object Pointer
1171 Node *lock_obj = NULL;
1172 if(method()->is_static()) {
1173 ciInstance* mirror = _method->holder()->java_mirror();
1174 const TypeInstPtr *t_lock = TypeInstPtr::make(mirror);
1175 lock_obj = makecon(t_lock);
1176 } else { // Else pass the "this" pointer,
1177 lock_obj = local(0); // which is Parm0 from StartNode
1178 }
1179 // Clear out dead values from the debug info.
1180 kill_dead_locals();
1181 // Build the FastLockNode
1182 _synch_lock = shared_lock(lock_obj);
1183 }
1185 // Feed profiling data for parameters to the type system so it can
1186 // propagate it as speculative types
1187 record_profiled_parameters_for_speculation();
1189 if (depth() == 1) {
1190 increment_and_test_invocation_counter(Tier2CompileThreshold);
1191 }
1192 }
1194 //------------------------------init_blocks------------------------------------
1195 // Initialize our parser map to contain the types/monitors at method entry.
1196 void Parse::init_blocks() {
1197 // Create the blocks.
1198 _block_count = flow()->block_count();
1199 _blocks = NEW_RESOURCE_ARRAY(Block, _block_count);
1200 Copy::zero_to_bytes(_blocks, sizeof(Block)*_block_count);
1202 int rpo;
1204 // Initialize the structs.
1205 for (rpo = 0; rpo < block_count(); rpo++) {
1206 Block* block = rpo_at(rpo);
1207 block->init_node(this, rpo);
1208 }
1210 // Collect predecessor and successor information.
1211 for (rpo = 0; rpo < block_count(); rpo++) {
1212 Block* block = rpo_at(rpo);
1213 block->init_graph(this);
1214 }
1215 }
1217 //-------------------------------init_node-------------------------------------
1218 void Parse::Block::init_node(Parse* outer, int rpo) {
1219 _flow = outer->flow()->rpo_at(rpo);
1220 _pred_count = 0;
1221 _preds_parsed = 0;
1222 _count = 0;
1223 assert(pred_count() == 0 && preds_parsed() == 0, "sanity");
1224 assert(!(is_merged() || is_parsed() || is_handler() || has_merged_backedge()), "sanity");
1225 assert(_live_locals.size() == 0, "sanity");
1227 // entry point has additional predecessor
1228 if (flow()->is_start()) _pred_count++;
1229 assert(flow()->is_start() == (this == outer->start_block()), "");
1230 }
1232 //-------------------------------init_graph------------------------------------
1233 void Parse::Block::init_graph(Parse* outer) {
1234 // Create the successor list for this parser block.
1235 GrowableArray<ciTypeFlow::Block*>* tfs = flow()->successors();
1236 GrowableArray<ciTypeFlow::Block*>* tfe = flow()->exceptions();
1237 int ns = tfs->length();
1238 int ne = tfe->length();
1239 _num_successors = ns;
1240 _all_successors = ns+ne;
1241 _successors = (ns+ne == 0) ? NULL : NEW_RESOURCE_ARRAY(Block*, ns+ne);
1242 int p = 0;
1243 for (int i = 0; i < ns+ne; i++) {
1244 ciTypeFlow::Block* tf2 = (i < ns) ? tfs->at(i) : tfe->at(i-ns);
1245 Block* block2 = outer->rpo_at(tf2->rpo());
1246 _successors[i] = block2;
1248 // Accumulate pred info for the other block, too.
1249 if (i < ns) {
1250 block2->_pred_count++;
1251 } else {
1252 block2->_is_handler = true;
1253 }
1255 #ifdef ASSERT
1256 // A block's successors must be distinguishable by BCI.
1257 // That is, no bytecode is allowed to branch to two different
1258 // clones of the same code location.
1259 for (int j = 0; j < i; j++) {
1260 Block* block1 = _successors[j];
1261 if (block1 == block2) continue; // duplicates are OK
1262 assert(block1->start() != block2->start(), "successors have unique bcis");
1263 }
1264 #endif
1265 }
1267 // Note: We never call next_path_num along exception paths, so they
1268 // never get processed as "ready". Also, the input phis of exception
1269 // handlers get specially processed, so that
1270 }
1272 //---------------------------successor_for_bci---------------------------------
1273 Parse::Block* Parse::Block::successor_for_bci(int bci) {
1274 for (int i = 0; i < all_successors(); i++) {
1275 Block* block2 = successor_at(i);
1276 if (block2->start() == bci) return block2;
1277 }
1278 // We can actually reach here if ciTypeFlow traps out a block
1279 // due to an unloaded class, and concurrently with compilation the
1280 // class is then loaded, so that a later phase of the parser is
1281 // able to see more of the bytecode CFG. Or, the flow pass and
1282 // the parser can have a minor difference of opinion about executability
1283 // of bytecodes. For example, "obj.field = null" is executable even
1284 // if the field's type is an unloaded class; the flow pass used to
1285 // make a trap for such code.
1286 return NULL;
1287 }
1290 //-----------------------------stack_type_at-----------------------------------
1291 const Type* Parse::Block::stack_type_at(int i) const {
1292 return get_type(flow()->stack_type_at(i));
1293 }
1296 //-----------------------------local_type_at-----------------------------------
1297 const Type* Parse::Block::local_type_at(int i) const {
1298 // Make dead locals fall to bottom.
1299 if (_live_locals.size() == 0) {
1300 MethodLivenessResult live_locals = flow()->outer()->method()->liveness_at_bci(start());
1301 // This bitmap can be zero length if we saw a breakpoint.
1302 // In such cases, pretend they are all live.
1303 ((Block*)this)->_live_locals = live_locals;
1304 }
1305 if (_live_locals.size() > 0 && !_live_locals.at(i))
1306 return Type::BOTTOM;
1308 return get_type(flow()->local_type_at(i));
1309 }
1312 #ifndef PRODUCT
1314 //----------------------------name_for_bc--------------------------------------
1315 // helper method for BytecodeParseHistogram
1316 static const char* name_for_bc(int i) {
1317 return Bytecodes::is_defined(i) ? Bytecodes::name(Bytecodes::cast(i)) : "xxxunusedxxx";
1318 }
1320 //----------------------------BytecodeParseHistogram------------------------------------
1321 Parse::BytecodeParseHistogram::BytecodeParseHistogram(Parse *p, Compile *c) {
1322 _parser = p;
1323 _compiler = c;
1324 if( ! _initialized ) { _initialized = true; reset(); }
1325 }
1327 //----------------------------current_count------------------------------------
1328 int Parse::BytecodeParseHistogram::current_count(BPHType bph_type) {
1329 switch( bph_type ) {
1330 case BPH_transforms: { return _parser->gvn().made_progress(); }
1331 case BPH_values: { return _parser->gvn().made_new_values(); }
1332 default: { ShouldNotReachHere(); return 0; }
1333 }
1334 }
1336 //----------------------------initialized--------------------------------------
1337 bool Parse::BytecodeParseHistogram::initialized() { return _initialized; }
1339 //----------------------------reset--------------------------------------------
1340 void Parse::BytecodeParseHistogram::reset() {
1341 int i = Bytecodes::number_of_codes;
1342 while (i-- > 0) { _bytecodes_parsed[i] = 0; _nodes_constructed[i] = 0; _nodes_transformed[i] = 0; _new_values[i] = 0; }
1343 }
1345 //----------------------------set_initial_state--------------------------------
1346 // Record info when starting to parse one bytecode
1347 void Parse::BytecodeParseHistogram::set_initial_state( Bytecodes::Code bc ) {
1348 if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1349 _initial_bytecode = bc;
1350 _initial_node_count = _compiler->unique();
1351 _initial_transforms = current_count(BPH_transforms);
1352 _initial_values = current_count(BPH_values);
1353 }
1354 }
1356 //----------------------------record_change--------------------------------
1357 // Record results of parsing one bytecode
1358 void Parse::BytecodeParseHistogram::record_change() {
1359 if( PrintParseStatistics && !_parser->is_osr_parse() ) {
1360 ++_bytecodes_parsed[_initial_bytecode];
1361 _nodes_constructed [_initial_bytecode] += (_compiler->unique() - _initial_node_count);
1362 _nodes_transformed [_initial_bytecode] += (current_count(BPH_transforms) - _initial_transforms);
1363 _new_values [_initial_bytecode] += (current_count(BPH_values) - _initial_values);
1364 }
1365 }
1368 //----------------------------print--------------------------------------------
1369 void Parse::BytecodeParseHistogram::print(float cutoff) {
1370 ResourceMark rm;
1371 // print profile
1372 int total = 0;
1373 int i = 0;
1374 for( i = 0; i < Bytecodes::number_of_codes; ++i ) { total += _bytecodes_parsed[i]; }
1375 int abs_sum = 0;
1376 tty->cr(); //0123456789012345678901234567890123456789012345678901234567890123456789
1377 tty->print_cr("Histogram of %d parsed bytecodes:", total);
1378 if( total == 0 ) { return; }
1379 tty->cr();
1380 tty->print_cr("absolute: count of compiled bytecodes of this type");
1381 tty->print_cr("relative: percentage contribution to compiled nodes");
1382 tty->print_cr("nodes : Average number of nodes constructed per bytecode");
1383 tty->print_cr("rnodes : Significance towards total nodes constructed, (nodes*relative)");
1384 tty->print_cr("transforms: Average amount of tranform progress per bytecode compiled");
1385 tty->print_cr("values : Average number of node values improved per bytecode");
1386 tty->print_cr("name : Bytecode name");
1387 tty->cr();
1388 tty->print_cr(" absolute relative nodes rnodes transforms values name");
1389 tty->print_cr("----------------------------------------------------------------------");
1390 while (--i > 0) {
1391 int abs = _bytecodes_parsed[i];
1392 float rel = abs * 100.0F / total;
1393 float nodes = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_constructed[i])/_bytecodes_parsed[i];
1394 float rnodes = _bytecodes_parsed[i] == 0 ? 0 : rel * nodes;
1395 float xforms = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _nodes_transformed[i])/_bytecodes_parsed[i];
1396 float values = _bytecodes_parsed[i] == 0 ? 0 : (1.0F * _new_values [i])/_bytecodes_parsed[i];
1397 if (cutoff <= rel) {
1398 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));
1399 abs_sum += abs;
1400 }
1401 }
1402 tty->print_cr("----------------------------------------------------------------------");
1403 float rel_sum = abs_sum * 100.0F / total;
1404 tty->print_cr("%10d %7.2f%% (cutoff = %.2f%%)", abs_sum, rel_sum, cutoff);
1405 tty->print_cr("----------------------------------------------------------------------");
1406 tty->cr();
1407 }
1408 #endif
1410 //----------------------------load_state_from----------------------------------
1411 // Load block/map/sp. But not do not touch iter/bci.
1412 void Parse::load_state_from(Block* block) {
1413 set_block(block);
1414 // load the block's JVM state:
1415 set_map(block->start_map());
1416 set_sp( block->start_sp());
1417 }
1420 //-----------------------------record_state------------------------------------
1421 void Parse::Block::record_state(Parse* p) {
1422 assert(!is_merged(), "can only record state once, on 1st inflow");
1423 assert(start_sp() == p->sp(), "stack pointer must agree with ciTypeFlow");
1424 set_start_map(p->stop());
1425 }
1428 //------------------------------do_one_block-----------------------------------
1429 void Parse::do_one_block() {
1430 if (TraceOptoParse) {
1431 Block *b = block();
1432 int ns = b->num_successors();
1433 int nt = b->all_successors();
1435 tty->print("Parsing block #%d at bci [%d,%d), successors: ",
1436 block()->rpo(), block()->start(), block()->limit());
1437 for (int i = 0; i < nt; i++) {
1438 tty->print((( i < ns) ? " %d" : " %d(e)"), b->successor_at(i)->rpo());
1439 }
1440 if (b->is_loop_head()) tty->print(" lphd");
1441 tty->cr();
1442 }
1444 assert(block()->is_merged(), "must be merged before being parsed");
1445 block()->mark_parsed();
1446 ++_blocks_parsed;
1448 // Set iterator to start of block.
1449 iter().reset_to_bci(block()->start());
1451 CompileLog* log = C->log();
1453 // Parse bytecodes
1454 while (!stopped() && !failing()) {
1455 iter().next();
1457 // Learn the current bci from the iterator:
1458 set_parse_bci(iter().cur_bci());
1460 if (bci() == block()->limit()) {
1461 // Do not walk into the next block until directed by do_all_blocks.
1462 merge(bci());
1463 break;
1464 }
1465 assert(bci() < block()->limit(), "bci still in block");
1467 if (log != NULL) {
1468 // Output an optional context marker, to help place actions
1469 // that occur during parsing of this BC. If there is no log
1470 // output until the next context string, this context string
1471 // will be silently ignored.
1472 log->set_context("bc code='%d' bci='%d'", (int)bc(), bci());
1473 }
1475 if (block()->has_trap_at(bci())) {
1476 // We must respect the flow pass's traps, because it will refuse
1477 // to produce successors for trapping blocks.
1478 int trap_index = block()->flow()->trap_index();
1479 assert(trap_index != 0, "trap index must be valid");
1480 uncommon_trap(trap_index);
1481 break;
1482 }
1484 NOT_PRODUCT( parse_histogram()->set_initial_state(bc()); );
1486 #ifdef ASSERT
1487 int pre_bc_sp = sp();
1488 int inputs, depth;
1489 bool have_se = !stopped() && compute_stack_effects(inputs, depth);
1490 assert(!have_se || pre_bc_sp >= inputs, err_msg_res("have enough stack to execute this BC: pre_bc_sp=%d, inputs=%d", pre_bc_sp, inputs));
1491 #endif //ASSERT
1493 do_one_bytecode();
1495 assert(!have_se || stopped() || failing() || (sp() - pre_bc_sp) == depth,
1496 err_msg_res("incorrect depth prediction: sp=%d, pre_bc_sp=%d, depth=%d", sp(), pre_bc_sp, depth));
1498 do_exceptions();
1500 NOT_PRODUCT( parse_histogram()->record_change(); );
1502 if (log != NULL)
1503 log->clear_context(); // skip marker if nothing was printed
1505 // Fall into next bytecode. Each bytecode normally has 1 sequential
1506 // successor which is typically made ready by visiting this bytecode.
1507 // If the successor has several predecessors, then it is a merge
1508 // point, starts a new basic block, and is handled like other basic blocks.
1509 }
1510 }
1513 //------------------------------merge------------------------------------------
1514 void Parse::set_parse_bci(int bci) {
1515 set_bci(bci);
1516 Node_Notes* nn = C->default_node_notes();
1517 if (nn == NULL) return;
1519 // Collect debug info for inlined calls unless -XX:-DebugInlinedCalls.
1520 if (!DebugInlinedCalls && depth() > 1) {
1521 return;
1522 }
1524 // Update the JVMS annotation, if present.
1525 JVMState* jvms = nn->jvms();
1526 if (jvms != NULL && jvms->bci() != bci) {
1527 // Update the JVMS.
1528 jvms = jvms->clone_shallow(C);
1529 jvms->set_bci(bci);
1530 nn->set_jvms(jvms);
1531 }
1532 }
1534 //------------------------------merge------------------------------------------
1535 // Merge the current mapping into the basic block starting at bci
1536 void Parse::merge(int target_bci) {
1537 Block* target = successor_for_bci(target_bci);
1538 if (target == NULL) { handle_missing_successor(target_bci); return; }
1539 assert(!target->is_ready(), "our arrival must be expected");
1540 int pnum = target->next_path_num();
1541 merge_common(target, pnum);
1542 }
1544 //-------------------------merge_new_path--------------------------------------
1545 // Merge the current mapping into the basic block, using a new path
1546 void Parse::merge_new_path(int target_bci) {
1547 Block* target = successor_for_bci(target_bci);
1548 if (target == NULL) { handle_missing_successor(target_bci); return; }
1549 assert(!target->is_ready(), "new path into frozen graph");
1550 int pnum = target->add_new_path();
1551 merge_common(target, pnum);
1552 }
1554 //-------------------------merge_exception-------------------------------------
1555 // Merge the current mapping into the basic block starting at bci
1556 // The ex_oop must be pushed on the stack, unlike throw_to_exit.
1557 void Parse::merge_exception(int target_bci) {
1558 assert(sp() == 1, "must have only the throw exception on the stack");
1559 Block* target = successor_for_bci(target_bci);
1560 if (target == NULL) { handle_missing_successor(target_bci); return; }
1561 assert(target->is_handler(), "exceptions are handled by special blocks");
1562 int pnum = target->add_new_path();
1563 merge_common(target, pnum);
1564 }
1566 //--------------------handle_missing_successor---------------------------------
1567 void Parse::handle_missing_successor(int target_bci) {
1568 #ifndef PRODUCT
1569 Block* b = block();
1570 int trap_bci = b->flow()->has_trap()? b->flow()->trap_bci(): -1;
1571 tty->print_cr("### Missing successor at bci:%d for block #%d (trap_bci:%d)", target_bci, b->rpo(), trap_bci);
1572 #endif
1573 ShouldNotReachHere();
1574 }
1576 //--------------------------merge_common---------------------------------------
1577 void Parse::merge_common(Parse::Block* target, int pnum) {
1578 if (TraceOptoParse) {
1579 tty->print("Merging state at block #%d bci:%d", target->rpo(), target->start());
1580 }
1582 // Zap extra stack slots to top
1583 assert(sp() == target->start_sp(), "");
1584 clean_stack(sp());
1586 if (!target->is_merged()) { // No prior mapping at this bci
1587 if (TraceOptoParse) { tty->print(" with empty state"); }
1589 // If this path is dead, do not bother capturing it as a merge.
1590 // It is "as if" we had 1 fewer predecessors from the beginning.
1591 if (stopped()) {
1592 if (TraceOptoParse) tty->print_cr(", but path is dead and doesn't count");
1593 return;
1594 }
1596 // Record that a new block has been merged.
1597 ++_blocks_merged;
1599 // Make a region if we know there are multiple or unpredictable inputs.
1600 // (Also, if this is a plain fall-through, we might see another region,
1601 // which must not be allowed into this block's map.)
1602 if (pnum > PhiNode::Input // Known multiple inputs.
1603 || target->is_handler() // These have unpredictable inputs.
1604 || target->is_loop_head() // Known multiple inputs
1605 || control()->is_Region()) { // We must hide this guy.
1607 int current_bci = bci();
1608 set_parse_bci(target->start()); // Set target bci
1609 if (target->is_SEL_head()) {
1610 DEBUG_ONLY( target->mark_merged_backedge(block()); )
1611 if (target->start() == 0) {
1612 // Add loop predicate for the special case when
1613 // there are backbranches to the method entry.
1614 add_predicate();
1615 }
1616 }
1617 // Add a Region to start the new basic block. Phis will be added
1618 // later lazily.
1619 int edges = target->pred_count();
1620 if (edges < pnum) edges = pnum; // might be a new path!
1621 RegionNode *r = new (C) RegionNode(edges+1);
1622 gvn().set_type(r, Type::CONTROL);
1623 record_for_igvn(r);
1624 // zap all inputs to NULL for debugging (done in Node(uint) constructor)
1625 // for (int j = 1; j < edges+1; j++) { r->init_req(j, NULL); }
1626 r->init_req(pnum, control());
1627 set_control(r);
1628 set_parse_bci(current_bci); // Restore bci
1629 }
1631 // Convert the existing Parser mapping into a mapping at this bci.
1632 store_state_to(target);
1633 assert(target->is_merged(), "do not come here twice");
1635 } else { // Prior mapping at this bci
1636 if (TraceOptoParse) { tty->print(" with previous state"); }
1637 #ifdef ASSERT
1638 if (target->is_SEL_head()) {
1639 target->mark_merged_backedge(block());
1640 }
1641 #endif
1642 // We must not manufacture more phis if the target is already parsed.
1643 bool nophi = target->is_parsed();
1645 SafePointNode* newin = map();// Hang on to incoming mapping
1646 Block* save_block = block(); // Hang on to incoming block;
1647 load_state_from(target); // Get prior mapping
1649 assert(newin->jvms()->locoff() == jvms()->locoff(), "JVMS layouts agree");
1650 assert(newin->jvms()->stkoff() == jvms()->stkoff(), "JVMS layouts agree");
1651 assert(newin->jvms()->monoff() == jvms()->monoff(), "JVMS layouts agree");
1652 assert(newin->jvms()->endoff() == jvms()->endoff(), "JVMS layouts agree");
1654 // Iterate over my current mapping and the old mapping.
1655 // Where different, insert Phi functions.
1656 // Use any existing Phi functions.
1657 assert(control()->is_Region(), "must be merging to a region");
1658 RegionNode* r = control()->as_Region();
1660 // Compute where to merge into
1661 // Merge incoming control path
1662 r->init_req(pnum, newin->control());
1664 if (pnum == 1) { // Last merge for this Region?
1665 if (!block()->flow()->is_irreducible_entry()) {
1666 Node* result = _gvn.transform_no_reclaim(r);
1667 if (r != result && TraceOptoParse) {
1668 tty->print_cr("Block #%d replace %d with %d", block()->rpo(), r->_idx, result->_idx);
1669 }
1670 }
1671 record_for_igvn(r);
1672 }
1674 // Update all the non-control inputs to map:
1675 assert(TypeFunc::Parms == newin->jvms()->locoff(), "parser map should contain only youngest jvms");
1676 bool check_elide_phi = target->is_SEL_backedge(save_block);
1677 for (uint j = 1; j < newin->req(); j++) {
1678 Node* m = map()->in(j); // Current state of target.
1679 Node* n = newin->in(j); // Incoming change to target state.
1680 PhiNode* phi;
1681 if (m->is_Phi() && m->as_Phi()->region() == r)
1682 phi = m->as_Phi();
1683 else
1684 phi = NULL;
1685 if (m != n) { // Different; must merge
1686 switch (j) {
1687 // Frame pointer and Return Address never changes
1688 case TypeFunc::FramePtr:// Drop m, use the original value
1689 case TypeFunc::ReturnAdr:
1690 break;
1691 case TypeFunc::Memory: // Merge inputs to the MergeMem node
1692 assert(phi == NULL, "the merge contains phis, not vice versa");
1693 merge_memory_edges(n->as_MergeMem(), pnum, nophi);
1694 continue;
1695 default: // All normal stuff
1696 if (phi == NULL) {
1697 const JVMState* jvms = map()->jvms();
1698 if (EliminateNestedLocks &&
1699 jvms->is_mon(j) && jvms->is_monitor_box(j)) {
1700 // BoxLock nodes are not commoning.
1701 // Use old BoxLock node as merged box.
1702 assert(newin->jvms()->is_monitor_box(j), "sanity");
1703 // This assert also tests that nodes are BoxLock.
1704 assert(BoxLockNode::same_slot(n, m), "sanity");
1705 C->gvn_replace_by(n, m);
1706 } else if (!check_elide_phi || !target->can_elide_SEL_phi(j)) {
1707 phi = ensure_phi(j, nophi);
1708 }
1709 }
1710 break;
1711 }
1712 }
1713 // At this point, n might be top if:
1714 // - there is no phi (because TypeFlow detected a conflict), or
1715 // - the corresponding control edges is top (a dead incoming path)
1716 // It is a bug if we create a phi which sees a garbage value on a live path.
1718 if (phi != NULL) {
1719 assert(n != top() || r->in(pnum) == top(), "live value must not be garbage");
1720 assert(phi->region() == r, "");
1721 phi->set_req(pnum, n); // Then add 'n' to the merge
1722 if (pnum == PhiNode::Input) {
1723 // Last merge for this Phi.
1724 // So far, Phis have had a reasonable type from ciTypeFlow.
1725 // Now _gvn will join that with the meet of current inputs.
1726 // BOTTOM is never permissible here, 'cause pessimistically
1727 // Phis of pointers cannot lose the basic pointer type.
1728 debug_only(const Type* bt1 = phi->bottom_type());
1729 assert(bt1 != Type::BOTTOM, "should not be building conflict phis");
1730 map()->set_req(j, _gvn.transform_no_reclaim(phi));
1731 debug_only(const Type* bt2 = phi->bottom_type());
1732 assert(bt2->higher_equal_speculative(bt1), "must be consistent with type-flow");
1733 record_for_igvn(phi);
1734 }
1735 }
1736 } // End of for all values to be merged
1738 if (pnum == PhiNode::Input &&
1739 !r->in(0)) { // The occasional useless Region
1740 assert(control() == r, "");
1741 set_control(r->nonnull_req());
1742 }
1744 map()->merge_replaced_nodes_with(newin);
1746 // newin has been subsumed into the lazy merge, and is now dead.
1747 set_block(save_block);
1749 stop(); // done with this guy, for now
1750 }
1752 if (TraceOptoParse) {
1753 tty->print_cr(" on path %d", pnum);
1754 }
1756 // Done with this parser state.
1757 assert(stopped(), "");
1758 }
1761 //--------------------------merge_memory_edges---------------------------------
1762 void Parse::merge_memory_edges(MergeMemNode* n, int pnum, bool nophi) {
1763 // (nophi means we must not create phis, because we already parsed here)
1764 assert(n != NULL, "");
1765 // Merge the inputs to the MergeMems
1766 MergeMemNode* m = merged_memory();
1768 assert(control()->is_Region(), "must be merging to a region");
1769 RegionNode* r = control()->as_Region();
1771 PhiNode* base = NULL;
1772 MergeMemNode* remerge = NULL;
1773 for (MergeMemStream mms(m, n); mms.next_non_empty2(); ) {
1774 Node *p = mms.force_memory();
1775 Node *q = mms.memory2();
1776 if (mms.is_empty() && nophi) {
1777 // Trouble: No new splits allowed after a loop body is parsed.
1778 // Instead, wire the new split into a MergeMem on the backedge.
1779 // The optimizer will sort it out, slicing the phi.
1780 if (remerge == NULL) {
1781 assert(base != NULL, "");
1782 assert(base->in(0) != NULL, "should not be xformed away");
1783 remerge = MergeMemNode::make(C, base->in(pnum));
1784 gvn().set_type(remerge, Type::MEMORY);
1785 base->set_req(pnum, remerge);
1786 }
1787 remerge->set_memory_at(mms.alias_idx(), q);
1788 continue;
1789 }
1790 assert(!q->is_MergeMem(), "");
1791 PhiNode* phi;
1792 if (p != q) {
1793 phi = ensure_memory_phi(mms.alias_idx(), nophi);
1794 } else {
1795 if (p->is_Phi() && p->as_Phi()->region() == r)
1796 phi = p->as_Phi();
1797 else
1798 phi = NULL;
1799 }
1800 // Insert q into local phi
1801 if (phi != NULL) {
1802 assert(phi->region() == r, "");
1803 p = phi;
1804 phi->set_req(pnum, q);
1805 if (mms.at_base_memory()) {
1806 base = phi; // delay transforming it
1807 } else if (pnum == 1) {
1808 record_for_igvn(phi);
1809 p = _gvn.transform_no_reclaim(phi);
1810 }
1811 mms.set_memory(p);// store back through the iterator
1812 }
1813 }
1814 // Transform base last, in case we must fiddle with remerging.
1815 if (base != NULL && pnum == 1) {
1816 record_for_igvn(base);
1817 m->set_base_memory( _gvn.transform_no_reclaim(base) );
1818 }
1819 }
1822 //------------------------ensure_phis_everywhere-------------------------------
1823 void Parse::ensure_phis_everywhere() {
1824 ensure_phi(TypeFunc::I_O);
1826 // Ensure a phi on all currently known memories.
1827 for (MergeMemStream mms(merged_memory()); mms.next_non_empty(); ) {
1828 ensure_memory_phi(mms.alias_idx());
1829 debug_only(mms.set_memory()); // keep the iterator happy
1830 }
1832 // Note: This is our only chance to create phis for memory slices.
1833 // If we miss a slice that crops up later, it will have to be
1834 // merged into the base-memory phi that we are building here.
1835 // Later, the optimizer will comb out the knot, and build separate
1836 // phi-loops for each memory slice that matters.
1838 // Monitors must nest nicely and not get confused amongst themselves.
1839 // Phi-ify everything up to the monitors, though.
1840 uint monoff = map()->jvms()->monoff();
1841 uint nof_monitors = map()->jvms()->nof_monitors();
1843 assert(TypeFunc::Parms == map()->jvms()->locoff(), "parser map should contain only youngest jvms");
1844 bool check_elide_phi = block()->is_SEL_head();
1845 for (uint i = TypeFunc::Parms; i < monoff; i++) {
1846 if (!check_elide_phi || !block()->can_elide_SEL_phi(i)) {
1847 ensure_phi(i);
1848 }
1849 }
1851 // Even monitors need Phis, though they are well-structured.
1852 // This is true for OSR methods, and also for the rare cases where
1853 // a monitor object is the subject of a replace_in_map operation.
1854 // See bugs 4426707 and 5043395.
1855 for (uint m = 0; m < nof_monitors; m++) {
1856 ensure_phi(map()->jvms()->monitor_obj_offset(m));
1857 }
1858 }
1861 //-----------------------------add_new_path------------------------------------
1862 // Add a previously unaccounted predecessor to this block.
1863 int Parse::Block::add_new_path() {
1864 // If there is no map, return the lowest unused path number.
1865 if (!is_merged()) return pred_count()+1; // there will be a map shortly
1867 SafePointNode* map = start_map();
1868 if (!map->control()->is_Region())
1869 return pred_count()+1; // there may be a region some day
1870 RegionNode* r = map->control()->as_Region();
1872 // Add new path to the region.
1873 uint pnum = r->req();
1874 r->add_req(NULL);
1876 for (uint i = 1; i < map->req(); i++) {
1877 Node* n = map->in(i);
1878 if (i == TypeFunc::Memory) {
1879 // Ensure a phi on all currently known memories.
1880 for (MergeMemStream mms(n->as_MergeMem()); mms.next_non_empty(); ) {
1881 Node* phi = mms.memory();
1882 if (phi->is_Phi() && phi->as_Phi()->region() == r) {
1883 assert(phi->req() == pnum, "must be same size as region");
1884 phi->add_req(NULL);
1885 }
1886 }
1887 } else {
1888 if (n->is_Phi() && n->as_Phi()->region() == r) {
1889 assert(n->req() == pnum, "must be same size as region");
1890 n->add_req(NULL);
1891 }
1892 }
1893 }
1895 return pnum;
1896 }
1898 //------------------------------ensure_phi-------------------------------------
1899 // Turn the idx'th entry of the current map into a Phi
1900 PhiNode *Parse::ensure_phi(int idx, bool nocreate) {
1901 SafePointNode* map = this->map();
1902 Node* region = map->control();
1903 assert(region->is_Region(), "");
1905 Node* o = map->in(idx);
1906 assert(o != NULL, "");
1908 if (o == top()) return NULL; // TOP always merges into TOP
1910 if (o->is_Phi() && o->as_Phi()->region() == region) {
1911 return o->as_Phi();
1912 }
1914 // Now use a Phi here for merging
1915 assert(!nocreate, "Cannot build a phi for a block already parsed.");
1916 const JVMState* jvms = map->jvms();
1917 const Type* t = NULL;
1918 if (jvms->is_loc(idx)) {
1919 t = block()->local_type_at(idx - jvms->locoff());
1920 } else if (jvms->is_stk(idx)) {
1921 t = block()->stack_type_at(idx - jvms->stkoff());
1922 } else if (jvms->is_mon(idx)) {
1923 assert(!jvms->is_monitor_box(idx), "no phis for boxes");
1924 t = TypeInstPtr::BOTTOM; // this is sufficient for a lock object
1925 } else if ((uint)idx < TypeFunc::Parms) {
1926 t = o->bottom_type(); // Type::RETURN_ADDRESS or such-like.
1927 } else {
1928 assert(false, "no type information for this phi");
1929 }
1931 // If the type falls to bottom, then this must be a local that
1932 // is mixing ints and oops or some such. Forcing it to top
1933 // makes it go dead.
1934 if (t == Type::BOTTOM) {
1935 map->set_req(idx, top());
1936 return NULL;
1937 }
1939 // Do not create phis for top either.
1940 // A top on a non-null control flow must be an unused even after the.phi.
1941 if (t == Type::TOP || t == Type::HALF) {
1942 map->set_req(idx, top());
1943 return NULL;
1944 }
1946 PhiNode* phi = PhiNode::make(region, o, t);
1947 gvn().set_type(phi, t);
1948 if (C->do_escape_analysis()) record_for_igvn(phi);
1949 map->set_req(idx, phi);
1950 return phi;
1951 }
1953 //--------------------------ensure_memory_phi----------------------------------
1954 // Turn the idx'th slice of the current memory into a Phi
1955 PhiNode *Parse::ensure_memory_phi(int idx, bool nocreate) {
1956 MergeMemNode* mem = merged_memory();
1957 Node* region = control();
1958 assert(region->is_Region(), "");
1960 Node *o = (idx == Compile::AliasIdxBot)? mem->base_memory(): mem->memory_at(idx);
1961 assert(o != NULL && o != top(), "");
1963 PhiNode* phi;
1964 if (o->is_Phi() && o->as_Phi()->region() == region) {
1965 phi = o->as_Phi();
1966 if (phi == mem->base_memory() && idx >= Compile::AliasIdxRaw) {
1967 // clone the shared base memory phi to make a new memory split
1968 assert(!nocreate, "Cannot build a phi for a block already parsed.");
1969 const Type* t = phi->bottom_type();
1970 const TypePtr* adr_type = C->get_adr_type(idx);
1971 phi = phi->slice_memory(adr_type);
1972 gvn().set_type(phi, t);
1973 }
1974 return phi;
1975 }
1977 // Now use a Phi here for merging
1978 assert(!nocreate, "Cannot build a phi for a block already parsed.");
1979 const Type* t = o->bottom_type();
1980 const TypePtr* adr_type = C->get_adr_type(idx);
1981 phi = PhiNode::make(region, o, t, adr_type);
1982 gvn().set_type(phi, t);
1983 if (idx == Compile::AliasIdxBot)
1984 mem->set_base_memory(phi);
1985 else
1986 mem->set_memory_at(idx, phi);
1987 return phi;
1988 }
1990 //------------------------------call_register_finalizer-----------------------
1991 // Check the klass of the receiver and call register_finalizer if the
1992 // class need finalization.
1993 void Parse::call_register_finalizer() {
1994 Node* receiver = local(0);
1995 assert(receiver != NULL && receiver->bottom_type()->isa_instptr() != NULL,
1996 "must have non-null instance type");
1998 const TypeInstPtr *tinst = receiver->bottom_type()->isa_instptr();
1999 if (tinst != NULL && tinst->klass()->is_loaded() && !tinst->klass_is_exact()) {
2000 // The type isn't known exactly so see if CHA tells us anything.
2001 ciInstanceKlass* ik = tinst->klass()->as_instance_klass();
2002 if (!Dependencies::has_finalizable_subclass(ik)) {
2003 // No finalizable subclasses so skip the dynamic check.
2004 C->dependencies()->assert_has_no_finalizable_subclasses(ik);
2005 return;
2006 }
2007 }
2009 // Insert a dynamic test for whether the instance needs
2010 // finalization. In general this will fold up since the concrete
2011 // class is often visible so the access flags are constant.
2012 Node* klass_addr = basic_plus_adr( receiver, receiver, oopDesc::klass_offset_in_bytes() );
2013 Node* klass = _gvn.transform(LoadKlassNode::make(_gvn, NULL, immutable_memory(), klass_addr, TypeInstPtr::KLASS));
2015 Node* access_flags_addr = basic_plus_adr(klass, klass, in_bytes(Klass::access_flags_offset()));
2016 Node* access_flags = make_load(NULL, access_flags_addr, TypeInt::INT, T_INT, MemNode::unordered);
2018 Node* mask = _gvn.transform(new (C) AndINode(access_flags, intcon(JVM_ACC_HAS_FINALIZER)));
2019 Node* check = _gvn.transform(new (C) CmpINode(mask, intcon(0)));
2020 Node* test = _gvn.transform(new (C) BoolNode(check, BoolTest::ne));
2022 IfNode* iff = create_and_map_if(control(), test, PROB_MAX, COUNT_UNKNOWN);
2024 RegionNode* result_rgn = new (C) RegionNode(3);
2025 record_for_igvn(result_rgn);
2027 Node *skip_register = _gvn.transform(new (C) IfFalseNode(iff));
2028 result_rgn->init_req(1, skip_register);
2030 Node *needs_register = _gvn.transform(new (C) IfTrueNode(iff));
2031 set_control(needs_register);
2032 if (stopped()) {
2033 // There is no slow path.
2034 result_rgn->init_req(2, top());
2035 } else {
2036 Node *call = make_runtime_call(RC_NO_LEAF,
2037 OptoRuntime::register_finalizer_Type(),
2038 OptoRuntime::register_finalizer_Java(),
2039 NULL, TypePtr::BOTTOM,
2040 receiver);
2041 make_slow_call_ex(call, env()->Throwable_klass(), true);
2043 Node* fast_io = call->in(TypeFunc::I_O);
2044 Node* fast_mem = call->in(TypeFunc::Memory);
2045 // These two phis are pre-filled with copies of of the fast IO and Memory
2046 Node* io_phi = PhiNode::make(result_rgn, fast_io, Type::ABIO);
2047 Node* mem_phi = PhiNode::make(result_rgn, fast_mem, Type::MEMORY, TypePtr::BOTTOM);
2049 result_rgn->init_req(2, control());
2050 io_phi ->init_req(2, i_o());
2051 mem_phi ->init_req(2, reset_memory());
2053 set_all_memory( _gvn.transform(mem_phi) );
2054 set_i_o( _gvn.transform(io_phi) );
2055 }
2057 set_control( _gvn.transform(result_rgn) );
2058 }
2060 // Add check to deoptimize if RTM state is not ProfileRTM
2061 void Parse::rtm_deopt() {
2062 #if INCLUDE_RTM_OPT
2063 if (C->profile_rtm()) {
2064 assert(C->method() != NULL, "only for normal compilations");
2065 assert(!C->method()->method_data()->is_empty(), "MDO is needed to record RTM state");
2066 assert(depth() == 1, "generate check only for main compiled method");
2068 // Set starting bci for uncommon trap.
2069 set_parse_bci(is_osr_parse() ? osr_bci() : 0);
2071 // Load the rtm_state from the MethodData.
2072 const TypePtr* adr_type = TypeMetadataPtr::make(C->method()->method_data());
2073 Node* mdo = makecon(adr_type);
2074 int offset = MethodData::rtm_state_offset_in_bytes();
2075 Node* adr_node = basic_plus_adr(mdo, mdo, offset);
2076 Node* rtm_state = make_load(control(), adr_node, TypeInt::INT, T_INT, adr_type, MemNode::unordered);
2078 // Separate Load from Cmp by Opaque.
2079 // In expand_macro_nodes() it will be replaced either
2080 // with this load when there are locks in the code
2081 // or with ProfileRTM (cmp->in(2)) otherwise so that
2082 // the check will fold.
2083 Node* profile_state = makecon(TypeInt::make(ProfileRTM));
2084 Node* opq = _gvn.transform( new (C) Opaque3Node(C, rtm_state, Opaque3Node::RTM_OPT) );
2085 Node* chk = _gvn.transform( new (C) CmpINode(opq, profile_state) );
2086 Node* tst = _gvn.transform( new (C) BoolNode(chk, BoolTest::eq) );
2087 // Branch to failure if state was changed
2088 { BuildCutout unless(this, tst, PROB_ALWAYS);
2089 uncommon_trap(Deoptimization::Reason_rtm_state_change,
2090 Deoptimization::Action_make_not_entrant);
2091 }
2092 }
2093 #endif
2094 }
2096 //------------------------------return_current---------------------------------
2097 // Append current _map to _exit_return
2098 void Parse::return_current(Node* value) {
2099 if (RegisterFinalizersAtInit &&
2100 method()->intrinsic_id() == vmIntrinsics::_Object_init) {
2101 call_register_finalizer();
2102 }
2104 // Do not set_parse_bci, so that return goo is credited to the return insn.
2105 set_bci(InvocationEntryBci);
2106 if (method()->is_synchronized() && GenerateSynchronizationCode) {
2107 shared_unlock(_synch_lock->box_node(), _synch_lock->obj_node());
2108 }
2109 if (C->env()->dtrace_method_probes()) {
2110 make_dtrace_method_exit(method());
2111 }
2112 SafePointNode* exit_return = _exits.map();
2113 exit_return->in( TypeFunc::Control )->add_req( control() );
2114 exit_return->in( TypeFunc::I_O )->add_req( i_o () );
2115 Node *mem = exit_return->in( TypeFunc::Memory );
2116 for (MergeMemStream mms(mem->as_MergeMem(), merged_memory()); mms.next_non_empty2(); ) {
2117 if (mms.is_empty()) {
2118 // get a copy of the base memory, and patch just this one input
2119 const TypePtr* adr_type = mms.adr_type(C);
2120 Node* phi = mms.force_memory()->as_Phi()->slice_memory(adr_type);
2121 assert(phi->as_Phi()->region() == mms.base_memory()->in(0), "");
2122 gvn().set_type_bottom(phi);
2123 phi->del_req(phi->req()-1); // prepare to re-patch
2124 mms.set_memory(phi);
2125 }
2126 mms.memory()->add_req(mms.memory2());
2127 }
2129 // frame pointer is always same, already captured
2130 if (value != NULL) {
2131 // If returning oops to an interface-return, there is a silent free
2132 // cast from oop to interface allowed by the Verifier. Make it explicit
2133 // here.
2134 Node* phi = _exits.argument(0);
2135 const TypeInstPtr *tr = phi->bottom_type()->isa_instptr();
2136 if (tr && tr->klass()->is_loaded() &&
2137 tr->klass()->is_interface()) {
2138 const TypeInstPtr *tp = value->bottom_type()->isa_instptr();
2139 if (tp && tp->klass()->is_loaded() &&
2140 !tp->klass()->is_interface()) {
2141 // sharpen the type eagerly; this eases certain assert checking
2142 if (tp->higher_equal(TypeInstPtr::NOTNULL))
2143 tr = tr->join_speculative(TypeInstPtr::NOTNULL)->is_instptr();
2144 value = _gvn.transform(new (C) CheckCastPPNode(0, value, tr));
2145 }
2146 } else {
2147 // Also handle returns of oop-arrays to an arrays-of-interface return
2148 const TypeInstPtr* phi_tip;
2149 const TypeInstPtr* val_tip;
2150 Type::get_arrays_base_elements(phi->bottom_type(), value->bottom_type(), &phi_tip, &val_tip);
2151 if (phi_tip != NULL && phi_tip->is_loaded() && phi_tip->klass()->is_interface() &&
2152 val_tip != NULL && val_tip->is_loaded() && !val_tip->klass()->is_interface()) {
2153 value = _gvn.transform(new (C) CheckCastPPNode(0, value, phi->bottom_type()));
2154 }
2155 }
2156 phi->add_req(value);
2157 }
2159 if (_first_return) {
2160 _exits.map()->transfer_replaced_nodes_from(map(), _new_idx);
2161 _first_return = false;
2162 } else {
2163 _exits.map()->merge_replaced_nodes_with(map());
2164 }
2166 stop_and_kill_map(); // This CFG path dies here
2167 }
2170 //------------------------------add_safepoint----------------------------------
2171 void Parse::add_safepoint() {
2172 // See if we can avoid this safepoint. No need for a SafePoint immediately
2173 // after a Call (except Leaf Call) or another SafePoint.
2174 Node *proj = control();
2175 bool add_poll_param = SafePointNode::needs_polling_address_input();
2176 uint parms = add_poll_param ? TypeFunc::Parms+1 : TypeFunc::Parms;
2177 if( proj->is_Proj() ) {
2178 Node *n0 = proj->in(0);
2179 if( n0->is_Catch() ) {
2180 n0 = n0->in(0)->in(0);
2181 assert( n0->is_Call(), "expect a call here" );
2182 }
2183 if( n0->is_Call() ) {
2184 if( n0->as_Call()->guaranteed_safepoint() )
2185 return;
2186 } else if( n0->is_SafePoint() && n0->req() >= parms ) {
2187 return;
2188 }
2189 }
2191 // Clear out dead values from the debug info.
2192 kill_dead_locals();
2194 // Clone the JVM State
2195 SafePointNode *sfpnt = new (C) SafePointNode(parms, NULL);
2197 // Capture memory state BEFORE a SafePoint. Since we can block at a
2198 // SafePoint we need our GC state to be safe; i.e. we need all our current
2199 // write barriers (card marks) to not float down after the SafePoint so we
2200 // must read raw memory. Likewise we need all oop stores to match the card
2201 // marks. If deopt can happen, we need ALL stores (we need the correct JVM
2202 // state on a deopt).
2204 // We do not need to WRITE the memory state after a SafePoint. The control
2205 // edge will keep card-marks and oop-stores from floating up from below a
2206 // SafePoint and our true dependency added here will keep them from floating
2207 // down below a SafePoint.
2209 // Clone the current memory state
2210 Node* mem = MergeMemNode::make(C, map()->memory());
2212 mem = _gvn.transform(mem);
2214 // Pass control through the safepoint
2215 sfpnt->init_req(TypeFunc::Control , control());
2216 // Fix edges normally used by a call
2217 sfpnt->init_req(TypeFunc::I_O , top() );
2218 sfpnt->init_req(TypeFunc::Memory , mem );
2219 sfpnt->init_req(TypeFunc::ReturnAdr, top() );
2220 sfpnt->init_req(TypeFunc::FramePtr , top() );
2222 // Create a node for the polling address
2223 if( add_poll_param ) {
2224 Node *polladr = ConPNode::make(C, (address)os::get_polling_page());
2225 sfpnt->init_req(TypeFunc::Parms+0, _gvn.transform(polladr));
2226 }
2228 // Fix up the JVM State edges
2229 add_safepoint_edges(sfpnt);
2230 Node *transformed_sfpnt = _gvn.transform(sfpnt);
2231 set_control(transformed_sfpnt);
2233 // Provide an edge from root to safepoint. This makes the safepoint
2234 // appear useful until the parse has completed.
2235 if( OptoRemoveUseless && transformed_sfpnt->is_SafePoint() ) {
2236 assert(C->root() != NULL, "Expect parse is still valid");
2237 C->root()->add_prec(transformed_sfpnt);
2238 }
2239 }
2241 #ifndef PRODUCT
2242 //------------------------show_parse_info--------------------------------------
2243 void Parse::show_parse_info() {
2244 InlineTree* ilt = NULL;
2245 if (C->ilt() != NULL) {
2246 JVMState* caller_jvms = is_osr_parse() ? caller()->caller() : caller();
2247 ilt = InlineTree::find_subtree_from_root(C->ilt(), caller_jvms, method());
2248 }
2249 if (PrintCompilation && Verbose) {
2250 if (depth() == 1) {
2251 if( ilt->count_inlines() ) {
2252 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2253 ilt->count_inline_bcs());
2254 tty->cr();
2255 }
2256 } else {
2257 if (method()->is_synchronized()) tty->print("s");
2258 if (method()->has_exception_handlers()) tty->print("!");
2259 // Check this is not the final compiled version
2260 if (C->trap_can_recompile()) {
2261 tty->print("-");
2262 } else {
2263 tty->print(" ");
2264 }
2265 method()->print_short_name();
2266 if (is_osr_parse()) {
2267 tty->print(" @ %d", osr_bci());
2268 }
2269 tty->print(" (%d bytes)",method()->code_size());
2270 if (ilt->count_inlines()) {
2271 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2272 ilt->count_inline_bcs());
2273 }
2274 tty->cr();
2275 }
2276 }
2277 if (PrintOpto && (depth() == 1 || PrintOptoInlining)) {
2278 // Print that we succeeded; suppress this message on the first osr parse.
2280 if (method()->is_synchronized()) tty->print("s");
2281 if (method()->has_exception_handlers()) tty->print("!");
2282 // Check this is not the final compiled version
2283 if (C->trap_can_recompile() && depth() == 1) {
2284 tty->print("-");
2285 } else {
2286 tty->print(" ");
2287 }
2288 if( depth() != 1 ) { tty->print(" "); } // missing compile count
2289 for (int i = 1; i < depth(); ++i) { tty->print(" "); }
2290 method()->print_short_name();
2291 if (is_osr_parse()) {
2292 tty->print(" @ %d", osr_bci());
2293 }
2294 if (ilt->caller_bci() != -1) {
2295 tty->print(" @ %d", ilt->caller_bci());
2296 }
2297 tty->print(" (%d bytes)",method()->code_size());
2298 if (ilt->count_inlines()) {
2299 tty->print(" __inlined %d (%d bytes)", ilt->count_inlines(),
2300 ilt->count_inline_bcs());
2301 }
2302 tty->cr();
2303 }
2304 }
2307 //------------------------------dump-------------------------------------------
2308 // Dump information associated with the bytecodes of current _method
2309 void Parse::dump() {
2310 if( method() != NULL ) {
2311 // Iterate over bytecodes
2312 ciBytecodeStream iter(method());
2313 for( Bytecodes::Code bc = iter.next(); bc != ciBytecodeStream::EOBC() ; bc = iter.next() ) {
2314 dump_bci( iter.cur_bci() );
2315 tty->cr();
2316 }
2317 }
2318 }
2320 // Dump information associated with a byte code index, 'bci'
2321 void Parse::dump_bci(int bci) {
2322 // Output info on merge-points, cloning, and within _jsr..._ret
2323 // NYI
2324 tty->print(" bci:%d", bci);
2325 }
2327 #endif