1 /*
2 * Copyright (c) 1998, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "asm/macroAssembler.inline.hpp"
26 #include "gc/shared/gc_globals.hpp"
27 #include "memory/allocation.inline.hpp"
28 #include "oops/compressedOops.hpp"
29 #include "opto/ad.hpp"
30 #include "opto/block.hpp"
31 #include "opto/c2compiler.hpp"
32 #include "opto/callnode.hpp"
33 #include "opto/cfgnode.hpp"
34 #include "opto/chaitin.hpp"
35 #include "opto/machnode.hpp"
36 #include "opto/runtime.hpp"
37 #include "runtime/os.inline.hpp"
38 #include "runtime/sharedRuntime.hpp"
39
40 // Optimization - Graph Style
41
42 // Check whether val is not-null-decoded compressed oop,
43 // i.e. will grab into the base of the heap if it represents null.
44 static bool accesses_heap_base_zone(Node *val) {
45 if (CompressedOops::base() != nullptr) { // Implies UseCompressedOops.
46 if (val && val->is_Mach()) {
47 if (val->as_Mach()->ideal_Opcode() == Op_DecodeN) {
48 // This assumes all Decodes with TypePtr::NotNull are matched to nodes that
49 // decode null to point to the heap base (Decode_NN).
50 if (val->bottom_type()->is_oopptr()->ptr() == TypePtr::NotNull) {
51 return true;
52 }
53 }
54 // Must recognize load operation with Decode matched in memory operand.
55 // We should not reach here except for PPC/AIX, as os::zero_page_read_protected()
56 // returns true everywhere else. On PPC, no such memory operands
57 // exist, therefore we did not yet implement a check for such operands.
58 NOT_AIX(Unimplemented());
59 }
60 }
61 return false;
62 }
63
64 static bool needs_explicit_null_check_for_read(Node *val) {
65 // On some OSes (AIX) the page at address 0 is only write protected.
66 // If so, only Store operations will trap.
67 if (os::zero_page_read_protected()) {
68 return false; // Implicit null check will work.
69 }
70 // Also a read accessing the base of a heap-based compressed heap will trap.
71 if (accesses_heap_base_zone(val) && // Hits the base zone page.
72 CompressedOops::use_implicit_null_checks()) { // Base zone page is protected.
73 return false;
74 }
75
76 return true;
77 }
78
79 void PhaseCFG::move_node_and_its_projections_to_block(Node* n, Block* b) {
80 assert(!is_CFG(n), "cannot move CFG node");
81 Block* old = get_block_for_node(n);
82 old->find_remove(n);
83 b->add_inst(n);
84 map_node_to_block(n, b);
85 // Check for Mach projections that also need to be moved.
86 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
87 Node* out = n->fast_out(i);
88 if (!out->is_MachProj()) {
89 continue;
90 }
91 assert(!n->is_MachProj(), "nested projections are not allowed");
92 move_node_and_its_projections_to_block(out, b);
93 }
94 }
95
96 void PhaseCFG::ensure_node_is_at_block_or_above(Node* n, Block* b) {
97 assert(!is_CFG(n), "cannot move CFG node");
98 Block* current = get_block_for_node(n);
99 if (current->dominates(b)) {
100 return; // n is already placed above b, do nothing.
101 }
102 // We only expect nodes without further inputs, like MachTemp or load Base.
103 assert(n->req() == 0 || (n->req() == 1 && n->in(0) == (Node*)C->root()),
104 "need for recursive hoisting not expected");
105 assert(b->dominates(current), "precondition: can only move n to b if b dominates n");
106 move_node_and_its_projections_to_block(n, b);
107 }
108
109 //------------------------------implicit_null_check----------------------------
110 // Detect implicit-null-check opportunities. Basically, find null checks
111 // with suitable memory ops nearby. Use the memory op to do the null check.
112 // I can generate a memory op if there is not one nearby.
113 // The proj is the control projection for the not-null case.
114 // The val is the pointer being checked for nullness or
115 // decodeHeapOop_not_null node if it did not fold into address.
116 void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allowed_reasons) {
117 // Assume if null check need for 0 offset then always needed
118 // Intel solaris doesn't support any null checks yet and no
119 // mechanism exists (yet) to set the switches at an os_cpu level
120 if( !ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(0)) return;
121
122 // Make sure the ptr-is-null path appears to be uncommon!
123 float f = block->end()->as_MachIf()->_prob;
124 if( proj->Opcode() == Op_IfTrue ) f = 1.0f - f;
125 if( f > PROB_UNLIKELY_MAG(4) ) return;
126
127 uint bidx = 0; // Capture index of value into memop
128 bool was_store; // Memory op is a store op
129
130 // Get the successor block for if the test ptr is non-null
131 Block* not_null_block; // this one goes with the proj
132 Block* null_block;
133 if (block->get_node(block->number_of_nodes()-1) == proj) {
134 null_block = block->_succs[0];
135 not_null_block = block->_succs[1];
136 } else {
137 assert(block->get_node(block->number_of_nodes()-2) == proj, "proj is one or the other");
138 not_null_block = block->_succs[0];
139 null_block = block->_succs[1];
140 }
141 while (null_block->is_Empty() == Block::empty_with_goto) {
142 null_block = null_block->_succs[0];
143 }
144
145 // Search the exception block for an uncommon trap.
146 // (See Parse::do_if and Parse::do_ifnull for the reason
147 // we need an uncommon trap. Briefly, we need a way to
148 // detect failure of this optimization, as in 6366351.)
149 {
150 bool found_trap = false;
151 for (uint i1 = 0; i1 < null_block->number_of_nodes(); i1++) {
152 Node* nn = null_block->get_node(i1);
153 if (nn->is_MachCall() &&
154 nn->as_MachCall()->entry_point() == OptoRuntime::uncommon_trap_blob()->entry_point()) {
155 const Type* trtype = nn->in(TypeFunc::Parms)->bottom_type();
156 if (trtype->isa_int() && trtype->is_int()->is_con()) {
157 jint tr_con = trtype->is_int()->get_con();
158 Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con);
159 Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con);
160 assert((int)reason < (int)BitsPerInt, "recode bit map");
161 if (is_set_nth_bit(allowed_reasons, (int) reason)
162 && action != Deoptimization::Action_none) {
163 // This uncommon trap is sure to recompile, eventually.
164 // When that happens, C->too_many_traps will prevent
165 // this transformation from happening again.
166 found_trap = true;
167 }
168 }
169 break;
170 }
171 }
172 if (!found_trap) {
173 // We did not find an uncommon trap.
174 return;
175 }
176 }
177
178 // Check for decodeHeapOop_not_null node which did not fold into address
179 bool is_decoden = ((intptr_t)val) & 1;
180 val = (Node*)(((intptr_t)val) & ~1);
181
182 assert(!is_decoden ||
183 ((val->in(0) == nullptr) && val->is_Mach() &&
184 (val->as_Mach()->ideal_Opcode() == Op_DecodeN)), "sanity");
185
186 // Search the successor block for a load or store who's base value is also
187 // the tested value. There may be several.
188 MachNode *best = nullptr; // Best found so far
189 for (DUIterator i = val->outs(); val->has_out(i); i++) {
190 Node *m = val->out(i);
191 if( !m->is_Mach() ) continue;
192 MachNode *mach = m->as_Mach();
193 if (mach->barrier_data() != 0 &&
194 !mach->is_late_expanded_null_check_candidate()) {
195 // Using memory accesses with barriers to perform implicit null checks is
196 // only supported if these are explicit marked as emitting a candidate
197 // memory access instruction at their initial address. If not marked as
198 // such, barrier-tagged operations might expand into one or several memory
199 // access instructions located at arbitrary offsets from the initial
200 // address, which would invalidate the implicit null exception table.
201 continue;
202 }
203 was_store = false;
204 int iop = mach->ideal_Opcode();
205 switch( iop ) {
206 case Op_LoadB:
207 case Op_LoadUB:
208 case Op_LoadUS:
209 case Op_LoadD:
210 case Op_LoadF:
211 case Op_LoadI:
212 case Op_LoadL:
213 case Op_LoadP:
214 case Op_LoadN:
215 case Op_LoadS:
216 case Op_LoadKlass:
217 case Op_LoadNKlass:
218 case Op_LoadRange:
219 case Op_LoadD_unaligned:
220 case Op_LoadL_unaligned:
221 assert(mach->in(2) == val, "should be address");
222 break;
223 case Op_StoreB:
224 case Op_StoreC:
225 case Op_StoreD:
226 case Op_StoreF:
227 case Op_StoreI:
228 case Op_StoreL:
229 case Op_StoreLSpecial:
230 case Op_StoreP:
231 case Op_StoreN:
232 case Op_StoreNKlass:
233 was_store = true; // Memory op is a store op
234 // Stores will have their address in slot 2 (memory in slot 1).
235 // If the value being nul-checked is in another slot, it means we
236 // are storing the checked value, which does NOT check the value!
237 if( mach->in(2) != val ) continue;
238 break; // Found a memory op?
239 case Op_StrComp:
240 case Op_StrEquals:
241 case Op_StrIndexOf:
242 case Op_StrIndexOfChar:
243 case Op_AryEq:
244 case Op_VectorizedHashCode:
245 case Op_StrInflatedCopy:
246 case Op_StrCompressedCopy:
247 case Op_EncodeISOArray:
248 case Op_CountPositives:
249 // Not a legit memory op for implicit null check regardless of
250 // embedded loads
251 continue;
252 default: // Also check for embedded loads
253 if( !mach->needs_anti_dependence_check() )
254 continue; // Not an memory op; skip it
255 if( must_clone[iop] ) {
256 // Do not move nodes which produce flags because
257 // RA will try to clone it to place near branch and
258 // it will cause recompilation, see clone_node().
259 continue;
260 }
261 {
262 // Check that value is used in memory address in
263 // instructions with embedded load (CmpP val1,(val2+off)).
264 Node* base;
265 Node* index;
266 const MachOper* oper = mach->memory_inputs(base, index);
267 if (oper == nullptr || oper == (MachOper*)-1) {
268 continue; // Not an memory op; skip it
269 }
270 if (val == base ||
271 (val == index && val->bottom_type()->isa_narrowoop())) {
272 break; // Found it
273 } else {
274 continue; // Skip it
275 }
276 }
277 break;
278 }
279
280 // On some OSes (AIX) the page at address 0 is only write protected.
281 // If so, only Store operations will trap.
282 // But a read accessing the base of a heap-based compressed heap will trap.
283 if (!was_store && needs_explicit_null_check_for_read(val)) {
284 continue;
285 }
286
287 // Check that node's control edge is not-null block's head or dominates it,
288 // otherwise we can't hoist it because there are other control dependencies.
289 Node* ctrl = mach->in(0);
290 if (ctrl != nullptr && !(ctrl == not_null_block->head() ||
291 get_block_for_node(ctrl)->dominates(not_null_block))) {
292 continue;
293 }
294
295 // check if the offset is not too high for implicit exception
296 {
297 intptr_t offset = 0;
298 const TypePtr *adr_type = nullptr; // Do not need this return value here
299 const Node* base = mach->get_base_and_disp(offset, adr_type);
300 if (base == nullptr || base == NodeSentinel) {
301 // Narrow oop address doesn't have base, only index.
302 // Give up if offset is beyond page size or if heap base is not protected.
303 if (val->bottom_type()->isa_narrowoop() &&
304 (MacroAssembler::needs_explicit_null_check(offset) ||
305 !CompressedOops::use_implicit_null_checks()))
306 continue;
307 // cannot reason about it; is probably not implicit null exception
308 } else {
309 const TypePtr* tptr;
310 if ((UseCompressedOops && CompressedOops::shift() == 0) ||
311 (UseCompressedClassPointers && CompressedKlassPointers::shift() == 0)) {
312 // 32-bits narrow oop can be the base of address expressions
313 tptr = base->get_ptr_type();
314 } else {
315 // only regular oops are expected here
316 tptr = base->bottom_type()->is_ptr();
317 }
318 // Give up if offset is not a compile-time constant.
319 if (offset == Type::OffsetBot || tptr->offset() == Type::OffsetBot)
320 continue;
321 offset += tptr->offset(); // correct if base is offsetted
322 // Give up if reference is beyond page size.
323 if (MacroAssembler::needs_explicit_null_check(offset))
324 continue;
325 // Give up if base is a decode node and the heap base is not protected.
326 if (base->is_Mach() && base->as_Mach()->ideal_Opcode() == Op_DecodeN &&
327 !CompressedOops::use_implicit_null_checks())
328 continue;
329 }
330 }
331
332 // Check ctrl input to see if the null-check dominates the memory op
333 Block *cb = get_block_for_node(mach);
334 cb = cb->_idom; // Always hoist at least 1 block
335 if( !was_store ) { // Stores can be hoisted only one block
336 while( cb->_dom_depth > (block->_dom_depth + 1))
337 cb = cb->_idom; // Hoist loads as far as we want
338 // The non-null-block should dominate the memory op, too. Live
339 // range spilling will insert a spill in the non-null-block if it is
340 // needs to spill the memory op for an implicit null check.
341 if (cb->_dom_depth == (block->_dom_depth + 1)) {
342 if (cb != not_null_block) continue;
343 cb = cb->_idom;
344 }
345 }
346 if( cb != block ) continue;
347
348 // Found a memory user; see if it can be hoisted to check-block
349 uint vidx = 0; // Capture index of value into memop
350 uint j;
351 for( j = mach->req()-1; j > 0; j-- ) {
352 if( mach->in(j) == val ) {
353 vidx = j;
354 // Ignore DecodeN val which could be hoisted to where needed.
355 if( is_decoden ) continue;
356 }
357 if (mach->in(j)->is_MachTemp()) {
358 assert(mach->in(j)->outcnt() == 1, "MachTemp nodes should not be shared");
359 // Ignore MachTemp inputs, they can be safely hoisted with the candidate.
360 // MachTemp nodes have no inputs themselves and are only used to reserve
361 // a scratch register for the implementation of the node (e.g. in
362 // late-expanded GC barriers).
363 continue;
364 }
365 // Block of memory-op input
366 Block* inb = get_block_for_node(mach->in(j));
367 if (mach->in(j)->is_Con() && mach->in(j)->req() == 1 && inb == get_block_for_node(mach)) {
368 // Ignore constant loads scheduled in the same block (we can simply hoist them as well)
369 continue;
370 }
371 Block *b = block; // Start from nul check
372 while( b != inb && b->_dom_depth > inb->_dom_depth )
373 b = b->_idom; // search upwards for input
374 // See if input dominates null check
375 if( b != inb )
376 break;
377 }
378 if( j > 0 )
379 continue;
380 Block *mb = get_block_for_node(mach);
381 // Hoisting stores requires more checks for the anti-dependence case.
382 // Give up hoisting if we have to move the store past any load.
383 if (was_store) {
384 // Make sure control does not do a merge (would have to check allpaths)
385 if (mb->num_preds() != 2) {
386 continue;
387 }
388 // mach is a store, hence block is the immediate dominator of mb.
389 // Due to the null-check shape of block (where its successors cannot re-join),
390 // block must be the direct predecessor of mb.
391 assert(get_block_for_node(mb->pred(1)) == block, "Unexpected predecessor block");
392 uint k;
393 uint num_nodes = mb->number_of_nodes();
394 for (k = 1; k < num_nodes; k++) {
395 Node *n = mb->get_node(k);
396 if (n->needs_anti_dependence_check() &&
397 n->in(LoadNode::Memory) == mach->in(StoreNode::Memory)) {
398 break; // Found anti-dependent load
399 }
400 }
401 if (k < num_nodes) {
402 continue; // Found anti-dependent load
403 }
404 }
405
406 // Make sure this memory op is not already being used for a NullCheck
407 Node *e = mb->end();
408 if( e->is_MachNullCheck() && e->in(1) == mach )
409 continue; // Already being used as a null check
410
411 // Found a candidate! Pick one with least dom depth - the highest
412 // in the dom tree should be closest to the null check.
413 if (best == nullptr || get_block_for_node(mach)->_dom_depth < get_block_for_node(best)->_dom_depth) {
414 best = mach;
415 bidx = vidx;
416 }
417 }
418 // No candidate!
419 if (best == nullptr) {
420 return;
421 }
422
423 // ---- Found an implicit null check
424 #ifndef PRODUCT
425 extern uint implicit_null_checks;
426 implicit_null_checks++;
427 #endif
428
429 if( is_decoden ) {
430 // Check if we need to hoist decodeHeapOop_not_null first.
431 Block *valb = get_block_for_node(val);
432 if( block != valb && block->_dom_depth < valb->_dom_depth ) {
433 // Hoist it up to the end of the test block together with its inputs if they exist.
434 for (uint i = 2; i < val->req(); i++) {
435 // DecodeN has 2 regular inputs + optional MachTemp or load Base inputs.
436 // Inputs of val may already be early enough, but if not move them together with val.
437 ensure_node_is_at_block_or_above(val->in(i), block);
438 }
439 move_node_and_its_projections_to_block(val, block);
440 }
441 }
442
443 // Hoist constant load inputs as well.
444 for (uint i = 1; i < best->req(); ++i) {
445 Node* n = best->in(i);
446 if (n->is_Con() && get_block_for_node(n) == get_block_for_node(best)) {
447 get_block_for_node(n)->find_remove(n);
448 block->add_inst(n);
449 map_node_to_block(n, block);
450 // Constant loads may kill flags (for example, when XORing a register).
451 // Check for flag-killing projections that also need to be hoisted.
452 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
453 Node* proj = n->fast_out(j);
454 if (proj->is_MachProj()) {
455 get_block_for_node(proj)->find_remove(proj);
456 block->add_inst(proj);
457 map_node_to_block(proj, block);
458 }
459 }
460 }
461 }
462
463
464 // Move any MachTemp inputs to the end of the test block.
465 for (uint i = 0; i < best->req(); i++) {
466 Node* n = best->in(i);
467 if (n == nullptr || !n->is_MachTemp()) {
468 continue;
469 }
470 ensure_node_is_at_block_or_above(n, block);
471 }
472
473 // Hoist the memory candidate up to the end of the test block.
474 move_node_and_its_projections_to_block(best, block);
475
476 // Move the control dependence if it is pinned to not-null block.
477 // Don't change it in other cases: null or dominating control.
478 Node* ctrl = best->in(0);
479 if (ctrl != nullptr && get_block_for_node(ctrl) == not_null_block) {
480 // Set it to control edge of null check.
481 best->set_req(0, proj->in(0)->in(0));
482 }
483
484 // proj==Op_True --> ne test; proj==Op_False --> eq test.
485 // One of two graph shapes got matched:
486 // (IfTrue (If (Bool NE (CmpP ptr null))))
487 // (IfFalse (If (Bool EQ (CmpP ptr null))))
488 // null checks are always branch-if-eq. If we see a IfTrue projection
489 // then we are replacing a 'ne' test with a 'eq' null check test.
490 // We need to flip the projections to keep the same semantics.
491 if( proj->Opcode() == Op_IfTrue ) {
492 // Swap order of projections in basic block to swap branch targets
493 Node *tmp1 = block->get_node(block->end_idx()+1);
494 Node *tmp2 = block->get_node(block->end_idx()+2);
495 block->map_node(tmp2, block->end_idx()+1);
496 block->map_node(tmp1, block->end_idx()+2);
497 Node *tmp = new Node(C->top()); // Use not null input
498 tmp1->replace_by(tmp);
499 tmp2->replace_by(tmp1);
500 tmp->replace_by(tmp2);
501 tmp->destruct(nullptr);
502 }
503
504 // Remove the existing null check; use a new implicit null check instead.
505 // Since schedule-local needs precise def-use info, we need to correct
506 // it as well.
507 Node *old_tst = proj->in(0);
508 MachNode *nul_chk = new MachNullCheckNode(old_tst->in(0),best,bidx);
509 block->map_node(nul_chk, block->end_idx());
510 map_node_to_block(nul_chk, block);
511 // Redirect users of old_test to nul_chk
512 for (DUIterator_Last i2min, i2 = old_tst->last_outs(i2min); i2 >= i2min; --i2)
513 old_tst->last_out(i2)->set_req(0, nul_chk);
514 // Clean-up any dead code
515 for (uint i3 = 0; i3 < old_tst->req(); i3++) {
516 Node* in = old_tst->in(i3);
517 old_tst->set_req(i3, nullptr);
518 if (in->outcnt() == 0) {
519 // Remove dead input node
520 in->disconnect_inputs(C);
521 block->find_remove(in);
522 }
523 }
524
525 latency_from_uses(nul_chk);
526 latency_from_uses(best);
527
528 // insert anti-dependences to defs in this block
529 if (! best->needs_anti_dependence_check()) {
530 for (uint k = 1; k < block->number_of_nodes(); k++) {
531 Node *n = block->get_node(k);
532 if (n->needs_anti_dependence_check() &&
533 n->in(LoadNode::Memory) == best->in(StoreNode::Memory)) {
534 // Found anti-dependent load
535 raise_above_anti_dependences(block, n);
536 if (C->failing()) {
537 return;
538 }
539 }
540 }
541 }
542 }
543
544
545 //------------------------------select-----------------------------------------
546 // Select a nice fellow from the worklist to schedule next. If there is only one
547 // choice, then use it. CreateEx nodes that are initially ready must start their
548 // blocks and are given the highest priority, by being placed at the beginning
549 // of the worklist. Next after initially-ready CreateEx nodes are projections,
550 // which must follow their parents, and CreateEx nodes with local input
551 // dependencies. Next are constants and CheckCastPP nodes. There are a number of
552 // other special cases, for instructions that consume condition codes, et al.
553 // These are chosen immediately. Some instructions are required to immediately
554 // precede the last instruction in the block, and these are taken last. Of the
555 // remaining cases (most), choose the instruction with the greatest latency
556 // (that is, the most number of pseudo-cycles required to the end of the
557 // routine). If there is a tie, choose the instruction with the most inputs.
558 Node* PhaseCFG::select(
559 Block* block,
560 Node_List &worklist,
561 GrowableArray<int> &ready_cnt,
562 VectorSet &next_call,
563 uint sched_slot,
564 intptr_t* recalc_pressure_nodes) {
565
566 // If only a single entry on the stack, use it
567 uint cnt = worklist.size();
568 if (cnt == 1) {
569 Node *n = worklist[0];
570 worklist.map(0,worklist.pop());
571 return n;
572 }
573
574 uint choice = 0; // Bigger is most important
575 uint latency = 0; // Bigger is scheduled first
576 uint score = 0; // Bigger is better
577 int idx = -1; // Index in worklist
578 int cand_cnt = 0; // Candidate count
579 bool block_size_threshold_ok = (recalc_pressure_nodes != nullptr) && (block->number_of_nodes() > 10);
580
581 for( uint i=0; i<cnt; i++ ) { // Inspect entire worklist
582 // Order in worklist is used to break ties.
583 // See caller for how this is used to delay scheduling
584 // of induction variable increments to after the other
585 // uses of the phi are scheduled.
586 Node *n = worklist[i]; // Get Node on worklist
587
588 int iop = n->is_Mach() ? n->as_Mach()->ideal_Opcode() : 0;
589 if (iop == Op_CreateEx || n->is_Proj()) {
590 // CreateEx nodes that are initially ready must start the block (after Phi
591 // and Parm nodes which are pre-scheduled) and get top priority. This is
592 // currently enforced by placing them at the beginning of the initial
593 // worklist and selecting them eagerly here. After these, projections and
594 // other CreateEx nodes are selected with equal priority.
595 worklist.map(i,worklist.pop());
596 return n;
597 }
598
599 if (n->Opcode() == Op_Con || iop == Op_CheckCastPP) {
600 // Constants and CheckCastPP nodes have higher priority than the rest of
601 // the nodes tested below. Record as current winner, but keep looking for
602 // higher-priority nodes in the worklist.
603 choice = 4;
604 // Latency and score are only used to break ties among low-priority nodes.
605 latency = 0;
606 score = 0;
607 idx = i;
608 continue;
609 }
610
611 // Final call in a block must be adjacent to 'catch'
612 Node *e = block->end();
613 if( e->is_Catch() && e->in(0)->in(0) == n )
614 continue;
615
616 // Memory op for an implicit null check has to be at the end of the block
617 if( e->is_MachNullCheck() && e->in(1) == n )
618 continue;
619
620 // Schedule IV increment last.
621 if (e->is_Mach() && e->as_Mach()->ideal_Opcode() == Op_CountedLoopEnd) {
622 // Cmp might be matched into CountedLoopEnd node.
623 Node *cmp = (e->in(1)->ideal_reg() == Op_RegFlags) ? e->in(1) : e;
624 if (cmp->req() > 1 && cmp->in(1) == n && n->is_iteratively_computed()) {
625 continue;
626 }
627 }
628
629 uint n_choice = 2;
630
631 // See if this instruction is consumed by a branch. If so, then (as the
632 // branch is the last instruction in the basic block) force it to the
633 // end of the basic block
634 if ( must_clone[iop] ) {
635 // See if any use is a branch
636 bool found_machif = false;
637
638 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
639 Node* use = n->fast_out(j);
640
641 // The use is a conditional branch, make them adjacent
642 if (use->is_MachIf() && get_block_for_node(use) == block) {
643 found_machif = true;
644 break;
645 }
646
647 // More than this instruction pending for successor to be ready,
648 // don't choose this if other opportunities are ready
649 if (ready_cnt.at(use->_idx) > 1)
650 n_choice = 1;
651 }
652
653 // loop terminated, prefer not to use this instruction
654 if (found_machif)
655 continue;
656 }
657
658 // See if this has a predecessor that is "must_clone", i.e. sets the
659 // condition code. If so, choose this first
660 for (uint j = 0; j < n->req() ; j++) {
661 Node *inn = n->in(j);
662 if (inn) {
663 if (inn->is_Mach() && must_clone[inn->as_Mach()->ideal_Opcode()] ) {
664 n_choice = 3;
665 break;
666 }
667 }
668 }
669
670 // MachTemps should be scheduled last so they are near their uses
671 if (n->is_MachTemp()) {
672 n_choice = 1;
673 }
674
675 uint n_latency = get_latency_for_node(n);
676 uint n_score = n->req(); // Many inputs get high score to break ties
677
678 if (OptoRegScheduling && block_size_threshold_ok) {
679 if (recalc_pressure_nodes[n->_idx] == 0x7fff7fff) {
680 _regalloc->_scratch_int_pressure.init(_regalloc->_sched_int_pressure.high_pressure_limit());
681 _regalloc->_scratch_float_pressure.init(_regalloc->_sched_float_pressure.high_pressure_limit());
682 // simulate the notion that we just picked this node to schedule
683 n->add_flag(Node::Flag_is_scheduled);
684 // now calculate its effect upon the graph if we did
685 adjust_register_pressure(n, block, recalc_pressure_nodes, false);
686 // return its state for finalize in case somebody else wins
687 n->remove_flag(Node::Flag_is_scheduled);
688 // now save the two final pressure components of register pressure, limiting pressure calcs to short size
689 short int_pressure = (short)_regalloc->_scratch_int_pressure.current_pressure();
690 short float_pressure = (short)_regalloc->_scratch_float_pressure.current_pressure();
691 recalc_pressure_nodes[n->_idx] = int_pressure;
692 recalc_pressure_nodes[n->_idx] |= (float_pressure << 16);
693 }
694
695 if (_scheduling_for_pressure) {
696 latency = n_latency;
697 if (n_choice != 3) {
698 // Now evaluate each register pressure component based on threshold in the score.
699 // In general the defining register type will dominate the score, ergo we will not see register pressure grow on both banks
700 // on a single instruction, but we might see it shrink on both banks.
701 // For each use of register that has a register class that is over the high pressure limit, we build n_score up for
702 // live ranges that terminate on this instruction.
703 if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) {
704 short int_pressure = (short)recalc_pressure_nodes[n->_idx];
705 n_score = (int_pressure < 0) ? ((score + n_score) - int_pressure) : (int_pressure > 0) ? 1 : n_score;
706 }
707 if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) {
708 short float_pressure = (short)(recalc_pressure_nodes[n->_idx] >> 16);
709 n_score = (float_pressure < 0) ? ((score + n_score) - float_pressure) : (float_pressure > 0) ? 1 : n_score;
710 }
711 } else {
712 // make sure we choose these candidates
713 score = 0;
714 }
715 }
716 }
717
718 // Keep best latency found
719 cand_cnt++;
720 if (choice < n_choice ||
721 (choice == n_choice &&
722 ((StressLCM && C->randomized_select(cand_cnt)) ||
723 (!StressLCM &&
724 (latency < n_latency ||
725 (latency == n_latency &&
726 (score < n_score))))))) {
727 choice = n_choice;
728 latency = n_latency;
729 score = n_score;
730 idx = i; // Also keep index in worklist
731 }
732 } // End of for all ready nodes in worklist
733
734 guarantee(idx >= 0, "index should be set");
735 Node *n = worklist[(uint)idx]; // Get the winner
736
737 worklist.map((uint)idx, worklist.pop()); // Compress worklist
738 return n;
739 }
740
741 //-------------------------adjust_register_pressure----------------------------
742 void PhaseCFG::adjust_register_pressure(Node* n, Block* block, intptr_t* recalc_pressure_nodes, bool finalize_mode) {
743 PhaseLive* liveinfo = _regalloc->get_live();
744 IndexSet* liveout = liveinfo->live(block);
745 // first adjust the register pressure for the sources
746 for (uint i = 1; i < n->req(); i++) {
747 bool lrg_ends = false;
748 Node *src_n = n->in(i);
749 if (src_n == nullptr) continue;
750 if (!src_n->is_Mach()) continue;
751 uint src = _regalloc->_lrg_map.find(src_n);
752 if (src == 0) continue;
753 LRG& lrg_src = _regalloc->lrgs(src);
754 // detect if the live range ends or not
755 if (liveout->member(src) == false) {
756 lrg_ends = true;
757 for (DUIterator_Fast jmax, j = src_n->fast_outs(jmax); j < jmax; j++) {
758 Node* m = src_n->fast_out(j); // Get user
759 if (m == n) continue;
760 if (!m->is_Mach()) continue;
761 MachNode *mach = m->as_Mach();
762 bool src_matches = false;
763 int iop = mach->ideal_Opcode();
764
765 switch (iop) {
766 case Op_StoreB:
767 case Op_StoreC:
768 case Op_StoreD:
769 case Op_StoreF:
770 case Op_StoreI:
771 case Op_StoreL:
772 case Op_StoreLSpecial:
773 case Op_StoreP:
774 case Op_StoreN:
775 case Op_StoreVector:
776 case Op_StoreVectorMasked:
777 case Op_StoreVectorScatter:
778 case Op_StoreVectorScatterMasked:
779 case Op_StoreNKlass:
780 for (uint k = 1; k < m->req(); k++) {
781 Node *in = m->in(k);
782 if (in == src_n) {
783 src_matches = true;
784 break;
785 }
786 }
787 break;
788
789 default:
790 src_matches = true;
791 break;
792 }
793
794 // If we have a store as our use, ignore the non source operands
795 if (src_matches == false) continue;
796
797 // Mark every unscheduled use which is not n with a recalculation
798 if ((get_block_for_node(m) == block) && (!m->is_scheduled())) {
799 if (finalize_mode && !m->is_Phi()) {
800 recalc_pressure_nodes[m->_idx] = 0x7fff7fff;
801 }
802 lrg_ends = false;
803 }
804 }
805 }
806 // if none, this live range ends and we can adjust register pressure
807 if (lrg_ends) {
808 if (finalize_mode) {
809 _regalloc->lower_pressure(block, 0, lrg_src, nullptr, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure);
810 } else {
811 _regalloc->lower_pressure(block, 0, lrg_src, nullptr, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure);
812 }
813 }
814 }
815
816 // now add the register pressure from the dest and evaluate which heuristic we should use:
817 // 1.) The default, latency scheduling
818 // 2.) Register pressure scheduling based on the high pressure limit threshold for int or float register stacks
819 uint dst = _regalloc->_lrg_map.find(n);
820 if (dst != 0) {
821 LRG& lrg_dst = _regalloc->lrgs(dst);
822 if (finalize_mode) {
823 _regalloc->raise_pressure(block, lrg_dst, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure);
824 // check to see if we fall over the register pressure cliff here
825 if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) {
826 _scheduling_for_pressure = true;
827 } else if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) {
828 _scheduling_for_pressure = true;
829 } else {
830 // restore latency scheduling mode
831 _scheduling_for_pressure = false;
832 }
833 } else {
834 _regalloc->raise_pressure(block, lrg_dst, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure);
835 }
836 }
837 }
838
839 //------------------------------set_next_call----------------------------------
840 void PhaseCFG::set_next_call(const Block* block, Node* init, VectorSet& next_call) const {
841 Node_List worklist;
842 worklist.push(init);
843
844 while (worklist.size() > 0) {
845 Node* n = worklist.pop();
846 if (next_call.test_set(n->_idx)) continue;
847 for (uint i = 0; i < n->len(); i++) {
848 Node* m = n->in(i);
849 if (m == nullptr) continue; // must see all nodes in block that precede call
850 if (get_block_for_node(m) == block) {
851 worklist.push(m);
852 }
853 }
854 }
855 }
856
857 //------------------------------needed_for_next_call---------------------------
858 // Set the flag 'next_call' for each Node that is needed for the next call to
859 // be scheduled. This flag lets me bias scheduling so Nodes needed for the
860 // next subroutine call get priority - basically it moves things NOT needed
861 // for the next call till after the call. This prevents me from trying to
862 // carry lots of stuff live across a call.
863 void PhaseCFG::needed_for_next_call(Block* block, Node* this_call, VectorSet& next_call) {
864 // Find the next control-defining Node in this block
865 Node* call = nullptr;
866 for (DUIterator_Fast imax, i = this_call->fast_outs(imax); i < imax; i++) {
867 Node* m = this_call->fast_out(i);
868 if (get_block_for_node(m) == block && // Local-block user
869 m != this_call && // Not self-start node
870 m->is_MachCall()) {
871 call = m;
872 break;
873 }
874 }
875 if (call == nullptr) return; // No next call (e.g., block end is near)
876 // Set next-call for all inputs to this call
877 set_next_call(block, call, next_call);
878 }
879
880 //------------------------------add_call_kills-------------------------------------
881 // helper function that adds caller save registers to MachProjNode
882 static void add_call_kills(MachProjNode *proj, RegMask& regs, const char* save_policy, bool exclude_soe) {
883 // Fill in the kill mask for the call
884 for( OptoReg::Name r = OptoReg::Name(0); r < _last_Mach_Reg; r=OptoReg::add(r,1) ) {
885 if( !regs.Member(r) ) { // Not already defined by the call
886 // Save-on-call register?
887 if ((save_policy[r] == 'C') ||
888 (save_policy[r] == 'A') ||
889 ((save_policy[r] == 'E') && exclude_soe)) {
890 proj->_rout.Insert(r);
891 }
892 }
893 }
894 }
895
896
897 //------------------------------sched_call-------------------------------------
898 uint PhaseCFG::sched_call(Block* block, uint node_cnt, Node_List& worklist, GrowableArray<int>& ready_cnt, MachCallNode* mcall, VectorSet& next_call) {
899 ResourceMark rm(C->regmask_arena());
900 RegMask regs(C->regmask_arena());
901
902 // Schedule all the users of the call right now. All the users are
903 // projection Nodes, so they must be scheduled next to the call.
904 // Collect all the defined registers.
905 for (DUIterator_Fast imax, i = mcall->fast_outs(imax); i < imax; i++) {
906 Node* n = mcall->fast_out(i);
907 assert( n->is_MachProj(), "" );
908 int n_cnt = ready_cnt.at(n->_idx)-1;
909 ready_cnt.at_put(n->_idx, n_cnt);
910 assert( n_cnt == 0, "" );
911 // Schedule next to call
912 block->map_node(n, node_cnt++);
913 // Collect defined registers
914 regs.OR(n->out_RegMask());
915 // Check for scheduling the next control-definer
916 if( n->bottom_type() == Type::CONTROL )
917 // Warm up next pile of heuristic bits
918 needed_for_next_call(block, n, next_call);
919
920 // Children of projections are now all ready
921 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
922 Node* m = n->fast_out(j); // Get user
923 if(get_block_for_node(m) != block) {
924 continue;
925 }
926 if( m->is_Phi() ) continue;
927 int m_cnt = ready_cnt.at(m->_idx) - 1;
928 ready_cnt.at_put(m->_idx, m_cnt);
929 if( m_cnt == 0 )
930 worklist.push(m);
931 }
932
933 }
934
935 // Act as if the call defines the Frame Pointer.
936 // Certainly the FP is alive and well after the call.
937 regs.Insert(_matcher.c_frame_pointer());
938
939 // Set all registers killed and not already defined by the call.
940 uint r_cnt = mcall->tf()->range_cc()->cnt();
941 int op = mcall->ideal_Opcode();
942 MachProjNode *proj = new MachProjNode( mcall, r_cnt+1, RegMask::Empty, MachProjNode::fat_proj );
943 map_node_to_block(proj, block);
944 block->insert_node(proj, node_cnt++);
945
946 // Select the right register save policy.
947 const char *save_policy = nullptr;
948 switch (op) {
949 case Op_CallRuntime:
950 case Op_CallLeaf:
951 case Op_CallLeafNoFP:
952 case Op_CallLeafVector:
953 // Calling C code so use C calling convention
954 save_policy = _matcher._c_reg_save_policy;
955 break;
956
957 case Op_CallStaticJava:
958 case Op_CallDynamicJava:
959 // Calling Java code so use Java calling convention
960 save_policy = _matcher._register_save_policy;
961 break;
962
963 default:
964 ShouldNotReachHere();
965 }
966
967 // When using CallRuntime mark SOE registers as killed by the call
968 // so values that could show up in the RegisterMap aren't live in a
969 // callee saved register since the register wouldn't know where to
970 // find them. CallLeaf and CallLeafNoFP are ok because they can't
971 // have debug info on them. Strictly speaking this only needs to be
972 // done for oops since idealreg2debugmask takes care of debug info
973 // references but there no way to handle oops differently than other
974 // pointers as far as the kill mask goes.
975 bool exclude_soe = op == Op_CallRuntime;
976 add_call_kills(proj, regs, save_policy, exclude_soe);
977
978 return node_cnt;
979 }
980
981
982 //------------------------------schedule_local---------------------------------
983 // Topological sort within a block. Someday become a real scheduler.
984 bool PhaseCFG::schedule_local(Block* block, GrowableArray<int>& ready_cnt, VectorSet& next_call, intptr_t *recalc_pressure_nodes) {
985 // Already "sorted" are the block start Node (as the first entry), and
986 // the block-ending Node and any trailing control projections. We leave
987 // these alone. PhiNodes and ParmNodes are made to follow the block start
988 // Node. Everything else gets topo-sorted.
989
990 #ifndef PRODUCT
991 if (trace_opto_pipelining()) {
992 tty->print_cr("# --- schedule_local B%d, before: ---", block->_pre_order);
993 for (uint i = 0;i < block->number_of_nodes(); i++) {
994 tty->print("# ");
995 block->get_node(i)->dump();
996 }
997 tty->print_cr("#");
998 }
999 #endif
1000
1001 // RootNode is already sorted
1002 if (block->number_of_nodes() == 1) {
1003 return true;
1004 }
1005
1006 bool block_size_threshold_ok = (recalc_pressure_nodes != nullptr) && (block->number_of_nodes() > 10);
1007
1008 // We track the uses of local definitions as input dependences so that
1009 // we know when a given instruction is available to be scheduled.
1010 uint i;
1011 if (OptoRegScheduling && block_size_threshold_ok) {
1012 for (i = 1; i < block->number_of_nodes(); i++) { // setup nodes for pressure calc
1013 Node *n = block->get_node(i);
1014 n->remove_flag(Node::Flag_is_scheduled);
1015 if (!n->is_Phi()) {
1016 recalc_pressure_nodes[n->_idx] = 0x7fff7fff;
1017 }
1018 }
1019 }
1020
1021 // Move PhiNodes and ParmNodes from 1 to cnt up to the start
1022 uint node_cnt = block->end_idx();
1023 uint phi_cnt = 1;
1024 for( i = 1; i<node_cnt; i++ ) { // Scan for Phi
1025 Node *n = block->get_node(i);
1026 if( n->is_Phi() || // Found a PhiNode or ParmNode
1027 (n->is_Proj() && n->in(0) == block->head()) ) {
1028 // Move guy at 'phi_cnt' to the end; makes a hole at phi_cnt
1029 block->map_node(block->get_node(phi_cnt), i);
1030 block->map_node(n, phi_cnt++); // swap Phi/Parm up front
1031 if (OptoRegScheduling && block_size_threshold_ok) {
1032 // mark n as scheduled
1033 n->add_flag(Node::Flag_is_scheduled);
1034 }
1035 } else { // All others
1036 // Count block-local inputs to 'n'
1037 uint cnt = n->len(); // Input count
1038 uint local = 0;
1039 for( uint j=0; j<cnt; j++ ) {
1040 Node *m = n->in(j);
1041 if( m && get_block_for_node(m) == block && !m->is_top() )
1042 local++; // One more block-local input
1043 }
1044 ready_cnt.at_put(n->_idx, local); // Count em up
1045 // A few node types require changing a required edge to a precedence edge
1046 // before allocation.
1047 if( n->is_Mach() && n->req() > TypeFunc::Parms &&
1048 (n->as_Mach()->ideal_Opcode() == Op_MemBarAcquire ||
1049 n->as_Mach()->ideal_Opcode() == Op_MemBarVolatile) ) {
1050 // MemBarAcquire could be created without Precedent edge.
1051 // del_req() replaces the specified edge with the last input edge
1052 // and then removes the last edge. If the specified edge > number of
1053 // edges the last edge will be moved outside of the input edges array
1054 // and the edge will be lost. This is why this code should be
1055 // executed only when Precedent (== TypeFunc::Parms) edge is present.
1056 Node *x = n->in(TypeFunc::Parms);
1057 if (x != nullptr && get_block_for_node(x) == block && n->find_prec_edge(x) != -1) {
1058 // Old edge to node within same block will get removed, but no precedence
1059 // edge will get added because it already exists. Update ready count.
1060 int cnt = ready_cnt.at(n->_idx);
1061 assert(cnt > 1, "MemBar node %d must not get ready here", n->_idx);
1062 ready_cnt.at_put(n->_idx, cnt-1);
1063 }
1064 n->del_req(TypeFunc::Parms);
1065 n->add_prec(x);
1066 }
1067 }
1068 }
1069 for(uint i2=i; i2< block->number_of_nodes(); i2++ ) // Trailing guys get zapped count
1070 ready_cnt.at_put(block->get_node(i2)->_idx, 0);
1071
1072 // All the prescheduled guys do not hold back internal nodes
1073 uint i3;
1074 for (i3 = 0; i3 < phi_cnt; i3++) { // For all pre-scheduled
1075 Node *n = block->get_node(i3); // Get pre-scheduled
1076 for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {
1077 Node* m = n->fast_out(j);
1078 if (get_block_for_node(m) == block) { // Local-block user
1079 int m_cnt = ready_cnt.at(m->_idx)-1;
1080 if (OptoRegScheduling && block_size_threshold_ok) {
1081 // mark m as scheduled
1082 if (m_cnt < 0) {
1083 m->add_flag(Node::Flag_is_scheduled);
1084 }
1085 }
1086 ready_cnt.at_put(m->_idx, m_cnt); // Fix ready count
1087 }
1088 }
1089 }
1090
1091 Node_List delay;
1092 // Make a worklist
1093 Node_List worklist;
1094 for(uint i4=i3; i4<node_cnt; i4++ ) { // Put ready guys on worklist
1095 Node *m = block->get_node(i4);
1096 if( !ready_cnt.at(m->_idx) ) { // Zero ready count?
1097 if (m->is_iteratively_computed()) {
1098 // Push induction variable increments last to allow other uses
1099 // of the phi to be scheduled first. The select() method breaks
1100 // ties in scheduling by worklist order.
1101 delay.push(m);
1102 } else if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CreateEx) {
1103 // Place CreateEx nodes that are initially ready at the beginning of the
1104 // worklist so they are selected first and scheduled at the block start.
1105 worklist.insert(0, m);
1106 } else {
1107 worklist.push(m); // Then on to worklist!
1108 }
1109 }
1110 }
1111 while (delay.size()) {
1112 Node* d = delay.pop();
1113 worklist.push(d);
1114 }
1115
1116 if (OptoRegScheduling && block_size_threshold_ok) {
1117 // To stage register pressure calculations we need to examine the live set variables
1118 // breaking them up by register class to compartmentalize the calculations.
1119 _regalloc->_sched_int_pressure.init(Matcher::int_pressure_limit());
1120 _regalloc->_sched_float_pressure.init(Matcher::float_pressure_limit());
1121 _regalloc->_scratch_int_pressure.init(Matcher::int_pressure_limit());
1122 _regalloc->_scratch_float_pressure.init(Matcher::float_pressure_limit());
1123
1124 _regalloc->compute_entry_block_pressure(block);
1125 }
1126
1127 // Warm up the 'next_call' heuristic bits
1128 needed_for_next_call(block, block->head(), next_call);
1129
1130 #ifndef PRODUCT
1131 if (trace_opto_pipelining()) {
1132 for (uint j=0; j< block->number_of_nodes(); j++) {
1133 Node *n = block->get_node(j);
1134 int idx = n->_idx;
1135 tty->print("# ready cnt:%3d ", ready_cnt.at(idx));
1136 tty->print("latency:%3d ", get_latency_for_node(n));
1137 tty->print("%4d: %s\n", idx, n->Name());
1138 }
1139 }
1140 #endif
1141
1142 uint max_idx = (uint)ready_cnt.length();
1143 // Pull from worklist and schedule
1144 while( worklist.size() ) { // Worklist is not ready
1145
1146 #ifndef PRODUCT
1147 if (trace_opto_pipelining()) {
1148 tty->print("# ready list:");
1149 for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
1150 Node *n = worklist[i]; // Get Node on worklist
1151 tty->print(" %d", n->_idx);
1152 }
1153 tty->cr();
1154 }
1155 #endif
1156
1157 // Select and pop a ready guy from worklist
1158 Node* n = select(block, worklist, ready_cnt, next_call, phi_cnt, recalc_pressure_nodes);
1159 block->map_node(n, phi_cnt++); // Schedule him next
1160
1161 if (OptoRegScheduling && block_size_threshold_ok) {
1162 n->add_flag(Node::Flag_is_scheduled);
1163
1164 // Now adjust the resister pressure with the node we selected
1165 if (!n->is_Phi()) {
1166 adjust_register_pressure(n, block, recalc_pressure_nodes, true);
1167 }
1168 }
1169
1170 #ifndef PRODUCT
1171 if (trace_opto_pipelining()) {
1172 tty->print("# select %d: %s", n->_idx, n->Name());
1173 tty->print(", latency:%d", get_latency_for_node(n));
1174 n->dump();
1175 if (Verbose) {
1176 tty->print("# ready list:");
1177 for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist
1178 Node *n = worklist[i]; // Get Node on worklist
1179 tty->print(" %d", n->_idx);
1180 }
1181 tty->cr();
1182 }
1183 }
1184
1185 #endif
1186 if( n->is_MachCall() ) {
1187 MachCallNode *mcall = n->as_MachCall();
1188 phi_cnt = sched_call(block, phi_cnt, worklist, ready_cnt, mcall, next_call);
1189 continue;
1190 }
1191
1192 if (n->is_Mach() && n->as_Mach()->has_call()) {
1193 RegMask regs;
1194 regs.Insert(_matcher.c_frame_pointer());
1195 regs.OR(n->out_RegMask());
1196
1197 MachProjNode *proj = new MachProjNode( n, 1, RegMask::Empty, MachProjNode::fat_proj );
1198 map_node_to_block(proj, block);
1199 block->insert_node(proj, phi_cnt++);
1200
1201 add_call_kills(proj, regs, _matcher._c_reg_save_policy, false);
1202 }
1203
1204 // Children are now all ready
1205 for (DUIterator_Fast i5max, i5 = n->fast_outs(i5max); i5 < i5max; i5++) {
1206 Node* m = n->fast_out(i5); // Get user
1207 if (get_block_for_node(m) != block) {
1208 continue;
1209 }
1210 if( m->is_Phi() ) continue;
1211 if (m->_idx >= max_idx) { // new node, skip it
1212 assert(m->is_MachProj() && n->is_Mach() && n->as_Mach()->has_call(), "unexpected node types");
1213 continue;
1214 }
1215 int m_cnt = ready_cnt.at(m->_idx) - 1;
1216 ready_cnt.at_put(m->_idx, m_cnt);
1217 if( m_cnt == 0 )
1218 worklist.push(m);
1219 }
1220 }
1221
1222 if( phi_cnt != block->end_idx() ) {
1223 // did not schedule all. Retry, Bailout, or Die
1224 if (C->subsume_loads() == true && !C->failing()) {
1225 // Retry with subsume_loads == false
1226 // If this is the first failure, the sentinel string will "stick"
1227 // to the Compile object, and the C2Compiler will see it and retry.
1228 C->record_failure(C2Compiler::retry_no_subsuming_loads());
1229 } else {
1230 assert(C->failure_is_artificial(), "graph should be schedulable");
1231 }
1232 // assert( phi_cnt == end_idx(), "did not schedule all" );
1233 return false;
1234 }
1235
1236 if (OptoRegScheduling && block_size_threshold_ok) {
1237 _regalloc->compute_exit_block_pressure(block);
1238 block->_reg_pressure = _regalloc->_sched_int_pressure.final_pressure();
1239 block->_freg_pressure = _regalloc->_sched_float_pressure.final_pressure();
1240 }
1241
1242 #ifndef PRODUCT
1243 if (trace_opto_pipelining()) {
1244 tty->print_cr("#");
1245 tty->print_cr("# after schedule_local");
1246 for (uint i = 0;i < block->number_of_nodes();i++) {
1247 tty->print("# ");
1248 block->get_node(i)->dump();
1249 }
1250 tty->print_cr("# ");
1251
1252 if (OptoRegScheduling && block_size_threshold_ok) {
1253 tty->print_cr("# pressure info : %d", block->_pre_order);
1254 _regalloc->print_pressure_info(_regalloc->_sched_int_pressure, "int register info");
1255 _regalloc->print_pressure_info(_regalloc->_sched_float_pressure, "float register info");
1256 }
1257 tty->cr();
1258 }
1259 #endif
1260
1261 return true;
1262 }
1263
1264 //--------------------------catch_cleanup_fix_all_inputs-----------------------
1265 static void catch_cleanup_fix_all_inputs(Node *use, Node *old_def, Node *new_def) {
1266 for (uint l = 0; l < use->len(); l++) {
1267 if (use->in(l) == old_def) {
1268 if (l < use->req()) {
1269 use->set_req(l, new_def);
1270 } else {
1271 use->rm_prec(l);
1272 use->add_prec(new_def);
1273 l--;
1274 }
1275 }
1276 }
1277 }
1278
1279 //------------------------------catch_cleanup_find_cloned_def------------------
1280 Node* PhaseCFG::catch_cleanup_find_cloned_def(Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {
1281 assert( use_blk != def_blk, "Inter-block cleanup only");
1282
1283 // The use is some block below the Catch. Find and return the clone of the def
1284 // that dominates the use. If there is no clone in a dominating block, then
1285 // create a phi for the def in a dominating block.
1286
1287 // Find which successor block dominates this use. The successor
1288 // blocks must all be single-entry (from the Catch only; I will have
1289 // split blocks to make this so), hence they all dominate.
1290 while( use_blk->_dom_depth > def_blk->_dom_depth+1 )
1291 use_blk = use_blk->_idom;
1292
1293 // Find the successor
1294 Node *fixup = nullptr;
1295
1296 uint j;
1297 for( j = 0; j < def_blk->_num_succs; j++ )
1298 if( use_blk == def_blk->_succs[j] )
1299 break;
1300
1301 if( j == def_blk->_num_succs ) {
1302 // Block at same level in dom-tree is not a successor. It needs a
1303 // PhiNode, the PhiNode uses from the def and IT's uses need fixup.
1304 Node_Array inputs;
1305 for(uint k = 1; k < use_blk->num_preds(); k++) {
1306 Block* block = get_block_for_node(use_blk->pred(k));
1307 inputs.map(k, catch_cleanup_find_cloned_def(block, def, def_blk, n_clone_idx));
1308 }
1309
1310 // Check to see if the use_blk already has an identical phi inserted.
1311 // If it exists, it will be at the first position since all uses of a
1312 // def are processed together.
1313 Node *phi = use_blk->get_node(1);
1314 if( phi->is_Phi() ) {
1315 fixup = phi;
1316 for (uint k = 1; k < use_blk->num_preds(); k++) {
1317 if (phi->in(k) != inputs[k]) {
1318 // Not a match
1319 fixup = nullptr;
1320 break;
1321 }
1322 }
1323 }
1324
1325 // If an existing PhiNode was not found, make a new one.
1326 if (fixup == nullptr) {
1327 Node *new_phi = PhiNode::make(use_blk->head(), def);
1328 use_blk->insert_node(new_phi, 1);
1329 map_node_to_block(new_phi, use_blk);
1330 for (uint k = 1; k < use_blk->num_preds(); k++) {
1331 new_phi->set_req(k, inputs[k]);
1332 }
1333 fixup = new_phi;
1334 }
1335
1336 } else {
1337 // Found the use just below the Catch. Make it use the clone.
1338 fixup = use_blk->get_node(n_clone_idx);
1339 }
1340
1341 return fixup;
1342 }
1343
1344 //--------------------------catch_cleanup_intra_block--------------------------
1345 // Fix all input edges in use that reference "def". The use is in the same
1346 // block as the def and both have been cloned in each successor block.
1347 static void catch_cleanup_intra_block(Node *use, Node *def, Block *blk, int beg, int n_clone_idx) {
1348
1349 // Both the use and def have been cloned. For each successor block,
1350 // get the clone of the use, and make its input the clone of the def
1351 // found in that block.
1352
1353 uint use_idx = blk->find_node(use);
1354 uint offset_idx = use_idx - beg;
1355 for( uint k = 0; k < blk->_num_succs; k++ ) {
1356 // Get clone in each successor block
1357 Block *sb = blk->_succs[k];
1358 Node *clone = sb->get_node(offset_idx+1);
1359 assert( clone->Opcode() == use->Opcode(), "" );
1360
1361 // Make use-clone reference the def-clone
1362 catch_cleanup_fix_all_inputs(clone, def, sb->get_node(n_clone_idx));
1363 }
1364 }
1365
1366 //------------------------------catch_cleanup_inter_block---------------------
1367 // Fix all input edges in use that reference "def". The use is in a different
1368 // block than the def.
1369 void PhaseCFG::catch_cleanup_inter_block(Node *use, Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {
1370 if( !use_blk ) return; // Can happen if the use is a precedence edge
1371
1372 Node *new_def = catch_cleanup_find_cloned_def(use_blk, def, def_blk, n_clone_idx);
1373 catch_cleanup_fix_all_inputs(use, def, new_def);
1374 }
1375
1376 //------------------------------call_catch_cleanup-----------------------------
1377 // If we inserted any instructions between a Call and his CatchNode,
1378 // clone the instructions on all paths below the Catch.
1379 void PhaseCFG::call_catch_cleanup(Block* block) {
1380
1381 // End of region to clone
1382 uint end = block->end_idx();
1383 if( !block->get_node(end)->is_Catch() ) return;
1384 // Start of region to clone
1385 uint beg = end;
1386 while(!block->get_node(beg-1)->is_MachProj() ||
1387 !block->get_node(beg-1)->in(0)->is_MachCall() ) {
1388 beg--;
1389 assert(beg > 0,"Catch cleanup walking beyond block boundary");
1390 }
1391 // Range of inserted instructions is [beg, end)
1392 if( beg == end ) return;
1393
1394 // Clone along all Catch output paths. Clone area between the 'beg' and
1395 // 'end' indices.
1396 for( uint i = 0; i < block->_num_succs; i++ ) {
1397 Block *sb = block->_succs[i];
1398 // Clone the entire area; ignoring the edge fixup for now.
1399 for( uint j = end; j > beg; j-- ) {
1400 Node *clone = block->get_node(j-1)->clone();
1401 sb->insert_node(clone, 1);
1402 map_node_to_block(clone, sb);
1403 if (clone->needs_anti_dependence_check()) {
1404 raise_above_anti_dependences(sb, clone);
1405 if (C->failing()) {
1406 return;
1407 }
1408 }
1409 }
1410 }
1411
1412
1413 // Fixup edges. Check the def-use info per cloned Node
1414 for(uint i2 = beg; i2 < end; i2++ ) {
1415 uint n_clone_idx = i2-beg+1; // Index of clone of n in each successor block
1416 Node *n = block->get_node(i2); // Node that got cloned
1417 // Need DU safe iterator because of edge manipulation in calls.
1418 Unique_Node_List* out = new Unique_Node_List();
1419 for (DUIterator_Fast j1max, j1 = n->fast_outs(j1max); j1 < j1max; j1++) {
1420 out->push(n->fast_out(j1));
1421 }
1422 uint max = out->size();
1423 for (uint j = 0; j < max; j++) {// For all users
1424 Node *use = out->pop();
1425 Block *buse = get_block_for_node(use);
1426 if( use->is_Phi() ) {
1427 for( uint k = 1; k < use->req(); k++ )
1428 if( use->in(k) == n ) {
1429 Block* b = get_block_for_node(buse->pred(k));
1430 Node *fixup = catch_cleanup_find_cloned_def(b, n, block, n_clone_idx);
1431 use->set_req(k, fixup);
1432 }
1433 } else {
1434 if (block == buse) {
1435 catch_cleanup_intra_block(use, n, block, beg, n_clone_idx);
1436 } else {
1437 catch_cleanup_inter_block(use, buse, n, block, n_clone_idx);
1438 }
1439 }
1440 } // End for all users
1441
1442 } // End of for all Nodes in cloned area
1443
1444 // Remove the now-dead cloned ops
1445 for(uint i3 = beg; i3 < end; i3++ ) {
1446 block->get_node(beg)->disconnect_inputs(C);
1447 block->remove_node(beg);
1448 }
1449
1450 // If the successor blocks have a CreateEx node, move it back to the top
1451 for (uint i4 = 0; i4 < block->_num_succs; i4++) {
1452 Block *sb = block->_succs[i4];
1453 uint new_cnt = end - beg;
1454 // Remove any newly created, but dead, nodes by traversing their schedule
1455 // backwards. Here, a dead node is a node whose only outputs (if any) are
1456 // unused projections.
1457 for (uint j = new_cnt; j > 0; j--) {
1458 Node *n = sb->get_node(j);
1459 // Individual projections are examined together with all siblings when
1460 // their parent is visited.
1461 if (n->is_Proj()) {
1462 continue;
1463 }
1464 bool dead = true;
1465 for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1466 Node* out = n->fast_out(i);
1467 // n is live if it has a non-projection output or a used projection.
1468 if (!out->is_Proj() || out->outcnt() > 0) {
1469 dead = false;
1470 break;
1471 }
1472 }
1473 if (dead) {
1474 // n's only outputs (if any) are unused projections scheduled next to n
1475 // (see PhaseCFG::select()). Remove these projections backwards.
1476 for (uint k = j + n->outcnt(); k > j; k--) {
1477 Node* proj = sb->get_node(k);
1478 assert(proj->is_Proj() && proj->in(0) == n,
1479 "projection should correspond to dead node");
1480 proj->disconnect_inputs(C);
1481 sb->remove_node(k);
1482 new_cnt--;
1483 }
1484 // Now remove the node itself.
1485 n->disconnect_inputs(C);
1486 sb->remove_node(j);
1487 new_cnt--;
1488 }
1489 }
1490 // If any newly created nodes remain, move the CreateEx node to the top
1491 if (new_cnt > 0) {
1492 Node *cex = sb->get_node(1+new_cnt);
1493 if( cex->is_Mach() && cex->as_Mach()->ideal_Opcode() == Op_CreateEx ) {
1494 sb->remove_node(1+new_cnt);
1495 sb->insert_node(cex, 1);
1496 }
1497 }
1498 }
1499 }