jdk
1/*
2* Copyright (c) 1998, 2024, 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 "precompiled.hpp"26#include "asm/macroAssembler.inline.hpp"27#include "gc/shared/gc_globals.hpp"28#include "memory/allocation.inline.hpp"29#include "oops/compressedOops.hpp"30#include "opto/ad.hpp"31#include "opto/block.hpp"32#include "opto/c2compiler.hpp"33#include "opto/callnode.hpp"34#include "opto/cfgnode.hpp"35#include "opto/machnode.hpp"36#include "opto/runtime.hpp"37#include "opto/chaitin.hpp"38#include "runtime/os.inline.hpp"39#include "runtime/sharedRuntime.hpp"40
41// Optimization - Graph Style
42
43// Check whether val is not-null-decoded compressed oop,
44// i.e. will grab into the base of the heap if it represents null.
45static bool accesses_heap_base_zone(Node *val) {46if (CompressedOops::base() != nullptr) { // Implies UseCompressedOops.47if (val && val->is_Mach()) {48if (val->as_Mach()->ideal_Opcode() == Op_DecodeN) {49// This assumes all Decodes with TypePtr::NotNull are matched to nodes that50// decode null to point to the heap base (Decode_NN).51if (val->bottom_type()->is_oopptr()->ptr() == TypePtr::NotNull) {52return true;53}54}55// Must recognize load operation with Decode matched in memory operand.56// We should not reach here except for PPC/AIX, as os::zero_page_read_protected()57// returns true everywhere else. On PPC, no such memory operands58// exist, therefore we did not yet implement a check for such operands.59NOT_AIX(Unimplemented());60}61}62return false;63}
64
65static bool needs_explicit_null_check_for_read(Node *val) {66// On some OSes (AIX) the page at address 0 is only write protected.67// If so, only Store operations will trap.68if (os::zero_page_read_protected()) {69return false; // Implicit null check will work.70}71// Also a read accessing the base of a heap-based compressed heap will trap.72if (accesses_heap_base_zone(val) && // Hits the base zone page.73CompressedOops::use_implicit_null_checks()) { // Base zone page is protected.74return false;75}76
77return true;78}
79
80//------------------------------implicit_null_check----------------------------
81// Detect implicit-null-check opportunities. Basically, find null checks
82// with suitable memory ops nearby. Use the memory op to do the null check.
83// I can generate a memory op if there is not one nearby.
84// The proj is the control projection for the not-null case.
85// The val is the pointer being checked for nullness or
86// decodeHeapOop_not_null node if it did not fold into address.
87void PhaseCFG::implicit_null_check(Block* block, Node *proj, Node *val, int allowed_reasons) {88// Assume if null check need for 0 offset then always needed89// Intel solaris doesn't support any null checks yet and no90// mechanism exists (yet) to set the switches at an os_cpu level91if( !ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(0)) return;92
93// Make sure the ptr-is-null path appears to be uncommon!94float f = block->end()->as_MachIf()->_prob;95if( proj->Opcode() == Op_IfTrue ) f = 1.0f - f;96if( f > PROB_UNLIKELY_MAG(4) ) return;97
98uint bidx = 0; // Capture index of value into memop99bool was_store; // Memory op is a store op100
101// Get the successor block for if the test ptr is non-null102Block* not_null_block; // this one goes with the proj103Block* null_block;104if (block->get_node(block->number_of_nodes()-1) == proj) {105null_block = block->_succs[0];106not_null_block = block->_succs[1];107} else {108assert(block->get_node(block->number_of_nodes()-2) == proj, "proj is one or the other");109not_null_block = block->_succs[0];110null_block = block->_succs[1];111}112while (null_block->is_Empty() == Block::empty_with_goto) {113null_block = null_block->_succs[0];114}115
116// Search the exception block for an uncommon trap.117// (See Parse::do_if and Parse::do_ifnull for the reason118// we need an uncommon trap. Briefly, we need a way to119// detect failure of this optimization, as in 6366351.)120{121bool found_trap = false;122for (uint i1 = 0; i1 < null_block->number_of_nodes(); i1++) {123Node* nn = null_block->get_node(i1);124if (nn->is_MachCall() &&125nn->as_MachCall()->entry_point() == SharedRuntime::uncommon_trap_blob()->entry_point()) {126const Type* trtype = nn->in(TypeFunc::Parms)->bottom_type();127if (trtype->isa_int() && trtype->is_int()->is_con()) {128jint tr_con = trtype->is_int()->get_con();129Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(tr_con);130Deoptimization::DeoptAction action = Deoptimization::trap_request_action(tr_con);131assert((int)reason < (int)BitsPerInt, "recode bit map");132if (is_set_nth_bit(allowed_reasons, (int) reason)133&& action != Deoptimization::Action_none) {134// This uncommon trap is sure to recompile, eventually.135// When that happens, C->too_many_traps will prevent136// this transformation from happening again.137found_trap = true;138}139}140break;141}142}143if (!found_trap) {144// We did not find an uncommon trap.145return;146}147}148
149// Check for decodeHeapOop_not_null node which did not fold into address150bool is_decoden = ((intptr_t)val) & 1;151val = (Node*)(((intptr_t)val) & ~1);152
153assert(!is_decoden ||154((val->in(0) == nullptr) && val->is_Mach() &&155(val->as_Mach()->ideal_Opcode() == Op_DecodeN)), "sanity");156
157// Search the successor block for a load or store who's base value is also158// the tested value. There may be several.159MachNode *best = nullptr; // Best found so far160for (DUIterator i = val->outs(); val->has_out(i); i++) {161Node *m = val->out(i);162if( !m->is_Mach() ) continue;163MachNode *mach = m->as_Mach();164was_store = false;165int iop = mach->ideal_Opcode();166switch( iop ) {167case Op_LoadB:168case Op_LoadUB:169case Op_LoadUS:170case Op_LoadD:171case Op_LoadF:172case Op_LoadI:173case Op_LoadL:174case Op_LoadP:175case Op_LoadN:176case Op_LoadS:177case Op_LoadKlass:178case Op_LoadNKlass:179case Op_LoadRange:180case Op_LoadD_unaligned:181case Op_LoadL_unaligned:182assert(mach->in(2) == val, "should be address");183break;184case Op_StoreB:185case Op_StoreC:186case Op_StoreCM:187case Op_StoreD:188case Op_StoreF:189case Op_StoreI:190case Op_StoreL:191case Op_StoreP:192case Op_StoreN:193case Op_StoreNKlass:194was_store = true; // Memory op is a store op195// Stores will have their address in slot 2 (memory in slot 1).196// If the value being nul-checked is in another slot, it means we197// are storing the checked value, which does NOT check the value!198if( mach->in(2) != val ) continue;199break; // Found a memory op?200case Op_StrComp:201case Op_StrEquals:202case Op_StrIndexOf:203case Op_StrIndexOfChar:204case Op_AryEq:205case Op_VectorizedHashCode:206case Op_StrInflatedCopy:207case Op_StrCompressedCopy:208case Op_EncodeISOArray:209case Op_CountPositives:210// Not a legit memory op for implicit null check regardless of211// embedded loads212continue;213default: // Also check for embedded loads214if( !mach->needs_anti_dependence_check() )215continue; // Not an memory op; skip it216if( must_clone[iop] ) {217// Do not move nodes which produce flags because218// RA will try to clone it to place near branch and219// it will cause recompilation, see clone_node().220continue;221}222{223// Check that value is used in memory address in224// instructions with embedded load (CmpP val1,(val2+off)).225Node* base;226Node* index;227const MachOper* oper = mach->memory_inputs(base, index);228if (oper == nullptr || oper == (MachOper*)-1) {229continue; // Not an memory op; skip it230}231if (val == base ||232(val == index && val->bottom_type()->isa_narrowoop())) {233break; // Found it234} else {235continue; // Skip it236}237}238break;239}240
241// On some OSes (AIX) the page at address 0 is only write protected.242// If so, only Store operations will trap.243// But a read accessing the base of a heap-based compressed heap will trap.244if (!was_store && needs_explicit_null_check_for_read(val)) {245continue;246}247
248// Check that node's control edge is not-null block's head or dominates it,249// otherwise we can't hoist it because there are other control dependencies.250Node* ctrl = mach->in(0);251if (ctrl != nullptr && !(ctrl == not_null_block->head() ||252get_block_for_node(ctrl)->dominates(not_null_block))) {253continue;254}255
256// check if the offset is not too high for implicit exception257{258intptr_t offset = 0;259const TypePtr *adr_type = nullptr; // Do not need this return value here260const Node* base = mach->get_base_and_disp(offset, adr_type);261if (base == nullptr || base == NodeSentinel) {262// Narrow oop address doesn't have base, only index.263// Give up if offset is beyond page size or if heap base is not protected.264if (val->bottom_type()->isa_narrowoop() &&265(MacroAssembler::needs_explicit_null_check(offset) ||266!CompressedOops::use_implicit_null_checks()))267continue;268// cannot reason about it; is probably not implicit null exception269} else {270const TypePtr* tptr;271if ((UseCompressedOops || UseCompressedClassPointers) &&272(CompressedOops::shift() == 0 || CompressedKlassPointers::shift() == 0)) {273// 32-bits narrow oop can be the base of address expressions274tptr = base->get_ptr_type();275} else {276// only regular oops are expected here277tptr = base->bottom_type()->is_ptr();278}279// Give up if offset is not a compile-time constant.280if (offset == Type::OffsetBot || tptr->_offset == Type::OffsetBot)281continue;282offset += tptr->_offset; // correct if base is offsetted283// Give up if reference is beyond page size.284if (MacroAssembler::needs_explicit_null_check(offset))285continue;286// Give up if base is a decode node and the heap base is not protected.287if (base->is_Mach() && base->as_Mach()->ideal_Opcode() == Op_DecodeN &&288!CompressedOops::use_implicit_null_checks())289continue;290}291}292
293// Check ctrl input to see if the null-check dominates the memory op294Block *cb = get_block_for_node(mach);295cb = cb->_idom; // Always hoist at least 1 block296if( !was_store ) { // Stores can be hoisted only one block297while( cb->_dom_depth > (block->_dom_depth + 1))298cb = cb->_idom; // Hoist loads as far as we want299// The non-null-block should dominate the memory op, too. Live300// range spilling will insert a spill in the non-null-block if it is301// needs to spill the memory op for an implicit null check.302if (cb->_dom_depth == (block->_dom_depth + 1)) {303if (cb != not_null_block) continue;304cb = cb->_idom;305}306}307if( cb != block ) continue;308
309// Found a memory user; see if it can be hoisted to check-block310uint vidx = 0; // Capture index of value into memop311uint j;312for( j = mach->req()-1; j > 0; j-- ) {313if( mach->in(j) == val ) {314vidx = j;315// Ignore DecodeN val which could be hoisted to where needed.316if( is_decoden ) continue;317}318// Block of memory-op input319Block *inb = get_block_for_node(mach->in(j));320Block *b = block; // Start from nul check321while( b != inb && b->_dom_depth > inb->_dom_depth )322b = b->_idom; // search upwards for input323// See if input dominates null check324if( b != inb )325break;326}327if( j > 0 )328continue;329Block *mb = get_block_for_node(mach);330// Hoisting stores requires more checks for the anti-dependence case.331// Give up hoisting if we have to move the store past any load.332if (was_store) {333// Make sure control does not do a merge (would have to check allpaths)334if (mb->num_preds() != 2) {335continue;336}337// mach is a store, hence block is the immediate dominator of mb.338// Due to the null-check shape of block (where its successors cannot re-join),339// block must be the direct predecessor of mb.340assert(get_block_for_node(mb->pred(1)) == block, "Unexpected predecessor block");341uint k;342uint num_nodes = mb->number_of_nodes();343for (k = 1; k < num_nodes; k++) {344Node *n = mb->get_node(k);345if (n->needs_anti_dependence_check() &&346n->in(LoadNode::Memory) == mach->in(StoreNode::Memory)) {347break; // Found anti-dependent load348}349}350if (k < num_nodes) {351continue; // Found anti-dependent load352}353}354
355// Make sure this memory op is not already being used for a NullCheck356Node *e = mb->end();357if( e->is_MachNullCheck() && e->in(1) == mach )358continue; // Already being used as a null check359
360// Found a candidate! Pick one with least dom depth - the highest361// in the dom tree should be closest to the null check.362if (best == nullptr || get_block_for_node(mach)->_dom_depth < get_block_for_node(best)->_dom_depth) {363best = mach;364bidx = vidx;365}366}367// No candidate!368if (best == nullptr) {369return;370}371
372// ---- Found an implicit null check373#ifndef PRODUCT374extern uint implicit_null_checks;375implicit_null_checks++;376#endif377
378if( is_decoden ) {379// Check if we need to hoist decodeHeapOop_not_null first.380Block *valb = get_block_for_node(val);381if( block != valb && block->_dom_depth < valb->_dom_depth ) {382// Hoist it up to the end of the test block together with its inputs if they exist.383for (uint i = 2; i < val->req(); i++) {384// DecodeN has 2 regular inputs + optional MachTemp or load Base inputs.385Node *temp = val->in(i);386Block *tempb = get_block_for_node(temp);387if (!tempb->dominates(block)) {388assert(block->dominates(tempb), "sanity check: temp node placement");389// We only expect nodes without further inputs, like MachTemp or load Base.390assert(temp->req() == 0 || (temp->req() == 1 && temp->in(0) == (Node*)C->root()),391"need for recursive hoisting not expected");392tempb->find_remove(temp);393block->add_inst(temp);394map_node_to_block(temp, block);395}396}397valb->find_remove(val);398block->add_inst(val);399map_node_to_block(val, block);400// DecodeN on x86 may kill flags. Check for flag-killing projections401// that also need to be hoisted.402for (DUIterator_Fast jmax, j = val->fast_outs(jmax); j < jmax; j++) {403Node* n = val->fast_out(j);404if( n->is_MachProj() ) {405get_block_for_node(n)->find_remove(n);406block->add_inst(n);407map_node_to_block(n, block);408}409}410}411}412// Hoist the memory candidate up to the end of the test block.413Block *old_block = get_block_for_node(best);414old_block->find_remove(best);415block->add_inst(best);416map_node_to_block(best, block);417
418// Move the control dependence if it is pinned to not-null block.419// Don't change it in other cases: null or dominating control.420Node* ctrl = best->in(0);421if (ctrl != nullptr && get_block_for_node(ctrl) == not_null_block) {422// Set it to control edge of null check.423best->set_req(0, proj->in(0)->in(0));424}425
426// Check for flag-killing projections that also need to be hoisted427// Should be DU safe because no edge updates.428for (DUIterator_Fast jmax, j = best->fast_outs(jmax); j < jmax; j++) {429Node* n = best->fast_out(j);430if( n->is_MachProj() ) {431get_block_for_node(n)->find_remove(n);432block->add_inst(n);433map_node_to_block(n, block);434}435}436
437// proj==Op_True --> ne test; proj==Op_False --> eq test.438// One of two graph shapes got matched:439// (IfTrue (If (Bool NE (CmpP ptr null))))440// (IfFalse (If (Bool EQ (CmpP ptr null))))441// null checks are always branch-if-eq. If we see a IfTrue projection442// then we are replacing a 'ne' test with a 'eq' null check test.443// We need to flip the projections to keep the same semantics.444if( proj->Opcode() == Op_IfTrue ) {445// Swap order of projections in basic block to swap branch targets446Node *tmp1 = block->get_node(block->end_idx()+1);447Node *tmp2 = block->get_node(block->end_idx()+2);448block->map_node(tmp2, block->end_idx()+1);449block->map_node(tmp1, block->end_idx()+2);450Node *tmp = new Node(C->top()); // Use not null input451tmp1->replace_by(tmp);452tmp2->replace_by(tmp1);453tmp->replace_by(tmp2);454tmp->destruct(nullptr);455}456
457// Remove the existing null check; use a new implicit null check instead.458// Since schedule-local needs precise def-use info, we need to correct459// it as well.460Node *old_tst = proj->in(0);461MachNode *nul_chk = new MachNullCheckNode(old_tst->in(0),best,bidx);462block->map_node(nul_chk, block->end_idx());463map_node_to_block(nul_chk, block);464// Redirect users of old_test to nul_chk465for (DUIterator_Last i2min, i2 = old_tst->last_outs(i2min); i2 >= i2min; --i2)466old_tst->last_out(i2)->set_req(0, nul_chk);467// Clean-up any dead code468for (uint i3 = 0; i3 < old_tst->req(); i3++) {469Node* in = old_tst->in(i3);470old_tst->set_req(i3, nullptr);471if (in->outcnt() == 0) {472// Remove dead input node473in->disconnect_inputs(C);474block->find_remove(in);475}476}477
478latency_from_uses(nul_chk);479latency_from_uses(best);480
481// insert anti-dependences to defs in this block482if (! best->needs_anti_dependence_check()) {483for (uint k = 1; k < block->number_of_nodes(); k++) {484Node *n = block->get_node(k);485if (n->needs_anti_dependence_check() &&486n->in(LoadNode::Memory) == best->in(StoreNode::Memory)) {487// Found anti-dependent load488insert_anti_dependences(block, n);489}490}491}492}
493
494
495//------------------------------select-----------------------------------------
496// Select a nice fellow from the worklist to schedule next. If there is only one
497// choice, then use it. CreateEx nodes that are initially ready must start their
498// blocks and are given the highest priority, by being placed at the beginning
499// of the worklist. Next after initially-ready CreateEx nodes are projections,
500// which must follow their parents, and CreateEx nodes with local input
501// dependencies. Next are constants and CheckCastPP nodes. There are a number of
502// other special cases, for instructions that consume condition codes, et al.
503// These are chosen immediately. Some instructions are required to immediately
504// precede the last instruction in the block, and these are taken last. Of the
505// remaining cases (most), choose the instruction with the greatest latency
506// (that is, the most number of pseudo-cycles required to the end of the
507// routine). If there is a tie, choose the instruction with the most inputs.
508Node* PhaseCFG::select(509Block* block,510Node_List &worklist,511GrowableArray<int> &ready_cnt,512VectorSet &next_call,513uint sched_slot,514intptr_t* recalc_pressure_nodes) {515
516// If only a single entry on the stack, use it517uint cnt = worklist.size();518if (cnt == 1) {519Node *n = worklist[0];520worklist.map(0,worklist.pop());521return n;522}523
524uint choice = 0; // Bigger is most important525uint latency = 0; // Bigger is scheduled first526uint score = 0; // Bigger is better527int idx = -1; // Index in worklist528int cand_cnt = 0; // Candidate count529bool block_size_threshold_ok = (recalc_pressure_nodes != nullptr) && (block->number_of_nodes() > 10);530
531for( uint i=0; i<cnt; i++ ) { // Inspect entire worklist532// Order in worklist is used to break ties.533// See caller for how this is used to delay scheduling534// of induction variable increments to after the other535// uses of the phi are scheduled.536Node *n = worklist[i]; // Get Node on worklist537
538int iop = n->is_Mach() ? n->as_Mach()->ideal_Opcode() : 0;539if (iop == Op_CreateEx || n->is_Proj()) {540// CreateEx nodes that are initially ready must start the block (after Phi541// and Parm nodes which are pre-scheduled) and get top priority. This is542// currently enforced by placing them at the beginning of the initial543// worklist and selecting them eagerly here. After these, projections and544// other CreateEx nodes are selected with equal priority.545worklist.map(i,worklist.pop());546return n;547}548
549if (n->Opcode() == Op_Con || iop == Op_CheckCastPP) {550// Constants and CheckCastPP nodes have higher priority than the rest of551// the nodes tested below. Record as current winner, but keep looking for552// higher-priority nodes in the worklist.553choice = 4;554// Latency and score are only used to break ties among low-priority nodes.555latency = 0;556score = 0;557idx = i;558continue;559}560
561// Final call in a block must be adjacent to 'catch'562Node *e = block->end();563if( e->is_Catch() && e->in(0)->in(0) == n )564continue;565
566// Memory op for an implicit null check has to be at the end of the block567if( e->is_MachNullCheck() && e->in(1) == n )568continue;569
570// Schedule IV increment last.571if (e->is_Mach() && e->as_Mach()->ideal_Opcode() == Op_CountedLoopEnd) {572// Cmp might be matched into CountedLoopEnd node.573Node *cmp = (e->in(1)->ideal_reg() == Op_RegFlags) ? e->in(1) : e;574if (cmp->req() > 1 && cmp->in(1) == n && n->is_iteratively_computed()) {575continue;576}577}578
579uint n_choice = 2;580
581// See if this instruction is consumed by a branch. If so, then (as the582// branch is the last instruction in the basic block) force it to the583// end of the basic block584if ( must_clone[iop] ) {585// See if any use is a branch586bool found_machif = false;587
588for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {589Node* use = n->fast_out(j);590
591// The use is a conditional branch, make them adjacent592if (use->is_MachIf() && get_block_for_node(use) == block) {593found_machif = true;594break;595}596
597// More than this instruction pending for successor to be ready,598// don't choose this if other opportunities are ready599if (ready_cnt.at(use->_idx) > 1)600n_choice = 1;601}602
603// loop terminated, prefer not to use this instruction604if (found_machif)605continue;606}607
608// See if this has a predecessor that is "must_clone", i.e. sets the609// condition code. If so, choose this first610for (uint j = 0; j < n->req() ; j++) {611Node *inn = n->in(j);612if (inn) {613if (inn->is_Mach() && must_clone[inn->as_Mach()->ideal_Opcode()] ) {614n_choice = 3;615break;616}617}618}619
620// MachTemps should be scheduled last so they are near their uses621if (n->is_MachTemp()) {622n_choice = 1;623}624
625uint n_latency = get_latency_for_node(n);626uint n_score = n->req(); // Many inputs get high score to break ties627
628if (OptoRegScheduling && block_size_threshold_ok) {629if (recalc_pressure_nodes[n->_idx] == 0x7fff7fff) {630_regalloc->_scratch_int_pressure.init(_regalloc->_sched_int_pressure.high_pressure_limit());631_regalloc->_scratch_float_pressure.init(_regalloc->_sched_float_pressure.high_pressure_limit());632// simulate the notion that we just picked this node to schedule633n->add_flag(Node::Flag_is_scheduled);634// now calculate its effect upon the graph if we did635adjust_register_pressure(n, block, recalc_pressure_nodes, false);636// return its state for finalize in case somebody else wins637n->remove_flag(Node::Flag_is_scheduled);638// now save the two final pressure components of register pressure, limiting pressure calcs to short size639short int_pressure = (short)_regalloc->_scratch_int_pressure.current_pressure();640short float_pressure = (short)_regalloc->_scratch_float_pressure.current_pressure();641recalc_pressure_nodes[n->_idx] = int_pressure;642recalc_pressure_nodes[n->_idx] |= (float_pressure << 16);643}644
645if (_scheduling_for_pressure) {646latency = n_latency;647if (n_choice != 3) {648// Now evaluate each register pressure component based on threshold in the score.649// In general the defining register type will dominate the score, ergo we will not see register pressure grow on both banks650// on a single instruction, but we might see it shrink on both banks.651// For each use of register that has a register class that is over the high pressure limit, we build n_score up for652// live ranges that terminate on this instruction.653if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) {654short int_pressure = (short)recalc_pressure_nodes[n->_idx];655n_score = (int_pressure < 0) ? ((score + n_score) - int_pressure) : (int_pressure > 0) ? 1 : n_score;656}657if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) {658short float_pressure = (short)(recalc_pressure_nodes[n->_idx] >> 16);659n_score = (float_pressure < 0) ? ((score + n_score) - float_pressure) : (float_pressure > 0) ? 1 : n_score;660}661} else {662// make sure we choose these candidates663score = 0;664}665}666}667
668// Keep best latency found669cand_cnt++;670if (choice < n_choice ||671(choice == n_choice &&672((StressLCM && C->randomized_select(cand_cnt)) ||673(!StressLCM &&674(latency < n_latency ||675(latency == n_latency &&676(score < n_score))))))) {677choice = n_choice;678latency = n_latency;679score = n_score;680idx = i; // Also keep index in worklist681}682} // End of for all ready nodes in worklist683
684guarantee(idx >= 0, "index should be set");685Node *n = worklist[(uint)idx]; // Get the winner686
687worklist.map((uint)idx, worklist.pop()); // Compress worklist688return n;689}
690
691//-------------------------adjust_register_pressure----------------------------
692void PhaseCFG::adjust_register_pressure(Node* n, Block* block, intptr_t* recalc_pressure_nodes, bool finalize_mode) {693PhaseLive* liveinfo = _regalloc->get_live();694IndexSet* liveout = liveinfo->live(block);695// first adjust the register pressure for the sources696for (uint i = 1; i < n->req(); i++) {697bool lrg_ends = false;698Node *src_n = n->in(i);699if (src_n == nullptr) continue;700if (!src_n->is_Mach()) continue;701uint src = _regalloc->_lrg_map.find(src_n);702if (src == 0) continue;703LRG& lrg_src = _regalloc->lrgs(src);704// detect if the live range ends or not705if (liveout->member(src) == false) {706lrg_ends = true;707for (DUIterator_Fast jmax, j = src_n->fast_outs(jmax); j < jmax; j++) {708Node* m = src_n->fast_out(j); // Get user709if (m == n) continue;710if (!m->is_Mach()) continue;711MachNode *mach = m->as_Mach();712bool src_matches = false;713int iop = mach->ideal_Opcode();714
715switch (iop) {716case Op_StoreB:717case Op_StoreC:718case Op_StoreCM:719case Op_StoreD:720case Op_StoreF:721case Op_StoreI:722case Op_StoreL:723case Op_StoreP:724case Op_StoreN:725case Op_StoreVector:726case Op_StoreVectorMasked:727case Op_StoreVectorScatter:728case Op_StoreVectorScatterMasked:729case Op_StoreNKlass:730for (uint k = 1; k < m->req(); k++) {731Node *in = m->in(k);732if (in == src_n) {733src_matches = true;734break;735}736}737break;738
739default:740src_matches = true;741break;742}743
744// If we have a store as our use, ignore the non source operands745if (src_matches == false) continue;746
747// Mark every unscheduled use which is not n with a recalculation748if ((get_block_for_node(m) == block) && (!m->is_scheduled())) {749if (finalize_mode && !m->is_Phi()) {750recalc_pressure_nodes[m->_idx] = 0x7fff7fff;751}752lrg_ends = false;753}754}755}756// if none, this live range ends and we can adjust register pressure757if (lrg_ends) {758if (finalize_mode) {759_regalloc->lower_pressure(block, 0, lrg_src, nullptr, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure);760} else {761_regalloc->lower_pressure(block, 0, lrg_src, nullptr, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure);762}763}764}765
766// now add the register pressure from the dest and evaluate which heuristic we should use:767// 1.) The default, latency scheduling768// 2.) Register pressure scheduling based on the high pressure limit threshold for int or float register stacks769uint dst = _regalloc->_lrg_map.find(n);770if (dst != 0) {771LRG& lrg_dst = _regalloc->lrgs(dst);772if (finalize_mode) {773_regalloc->raise_pressure(block, lrg_dst, _regalloc->_sched_int_pressure, _regalloc->_sched_float_pressure);774// check to see if we fall over the register pressure cliff here775if (_regalloc->_sched_int_pressure.current_pressure() > _regalloc->_sched_int_pressure.high_pressure_limit()) {776_scheduling_for_pressure = true;777} else if (_regalloc->_sched_float_pressure.current_pressure() > _regalloc->_sched_float_pressure.high_pressure_limit()) {778_scheduling_for_pressure = true;779} else {780// restore latency scheduling mode781_scheduling_for_pressure = false;782}783} else {784_regalloc->raise_pressure(block, lrg_dst, _regalloc->_scratch_int_pressure, _regalloc->_scratch_float_pressure);785}786}787}
788
789//------------------------------set_next_call----------------------------------
790void PhaseCFG::set_next_call(Block* block, Node* n, VectorSet& next_call) {791if( next_call.test_set(n->_idx) ) return;792for( uint i=0; i<n->len(); i++ ) {793Node *m = n->in(i);794if( !m ) continue; // must see all nodes in block that precede call795if (get_block_for_node(m) == block) {796set_next_call(block, m, next_call);797}798}799}
800
801//------------------------------needed_for_next_call---------------------------
802// Set the flag 'next_call' for each Node that is needed for the next call to
803// be scheduled. This flag lets me bias scheduling so Nodes needed for the
804// next subroutine call get priority - basically it moves things NOT needed
805// for the next call till after the call. This prevents me from trying to
806// carry lots of stuff live across a call.
807void PhaseCFG::needed_for_next_call(Block* block, Node* this_call, VectorSet& next_call) {808// Find the next control-defining Node in this block809Node* call = nullptr;810for (DUIterator_Fast imax, i = this_call->fast_outs(imax); i < imax; i++) {811Node* m = this_call->fast_out(i);812if (get_block_for_node(m) == block && // Local-block user813m != this_call && // Not self-start node814m->is_MachCall()) {815call = m;816break;817}818}819if (call == nullptr) return; // No next call (e.g., block end is near)820// Set next-call for all inputs to this call821set_next_call(block, call, next_call);822}
823
824//------------------------------add_call_kills-------------------------------------
825// helper function that adds caller save registers to MachProjNode
826static void add_call_kills(MachProjNode *proj, RegMask& regs, const char* save_policy, bool exclude_soe) {827// Fill in the kill mask for the call828for( OptoReg::Name r = OptoReg::Name(0); r < _last_Mach_Reg; r=OptoReg::add(r,1) ) {829if( !regs.Member(r) ) { // Not already defined by the call830// Save-on-call register?831if ((save_policy[r] == 'C') ||832(save_policy[r] == 'A') ||833((save_policy[r] == 'E') && exclude_soe)) {834proj->_rout.Insert(r);835}836}837}838}
839
840
841//------------------------------sched_call-------------------------------------
842uint PhaseCFG::sched_call(Block* block, uint node_cnt, Node_List& worklist, GrowableArray<int>& ready_cnt, MachCallNode* mcall, VectorSet& next_call) {843RegMask regs;844
845// Schedule all the users of the call right now. All the users are846// projection Nodes, so they must be scheduled next to the call.847// Collect all the defined registers.848for (DUIterator_Fast imax, i = mcall->fast_outs(imax); i < imax; i++) {849Node* n = mcall->fast_out(i);850assert( n->is_MachProj(), "" );851int n_cnt = ready_cnt.at(n->_idx)-1;852ready_cnt.at_put(n->_idx, n_cnt);853assert( n_cnt == 0, "" );854// Schedule next to call855block->map_node(n, node_cnt++);856// Collect defined registers857regs.OR(n->out_RegMask());858// Check for scheduling the next control-definer859if( n->bottom_type() == Type::CONTROL )860// Warm up next pile of heuristic bits861needed_for_next_call(block, n, next_call);862
863// Children of projections are now all ready864for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {865Node* m = n->fast_out(j); // Get user866if(get_block_for_node(m) != block) {867continue;868}869if( m->is_Phi() ) continue;870int m_cnt = ready_cnt.at(m->_idx) - 1;871ready_cnt.at_put(m->_idx, m_cnt);872if( m_cnt == 0 )873worklist.push(m);874}875
876}877
878// Act as if the call defines the Frame Pointer.879// Certainly the FP is alive and well after the call.880regs.Insert(_matcher.c_frame_pointer());881
882// Set all registers killed and not already defined by the call.883uint r_cnt = mcall->tf()->range()->cnt();884int op = mcall->ideal_Opcode();885MachProjNode *proj = new MachProjNode( mcall, r_cnt+1, RegMask::Empty, MachProjNode::fat_proj );886map_node_to_block(proj, block);887block->insert_node(proj, node_cnt++);888
889// Select the right register save policy.890const char *save_policy = nullptr;891switch (op) {892case Op_CallRuntime:893case Op_CallLeaf:894case Op_CallLeafNoFP:895case Op_CallLeafVector:896// Calling C code so use C calling convention897save_policy = _matcher._c_reg_save_policy;898break;899
900case Op_CallStaticJava:901case Op_CallDynamicJava:902// Calling Java code so use Java calling convention903save_policy = _matcher._register_save_policy;904break;905
906default:907ShouldNotReachHere();908}909
910// When using CallRuntime mark SOE registers as killed by the call911// so values that could show up in the RegisterMap aren't live in a912// callee saved register since the register wouldn't know where to913// find them. CallLeaf and CallLeafNoFP are ok because they can't914// have debug info on them. Strictly speaking this only needs to be915// done for oops since idealreg2debugmask takes care of debug info916// references but there no way to handle oops differently than other917// pointers as far as the kill mask goes.918bool exclude_soe = op == Op_CallRuntime;919
920// If the call is a MethodHandle invoke, we need to exclude the921// register which is used to save the SP value over MH invokes from922// the mask. Otherwise this register could be used for923// deoptimization information.924if (op == Op_CallStaticJava) {925MachCallStaticJavaNode* mcallstaticjava = (MachCallStaticJavaNode*) mcall;926if (mcallstaticjava->_method_handle_invoke)927proj->_rout.OR(Matcher::method_handle_invoke_SP_save_mask());928}929
930add_call_kills(proj, regs, save_policy, exclude_soe);931
932return node_cnt;933}
934
935
936//------------------------------schedule_local---------------------------------
937// Topological sort within a block. Someday become a real scheduler.
938bool PhaseCFG::schedule_local(Block* block, GrowableArray<int>& ready_cnt, VectorSet& next_call, intptr_t *recalc_pressure_nodes) {939// Already "sorted" are the block start Node (as the first entry), and940// the block-ending Node and any trailing control projections. We leave941// these alone. PhiNodes and ParmNodes are made to follow the block start942// Node. Everything else gets topo-sorted.943
944#ifndef PRODUCT945if (trace_opto_pipelining()) {946tty->print_cr("# --- schedule_local B%d, before: ---", block->_pre_order);947for (uint i = 0;i < block->number_of_nodes(); i++) {948tty->print("# ");949block->get_node(i)->dump();950}951tty->print_cr("#");952}953#endif954
955// RootNode is already sorted956if (block->number_of_nodes() == 1) {957return true;958}959
960bool block_size_threshold_ok = (recalc_pressure_nodes != nullptr) && (block->number_of_nodes() > 10);961
962// We track the uses of local definitions as input dependences so that963// we know when a given instruction is available to be scheduled.964uint i;965if (OptoRegScheduling && block_size_threshold_ok) {966for (i = 1; i < block->number_of_nodes(); i++) { // setup nodes for pressure calc967Node *n = block->get_node(i);968n->remove_flag(Node::Flag_is_scheduled);969if (!n->is_Phi()) {970recalc_pressure_nodes[n->_idx] = 0x7fff7fff;971}972}973}974
975// Move PhiNodes and ParmNodes from 1 to cnt up to the start976uint node_cnt = block->end_idx();977uint phi_cnt = 1;978for( i = 1; i<node_cnt; i++ ) { // Scan for Phi979Node *n = block->get_node(i);980if( n->is_Phi() || // Found a PhiNode or ParmNode981(n->is_Proj() && n->in(0) == block->head()) ) {982// Move guy at 'phi_cnt' to the end; makes a hole at phi_cnt983block->map_node(block->get_node(phi_cnt), i);984block->map_node(n, phi_cnt++); // swap Phi/Parm up front985if (OptoRegScheduling && block_size_threshold_ok) {986// mark n as scheduled987n->add_flag(Node::Flag_is_scheduled);988}989} else { // All others990// Count block-local inputs to 'n'991uint cnt = n->len(); // Input count992uint local = 0;993for( uint j=0; j<cnt; j++ ) {994Node *m = n->in(j);995if( m && get_block_for_node(m) == block && !m->is_top() )996local++; // One more block-local input997}998ready_cnt.at_put(n->_idx, local); // Count em up999
1000#ifdef ASSERT1001if (UseG1GC) {1002if( n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_StoreCM ) {1003// Check the precedence edges1004for (uint prec = n->req(); prec < n->len(); prec++) {1005Node* oop_store = n->in(prec);1006if (oop_store != nullptr) {1007assert(get_block_for_node(oop_store)->_dom_depth <= block->_dom_depth, "oop_store must dominate card-mark");1008}1009}1010}1011}1012#endif1013
1014// A few node types require changing a required edge to a precedence edge1015// before allocation.1016if( n->is_Mach() && n->req() > TypeFunc::Parms &&1017(n->as_Mach()->ideal_Opcode() == Op_MemBarAcquire ||1018n->as_Mach()->ideal_Opcode() == Op_MemBarVolatile) ) {1019// MemBarAcquire could be created without Precedent edge.1020// del_req() replaces the specified edge with the last input edge1021// and then removes the last edge. If the specified edge > number of1022// edges the last edge will be moved outside of the input edges array1023// and the edge will be lost. This is why this code should be1024// executed only when Precedent (== TypeFunc::Parms) edge is present.1025Node *x = n->in(TypeFunc::Parms);1026if (x != nullptr && get_block_for_node(x) == block && n->find_prec_edge(x) != -1) {1027// Old edge to node within same block will get removed, but no precedence1028// edge will get added because it already exists. Update ready count.1029int cnt = ready_cnt.at(n->_idx);1030assert(cnt > 1, "MemBar node %d must not get ready here", n->_idx);1031ready_cnt.at_put(n->_idx, cnt-1);1032}1033n->del_req(TypeFunc::Parms);1034n->add_prec(x);1035}1036}1037}1038for(uint i2=i; i2< block->number_of_nodes(); i2++ ) // Trailing guys get zapped count1039ready_cnt.at_put(block->get_node(i2)->_idx, 0);1040
1041// All the prescheduled guys do not hold back internal nodes1042uint i3;1043for (i3 = 0; i3 < phi_cnt; i3++) { // For all pre-scheduled1044Node *n = block->get_node(i3); // Get pre-scheduled1045for (DUIterator_Fast jmax, j = n->fast_outs(jmax); j < jmax; j++) {1046Node* m = n->fast_out(j);1047if (get_block_for_node(m) == block) { // Local-block user1048int m_cnt = ready_cnt.at(m->_idx)-1;1049if (OptoRegScheduling && block_size_threshold_ok) {1050// mark m as scheduled1051if (m_cnt < 0) {1052m->add_flag(Node::Flag_is_scheduled);1053}1054}1055ready_cnt.at_put(m->_idx, m_cnt); // Fix ready count1056}1057}1058}1059
1060Node_List delay;1061// Make a worklist1062Node_List worklist;1063for(uint i4=i3; i4<node_cnt; i4++ ) { // Put ready guys on worklist1064Node *m = block->get_node(i4);1065if( !ready_cnt.at(m->_idx) ) { // Zero ready count?1066if (m->is_iteratively_computed()) {1067// Push induction variable increments last to allow other uses1068// of the phi to be scheduled first. The select() method breaks1069// ties in scheduling by worklist order.1070delay.push(m);1071} else if (m->is_Mach() && m->as_Mach()->ideal_Opcode() == Op_CreateEx) {1072// Place CreateEx nodes that are initially ready at the beginning of the1073// worklist so they are selected first and scheduled at the block start.1074worklist.insert(0, m);1075} else {1076worklist.push(m); // Then on to worklist!1077}1078}1079}1080while (delay.size()) {1081Node* d = delay.pop();1082worklist.push(d);1083}1084
1085if (OptoRegScheduling && block_size_threshold_ok) {1086// To stage register pressure calculations we need to examine the live set variables1087// breaking them up by register class to compartmentalize the calculations.1088_regalloc->_sched_int_pressure.init(Matcher::int_pressure_limit());1089_regalloc->_sched_float_pressure.init(Matcher::float_pressure_limit());1090_regalloc->_scratch_int_pressure.init(Matcher::int_pressure_limit());1091_regalloc->_scratch_float_pressure.init(Matcher::float_pressure_limit());1092
1093_regalloc->compute_entry_block_pressure(block);1094}1095
1096// Warm up the 'next_call' heuristic bits1097needed_for_next_call(block, block->head(), next_call);1098
1099#ifndef PRODUCT1100if (trace_opto_pipelining()) {1101for (uint j=0; j< block->number_of_nodes(); j++) {1102Node *n = block->get_node(j);1103int idx = n->_idx;1104tty->print("# ready cnt:%3d ", ready_cnt.at(idx));1105tty->print("latency:%3d ", get_latency_for_node(n));1106tty->print("%4d: %s\n", idx, n->Name());1107}1108}1109#endif1110
1111uint max_idx = (uint)ready_cnt.length();1112// Pull from worklist and schedule1113while( worklist.size() ) { // Worklist is not ready1114
1115#ifndef PRODUCT1116if (trace_opto_pipelining()) {1117tty->print("# ready list:");1118for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist1119Node *n = worklist[i]; // Get Node on worklist1120tty->print(" %d", n->_idx);1121}1122tty->cr();1123}1124#endif1125
1126// Select and pop a ready guy from worklist1127Node* n = select(block, worklist, ready_cnt, next_call, phi_cnt, recalc_pressure_nodes);1128block->map_node(n, phi_cnt++); // Schedule him next1129
1130if (OptoRegScheduling && block_size_threshold_ok) {1131n->add_flag(Node::Flag_is_scheduled);1132
1133// Now adjust the resister pressure with the node we selected1134if (!n->is_Phi()) {1135adjust_register_pressure(n, block, recalc_pressure_nodes, true);1136}1137}1138
1139#ifndef PRODUCT1140if (trace_opto_pipelining()) {1141tty->print("# select %d: %s", n->_idx, n->Name());1142tty->print(", latency:%d", get_latency_for_node(n));1143n->dump();1144if (Verbose) {1145tty->print("# ready list:");1146for( uint i=0; i<worklist.size(); i++ ) { // Inspect entire worklist1147Node *n = worklist[i]; // Get Node on worklist1148tty->print(" %d", n->_idx);1149}1150tty->cr();1151}1152}1153
1154#endif1155if( n->is_MachCall() ) {1156MachCallNode *mcall = n->as_MachCall();1157phi_cnt = sched_call(block, phi_cnt, worklist, ready_cnt, mcall, next_call);1158continue;1159}1160
1161if (n->is_Mach() && n->as_Mach()->has_call()) {1162RegMask regs;1163regs.Insert(_matcher.c_frame_pointer());1164regs.OR(n->out_RegMask());1165
1166MachProjNode *proj = new MachProjNode( n, 1, RegMask::Empty, MachProjNode::fat_proj );1167map_node_to_block(proj, block);1168block->insert_node(proj, phi_cnt++);1169
1170add_call_kills(proj, regs, _matcher._c_reg_save_policy, false);1171}1172
1173// Children are now all ready1174for (DUIterator_Fast i5max, i5 = n->fast_outs(i5max); i5 < i5max; i5++) {1175Node* m = n->fast_out(i5); // Get user1176if (get_block_for_node(m) != block) {1177continue;1178}1179if( m->is_Phi() ) continue;1180if (m->_idx >= max_idx) { // new node, skip it1181assert(m->is_MachProj() && n->is_Mach() && n->as_Mach()->has_call(), "unexpected node types");1182continue;1183}1184int m_cnt = ready_cnt.at(m->_idx) - 1;1185ready_cnt.at_put(m->_idx, m_cnt);1186if( m_cnt == 0 )1187worklist.push(m);1188}1189}1190
1191if( phi_cnt != block->end_idx() ) {1192// did not schedule all. Retry, Bailout, or Die1193if (C->subsume_loads() == true && !C->failing()) {1194// Retry with subsume_loads == false1195// If this is the first failure, the sentinel string will "stick"1196// to the Compile object, and the C2Compiler will see it and retry.1197C->record_failure(C2Compiler::retry_no_subsuming_loads());1198} else {1199assert(false, "graph should be schedulable");1200}1201// assert( phi_cnt == end_idx(), "did not schedule all" );1202return false;1203}1204
1205if (OptoRegScheduling && block_size_threshold_ok) {1206_regalloc->compute_exit_block_pressure(block);1207block->_reg_pressure = _regalloc->_sched_int_pressure.final_pressure();1208block->_freg_pressure = _regalloc->_sched_float_pressure.final_pressure();1209}1210
1211#ifndef PRODUCT1212if (trace_opto_pipelining()) {1213tty->print_cr("#");1214tty->print_cr("# after schedule_local");1215for (uint i = 0;i < block->number_of_nodes();i++) {1216tty->print("# ");1217block->get_node(i)->dump();1218}1219tty->print_cr("# ");1220
1221if (OptoRegScheduling && block_size_threshold_ok) {1222tty->print_cr("# pressure info : %d", block->_pre_order);1223_regalloc->print_pressure_info(_regalloc->_sched_int_pressure, "int register info");1224_regalloc->print_pressure_info(_regalloc->_sched_float_pressure, "float register info");1225}1226tty->cr();1227}1228#endif1229
1230return true;1231}
1232
1233//--------------------------catch_cleanup_fix_all_inputs-----------------------
1234static void catch_cleanup_fix_all_inputs(Node *use, Node *old_def, Node *new_def) {1235for (uint l = 0; l < use->len(); l++) {1236if (use->in(l) == old_def) {1237if (l < use->req()) {1238use->set_req(l, new_def);1239} else {1240use->rm_prec(l);1241use->add_prec(new_def);1242l--;1243}1244}1245}1246}
1247
1248//------------------------------catch_cleanup_find_cloned_def------------------
1249Node* PhaseCFG::catch_cleanup_find_cloned_def(Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {1250assert( use_blk != def_blk, "Inter-block cleanup only");1251
1252// The use is some block below the Catch. Find and return the clone of the def1253// that dominates the use. If there is no clone in a dominating block, then1254// create a phi for the def in a dominating block.1255
1256// Find which successor block dominates this use. The successor1257// blocks must all be single-entry (from the Catch only; I will have1258// split blocks to make this so), hence they all dominate.1259while( use_blk->_dom_depth > def_blk->_dom_depth+1 )1260use_blk = use_blk->_idom;1261
1262// Find the successor1263Node *fixup = nullptr;1264
1265uint j;1266for( j = 0; j < def_blk->_num_succs; j++ )1267if( use_blk == def_blk->_succs[j] )1268break;1269
1270if( j == def_blk->_num_succs ) {1271// Block at same level in dom-tree is not a successor. It needs a1272// PhiNode, the PhiNode uses from the def and IT's uses need fixup.1273Node_Array inputs;1274for(uint k = 1; k < use_blk->num_preds(); k++) {1275Block* block = get_block_for_node(use_blk->pred(k));1276inputs.map(k, catch_cleanup_find_cloned_def(block, def, def_blk, n_clone_idx));1277}1278
1279// Check to see if the use_blk already has an identical phi inserted.1280// If it exists, it will be at the first position since all uses of a1281// def are processed together.1282Node *phi = use_blk->get_node(1);1283if( phi->is_Phi() ) {1284fixup = phi;1285for (uint k = 1; k < use_blk->num_preds(); k++) {1286if (phi->in(k) != inputs[k]) {1287// Not a match1288fixup = nullptr;1289break;1290}1291}1292}1293
1294// If an existing PhiNode was not found, make a new one.1295if (fixup == nullptr) {1296Node *new_phi = PhiNode::make(use_blk->head(), def);1297use_blk->insert_node(new_phi, 1);1298map_node_to_block(new_phi, use_blk);1299for (uint k = 1; k < use_blk->num_preds(); k++) {1300new_phi->set_req(k, inputs[k]);1301}1302fixup = new_phi;1303}1304
1305} else {1306// Found the use just below the Catch. Make it use the clone.1307fixup = use_blk->get_node(n_clone_idx);1308}1309
1310return fixup;1311}
1312
1313//--------------------------catch_cleanup_intra_block--------------------------
1314// Fix all input edges in use that reference "def". The use is in the same
1315// block as the def and both have been cloned in each successor block.
1316static void catch_cleanup_intra_block(Node *use, Node *def, Block *blk, int beg, int n_clone_idx) {1317
1318// Both the use and def have been cloned. For each successor block,1319// get the clone of the use, and make its input the clone of the def1320// found in that block.1321
1322uint use_idx = blk->find_node(use);1323uint offset_idx = use_idx - beg;1324for( uint k = 0; k < blk->_num_succs; k++ ) {1325// Get clone in each successor block1326Block *sb = blk->_succs[k];1327Node *clone = sb->get_node(offset_idx+1);1328assert( clone->Opcode() == use->Opcode(), "" );1329
1330// Make use-clone reference the def-clone1331catch_cleanup_fix_all_inputs(clone, def, sb->get_node(n_clone_idx));1332}1333}
1334
1335//------------------------------catch_cleanup_inter_block---------------------
1336// Fix all input edges in use that reference "def". The use is in a different
1337// block than the def.
1338void PhaseCFG::catch_cleanup_inter_block(Node *use, Block *use_blk, Node *def, Block *def_blk, int n_clone_idx) {1339if( !use_blk ) return; // Can happen if the use is a precedence edge1340
1341Node *new_def = catch_cleanup_find_cloned_def(use_blk, def, def_blk, n_clone_idx);1342catch_cleanup_fix_all_inputs(use, def, new_def);1343}
1344
1345//------------------------------call_catch_cleanup-----------------------------
1346// If we inserted any instructions between a Call and his CatchNode,
1347// clone the instructions on all paths below the Catch.
1348void PhaseCFG::call_catch_cleanup(Block* block) {1349
1350// End of region to clone1351uint end = block->end_idx();1352if( !block->get_node(end)->is_Catch() ) return;1353// Start of region to clone1354uint beg = end;1355while(!block->get_node(beg-1)->is_MachProj() ||1356!block->get_node(beg-1)->in(0)->is_MachCall() ) {1357beg--;1358assert(beg > 0,"Catch cleanup walking beyond block boundary");1359}1360// Range of inserted instructions is [beg, end)1361if( beg == end ) return;1362
1363// Clone along all Catch output paths. Clone area between the 'beg' and1364// 'end' indices.1365for( uint i = 0; i < block->_num_succs; i++ ) {1366Block *sb = block->_succs[i];1367// Clone the entire area; ignoring the edge fixup for now.1368for( uint j = end; j > beg; j-- ) {1369Node *clone = block->get_node(j-1)->clone();1370sb->insert_node(clone, 1);1371map_node_to_block(clone, sb);1372if (clone->needs_anti_dependence_check()) {1373insert_anti_dependences(sb, clone);1374}1375}1376}1377
1378
1379// Fixup edges. Check the def-use info per cloned Node1380for(uint i2 = beg; i2 < end; i2++ ) {1381uint n_clone_idx = i2-beg+1; // Index of clone of n in each successor block1382Node *n = block->get_node(i2); // Node that got cloned1383// Need DU safe iterator because of edge manipulation in calls.1384Unique_Node_List* out = new Unique_Node_List();1385for (DUIterator_Fast j1max, j1 = n->fast_outs(j1max); j1 < j1max; j1++) {1386out->push(n->fast_out(j1));1387}1388uint max = out->size();1389for (uint j = 0; j < max; j++) {// For all users1390Node *use = out->pop();1391Block *buse = get_block_for_node(use);1392if( use->is_Phi() ) {1393for( uint k = 1; k < use->req(); k++ )1394if( use->in(k) == n ) {1395Block* b = get_block_for_node(buse->pred(k));1396Node *fixup = catch_cleanup_find_cloned_def(b, n, block, n_clone_idx);1397use->set_req(k, fixup);1398}1399} else {1400if (block == buse) {1401catch_cleanup_intra_block(use, n, block, beg, n_clone_idx);1402} else {1403catch_cleanup_inter_block(use, buse, n, block, n_clone_idx);1404}1405}1406} // End for all users1407
1408} // End of for all Nodes in cloned area1409
1410// Remove the now-dead cloned ops1411for(uint i3 = beg; i3 < end; i3++ ) {1412block->get_node(beg)->disconnect_inputs(C);1413block->remove_node(beg);1414}1415
1416// If the successor blocks have a CreateEx node, move it back to the top1417for (uint i4 = 0; i4 < block->_num_succs; i4++) {1418Block *sb = block->_succs[i4];1419uint new_cnt = end - beg;1420// Remove any newly created, but dead, nodes by traversing their schedule1421// backwards. Here, a dead node is a node whose only outputs (if any) are1422// unused projections.1423for (uint j = new_cnt; j > 0; j--) {1424Node *n = sb->get_node(j);1425// Individual projections are examined together with all siblings when1426// their parent is visited.1427if (n->is_Proj()) {1428continue;1429}1430bool dead = true;1431for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {1432Node* out = n->fast_out(i);1433// n is live if it has a non-projection output or a used projection.1434if (!out->is_Proj() || out->outcnt() > 0) {1435dead = false;1436break;1437}1438}1439if (dead) {1440// n's only outputs (if any) are unused projections scheduled next to n1441// (see PhaseCFG::select()). Remove these projections backwards.1442for (uint k = j + n->outcnt(); k > j; k--) {1443Node* proj = sb->get_node(k);1444assert(proj->is_Proj() && proj->in(0) == n,1445"projection should correspond to dead node");1446proj->disconnect_inputs(C);1447sb->remove_node(k);1448new_cnt--;1449}1450// Now remove the node itself.1451n->disconnect_inputs(C);1452sb->remove_node(j);1453new_cnt--;1454}1455}1456// If any newly created nodes remain, move the CreateEx node to the top1457if (new_cnt > 0) {1458Node *cex = sb->get_node(1+new_cnt);1459if( cex->is_Mach() && cex->as_Mach()->ideal_Opcode() == Op_CreateEx ) {1460sb->remove_node(1+new_cnt);1461sb->insert_node(cex, 1);1462}1463}1464}1465}
1466