Wed, 13 Apr 2011 14:33:03 -0700
6988308: assert((cnt > 0.0f) && (prob > 0.0f)) failed: Bad frequency assignment in if
Summary: Make sure cnt doesn't become negative and integer overflow doesn't happen.
Reviewed-by: kvn, twisti
1 /*
2 * Copyright (c) 1998, 2011, 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 "memory/allocation.inline.hpp"
27 #include "opto/block.hpp"
28 #include "opto/c2compiler.hpp"
29 #include "opto/callnode.hpp"
30 #include "opto/cfgnode.hpp"
31 #include "opto/machnode.hpp"
32 #include "opto/runtime.hpp"
33 #ifdef TARGET_ARCH_MODEL_x86_32
34 # include "adfiles/ad_x86_32.hpp"
35 #endif
36 #ifdef TARGET_ARCH_MODEL_x86_64
37 # include "adfiles/ad_x86_64.hpp"
38 #endif
39 #ifdef TARGET_ARCH_MODEL_sparc
40 # include "adfiles/ad_sparc.hpp"
41 #endif
42 #ifdef TARGET_ARCH_MODEL_zero
43 # include "adfiles/ad_zero.hpp"
44 #endif
45 #ifdef TARGET_ARCH_MODEL_arm
46 # include "adfiles/ad_arm.hpp"
47 #endif
49 // Optimization - Graph Style
51 //------------------------------implicit_null_check----------------------------
52 // Detect implicit-null-check opportunities. Basically, find NULL checks
53 // with suitable memory ops nearby. Use the memory op to do the NULL check.
54 // I can generate a memory op if there is not one nearby.
55 // The proj is the control projection for the not-null case.
56 // The val is the pointer being checked for nullness or
57 // decodeHeapOop_not_null node if it did not fold into address.
58 void Block::implicit_null_check(PhaseCFG *cfg, Node *proj, Node *val, int allowed_reasons) {
59 // Assume if null check need for 0 offset then always needed
60 // Intel solaris doesn't support any null checks yet and no
61 // mechanism exists (yet) to set the switches at an os_cpu level
62 if( !ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(0)) return;
64 // Make sure the ptr-is-null path appears to be uncommon!
65 float f = end()->as_MachIf()->_prob;
66 if( proj->Opcode() == Op_IfTrue ) f = 1.0f - f;
67 if( f > PROB_UNLIKELY_MAG(4) ) return;
69 uint bidx = 0; // Capture index of value into memop
70 bool was_store; // Memory op is a store op
72 // Get the successor block for if the test ptr is non-null
73 Block* not_null_block; // this one goes with the proj
74 Block* null_block;
75 if (_nodes[_nodes.size()-1] == proj) {
76 null_block = _succs[0];
77 not_null_block = _succs[1];
78 } else {
79 assert(_nodes[_nodes.size()-2] == proj, "proj is one or the other");
80 not_null_block = _succs[0];
81 null_block = _succs[1];
82 }
83 while (null_block->is_Empty() == Block::empty_with_goto) {
84 null_block = null_block->_succs[0];
85 }
87 // Search the exception block for an uncommon trap.
88 // (See Parse::do_if and Parse::do_ifnull for the reason
89 // we need an uncommon trap. Briefly, we need a way to
90 // detect failure of this optimization, as in 6366351.)
91 {
92 bool found_trap = false;
93 for (uint i1 = 0; i1 < null_block->_nodes.size(); i1++) {
94 Node* nn = null_block->_nodes[i1];
95 if (nn->is_MachCall() &&
96 nn->as_MachCall()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point()) {
97 const Type* trtype = nn->in(TypeFunc::Parms)->bottom_type();
98 if (trtype->isa_int() && trtype->is_int()->is_con()) {
99 jint tr_con = trtype->is_int()->get_con();
100 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con);
101 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con);
102 assert((int)reason < (int)BitsPerInt, "recode bit map");
103 if (is_set_nth_bit(allowed_reasons, (int) reason)
104 && action != Deoptimization::Action_none) {
105 // This uncommon trap is sure to recompile, eventually.
106 // When that happens, C->too_many_traps will prevent
107 // this transformation from happening again.
108 found_trap = true;
109 }
110 }
111 break;
112 }
113 }
114 if (!found_trap) {
115 // We did not find an uncommon trap.
116 return;
117 }
118 }
120 // Check for decodeHeapOop_not_null node which did not fold into address
121 bool is_decoden = ((intptr_t)val) & 1;
122 val = (Node*)(((intptr_t)val) & ~1);
124 assert(!is_decoden || (val->in(0) == NULL) && val->is_Mach() &&
125 (val->as_Mach()->ideal_Opcode() == Op_DecodeN), "sanity");
127 // Search the successor block for a load or store who's base value is also
128 // the tested value. There may be several.
129 Node_List *out = new Node_List(Thread::current()->resource_area());
130 MachNode *best = NULL; // Best found so far
131 for (DUIterator i = val->outs(); val->has_out(i); i++) {
132 Node *m = val->out(i);
133 if( !m->is_Mach() ) continue;
134 MachNode *mach = m->as_Mach();
135 was_store = false;
136 int iop = mach->ideal_Opcode();
137 switch( iop ) {
138 case Op_LoadB:
139 case Op_LoadUS:
140 case Op_LoadD:
141 case Op_LoadF:
142 case Op_LoadI:
143 case Op_LoadL:
144 case Op_LoadP:
145 case Op_LoadN:
146 case Op_LoadS:
147 case Op_LoadKlass:
148 case Op_LoadNKlass:
149 case Op_LoadRange:
150 case Op_LoadD_unaligned:
151 case Op_LoadL_unaligned:
152 assert(mach->in(2) == val, "should be address");
153 break;
154 case Op_StoreB:
155 case Op_StoreC:
156 case Op_StoreCM:
157 case Op_StoreD:
158 case Op_StoreF:
159 case Op_StoreI:
160 case Op_StoreL:
161 case Op_StoreP:
162 case Op_StoreN:
163 was_store = true; // Memory op is a store op
164 // Stores will have their address in slot 2 (memory in slot 1).
165 // If the value being nul-checked is in another slot, it means we
166 // are storing the checked value, which does NOT check the value!
167 if( mach->in(2) != val ) continue;
168 break; // Found a memory op?
169 case Op_StrComp:
170 case Op_StrEquals:
171 case Op_StrIndexOf:
172 case Op_AryEq:
173 // Not a legit memory op for implicit null check regardless of
174 // embedded loads
175 continue;
176 default: // Also check for embedded loads
177 if( !mach->needs_anti_dependence_check() )
178 continue; // Not an memory op; skip it
179 if( must_clone[iop] ) {
180 // Do not move nodes which produce flags because
181 // RA will try to clone it to place near branch and
182 // it will cause recompilation, see clone_node().
183 continue;
184 }
185 {
186 // Check that value is used in memory address in
187 // instructions with embedded load (CmpP val1,(val2+off)).
188 Node* base;
189 Node* index;
190 const MachOper* oper = mach->memory_inputs(base, index);
191 if (oper == NULL || oper == (MachOper*)-1) {
192 continue; // Not an memory op; skip it
193 }
194 if (val == base ||
195 val == index && val->bottom_type()->isa_narrowoop()) {
196 break; // Found it
197 } else {
198 continue; // Skip it
199 }
200 }
201 break;
202 }
203 // check if the offset is not too high for implicit exception
204 {
205 intptr_t offset = 0;
206 const TypePtr *adr_type = NULL; // Do not need this return value here
207 const Node* base = mach->get_base_and_disp(offset, adr_type);
208 if (base == NULL || base == NodeSentinel) {
209 // Narrow oop address doesn't have base, only index
210 if( val->bottom_type()->isa_narrowoop() &&
211 MacroAssembler::needs_explicit_null_check(offset) )
212 continue; // Give up if offset is beyond page size
213 // cannot reason about it; is probably not implicit null exception
214 } else {
215 const TypePtr* tptr;
216 if (UseCompressedOops && Universe::narrow_oop_shift() == 0) {
217 // 32-bits narrow oop can be the base of address expressions
218 tptr = base->bottom_type()->make_ptr();
219 } else {
220 // only regular oops are expected here
221 tptr = base->bottom_type()->is_ptr();
222 }
223 // Give up if offset is not a compile-time constant
224 if( offset == Type::OffsetBot || tptr->_offset == Type::OffsetBot )
225 continue;
226 offset += tptr->_offset; // correct if base is offseted
227 if( MacroAssembler::needs_explicit_null_check(offset) )
228 continue; // Give up is reference is beyond 4K page size
229 }
230 }
232 // Check ctrl input to see if the null-check dominates the memory op
233 Block *cb = cfg->_bbs[mach->_idx];
234 cb = cb->_idom; // Always hoist at least 1 block
235 if( !was_store ) { // Stores can be hoisted only one block
236 while( cb->_dom_depth > (_dom_depth + 1))
237 cb = cb->_idom; // Hoist loads as far as we want
238 // The non-null-block should dominate the memory op, too. Live
239 // range spilling will insert a spill in the non-null-block if it is
240 // needs to spill the memory op for an implicit null check.
241 if (cb->_dom_depth == (_dom_depth + 1)) {
242 if (cb != not_null_block) continue;
243 cb = cb->_idom;
244 }
245 }
246 if( cb != this ) continue;
248 // Found a memory user; see if it can be hoisted to check-block
249 uint vidx = 0; // Capture index of value into memop
250 uint j;
251 for( j = mach->req()-1; j > 0; j-- ) {
252 if( mach->in(j) == val ) {
253 vidx = j;
254 // Ignore DecodeN val which could be hoisted to where needed.
255 if( is_decoden ) continue;
256 }
257 // Block of memory-op input
258 Block *inb = cfg->_bbs[mach->in(j)->_idx];
259 Block *b = this; // Start from nul check
260 while( b != inb && b->_dom_depth > inb->_dom_depth )
261 b = b->_idom; // search upwards for input
262 // See if input dominates null check
263 if( b != inb )
264 break;
265 }
266 if( j > 0 )
267 continue;
268 Block *mb = cfg->_bbs[mach->_idx];
269 // Hoisting stores requires more checks for the anti-dependence case.
270 // Give up hoisting if we have to move the store past any load.
271 if( was_store ) {
272 Block *b = mb; // Start searching here for a local load
273 // mach use (faulting) trying to hoist
274 // n might be blocker to hoisting
275 while( b != this ) {
276 uint k;
277 for( k = 1; k < b->_nodes.size(); k++ ) {
278 Node *n = b->_nodes[k];
279 if( n->needs_anti_dependence_check() &&
280 n->in(LoadNode::Memory) == mach->in(StoreNode::Memory) )
281 break; // Found anti-dependent load
282 }
283 if( k < b->_nodes.size() )
284 break; // Found anti-dependent load
285 // Make sure control does not do a merge (would have to check allpaths)
286 if( b->num_preds() != 2 ) break;
287 b = cfg->_bbs[b->pred(1)->_idx]; // Move up to predecessor block
288 }
289 if( b != this ) continue;
290 }
292 // Make sure this memory op is not already being used for a NullCheck
293 Node *e = mb->end();
294 if( e->is_MachNullCheck() && e->in(1) == mach )
295 continue; // Already being used as a NULL check
297 // Found a candidate! Pick one with least dom depth - the highest
298 // in the dom tree should be closest to the null check.
299 if( !best ||
300 cfg->_bbs[mach->_idx]->_dom_depth < cfg->_bbs[best->_idx]->_dom_depth ) {
301 best = mach;
302 bidx = vidx;
304 }
305 }
306 // No candidate!
307 if( !best ) return;
309 // ---- Found an implicit null check
310 extern int implicit_null_checks;
311 implicit_null_checks++;
313 if( is_decoden ) {
314 // Check if we need to hoist decodeHeapOop_not_null first.
315 Block *valb = cfg->_bbs[val->_idx];
316 if( this != valb && this->_dom_depth < valb->_dom_depth ) {
317 // Hoist it up to the end of the test block.
318 valb->find_remove(val);
319 this->add_inst(val);
320 cfg->_bbs.map(val->_idx,this);
321 // DecodeN on x86 may kill flags. Check for flag-killing projections
322 // that also need to be hoisted.
323 for (DUIterator_Fast jmax, j = val->fast_outs(jmax); j < jmax; j++) {
324 Node* n = val->fast_out(j);
325 if( n->Opcode() == Op_MachProj ) {
326 cfg->_bbs[n->_idx]->find_remove(n);
327 this->add_inst(n);
328 cfg->_bbs.map(n->_idx,this);
329 }
330 }
331 }
332 }
333 // Hoist the memory candidate up to the end of the test block.
334 Block *old_block = cfg->_bbs[best->_idx];
335 old_block->find_remove(best);
336 add_inst(best);
337 cfg->_bbs.map(best->_idx,this);
339 // Move the control dependence
340 if (best->in(0) && best->in(0) == old_block->_nodes[0])
341 best->set_req(0, _nodes[0]);
343 // Check for flag-killing projections that also need to be hoisted
344 // Should be DU safe because no edge updates.
345 for (DUIterator_Fast jmax, j = best->fast_outs(jmax); j < jmax; j++) {
346 Node* n = best->fast_out(j);
347 if( n->Opcode() == Op_MachProj ) {
348 cfg->_bbs[n->_idx]->find_remove(n);
349 add_inst(n);
350 cfg->_bbs.map(n->_idx,this);
351 }
352 }
354 Compile *C = cfg->C;
355 // proj==Op_True --> ne test; proj==Op_False --> eq test.
356 // One of two graph shapes got matched:
357 // (IfTrue (If (Bool NE (CmpP ptr NULL))))
358 // (IfFalse (If (Bool EQ (CmpP ptr NULL))))
359 // NULL checks are always branch-if-eq. If we see a IfTrue projection
360 // then we are replacing a 'ne' test with a 'eq' NULL check test.
361 // We need to flip the projections to keep the same semantics.
362 if( proj->Opcode() == Op_IfTrue ) {
363 // Swap order of projections in basic block to swap branch targets
364 Node *tmp1 = _nodes[end_idx()+1];
365 Node *tmp2 = _nodes[end_idx()+2];
366 _nodes.map(end_idx()+1, tmp2);
367 _nodes.map(end_idx()+2, tmp1);
368 Node *tmp = new (C, 1) Node(C->top()); // Use not NULL input
369 tmp1->replace_by(tmp);
370 tmp2->replace_by(tmp1);
371 tmp->replace_by(tmp2);
372 tmp->destruct();
373 }
375 // Remove the existing null check; use a new implicit null check instead.
376 // Since schedule-local needs precise def-use info, we need to correct
377 // it as well.
378 Node *old_tst = proj->in(0);
379 MachNode *nul_chk = new (C) MachNullCheckNode(old_tst->in(0),best,bidx);
380 _nodes.map(end_idx(),nul_chk);
381 cfg->_bbs.map(nul_chk->_idx,this);
382 // Redirect users of old_test to nul_chk
383 for (DUIterator_Last i2min, i2 = old_tst->last_outs(i2min); i2 >= i2min; --i2)
384 old_tst->last_out(i2)->set_req(0, nul_chk);
385 // Clean-up any dead code
386 for (uint i3 = 0; i3 < old_tst->req(); i3++)
387 old_tst->set_req(i3, NULL);
389 cfg->latency_from_uses(nul_chk);
390 cfg->latency_from_uses(best);
391 }
394 //------------------------------select-----------------------------------------
395 // Select a nice fellow from the worklist to schedule next. If there is only
396 // one choice, then use it. Projections take top priority for correctness
397 // reasons - if I see a projection, then it is next. There are a number of
398 // other special cases, for instructions that consume condition codes, et al.
399 // These are chosen immediately. Some instructions are required to immediately
400 // precede the last instruction in the block, and these are taken last. Of the
401 // remaining cases (most), choose the instruction with the greatest latency
402 // (that is, the most number of pseudo-cycles required to the end of the
403 // routine). If there is a tie, choose the instruction with the most inputs.
404 Node *Block::select(PhaseCFG *cfg, Node_List &worklist, int *ready_cnt, VectorSet &next_call, uint sched_slot) {
406 // If only a single entry on the stack, use it
407 uint cnt = worklist.size();
408 if (cnt == 1) {
409 Node *n = worklist[0];
410 worklist.map(0,worklist.pop());
411 return n;
412 }
414 uint choice = 0; // Bigger is most important
415 uint latency = 0; // Bigger is scheduled first
416 uint score = 0; // Bigger is better
417 int idx = -1; // Index in worklist
419 for( uint i=0; i<cnt; i++ ) { // Inspect entire worklist
420 // Order in worklist is used to break ties.
421 // See caller for how this is used to delay scheduling
422 // of induction variable increments to after the other
423 // uses of the phi are scheduled.
424 Node *n = worklist[i]; // Get Node on worklist
426 int iop = n->is_Mach() ? n->as_Mach()->ideal_Opcode() : 0;
427 if( n->is_Proj() || // Projections always win
428 n->Opcode()== Op_Con || // So does constant 'Top'
429 iop == Op_CreateEx || // Create-exception must start block
430 iop == Op_CheckCastPP
431 ) {
432 worklist.map(i,worklist.pop());
433 return n;
434 }
436 // Final call in a block must be adjacent to 'catch'
437 Node *e = end();
438 if( e->is_Catch() && e->in(0)->in(0) == n )
439 continue;
441 // Memory op for an implicit null check has to be at the end of the block
442 if( e->is_MachNullCheck() && e->in(1) == n )
443 continue;
445 uint n_choice = 2;
447 // See if this instruction is consumed by a branch. If so, then (as the
448 // branch is the last instruction in the basic block) force it to the
449 // end of the basic block
450 if ( must_clone[iop] ) {
451 // See if any use is a branch
452 bool found_machif = false;
454 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
455 Node* use = n->fast_out(j);
457 // The use is a conditional branch, make them adjacent
458 if (use->is_MachIf() && cfg->_bbs[use->_idx]==this ) {
459 found_machif = true;
460 break;
461 }
463 // More than this instruction pending for successor to be ready,
464 // don't choose this if other opportunities are ready
465 if (ready_cnt[use->_idx] > 1)
466 n_choice = 1;
467 }
469 // loop terminated, prefer not to use this instruction
470 if (found_machif)
471 continue;
472 }
474 // See if this has a predecessor that is "must_clone", i.e. sets the
475 // condition code. If so, choose this first
476 for (uint j = 0; j < n->req() ; j++) {
477 Node *inn = n->in(j);
478 if (inn) {
479 if (inn->is_Mach() && must_clone[inn->as_Mach()->ideal_Opcode()] ) {
480 n_choice = 3;
481 break;
482 }
483 }
484 }
486 // MachTemps should be scheduled last so they are near their uses
487 if (n->is_MachTemp()) {
488 n_choice = 1;
489 }
491 uint n_latency = cfg->_node_latency->at_grow(n->_idx);
492 uint n_score = n->req(); // Many inputs get high score to break ties
494 // Keep best latency found
495 if( choice < n_choice ||
496 ( choice == n_choice &&
497 ( latency < n_latency ||
498 ( latency == n_latency &&
499 ( score < n_score ))))) {
500 choice = n_choice;
501 latency = n_latency;
502 score = n_score;
503 idx = i; // Also keep index in worklist
504 }
505 } // End of for all ready nodes in worklist
507 assert(idx >= 0, "index should be set");
508 Node *n = worklist[(uint)idx]; // Get the winner
510 worklist.map((uint)idx, worklist.pop()); // Compress worklist
511 return n;
512 }
515 //------------------------------set_next_call----------------------------------
516 void Block::set_next_call( Node *n, VectorSet &next_call, Block_Array &bbs ) {
517 if( next_call.test_set(n->_idx) ) return;
518 for( uint i=0; i<n->len(); i++ ) {
519 Node *m = n->in(i);
520 if( !m ) continue; // must see all nodes in block that precede call
521 if( bbs[m->_idx] == this )
522 set_next_call( m, next_call, bbs );
523 }
524 }
526 //------------------------------needed_for_next_call---------------------------
527 // Set the flag 'next_call' for each Node that is needed for the next call to
528 // be scheduled. This flag lets me bias scheduling so Nodes needed for the
529 // next subroutine call get priority - basically it moves things NOT needed
530 // for the next call till after the call. This prevents me from trying to
531 // carry lots of stuff live across a call.
532 void Block::needed_for_next_call(Node *this_call, VectorSet &next_call, Block_Array &bbs) {
533 // Find the next control-defining Node in this block
534 Node* call = NULL;
535 for (DUIterator_Fast imax, i = this_call->fast_outs(imax); i < imax; i++) {
536 Node* m = this_call->fast_out(i);
537 if( bbs[m->_idx] == this && // Local-block user
538 m != this_call && // Not self-start node
539 m->is_Call() )
540 call = m;
541 break;
542 }
543 if (call == NULL) return; // No next call (e.g., block end is near)
544 // Set next-call for all inputs to this call
545 set_next_call(call, next_call, bbs);
546 }
548 //------------------------------sched_call-------------------------------------
549 uint Block::sched_call( Matcher &matcher, Block_Array &bbs, uint node_cnt, Node_List &worklist, int *ready_cnt, MachCallNode *mcall, VectorSet &next_call ) {
550 RegMask regs;
552 // Schedule all the users of the call right now. All the users are
553 // projection Nodes, so they must be scheduled next to the call.
554 // Collect all the defined registers.
555 for (DUIterator_Fast imax, i = mcall->fast_outs(imax); i < imax; i++) {
556 Node* n = mcall->fast_out(i);
557 assert( n->Opcode()==Op_MachProj, "" );
558 --ready_cnt[n->_idx];
559 assert( !ready_cnt[n->_idx], "" );
560 // Schedule next to call
561 _nodes.map(node_cnt++, n);
562 // Collect defined registers
563 regs.OR(n->out_RegMask());
564 // Check for scheduling the next control-definer
565 if( n->bottom_type() == Type::CONTROL )
566 // Warm up next pile of heuristic bits
567 needed_for_next_call(n, next_call, bbs);
569 // Children of projections are now all ready
570 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
571 Node* m = n->fast_out(j); // Get user
572 if( bbs[m->_idx] != this ) continue;
573 if( m->is_Phi() ) continue;
574 if( !--ready_cnt[m->_idx] )
575 worklist.push(m);
576 }
578 }
580 // Act as if the call defines the Frame Pointer.
581 // Certainly the FP is alive and well after the call.
582 regs.Insert(matcher.c_frame_pointer());
584 // Set all registers killed and not already defined by the call.
585 uint r_cnt = mcall->tf()->range()->cnt();
586 int op = mcall->ideal_Opcode();
587 MachProjNode *proj = new (matcher.C, 1) MachProjNode( mcall, r_cnt+1, RegMask::Empty, MachProjNode::fat_proj );
588 bbs.map(proj->_idx,this);
589 _nodes.insert(node_cnt++, proj);
591 // Select the right register save policy.
592 const char * save_policy;
593 switch (op) {
594 case Op_CallRuntime:
595 case Op_CallLeaf:
596 case Op_CallLeafNoFP:
597 // Calling C code so use C calling convention
598 save_policy = matcher._c_reg_save_policy;
599 break;
601 case Op_CallStaticJava:
602 case Op_CallDynamicJava:
603 // Calling Java code so use Java calling convention
604 save_policy = matcher._register_save_policy;
605 break;
607 default:
608 ShouldNotReachHere();
609 }
611 // When using CallRuntime mark SOE registers as killed by the call
612 // so values that could show up in the RegisterMap aren't live in a
613 // callee saved register since the register wouldn't know where to
614 // find them. CallLeaf and CallLeafNoFP are ok because they can't
615 // have debug info on them. Strictly speaking this only needs to be
616 // done for oops since idealreg2debugmask takes care of debug info
617 // references but there no way to handle oops differently than other
618 // pointers as far as the kill mask goes.
619 bool exclude_soe = op == Op_CallRuntime;
621 // If the call is a MethodHandle invoke, we need to exclude the
622 // register which is used to save the SP value over MH invokes from
623 // the mask. Otherwise this register could be used for
624 // deoptimization information.
625 if (op == Op_CallStaticJava) {
626 MachCallStaticJavaNode* mcallstaticjava = (MachCallStaticJavaNode*) mcall;
627 if (mcallstaticjava->_method_handle_invoke)
628 proj->_rout.OR(Matcher::method_handle_invoke_SP_save_mask());
629 }
631 // Fill in the kill mask for the call
632 for( OptoReg::Name r = OptoReg::Name(0); r < _last_Mach_Reg; r=OptoReg::add(r,1) ) {
633 if( !regs.Member(r) ) { // Not already defined by the call
634 // Save-on-call register?
635 if ((save_policy[r] == 'C') ||
636 (save_policy[r] == 'A') ||
637 ((save_policy[r] == 'E') && exclude_soe)) {
638 proj->_rout.Insert(r);
639 }
640 }
641 }
643 return node_cnt;
644 }
647 //------------------------------schedule_local---------------------------------
648 // Topological sort within a block. Someday become a real scheduler.
649 bool Block::schedule_local(PhaseCFG *cfg, Matcher &matcher, int *ready_cnt, VectorSet &next_call) {
650 // Already "sorted" are the block start Node (as the first entry), and
651 // the block-ending Node and any trailing control projections. We leave
652 // these alone. PhiNodes and ParmNodes are made to follow the block start
653 // Node. Everything else gets topo-sorted.
655 #ifndef PRODUCT
656 if (cfg->trace_opto_pipelining()) {
657 tty->print_cr("# --- schedule_local B%d, before: ---", _pre_order);
658 for (uint i = 0;i < _nodes.size();i++) {
659 tty->print("# ");
660 _nodes[i]->fast_dump();
661 }
662 tty->print_cr("#");
663 }
664 #endif
666 // RootNode is already sorted
667 if( _nodes.size() == 1 ) return true;
669 // Move PhiNodes and ParmNodes from 1 to cnt up to the start
670 uint node_cnt = end_idx();
671 uint phi_cnt = 1;
672 uint i;
673 for( i = 1; i<node_cnt; i++ ) { // Scan for Phi
674 Node *n = _nodes[i];
675 if( n->is_Phi() || // Found a PhiNode or ParmNode
676 (n->is_Proj() && n->in(0) == head()) ) {
677 // Move guy at 'phi_cnt' to the end; makes a hole at phi_cnt
678 _nodes.map(i,_nodes[phi_cnt]);
679 _nodes.map(phi_cnt++,n); // swap Phi/Parm up front
680 } else { // All others
681 // Count block-local inputs to 'n'
682 uint cnt = n->len(); // Input count
683 uint local = 0;
684 for( uint j=0; j<cnt; j++ ) {
685 Node *m = n->in(j);
686 if( m && cfg->_bbs[m->_idx] == this && !m->is_top() )
687 local++; // One more block-local input
688 }
689 ready_cnt[n->_idx] = local; // Count em up
691 // A few node types require changing a required edge to a precedence edge
692 // before allocation.
693 if( UseConcMarkSweepGC || UseG1GC ) {
694 if( n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_StoreCM ) {
695 // Note: Required edges with an index greater than oper_input_base
696 // are not supported by the allocator.
697 // Note2: Can only depend on unmatched edge being last,
698 // can not depend on its absolute position.
699 Node *oop_store = n->in(n->req() - 1);
700 n->del_req(n->req() - 1);
701 n->add_prec(oop_store);
702 assert(cfg->_bbs[oop_store->_idx]->_dom_depth <= this->_dom_depth, "oop_store must dominate card-mark");
703 }
704 }
705 if( n->is_Mach() && n->req() > TypeFunc::Parms &&
706 (n->as_Mach()->ideal_Opcode() == Op_MemBarAcquire ||
707 n->as_Mach()->ideal_Opcode() == Op_MemBarVolatile) ) {
708 // MemBarAcquire could be created without Precedent edge.
709 // del_req() replaces the specified edge with the last input edge
710 // and then removes the last edge. If the specified edge > number of
711 // edges the last edge will be moved outside of the input edges array
712 // and the edge will be lost. This is why this code should be
713 // executed only when Precedent (== TypeFunc::Parms) edge is present.
714 Node *x = n->in(TypeFunc::Parms);
715 n->del_req(TypeFunc::Parms);
716 n->add_prec(x);
717 }
718 }
719 }
720 for(uint i2=i; i2<_nodes.size(); i2++ ) // Trailing guys get zapped count
721 ready_cnt[_nodes[i2]->_idx] = 0;
723 // All the prescheduled guys do not hold back internal nodes
724 uint i3;
725 for(i3 = 0; i3<phi_cnt; i3++ ) { // For all pre-scheduled
726 Node *n = _nodes[i3]; // Get pre-scheduled
727 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
728 Node* m = n->fast_out(j);
729 if( cfg->_bbs[m->_idx] ==this ) // Local-block user
730 ready_cnt[m->_idx]--; // Fix ready count
731 }
732 }
734 Node_List delay;
735 // Make a worklist
736 Node_List worklist;
737 for(uint i4=i3; i4<node_cnt; i4++ ) { // Put ready guys on worklist
738 Node *m = _nodes[i4];
739 if( !ready_cnt[m->_idx] ) { // Zero ready count?
740 if (m->is_iteratively_computed()) {
741 // Push induction variable increments last to allow other uses
742 // of the phi to be scheduled first. The select() method breaks
743 // ties in scheduling by worklist order.
744 delay.push(m);
745 } else if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CreateEx) {
746 // Force the CreateEx to the top of the list so it's processed
747 // first and ends up at the start of the block.
748 worklist.insert(0, m);
749 } else {
750 worklist.push(m); // Then on to worklist!
751 }
752 }
753 }
754 while (delay.size()) {
755 Node* d = delay.pop();
756 worklist.push(d);
757 }
759 // Warm up the 'next_call' heuristic bits
760 needed_for_next_call(_nodes[0], next_call, cfg->_bbs);
762 #ifndef PRODUCT
763 if (cfg->trace_opto_pipelining()) {
764 for (uint j=0; j<_nodes.size(); j++) {
765 Node *n = _nodes[j];
766 int idx = n->_idx;
767 tty->print("# ready cnt:%3d ", ready_cnt[idx]);
768 tty->print("latency:%3d ", cfg->_node_latency->at_grow(idx));
769 tty->print("%4d: %s\n", idx, n->Name());
770 }
771 }
772 #endif
774 // Pull from worklist and schedule
775 while( worklist.size() ) { // Worklist is not ready
777 #ifndef PRODUCT
778 if (cfg->trace_opto_pipelining()) {
779 tty->print("# ready list:");
780 for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
781 Node *n = worklist[i]; // Get Node on worklist
782 tty->print(" %d", n->_idx);
783 }
784 tty->cr();
785 }
786 #endif
788 // Select and pop a ready guy from worklist
789 Node* n = select(cfg, worklist, ready_cnt, next_call, phi_cnt);
790 _nodes.map(phi_cnt++,n); // Schedule him next
792 #ifndef PRODUCT
793 if (cfg->trace_opto_pipelining()) {
794 tty->print("# select %d: %s", n->_idx, n->Name());
795 tty->print(", latency:%d", cfg->_node_latency->at_grow(n->_idx));
796 n->dump();
797 if (Verbose) {
798 tty->print("# ready list:");
799 for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
800 Node *n = worklist[i]; // Get Node on worklist
801 tty->print(" %d", n->_idx);
802 }
803 tty->cr();
804 }
805 }
807 #endif
808 if( n->is_MachCall() ) {
809 MachCallNode *mcall = n->as_MachCall();
810 phi_cnt = sched_call(matcher, cfg->_bbs, phi_cnt, worklist, ready_cnt, mcall, next_call);
811 continue;
812 }
813 // Children are now all ready
814 for (DUIterator_Fast i5max, i5 = n->fast_outs(i5max); i5 < i5max; i5++) {
815 Node* m = n->fast_out(i5); // Get user
816 if( cfg->_bbs[m->_idx] != this ) continue;
817 if( m->is_Phi() ) continue;
818 if( !--ready_cnt[m->_idx] )
819 worklist.push(m);
820 }
821 }
823 if( phi_cnt != end_idx() ) {
824 // did not schedule all. Retry, Bailout, or Die
825 Compile* C = matcher.C;
826 if (C->subsume_loads() == true && !C->failing()) {
827 // Retry with subsume_loads == false
828 // If this is the first failure, the sentinel string will "stick"
829 // to the Compile object, and the C2Compiler will see it and retry.
830 C->record_failure(C2Compiler::retry_no_subsuming_loads());
831 }
832 // assert( phi_cnt == end_idx(), "did not schedule all" );
833 return false;
834 }
836 #ifndef PRODUCT
837 if (cfg->trace_opto_pipelining()) {
838 tty->print_cr("#");
839 tty->print_cr("# after schedule_local");
840 for (uint i = 0;i < _nodes.size();i++) {
841 tty->print("# ");
842 _nodes[i]->fast_dump();
843 }
844 tty->cr();
845 }
846 #endif
849 return true;
850 }
852 //--------------------------catch_cleanup_fix_all_inputs-----------------------
853 static void catch_cleanup_fix_all_inputs(Node *use, Node *old_def, Node *new_def) {
854 for (uint l = 0; l < use->len(); l++) {
855 if (use->in(l) == old_def) {
856 if (l < use->req()) {
857 use->set_req(l, new_def);
858 } else {
859 use->rm_prec(l);
860 use->add_prec(new_def);
861 l--;
862 }
863 }
864 }
865 }
867 //------------------------------catch_cleanup_find_cloned_def------------------
868 static Node *catch_cleanup_find_cloned_def(Block *use_blk, Node *def, Block *def_blk, Block_Array &bbs, int n_clone_idx) {
869 assert( use_blk != def_blk, "Inter-block cleanup only");
871 // The use is some block below the Catch. Find and return the clone of the def
872 // that dominates the use. If there is no clone in a dominating block, then
873 // create a phi for the def in a dominating block.
875 // Find which successor block dominates this use. The successor
876 // blocks must all be single-entry (from the Catch only; I will have
877 // split blocks to make this so), hence they all dominate.
878 while( use_blk->_dom_depth > def_blk->_dom_depth+1 )
879 use_blk = use_blk->_idom;
881 // Find the successor
882 Node *fixup = NULL;
884 uint j;
885 for( j = 0; j < def_blk->_num_succs; j++ )
886 if( use_blk == def_blk->_succs[j] )
887 break;
889 if( j == def_blk->_num_succs ) {
890 // Block at same level in dom-tree is not a successor. It needs a
891 // PhiNode, the PhiNode uses from the def and IT's uses need fixup.
892 Node_Array inputs = new Node_List(Thread::current()->resource_area());
893 for(uint k = 1; k < use_blk->num_preds(); k++) {
894 inputs.map(k, catch_cleanup_find_cloned_def(bbs[use_blk->pred(k)->_idx], def, def_blk, bbs, n_clone_idx));
895 }
897 // Check to see if the use_blk already has an identical phi inserted.
898 // If it exists, it will be at the first position since all uses of a
899 // def are processed together.
900 Node *phi = use_blk->_nodes[1];
901 if( phi->is_Phi() ) {
902 fixup = phi;
903 for (uint k = 1; k < use_blk->num_preds(); k++) {
904 if (phi->in(k) != inputs[k]) {
905 // Not a match
906 fixup = NULL;
907 break;
908 }
909 }
910 }
912 // If an existing PhiNode was not found, make a new one.
913 if (fixup == NULL) {
914 Node *new_phi = PhiNode::make(use_blk->head(), def);
915 use_blk->_nodes.insert(1, new_phi);
916 bbs.map(new_phi->_idx, use_blk);
917 for (uint k = 1; k < use_blk->num_preds(); k++) {
918 new_phi->set_req(k, inputs[k]);
919 }
920 fixup = new_phi;
921 }
923 } else {
924 // Found the use just below the Catch. Make it use the clone.
925 fixup = use_blk->_nodes[n_clone_idx];
926 }
928 return fixup;
929 }
931 //--------------------------catch_cleanup_intra_block--------------------------
932 // Fix all input edges in use that reference "def". The use is in the same
933 // block as the def and both have been cloned in each successor block.
934 static void catch_cleanup_intra_block(Node *use, Node *def, Block *blk, int beg, int n_clone_idx) {
936 // Both the use and def have been cloned. For each successor block,
937 // get the clone of the use, and make its input the clone of the def
938 // found in that block.
940 uint use_idx = blk->find_node(use);
941 uint offset_idx = use_idx - beg;
942 for( uint k = 0; k < blk->_num_succs; k++ ) {
943 // Get clone in each successor block
944 Block *sb = blk->_succs[k];
945 Node *clone = sb->_nodes[offset_idx+1];
946 assert( clone->Opcode() == use->Opcode(), "" );
948 // Make use-clone reference the def-clone
949 catch_cleanup_fix_all_inputs(clone, def, sb->_nodes[n_clone_idx]);
950 }
951 }
953 //------------------------------catch_cleanup_inter_block---------------------
954 // Fix all input edges in use that reference "def". The use is in a different
955 // block than the def.
956 static void catch_cleanup_inter_block(Node *use, Block *use_blk, Node *def, Block *def_blk, Block_Array &bbs, int n_clone_idx) {
957 if( !use_blk ) return; // Can happen if the use is a precedence edge
959 Node *new_def = catch_cleanup_find_cloned_def(use_blk, def, def_blk, bbs, n_clone_idx);
960 catch_cleanup_fix_all_inputs(use, def, new_def);
961 }
963 //------------------------------call_catch_cleanup-----------------------------
964 // If we inserted any instructions between a Call and his CatchNode,
965 // clone the instructions on all paths below the Catch.
966 void Block::call_catch_cleanup(Block_Array &bbs) {
968 // End of region to clone
969 uint end = end_idx();
970 if( !_nodes[end]->is_Catch() ) return;
971 // Start of region to clone
972 uint beg = end;
973 while( _nodes[beg-1]->Opcode() != Op_MachProj ||
974 !_nodes[beg-1]->in(0)->is_Call() ) {
975 beg--;
976 assert(beg > 0,"Catch cleanup walking beyond block boundary");
977 }
978 // Range of inserted instructions is [beg, end)
979 if( beg == end ) return;
981 // Clone along all Catch output paths. Clone area between the 'beg' and
982 // 'end' indices.
983 for( uint i = 0; i < _num_succs; i++ ) {
984 Block *sb = _succs[i];
985 // Clone the entire area; ignoring the edge fixup for now.
986 for( uint j = end; j > beg; j-- ) {
987 // It is safe here to clone a node with anti_dependence
988 // since clones dominate on each path.
989 Node *clone = _nodes[j-1]->clone();
990 sb->_nodes.insert( 1, clone );
991 bbs.map(clone->_idx,sb);
992 }
993 }
996 // Fixup edges. Check the def-use info per cloned Node
997 for(uint i2 = beg; i2 < end; i2++ ) {
998 uint n_clone_idx = i2-beg+1; // Index of clone of n in each successor block
999 Node *n = _nodes[i2]; // Node that got cloned
1000 // Need DU safe iterator because of edge manipulation in calls.
1001 Unique_Node_List *out = new Unique_Node_List(Thread::current()->resource_area());
1002 for (DUIterator_Fast j1max, j1 = n->fast_outs(j1max); j1 < j1max; j1++) {
1003 out->push(n->fast_out(j1));
1004 }
1005 uint max = out->size();
1006 for (uint j = 0; j < max; j++) {// For all users
1007 Node *use = out->pop();
1008 Block *buse = bbs[use->_idx];
1009 if( use->is_Phi() ) {
1010 for( uint k = 1; k < use->req(); k++ )
1011 if( use->in(k) == n ) {
1012 Node *fixup = catch_cleanup_find_cloned_def(bbs[buse->pred(k)->_idx], n, this, bbs, n_clone_idx);
1013 use->set_req(k, fixup);
1014 }
1015 } else {
1016 if (this == buse) {
1017 catch_cleanup_intra_block(use, n, this, beg, n_clone_idx);
1018 } else {
1019 catch_cleanup_inter_block(use, buse, n, this, bbs, n_clone_idx);
1020 }
1021 }
1022 } // End for all users
1024 } // End of for all Nodes in cloned area
1026 // Remove the now-dead cloned ops
1027 for(uint i3 = beg; i3 < end; i3++ ) {
1028 _nodes[beg]->disconnect_inputs(NULL);
1029 _nodes.remove(beg);
1030 }
1032 // If the successor blocks have a CreateEx node, move it back to the top
1033 for(uint i4 = 0; i4 < _num_succs; i4++ ) {
1034 Block *sb = _succs[i4];
1035 uint new_cnt = end - beg;
1036 // Remove any newly created, but dead, nodes.
1037 for( uint j = new_cnt; j > 0; j-- ) {
1038 Node *n = sb->_nodes[j];
1039 if (n->outcnt() == 0 &&
1040 (!n->is_Proj() || n->as_Proj()->in(0)->outcnt() == 1) ){
1041 n->disconnect_inputs(NULL);
1042 sb->_nodes.remove(j);
1043 new_cnt--;
1044 }
1045 }
1046 // If any newly created nodes remain, move the CreateEx node to the top
1047 if (new_cnt > 0) {
1048 Node *cex = sb->_nodes[1+new_cnt];
1049 if( cex->is_Mach() && cex->as_Mach()->ideal_Opcode() == Op_CreateEx ) {
1050 sb->_nodes.remove(1+new_cnt);
1051 sb->_nodes.insert(1,cex);
1052 }
1053 }
1054 }
1055 }