Path: blob/master/src/hotspot/share/opto/block.cpp
40930 views
/*1* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "libadt/vectset.hpp"26#include "memory/allocation.inline.hpp"27#include "memory/resourceArea.hpp"28#include "compiler/compilerDirectives.hpp"29#include "opto/block.hpp"30#include "opto/cfgnode.hpp"31#include "opto/chaitin.hpp"32#include "opto/loopnode.hpp"33#include "opto/machnode.hpp"34#include "opto/matcher.hpp"35#include "opto/opcodes.hpp"36#include "opto/rootnode.hpp"37#include "utilities/copy.hpp"38#include "utilities/powerOfTwo.hpp"3940void Block_Array::grow( uint i ) {41assert(i >= Max(), "must be an overflow");42debug_only(_limit = i+1);43if( i < _size ) return;44if( !_size ) {45_size = 1;46_blocks = (Block**)_arena->Amalloc( _size * sizeof(Block*) );47_blocks[0] = NULL;48}49uint old = _size;50_size = next_power_of_2(i);51_blocks = (Block**)_arena->Arealloc( _blocks, old*sizeof(Block*),_size*sizeof(Block*));52Copy::zero_to_bytes( &_blocks[old], (_size-old)*sizeof(Block*) );53}5455void Block_List::remove(uint i) {56assert(i < _cnt, "index out of bounds");57Copy::conjoint_words_to_lower((HeapWord*)&_blocks[i+1], (HeapWord*)&_blocks[i], ((_cnt-i-1)*sizeof(Block*)));58pop(); // shrink list by one block59}6061void Block_List::insert(uint i, Block *b) {62push(b); // grow list by one block63Copy::conjoint_words_to_higher((HeapWord*)&_blocks[i], (HeapWord*)&_blocks[i+1], ((_cnt-i-1)*sizeof(Block*)));64_blocks[i] = b;65}6667#ifndef PRODUCT68void Block_List::print() {69for (uint i=0; i < size(); i++) {70tty->print("B%d ", _blocks[i]->_pre_order);71}72tty->print("size = %d\n", size());73}74#endif7576uint Block::code_alignment() const {77// Check for Root block78if (_pre_order == 0) return CodeEntryAlignment;79// Check for Start block80if (_pre_order == 1) return InteriorEntryAlignment;81// Check for loop alignment82if (has_loop_alignment()) return loop_alignment();8384return relocInfo::addr_unit(); // no particular alignment85}8687uint Block::compute_loop_alignment() {88Node *h = head();89int unit_sz = relocInfo::addr_unit();90if (h->is_Loop() && h->as_Loop()->is_inner_loop()) {91// Pre- and post-loops have low trip count so do not bother with92// NOPs for align loop head. The constants are hidden from tuning93// but only because my "divide by 4" heuristic surely gets nearly94// all possible gain (a "do not align at all" heuristic has a95// chance of getting a really tiny gain).96if (h->is_CountedLoop() && (h->as_CountedLoop()->is_pre_loop() ||97h->as_CountedLoop()->is_post_loop())) {98return (OptoLoopAlignment > 4*unit_sz) ? (OptoLoopAlignment>>2) : unit_sz;99}100// Loops with low backedge frequency should not be aligned.101Node *n = h->in(LoopNode::LoopBackControl)->in(0);102if (n->is_MachIf() && n->as_MachIf()->_prob < 0.01) {103return unit_sz; // Loop does not loop, more often than not!104}105return OptoLoopAlignment; // Otherwise align loop head106}107108return unit_sz; // no particular alignment109}110111// Compute the size of first 'inst_cnt' instructions in this block.112// Return the number of instructions left to compute if the block has113// less then 'inst_cnt' instructions. Stop, and return 0 if sum_size114// exceeds OptoLoopAlignment.115uint Block::compute_first_inst_size(uint& sum_size, uint inst_cnt,116PhaseRegAlloc* ra) {117uint last_inst = number_of_nodes();118for( uint j = 0; j < last_inst && inst_cnt > 0; j++ ) {119uint inst_size = get_node(j)->size(ra);120if( inst_size > 0 ) {121inst_cnt--;122uint sz = sum_size + inst_size;123if( sz <= (uint)OptoLoopAlignment ) {124// Compute size of instructions which fit into fetch buffer only125// since all inst_cnt instructions will not fit even if we align them.126sum_size = sz;127} else {128return 0;129}130}131}132return inst_cnt;133}134135uint Block::find_node( const Node *n ) const {136for( uint i = 0; i < number_of_nodes(); i++ ) {137if( get_node(i) == n )138return i;139}140ShouldNotReachHere();141return 0;142}143144// Find and remove n from block list145void Block::find_remove( const Node *n ) {146remove_node(find_node(n));147}148149bool Block::contains(const Node *n) const {150return _nodes.contains(n);151}152153// Return empty status of a block. Empty blocks contain only the head, other154// ideal nodes, and an optional trailing goto.155int Block::is_Empty() const {156157// Root or start block is not considered empty158if (head()->is_Root() || head()->is_Start()) {159return not_empty;160}161162int success_result = completely_empty;163int end_idx = number_of_nodes() - 1;164165// Check for ending goto166if ((end_idx > 0) && (get_node(end_idx)->is_MachGoto())) {167success_result = empty_with_goto;168end_idx--;169}170171// Unreachable blocks are considered empty172if (num_preds() <= 1) {173return success_result;174}175176// Ideal nodes are allowable in empty blocks: skip them Only MachNodes177// turn directly into code, because only MachNodes have non-trivial178// emit() functions.179while ((end_idx > 0) && !get_node(end_idx)->is_Mach()) {180end_idx--;181}182183// No room for any interesting instructions?184if (end_idx == 0) {185return success_result;186}187188return not_empty;189}190191// Return true if the block's code implies that it is likely to be192// executed infrequently. Check to see if the block ends in a Halt or193// a low probability call.194bool Block::has_uncommon_code() const {195Node* en = end();196197if (en->is_MachGoto())198en = en->in(0);199if (en->is_Catch())200en = en->in(0);201if (en->is_MachProj() && en->in(0)->is_MachCall()) {202MachCallNode* call = en->in(0)->as_MachCall();203if (call->cnt() != COUNT_UNKNOWN && call->cnt() <= PROB_UNLIKELY_MAG(4)) {204// This is true for slow-path stubs like new_{instance,array},205// slow_arraycopy, complete_monitor_locking, uncommon_trap.206// The magic number corresponds to the probability of an uncommon_trap,207// even though it is a count not a probability.208return true;209}210}211212int op = en->is_Mach() ? en->as_Mach()->ideal_Opcode() : en->Opcode();213return op == Op_Halt;214}215216// True if block is low enough frequency or guarded by a test which217// mostly does not go here.218bool PhaseCFG::is_uncommon(const Block* block) {219// Initial blocks must never be moved, so are never uncommon.220if (block->head()->is_Root() || block->head()->is_Start()) return false;221222// Check for way-low freq223if(block->_freq < BLOCK_FREQUENCY(0.00001f) ) return true;224225// Look for code shape indicating uncommon_trap or slow path226if (block->has_uncommon_code()) return true;227228const float epsilon = 0.05f;229const float guard_factor = PROB_UNLIKELY_MAG(4) / (1.f - epsilon);230uint uncommon_preds = 0;231uint freq_preds = 0;232uint uncommon_for_freq_preds = 0;233234for( uint i=1; i< block->num_preds(); i++ ) {235Block* guard = get_block_for_node(block->pred(i));236// Check to see if this block follows its guard 1 time out of 10000237// or less.238//239// See list of magnitude-4 unlikely probabilities in cfgnode.hpp which240// we intend to be "uncommon", such as slow-path TLE allocation,241// predicted call failure, and uncommon trap triggers.242//243// Use an epsilon value of 5% to allow for variability in frequency244// predictions and floating point calculations. The net effect is245// that guard_factor is set to 9500.246//247// Ignore low-frequency blocks.248// The next check is (guard->_freq < 1.e-5 * 9500.).249if(guard->_freq*BLOCK_FREQUENCY(guard_factor) < BLOCK_FREQUENCY(0.00001f)) {250uncommon_preds++;251} else {252freq_preds++;253if(block->_freq < guard->_freq * guard_factor ) {254uncommon_for_freq_preds++;255}256}257}258if( block->num_preds() > 1 &&259// The block is uncommon if all preds are uncommon or260(uncommon_preds == (block->num_preds()-1) ||261// it is uncommon for all frequent preds.262uncommon_for_freq_preds == freq_preds) ) {263return true;264}265return false;266}267268#ifndef PRODUCT269void Block::dump_bidx(const Block* orig, outputStream* st) const {270if (_pre_order) st->print("B%d", _pre_order);271else st->print("N%d", head()->_idx);272273if (Verbose && orig != this) {274// Dump the original block's idx275st->print(" (");276orig->dump_bidx(orig, st);277st->print(")");278}279}280281void Block::dump_pred(const PhaseCFG* cfg, Block* orig, outputStream* st) const {282if (is_connector()) {283for (uint i=1; i<num_preds(); i++) {284Block *p = cfg->get_block_for_node(pred(i));285p->dump_pred(cfg, orig, st);286}287} else {288dump_bidx(orig, st);289st->print(" ");290}291}292293void Block::dump_head(const PhaseCFG* cfg, outputStream* st) const {294// Print the basic block.295dump_bidx(this, st);296st->print(": ");297298// Print the outgoing CFG edges.299st->print("#\tout( ");300for( uint i=0; i<_num_succs; i++ ) {301non_connector_successor(i)->dump_bidx(_succs[i], st);302st->print(" ");303}304305// Print the incoming CFG edges.306st->print(") <- ");307if( head()->is_block_start() ) {308st->print("in( ");309for (uint i=1; i<num_preds(); i++) {310Node *s = pred(i);311if (cfg != NULL) {312Block *p = cfg->get_block_for_node(s);313p->dump_pred(cfg, p, st);314} else {315while (!s->is_block_start()) {316s = s->in(0);317}318st->print("N%d ", s->_idx );319}320}321st->print(") ");322} else {323st->print("BLOCK HEAD IS JUNK ");324}325326// Print loop, if any327const Block *bhead = this; // Head of self-loop328Node *bh = bhead->head();329330if ((cfg != NULL) && bh->is_Loop() && !head()->is_Root()) {331LoopNode *loop = bh->as_Loop();332const Block *bx = cfg->get_block_for_node(loop->in(LoopNode::LoopBackControl));333while (bx->is_connector()) {334bx = cfg->get_block_for_node(bx->pred(1));335}336st->print("Loop( B%d-B%d ", bhead->_pre_order, bx->_pre_order);337// Dump any loop-specific bits, especially for CountedLoops.338loop->dump_spec(st);339st->print(")");340} else if (has_loop_alignment()) {341st->print("top-of-loop");342}343344// Print frequency and other optimization-relevant information345st->print(" Freq: %g",_freq);346if( Verbose || WizardMode ) {347st->print(" IDom: %d/#%d", _idom ? _idom->_pre_order : 0, _dom_depth);348st->print(" RegPressure: %d",_reg_pressure);349st->print(" IHRP Index: %d",_ihrp_index);350st->print(" FRegPressure: %d",_freg_pressure);351st->print(" FHRP Index: %d",_fhrp_index);352}353st->cr();354}355356void Block::dump() const {357dump(NULL);358}359360void Block::dump(const PhaseCFG* cfg) const {361dump_head(cfg);362for (uint i=0; i< number_of_nodes(); i++) {363get_node(i)->dump();364}365tty->print("\n");366}367#endif368369PhaseCFG::PhaseCFG(Arena* arena, RootNode* root, Matcher& matcher)370: Phase(CFG)371, _root(root)372, _block_arena(arena)373, _regalloc(NULL)374, _scheduling_for_pressure(false)375, _matcher(matcher)376, _node_to_block_mapping(arena)377, _node_latency(NULL)378#ifndef PRODUCT379, _trace_opto_pipelining(C->directive()->TraceOptoPipeliningOption)380#endif381#ifdef ASSERT382, _raw_oops(arena)383#endif384{385ResourceMark rm;386// I'll need a few machine-specific GotoNodes. Make an Ideal GotoNode,387// then Match it into a machine-specific Node. Then clone the machine388// Node on demand.389Node *x = new GotoNode(NULL);390x->init_req(0, x);391_goto = matcher.match_tree(x);392assert(_goto != NULL, "");393_goto->set_req(0,_goto);394395// Build the CFG in Reverse Post Order396_number_of_blocks = build_cfg();397_root_block = get_block_for_node(_root);398}399400// Build a proper looking CFG. Make every block begin with either a StartNode401// or a RegionNode. Make every block end with either a Goto, If or Return.402// The RootNode both starts and ends it's own block. Do this with a recursive403// backwards walk over the control edges.404uint PhaseCFG::build_cfg() {405VectorSet visited;406407// Allocate stack with enough space to avoid frequent realloc408Node_Stack nstack(C->live_nodes() >> 1);409nstack.push(_root, 0);410uint sum = 0; // Counter for blocks411412while (nstack.is_nonempty()) {413// node and in's index from stack's top414// 'np' is _root (see above) or RegionNode, StartNode: we push on stack415// only nodes which point to the start of basic block (see below).416Node *np = nstack.node();417// idx > 0, except for the first node (_root) pushed on stack418// at the beginning when idx == 0.419// We will use the condition (idx == 0) later to end the build.420uint idx = nstack.index();421Node *proj = np->in(idx);422const Node *x = proj->is_block_proj();423// Does the block end with a proper block-ending Node? One of Return,424// If or Goto? (This check should be done for visited nodes also).425if (x == NULL) { // Does not end right...426Node *g = _goto->clone(); // Force it to end in a Goto427g->set_req(0, proj);428np->set_req(idx, g);429x = proj = g;430}431if (!visited.test_set(x->_idx)) { // Visit this block once432// Skip any control-pinned middle'in stuff433Node *p = proj;434do {435proj = p; // Update pointer to last Control436p = p->in(0); // Move control forward437} while( !p->is_block_proj() &&438!p->is_block_start() );439// Make the block begin with one of Region or StartNode.440if( !p->is_block_start() ) {441RegionNode *r = new RegionNode( 2 );442r->init_req(1, p); // Insert RegionNode in the way443proj->set_req(0, r); // Insert RegionNode in the way444p = r;445}446// 'p' now points to the start of this basic block447448// Put self in array of basic blocks449Block *bb = new (_block_arena) Block(_block_arena, p);450map_node_to_block(p, bb);451map_node_to_block(x, bb);452if( x != p ) { // Only for root is x == p453bb->push_node((Node*)x);454}455// Now handle predecessors456++sum; // Count 1 for self block457uint cnt = bb->num_preds();458for (int i = (cnt - 1); i > 0; i-- ) { // For all predecessors459Node *prevproj = p->in(i); // Get prior input460assert( !prevproj->is_Con(), "dead input not removed" );461// Check to see if p->in(i) is a "control-dependent" CFG edge -462// i.e., it splits at the source (via an IF or SWITCH) and merges463// at the destination (via a many-input Region).464// This breaks critical edges. The RegionNode to start the block465// will be added when <p,i> is pulled off the node stack466if ( cnt > 2 ) { // Merging many things?467assert( prevproj== bb->pred(i),"");468if(prevproj->is_block_proj() != prevproj) { // Control-dependent edge?469// Force a block on the control-dependent edge470Node *g = _goto->clone(); // Force it to end in a Goto471g->set_req(0,prevproj);472p->set_req(i,g);473}474}475nstack.push(p, i); // 'p' is RegionNode or StartNode476}477} else { // Post-processing visited nodes478nstack.pop(); // remove node from stack479// Check if it the fist node pushed on stack at the beginning.480if (idx == 0) break; // end of the build481// Find predecessor basic block482Block *pb = get_block_for_node(x);483// Insert into nodes array, if not already there484if (!has_block(proj)) {485assert( x != proj, "" );486// Map basic block of projection487map_node_to_block(proj, pb);488pb->push_node(proj);489}490// Insert self as a child of my predecessor block491pb->_succs.map(pb->_num_succs++, get_block_for_node(np));492assert( pb->get_node(pb->number_of_nodes() - pb->_num_succs)->is_block_proj(),493"too many control users, not a CFG?" );494}495}496// Return number of basic blocks for all children and self497return sum;498}499500// Inserts a goto & corresponding basic block between501// block[block_no] and its succ_no'th successor block502void PhaseCFG::insert_goto_at(uint block_no, uint succ_no) {503// get block with block_no504assert(block_no < number_of_blocks(), "illegal block number");505Block* in = get_block(block_no);506// get successor block succ_no507assert(succ_no < in->_num_succs, "illegal successor number");508Block* out = in->_succs[succ_no];509// Compute frequency of the new block. Do this before inserting510// new block in case succ_prob() needs to infer the probability from511// surrounding blocks.512float freq = in->_freq * in->succ_prob(succ_no);513// get ProjNode corresponding to the succ_no'th successor of the in block514ProjNode* proj = in->get_node(in->number_of_nodes() - in->_num_succs + succ_no)->as_Proj();515// create region for basic block516RegionNode* region = new RegionNode(2);517region->init_req(1, proj);518// setup corresponding basic block519Block* block = new (_block_arena) Block(_block_arena, region);520map_node_to_block(region, block);521C->regalloc()->set_bad(region->_idx);522// add a goto node523Node* gto = _goto->clone(); // get a new goto node524gto->set_req(0, region);525// add it to the basic block526block->push_node(gto);527map_node_to_block(gto, block);528C->regalloc()->set_bad(gto->_idx);529// hook up successor block530block->_succs.map(block->_num_succs++, out);531// remap successor's predecessors if necessary532for (uint i = 1; i < out->num_preds(); i++) {533if (out->pred(i) == proj) out->head()->set_req(i, gto);534}535// remap predecessor's successor to new block536in->_succs.map(succ_no, block);537// Set the frequency of the new block538block->_freq = freq;539// add new basic block to basic block list540add_block_at(block_no + 1, block);541}542543// Does this block end in a multiway branch that cannot have the default case544// flipped for another case?545static bool no_flip_branch(Block *b) {546int branch_idx = b->number_of_nodes() - b->_num_succs-1;547if (branch_idx < 1) {548return false;549}550Node *branch = b->get_node(branch_idx);551if (branch->is_Catch()) {552return true;553}554if (branch->is_Mach()) {555if (branch->is_MachNullCheck()) {556return true;557}558int iop = branch->as_Mach()->ideal_Opcode();559if (iop == Op_FastLock || iop == Op_FastUnlock) {560return true;561}562// Don't flip if branch has an implicit check.563if (branch->as_Mach()->is_TrapBasedCheckNode()) {564return true;565}566}567return false;568}569570// Check for NeverBranch at block end. This needs to become a GOTO to the571// true target. NeverBranch are treated as a conditional branch that always572// goes the same direction for most of the optimizer and are used to give a573// fake exit path to infinite loops. At this late stage they need to turn574// into Goto's so that when you enter the infinite loop you indeed hang.575void PhaseCFG::convert_NeverBranch_to_Goto(Block *b) {576// Find true target577int end_idx = b->end_idx();578int idx = b->get_node(end_idx+1)->as_Proj()->_con;579Block *succ = b->_succs[idx];580Node* gto = _goto->clone(); // get a new goto node581gto->set_req(0, b->head());582Node *bp = b->get_node(end_idx);583b->map_node(gto, end_idx); // Slam over NeverBranch584map_node_to_block(gto, b);585C->regalloc()->set_bad(gto->_idx);586b->pop_node(); // Yank projections587b->pop_node(); // Yank projections588b->_succs.map(0,succ); // Map only successor589b->_num_succs = 1;590// remap successor's predecessors if necessary591uint j;592for( j = 1; j < succ->num_preds(); j++)593if( succ->pred(j)->in(0) == bp )594succ->head()->set_req(j, gto);595// Kill alternate exit path596Block *dead = b->_succs[1-idx];597for( j = 1; j < dead->num_preds(); j++)598if( dead->pred(j)->in(0) == bp )599break;600// Scan through block, yanking dead path from601// all regions and phis.602dead->head()->del_req(j);603for( int k = 1; dead->get_node(k)->is_Phi(); k++ )604dead->get_node(k)->del_req(j);605}606607// Helper function to move block bx to the slot following b_index. Return608// true if the move is successful, otherwise false609bool PhaseCFG::move_to_next(Block* bx, uint b_index) {610if (bx == NULL) return false;611612// Return false if bx is already scheduled.613uint bx_index = bx->_pre_order;614if ((bx_index <= b_index) && (get_block(bx_index) == bx)) {615return false;616}617618// Find the current index of block bx on the block list619bx_index = b_index + 1;620while (bx_index < number_of_blocks() && get_block(bx_index) != bx) {621bx_index++;622}623assert(get_block(bx_index) == bx, "block not found");624625// If the previous block conditionally falls into bx, return false,626// because moving bx will create an extra jump.627for(uint k = 1; k < bx->num_preds(); k++ ) {628Block* pred = get_block_for_node(bx->pred(k));629if (pred == get_block(bx_index - 1)) {630if (pred->_num_succs != 1) {631return false;632}633}634}635636// Reinsert bx just past block 'b'637_blocks.remove(bx_index);638_blocks.insert(b_index + 1, bx);639return true;640}641642// Move empty and uncommon blocks to the end.643void PhaseCFG::move_to_end(Block *b, uint i) {644int e = b->is_Empty();645if (e != Block::not_empty) {646if (e == Block::empty_with_goto) {647// Remove the goto, but leave the block.648b->pop_node();649}650// Mark this block as a connector block, which will cause it to be651// ignored in certain functions such as non_connector_successor().652b->set_connector();653}654// Move the empty block to the end, and don't recheck.655_blocks.remove(i);656_blocks.push(b);657}658659// Set loop alignment for every block660void PhaseCFG::set_loop_alignment() {661uint last = number_of_blocks();662assert(get_block(0) == get_root_block(), "");663664for (uint i = 1; i < last; i++) {665Block* block = get_block(i);666if (block->head()->is_Loop()) {667block->set_loop_alignment(block);668}669}670}671672// Make empty basic blocks to be "connector" blocks, Move uncommon blocks673// to the end.674void PhaseCFG::remove_empty_blocks() {675// Move uncommon blocks to the end676uint last = number_of_blocks();677assert(get_block(0) == get_root_block(), "");678679for (uint i = 1; i < last; i++) {680Block* block = get_block(i);681if (block->is_connector()) {682break;683}684685// Check for NeverBranch at block end. This needs to become a GOTO to the686// true target. NeverBranch are treated as a conditional branch that687// always goes the same direction for most of the optimizer and are used688// to give a fake exit path to infinite loops. At this late stage they689// need to turn into Goto's so that when you enter the infinite loop you690// indeed hang.691if (block->get_node(block->end_idx())->Opcode() == Op_NeverBranch) {692convert_NeverBranch_to_Goto(block);693}694695// Look for uncommon blocks and move to end.696if (!C->do_freq_based_layout()) {697if (is_uncommon(block)) {698move_to_end(block, i);699last--; // No longer check for being uncommon!700if (no_flip_branch(block)) { // Fall-thru case must follow?701// Find the fall-thru block702block = get_block(i);703move_to_end(block, i);704last--;705}706// backup block counter post-increment707i--;708}709}710}711712// Move empty blocks to the end713last = number_of_blocks();714for (uint i = 1; i < last; i++) {715Block* block = get_block(i);716if (block->is_Empty() != Block::not_empty) {717move_to_end(block, i);718last--;719i--;720}721} // End of for all blocks722}723724Block *PhaseCFG::fixup_trap_based_check(Node *branch, Block *block, int block_pos, Block *bnext) {725// Trap based checks must fall through to the successor with726// PROB_ALWAYS.727// They should be an If with 2 successors.728assert(branch->is_MachIf(), "must be If");729assert(block->_num_succs == 2, "must have 2 successors");730731// Get the If node and the projection for the first successor.732MachIfNode *iff = block->get_node(block->number_of_nodes()-3)->as_MachIf();733ProjNode *proj0 = block->get_node(block->number_of_nodes()-2)->as_Proj();734ProjNode *proj1 = block->get_node(block->number_of_nodes()-1)->as_Proj();735ProjNode *projt = (proj0->Opcode() == Op_IfTrue) ? proj0 : proj1;736ProjNode *projf = (proj0->Opcode() == Op_IfFalse) ? proj0 : proj1;737738// Assert that proj0 and succs[0] match up. Similarly for proj1 and succs[1].739assert(proj0->raw_out(0) == block->_succs[0]->head(), "Mismatch successor 0");740assert(proj1->raw_out(0) == block->_succs[1]->head(), "Mismatch successor 1");741742ProjNode *proj_always;743ProjNode *proj_never;744// We must negate the branch if the implicit check doesn't follow745// the branch's TRUE path. Then, the new TRUE branch target will746// be the old FALSE branch target.747if (iff->_prob <= 2*PROB_NEVER) { // There are small rounding errors.748proj_never = projt;749proj_always = projf;750} else {751// We must negate the branch if the trap doesn't follow the752// branch's TRUE path. Then, the new TRUE branch target will753// be the old FALSE branch target.754proj_never = projf;755proj_always = projt;756iff->negate();757}758assert(iff->_prob <= 2*PROB_NEVER, "Trap based checks are expected to trap never!");759// Map the successors properly760block->_succs.map(0, get_block_for_node(proj_never ->raw_out(0))); // The target of the trap.761block->_succs.map(1, get_block_for_node(proj_always->raw_out(0))); // The fall through target.762763if (block->get_node(block->number_of_nodes() - block->_num_succs + 1) != proj_always) {764block->map_node(proj_never, block->number_of_nodes() - block->_num_succs + 0);765block->map_node(proj_always, block->number_of_nodes() - block->_num_succs + 1);766}767768// Place the fall through block after this block.769Block *bs1 = block->non_connector_successor(1);770if (bs1 != bnext && move_to_next(bs1, block_pos)) {771bnext = bs1;772}773// If the fall through block still is not the next block, insert a goto.774if (bs1 != bnext) {775insert_goto_at(block_pos, 1);776}777return bnext;778}779780// Fix up the final control flow for basic blocks.781void PhaseCFG::fixup_flow() {782// Fixup final control flow for the blocks. Remove jump-to-next783// block. If neither arm of an IF follows the conditional branch, we784// have to add a second jump after the conditional. We place the785// TRUE branch target in succs[0] for both GOTOs and IFs.786for (uint i = 0; i < number_of_blocks(); i++) {787Block* block = get_block(i);788block->_pre_order = i; // turn pre-order into block-index789790// Connector blocks need no further processing.791if (block->is_connector()) {792assert((i+1) == number_of_blocks() || get_block(i + 1)->is_connector(), "All connector blocks should sink to the end");793continue;794}795assert(block->is_Empty() != Block::completely_empty, "Empty blocks should be connectors");796797Block* bnext = (i < number_of_blocks() - 1) ? get_block(i + 1) : NULL;798Block* bs0 = block->non_connector_successor(0);799800// Check for multi-way branches where I cannot negate the test to801// exchange the true and false targets.802if (no_flip_branch(block)) {803// Find fall through case - if must fall into its target.804// Get the index of the branch's first successor.805int branch_idx = block->number_of_nodes() - block->_num_succs;806807// The branch is 1 before the branch's first successor.808Node *branch = block->get_node(branch_idx-1);809810// Handle no-flip branches which have implicit checks and which require811// special block ordering and individual semantics of the 'fall through812// case'.813if ((TrapBasedNullChecks || TrapBasedRangeChecks) &&814branch->is_Mach() && branch->as_Mach()->is_TrapBasedCheckNode()) {815bnext = fixup_trap_based_check(branch, block, i, bnext);816} else {817// Else, default handling for no-flip branches818for (uint j2 = 0; j2 < block->_num_succs; j2++) {819const ProjNode* p = block->get_node(branch_idx + j2)->as_Proj();820if (p->_con == 0) {821// successor j2 is fall through case822if (block->non_connector_successor(j2) != bnext) {823// but it is not the next block => insert a goto824insert_goto_at(i, j2);825}826// Put taken branch in slot 0827if (j2 == 0 && block->_num_succs == 2) {828// Flip targets in succs map829Block *tbs0 = block->_succs[0];830Block *tbs1 = block->_succs[1];831block->_succs.map(0, tbs1);832block->_succs.map(1, tbs0);833}834break;835}836}837}838839// Remove all CatchProjs840for (uint j = 0; j < block->_num_succs; j++) {841block->pop_node();842}843844} else if (block->_num_succs == 1) {845// Block ends in a Goto?846if (bnext == bs0) {847// We fall into next block; remove the Goto848block->pop_node();849}850851} else if(block->_num_succs == 2) { // Block ends in a If?852// Get opcode of 1st projection (matches _succs[0])853// Note: Since this basic block has 2 exits, the last 2 nodes must854// be projections (in any order), the 3rd last node must be855// the IfNode (we have excluded other 2-way exits such as856// CatchNodes already).857MachNode* iff = block->get_node(block->number_of_nodes() - 3)->as_Mach();858ProjNode* proj0 = block->get_node(block->number_of_nodes() - 2)->as_Proj();859ProjNode* proj1 = block->get_node(block->number_of_nodes() - 1)->as_Proj();860861// Assert that proj0 and succs[0] match up. Similarly for proj1 and succs[1].862assert(proj0->raw_out(0) == block->_succs[0]->head(), "Mismatch successor 0");863assert(proj1->raw_out(0) == block->_succs[1]->head(), "Mismatch successor 1");864865Block* bs1 = block->non_connector_successor(1);866867// Check for neither successor block following the current868// block ending in a conditional. If so, move one of the869// successors after the current one, provided that the870// successor was previously unscheduled, but moveable871// (i.e., all paths to it involve a branch).872if (!C->do_freq_based_layout() && bnext != bs0 && bnext != bs1) {873// Choose the more common successor based on the probability874// of the conditional branch.875Block* bx = bs0;876Block* by = bs1;877878// _prob is the probability of taking the true path. Make879// p the probability of taking successor #1.880float p = iff->as_MachIf()->_prob;881if (proj0->Opcode() == Op_IfTrue) {882p = 1.0 - p;883}884885// Prefer successor #1 if p > 0.5886if (p > PROB_FAIR) {887bx = bs1;888by = bs0;889}890891// Attempt the more common successor first892if (move_to_next(bx, i)) {893bnext = bx;894} else if (move_to_next(by, i)) {895bnext = by;896}897}898899// Check for conditional branching the wrong way. Negate900// conditional, if needed, so it falls into the following block901// and branches to the not-following block.902903// Check for the next block being in succs[0]. We are going to branch904// to succs[0], so we want the fall-thru case as the next block in905// succs[1].906if (bnext == bs0) {907// Fall-thru case in succs[0], so flip targets in succs map908Block* tbs0 = block->_succs[0];909Block* tbs1 = block->_succs[1];910block->_succs.map(0, tbs1);911block->_succs.map(1, tbs0);912// Flip projection for each target913ProjNode* tmp = proj0;914proj0 = proj1;915proj1 = tmp;916917} else if(bnext != bs1) {918// Need a double-branch919// The existing conditional branch need not change.920// Add a unconditional branch to the false target.921// Alas, it must appear in its own block and adding a922// block this late in the game is complicated. Sigh.923insert_goto_at(i, 1);924}925926// Make sure we TRUE branch to the target927if (proj0->Opcode() == Op_IfFalse) {928iff->as_MachIf()->negate();929}930931block->pop_node(); // Remove IfFalse & IfTrue projections932block->pop_node();933934} else {935// Multi-exit block, e.g. a switch statement936// But we don't need to do anything here937}938} // End of for all blocks939}940941942// postalloc_expand: Expand nodes after register allocation.943//944// postalloc_expand has to be called after register allocation, just945// before output (i.e. scheduling). It only gets called if946// Matcher::require_postalloc_expand is true.947//948// Background:949//950// Nodes that are expandend (one compound node requiring several951// assembler instructions to be implemented split into two or more952// non-compound nodes) after register allocation are not as nice as953// the ones expanded before register allocation - they don't954// participate in optimizations as global code motion. But after955// register allocation we can expand nodes that use registers which956// are not spillable or registers that are not allocated, because the957// old compound node is simply replaced (in its location in the basic958// block) by a new subgraph which does not contain compound nodes any959// more. The scheduler called during output can later on process these960// non-compound nodes.961//962// Implementation:963//964// Nodes requiring postalloc expand are specified in the ad file by using965// a postalloc_expand statement instead of ins_encode. A postalloc_expand966// contains a single call to an encoding, as does an ins_encode967// statement. Instead of an emit() function a postalloc_expand() function968// is generated that doesn't emit assembler but creates a new969// subgraph. The code below calls this postalloc_expand function for each970// node with the appropriate attribute. This function returns the new971// nodes generated in an array passed in the call. The old node,972// potential MachTemps before and potential Projs after it then get973// disconnected and replaced by the new nodes. The instruction974// generating the result has to be the last one in the array. In975// general it is assumed that Projs after the node expanded are976// kills. These kills are not required any more after expanding as977// there are now explicitly visible def-use chains and the Projs are978// removed. This does not hold for calls: They do not only have979// kill-Projs but also Projs defining values. Therefore Projs after980// the node expanded are removed for all but for calls. If a node is981// to be reused, it must be added to the nodes list returned, and it982// will be added again.983//984// Implementing the postalloc_expand function for a node in an enc_class985// is rather tedious. It requires knowledge about many node details, as986// the nodes and the subgraph must be hand crafted. To simplify this,987// adlc generates some utility variables into the postalloc_expand function,988// e.g., holding the operands as specified by the postalloc_expand encoding989// specification, e.g.:990// * unsigned idx_<par_name> holding the index of the node in the ins991// * Node *n_<par_name> holding the node loaded from the ins992// * MachOpnd *op_<par_name> holding the corresponding operand993//994// The ordering of operands can not be determined by looking at a995// rule. Especially if a match rule matches several different trees,996// several nodes are generated from one instruct specification with997// different operand orderings. In this case the adlc generated998// variables are the only way to access the ins and operands999// deterministically.1000//1001// If assigning a register to a node that contains an oop, don't1002// forget to call ra_->set_oop() for the node.1003void PhaseCFG::postalloc_expand(PhaseRegAlloc* _ra) {1004GrowableArray <Node *> new_nodes(32); // Array with new nodes filled by postalloc_expand function of node.1005GrowableArray <Node *> remove(32);1006GrowableArray <Node *> succs(32);1007unsigned int max_idx = C->unique(); // Remember to distinguish new from old nodes.1008DEBUG_ONLY(bool foundNode = false);10091010// for all blocks1011for (uint i = 0; i < number_of_blocks(); i++) {1012Block *b = _blocks[i];1013// For all instructions in the current block.1014for (uint j = 0; j < b->number_of_nodes(); j++) {1015Node *n = b->get_node(j);1016if (n->is_Mach() && n->as_Mach()->requires_postalloc_expand()) {1017#ifdef ASSERT1018if (TracePostallocExpand) {1019if (!foundNode) {1020foundNode = true;1021tty->print("POSTALLOC EXPANDING %d %s\n", C->compile_id(),1022C->method() ? C->method()->name()->as_utf8() : C->stub_name());1023}1024tty->print(" postalloc expanding "); n->dump();1025if (Verbose) {1026tty->print(" with ins:\n");1027for (uint k = 0; k < n->len(); ++k) {1028if (n->in(k)) { tty->print(" "); n->in(k)->dump(); }1029}1030}1031}1032#endif1033new_nodes.clear();1034// Collect nodes that have to be removed from the block later on.1035uint req = n->req();1036remove.clear();1037for (uint k = 0; k < req; ++k) {1038if (n->in(k) && n->in(k)->is_MachTemp()) {1039remove.push(n->in(k)); // MachTemps which are inputs to the old node have to be removed.1040n->in(k)->del_req(0);1041j--;1042}1043}10441045// Check whether we can allocate enough nodes. We set a fix limit for1046// the size of postalloc expands with this.1047uint unique_limit = C->unique() + 40;1048if (unique_limit >= _ra->node_regs_max_index()) {1049Compile::current()->record_failure("out of nodes in postalloc expand");1050return;1051}10521053// Emit (i.e. generate new nodes).1054n->as_Mach()->postalloc_expand(&new_nodes, _ra);10551056assert(C->unique() < unique_limit, "You allocated too many nodes in your postalloc expand.");10571058// Disconnect the inputs of the old node.1059//1060// We reuse MachSpillCopy nodes. If we need to expand them, there1061// are many, so reusing pays off. If reused, the node already1062// has the new ins. n must be the last node on new_nodes list.1063if (!n->is_MachSpillCopy()) {1064for (int k = req - 1; k >= 0; --k) {1065n->del_req(k);1066}1067}10681069#ifdef ASSERT1070// Check that all nodes have proper operands.1071for (int k = 0; k < new_nodes.length(); ++k) {1072if (new_nodes.at(k)->_idx < max_idx || !new_nodes.at(k)->is_Mach()) continue; // old node, Proj ...1073MachNode *m = new_nodes.at(k)->as_Mach();1074for (unsigned int l = 0; l < m->num_opnds(); ++l) {1075if (MachOper::notAnOper(m->_opnds[l])) {1076outputStream *os = tty;1077os->print("Node %s ", m->Name());1078os->print("has invalid opnd %d: %p\n", l, m->_opnds[l]);1079assert(0, "Invalid operands, see inline trace in hs_err_pid file.");1080}1081}1082}1083#endif10841085// Collect succs of old node in remove (for projections) and in succs (for1086// all other nodes) do _not_ collect projections in remove (but in succs)1087// in case the node is a call. We need the projections for calls as they are1088// associated with registes (i.e. they are defs).1089succs.clear();1090for (DUIterator k = n->outs(); n->has_out(k); k++) {1091if (n->out(k)->is_Proj() && !n->is_MachCall() && !n->is_MachBranch()) {1092remove.push(n->out(k));1093} else {1094succs.push(n->out(k));1095}1096}1097// Replace old node n as input of its succs by last of the new nodes.1098for (int k = 0; k < succs.length(); ++k) {1099Node *succ = succs.at(k);1100for (uint l = 0; l < succ->req(); ++l) {1101if (succ->in(l) == n) {1102succ->set_req(l, new_nodes.at(new_nodes.length() - 1));1103}1104}1105for (uint l = succ->req(); l < succ->len(); ++l) {1106if (succ->in(l) == n) {1107succ->set_prec(l, new_nodes.at(new_nodes.length() - 1));1108}1109}1110}11111112// Index of old node in block.1113uint index = b->find_node(n);1114// Insert new nodes into block and map them in nodes->blocks array1115// and remember last node in n2.1116Node *n2 = NULL;1117for (int k = 0; k < new_nodes.length(); ++k) {1118n2 = new_nodes.at(k);1119b->insert_node(n2, ++index);1120map_node_to_block(n2, b);1121}11221123// Add old node n to remove and remove them all from block.1124remove.push(n);1125j--;1126#ifdef ASSERT1127if (TracePostallocExpand && Verbose) {1128tty->print(" removing:\n");1129for (int k = 0; k < remove.length(); ++k) {1130tty->print(" "); remove.at(k)->dump();1131}1132tty->print(" inserting:\n");1133for (int k = 0; k < new_nodes.length(); ++k) {1134tty->print(" "); new_nodes.at(k)->dump();1135}1136}1137#endif1138for (int k = 0; k < remove.length(); ++k) {1139if (b->contains(remove.at(k))) {1140b->find_remove(remove.at(k));1141} else {1142assert(remove.at(k)->is_Proj() && (remove.at(k)->in(0)->is_MachBranch()), "");1143}1144}1145// If anything has been inserted (n2 != NULL), continue after last node inserted.1146// This does not always work. Some postalloc expands don't insert any nodes, if they1147// do optimizations (e.g., max(x,x)). In this case we decrement j accordingly.1148j = n2 ? b->find_node(n2) : j;1149}1150}1151}11521153#ifdef ASSERT1154if (foundNode) {1155tty->print("FINISHED %d %s\n", C->compile_id(),1156C->method() ? C->method()->name()->as_utf8() : C->stub_name());1157tty->flush();1158}1159#endif1160}116111621163//------------------------------dump-------------------------------------------1164#ifndef PRODUCT1165void PhaseCFG::_dump_cfg( const Node *end, VectorSet &visited ) const {1166const Node *x = end->is_block_proj();1167assert( x, "not a CFG" );11681169// Do not visit this block again1170if( visited.test_set(x->_idx) ) return;11711172// Skip through this block1173const Node *p = x;1174do {1175p = p->in(0); // Move control forward1176assert( !p->is_block_proj() || p->is_Root(), "not a CFG" );1177} while( !p->is_block_start() );11781179// Recursively visit1180for (uint i = 1; i < p->req(); i++) {1181_dump_cfg(p->in(i), visited);1182}11831184// Dump the block1185get_block_for_node(p)->dump(this);1186}11871188void PhaseCFG::dump( ) const {1189tty->print("\n--- CFG --- %d BBs\n", number_of_blocks());1190if (_blocks.size()) { // Did we do basic-block layout?1191for (uint i = 0; i < number_of_blocks(); i++) {1192const Block* block = get_block(i);1193block->dump(this);1194}1195} else { // Else do it with a DFS1196VectorSet visited(_block_arena);1197_dump_cfg(_root,visited);1198}1199}12001201void PhaseCFG::dump_headers() {1202for (uint i = 0; i < number_of_blocks(); i++) {1203Block* block = get_block(i);1204if (block != NULL) {1205block->dump_head(this);1206}1207}1208}1209#endif // !PRODUCT12101211#ifdef ASSERT1212void PhaseCFG::verify_memory_writer_placement(const Block* b, const Node* n) const {1213if (!n->is_memory_writer()) {1214return;1215}1216CFGLoop* home_or_ancestor = find_block_for_node(n->in(0))->_loop;1217bool found = false;1218do {1219if (b->_loop == home_or_ancestor) {1220found = true;1221break;1222}1223home_or_ancestor = home_or_ancestor->parent();1224} while (home_or_ancestor != NULL);1225assert(found, "block b is not in n's home loop or an ancestor of it");1226}12271228void PhaseCFG::verify() const {1229// Verify sane CFG1230for (uint i = 0; i < number_of_blocks(); i++) {1231Block* block = get_block(i);1232uint cnt = block->number_of_nodes();1233uint j;1234for (j = 0; j < cnt; j++) {1235Node *n = block->get_node(j);1236assert(get_block_for_node(n) == block, "");1237if (j >= 1 && n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_CreateEx) {1238assert(j == 1 || block->get_node(j-1)->is_Phi(), "CreateEx must be first instruction in block");1239}1240verify_memory_writer_placement(block, n);1241if (n->needs_anti_dependence_check()) {1242verify_anti_dependences(block, n);1243}1244for (uint k = 0; k < n->req(); k++) {1245Node *def = n->in(k);1246if (def && def != n) {1247Block* def_block = get_block_for_node(def);1248assert(def_block || def->is_Con(), "must have block; constants for debug info ok");1249// Verify that all definitions dominate their uses (except for virtual1250// instructions merging multiple definitions).1251assert(n->is_Root() || n->is_Region() || n->is_Phi() || n->is_MachMerge() ||1252def_block->dominates(block),1253"uses must be dominated by definitions");1254// Verify that instructions in the block are in correct order.1255// Uses must follow their definition if they are at the same block.1256// Mostly done to check that MachSpillCopy nodes are placed correctly1257// when CreateEx node is moved in build_ifg_physical().1258if (def_block == block && !(block->head()->is_Loop() && n->is_Phi()) &&1259// See (+++) comment in reg_split.cpp1260!(n->jvms() != NULL && n->jvms()->is_monitor_use(k))) {1261bool is_loop = false;1262if (n->is_Phi()) {1263for (uint l = 1; l < def->req(); l++) {1264if (n == def->in(l)) {1265is_loop = true;1266break; // Some kind of loop1267}1268}1269}1270assert(is_loop || block->find_node(def) < j, "uses must follow definitions");1271}1272}1273}1274if (n->is_Proj()) {1275assert(j >= 1, "a projection cannot be the first instruction in a block");1276Node* pred = block->get_node(j - 1);1277Node* parent = n->in(0);1278assert(parent != NULL, "projections must have a parent");1279assert(pred == parent || (pred->is_Proj() && pred->in(0) == parent),1280"projections must follow their parents or other sibling projections");1281}1282}12831284j = block->end_idx();1285Node* bp = (Node*)block->get_node(block->number_of_nodes() - 1)->is_block_proj();1286assert(bp, "last instruction must be a block proj");1287assert(bp == block->get_node(j), "wrong number of successors for this block");1288if (bp->is_Catch()) {1289while (block->get_node(--j)->is_MachProj()) {1290;1291}1292assert(block->get_node(j)->is_MachCall(), "CatchProj must follow call");1293} else if (bp->is_Mach() && bp->as_Mach()->ideal_Opcode() == Op_If) {1294assert(block->_num_succs == 2, "Conditional branch must have two targets");1295}1296}1297}1298#endif // ASSERT12991300UnionFind::UnionFind( uint max ) : _cnt(max), _max(max), _indices(NEW_RESOURCE_ARRAY(uint,max)) {1301Copy::zero_to_bytes( _indices, sizeof(uint)*max );1302}13031304void UnionFind::extend( uint from_idx, uint to_idx ) {1305_nesting.check();1306if( from_idx >= _max ) {1307uint size = 16;1308while( size <= from_idx ) size <<=1;1309_indices = REALLOC_RESOURCE_ARRAY( uint, _indices, _max, size );1310_max = size;1311}1312while( _cnt <= from_idx ) _indices[_cnt++] = 0;1313_indices[from_idx] = to_idx;1314}13151316void UnionFind::reset( uint max ) {1317// Force the Union-Find mapping to be at least this large1318extend(max,0);1319// Initialize to be the ID mapping.1320for( uint i=0; i<max; i++ ) map(i,i);1321}13221323// Straight out of Tarjan's union-find algorithm1324uint UnionFind::Find_compress( uint idx ) {1325uint cur = idx;1326uint next = lookup(cur);1327while( next != cur ) { // Scan chain of equivalences1328assert( next < cur, "always union smaller" );1329cur = next; // until find a fixed-point1330next = lookup(cur);1331}1332// Core of union-find algorithm: update chain of1333// equivalences to be equal to the root.1334while( idx != next ) {1335uint tmp = lookup(idx);1336map(idx, next);1337idx = tmp;1338}1339return idx;1340}13411342// Like Find above, but no path compress, so bad asymptotic behavior1343uint UnionFind::Find_const( uint idx ) const {1344if( idx == 0 ) return idx; // Ignore the zero idx1345// Off the end? This can happen during debugging dumps1346// when data structures have not finished being updated.1347if( idx >= _max ) return idx;1348uint next = lookup(idx);1349while( next != idx ) { // Scan chain of equivalences1350idx = next; // until find a fixed-point1351next = lookup(idx);1352}1353return next;1354}13551356// union 2 sets together.1357void UnionFind::Union( uint idx1, uint idx2 ) {1358uint src = Find(idx1);1359uint dst = Find(idx2);1360assert( src, "" );1361assert( dst, "" );1362assert( src < _max, "oob" );1363assert( dst < _max, "oob" );1364assert( src < dst, "always union smaller" );1365map(dst,src);1366}13671368#ifndef PRODUCT1369void Trace::dump( ) const {1370tty->print_cr("Trace (freq %f)", first_block()->_freq);1371for (Block *b = first_block(); b != NULL; b = next(b)) {1372tty->print(" B%d", b->_pre_order);1373if (b->head()->is_Loop()) {1374tty->print(" (L%d)", b->compute_loop_alignment());1375}1376if (b->has_loop_alignment()) {1377tty->print(" (T%d)", b->code_alignment());1378}1379}1380tty->cr();1381}13821383void CFGEdge::dump( ) const {1384tty->print(" B%d --> B%d Freq: %f out:%3d%% in:%3d%% State: ",1385from()->_pre_order, to()->_pre_order, freq(), _from_pct, _to_pct);1386switch(state()) {1387case connected:1388tty->print("connected");1389break;1390case open:1391tty->print("open");1392break;1393case interior:1394tty->print("interior");1395break;1396}1397if (infrequent()) {1398tty->print(" infrequent");1399}1400tty->cr();1401}1402#endif14031404// Comparison function for edges1405static int edge_order(CFGEdge **e0, CFGEdge **e1) {1406float freq0 = (*e0)->freq();1407float freq1 = (*e1)->freq();1408if (freq0 != freq1) {1409return freq0 > freq1 ? -1 : 1;1410}14111412int dist0 = (*e0)->to()->_rpo - (*e0)->from()->_rpo;1413int dist1 = (*e1)->to()->_rpo - (*e1)->from()->_rpo;14141415return dist1 - dist0;1416}14171418// Comparison function for edges1419extern "C" int trace_frequency_order(const void *p0, const void *p1) {1420Trace *tr0 = *(Trace **) p0;1421Trace *tr1 = *(Trace **) p1;1422Block *b0 = tr0->first_block();1423Block *b1 = tr1->first_block();14241425// The trace of connector blocks goes at the end;1426// we only expect one such trace1427if (b0->is_connector() != b1->is_connector()) {1428return b1->is_connector() ? -1 : 1;1429}14301431// Pull more frequently executed blocks to the beginning1432float freq0 = b0->_freq;1433float freq1 = b1->_freq;1434if (freq0 != freq1) {1435return freq0 > freq1 ? -1 : 1;1436}14371438int diff = tr0->first_block()->_rpo - tr1->first_block()->_rpo;14391440return diff;1441}14421443// Find edges of interest, i.e, those which can fall through. Presumes that1444// edges which don't fall through are of low frequency and can be generally1445// ignored. Initialize the list of traces.1446void PhaseBlockLayout::find_edges() {1447// Walk the blocks, creating edges and Traces1448uint i;1449Trace *tr = NULL;1450for (i = 0; i < _cfg.number_of_blocks(); i++) {1451Block* b = _cfg.get_block(i);1452tr = new Trace(b, next, prev);1453traces[tr->id()] = tr;14541455// All connector blocks should be at the end of the list1456if (b->is_connector()) break;14571458// If this block and the next one have a one-to-one successor1459// predecessor relationship, simply append the next block1460int nfallthru = b->num_fall_throughs();1461while (nfallthru == 1 &&1462b->succ_fall_through(0)) {1463Block *n = b->_succs[0];14641465// Skip over single-entry connector blocks, we don't want to1466// add them to the trace.1467while (n->is_connector() && n->num_preds() == 1) {1468n = n->_succs[0];1469}14701471// We see a merge point, so stop search for the next block1472if (n->num_preds() != 1) break;14731474i++;1475assert(n == _cfg.get_block(i), "expecting next block");1476tr->append(n);1477uf->map(n->_pre_order, tr->id());1478traces[n->_pre_order] = NULL;1479nfallthru = b->num_fall_throughs();1480b = n;1481}14821483if (nfallthru > 0) {1484// Create a CFGEdge for each outgoing1485// edge that could be a fall-through.1486for (uint j = 0; j < b->_num_succs; j++ ) {1487if (b->succ_fall_through(j)) {1488Block *target = b->non_connector_successor(j);1489float freq = b->_freq * b->succ_prob(j);1490int from_pct = (int) ((100 * freq) / b->_freq);1491int to_pct = (int) ((100 * freq) / target->_freq);1492edges->append(new CFGEdge(b, target, freq, from_pct, to_pct));1493}1494}1495}1496}14971498// Group connector blocks into one trace1499for (i++; i < _cfg.number_of_blocks(); i++) {1500Block *b = _cfg.get_block(i);1501assert(b->is_connector(), "connector blocks at the end");1502tr->append(b);1503uf->map(b->_pre_order, tr->id());1504traces[b->_pre_order] = NULL;1505}1506}15071508// Union two traces together in uf, and null out the trace in the list1509void PhaseBlockLayout::union_traces(Trace* updated_trace, Trace* old_trace) {1510uint old_id = old_trace->id();1511uint updated_id = updated_trace->id();15121513uint lo_id = updated_id;1514uint hi_id = old_id;15151516// If from is greater than to, swap values to meet1517// UnionFind guarantee.1518if (updated_id > old_id) {1519lo_id = old_id;1520hi_id = updated_id;15211522// Fix up the trace ids1523traces[lo_id] = traces[updated_id];1524updated_trace->set_id(lo_id);1525}15261527// Union the lower with the higher and remove the pointer1528// to the higher.1529uf->Union(lo_id, hi_id);1530traces[hi_id] = NULL;1531}15321533// Append traces together via the most frequently executed edges1534void PhaseBlockLayout::grow_traces() {1535// Order the edges, and drive the growth of Traces via the most1536// frequently executed edges.1537edges->sort(edge_order);1538for (int i = 0; i < edges->length(); i++) {1539CFGEdge *e = edges->at(i);15401541if (e->state() != CFGEdge::open) continue;15421543Block *src_block = e->from();1544Block *targ_block = e->to();15451546// Don't grow traces along backedges?1547if (!BlockLayoutRotateLoops) {1548if (targ_block->_rpo <= src_block->_rpo) {1549targ_block->set_loop_alignment(targ_block);1550continue;1551}1552}15531554Trace *src_trace = trace(src_block);1555Trace *targ_trace = trace(targ_block);15561557// If the edge in question can join two traces at their ends,1558// append one trace to the other.1559if (src_trace->last_block() == src_block) {1560if (src_trace == targ_trace) {1561e->set_state(CFGEdge::interior);1562if (targ_trace->backedge(e)) {1563// Reset i to catch any newly eligible edge1564// (Or we could remember the first "open" edge, and reset there)1565i = 0;1566}1567} else if (targ_trace->first_block() == targ_block) {1568e->set_state(CFGEdge::connected);1569src_trace->append(targ_trace);1570union_traces(src_trace, targ_trace);1571}1572}1573}1574}15751576// Embed one trace into another, if the fork or join points are sufficiently1577// balanced.1578void PhaseBlockLayout::merge_traces(bool fall_thru_only) {1579// Walk the edge list a another time, looking at unprocessed edges.1580// Fold in diamonds1581for (int i = 0; i < edges->length(); i++) {1582CFGEdge *e = edges->at(i);15831584if (e->state() != CFGEdge::open) continue;1585if (fall_thru_only) {1586if (e->infrequent()) continue;1587}15881589Block *src_block = e->from();1590Trace *src_trace = trace(src_block);1591bool src_at_tail = src_trace->last_block() == src_block;15921593Block *targ_block = e->to();1594Trace *targ_trace = trace(targ_block);1595bool targ_at_start = targ_trace->first_block() == targ_block;15961597if (src_trace == targ_trace) {1598// This may be a loop, but we can't do much about it.1599e->set_state(CFGEdge::interior);1600continue;1601}16021603if (fall_thru_only) {1604// If the edge links the middle of two traces, we can't do anything.1605// Mark the edge and continue.1606if (!src_at_tail & !targ_at_start) {1607continue;1608}16091610// Don't grow traces along backedges?1611if (!BlockLayoutRotateLoops && (targ_block->_rpo <= src_block->_rpo)) {1612continue;1613}16141615// If both ends of the edge are available, why didn't we handle it earlier?1616assert(src_at_tail ^ targ_at_start, "Should have caught this edge earlier.");16171618if (targ_at_start) {1619// Insert the "targ" trace in the "src" trace if the insertion point1620// is a two way branch.1621// Better profitability check possible, but may not be worth it.1622// Someday, see if the this "fork" has an associated "join";1623// then make a policy on merging this trace at the fork or join.1624// For example, other things being equal, it may be better to place this1625// trace at the join point if the "src" trace ends in a two-way, but1626// the insertion point is one-way.1627assert(src_block->num_fall_throughs() == 2, "unexpected diamond");1628e->set_state(CFGEdge::connected);1629src_trace->insert_after(src_block, targ_trace);1630union_traces(src_trace, targ_trace);1631} else if (src_at_tail) {1632if (src_trace != trace(_cfg.get_root_block())) {1633e->set_state(CFGEdge::connected);1634targ_trace->insert_before(targ_block, src_trace);1635union_traces(targ_trace, src_trace);1636}1637}1638} else if (e->state() == CFGEdge::open) {1639// Append traces, even without a fall-thru connection.1640// But leave root entry at the beginning of the block list.1641if (targ_trace != trace(_cfg.get_root_block())) {1642e->set_state(CFGEdge::connected);1643src_trace->append(targ_trace);1644union_traces(src_trace, targ_trace);1645}1646}1647}1648}16491650// Order the sequence of the traces in some desirable way, and fixup the1651// jumps at the end of each block.1652void PhaseBlockLayout::reorder_traces(int count) {1653ResourceArea *area = Thread::current()->resource_area();1654Trace ** new_traces = NEW_ARENA_ARRAY(area, Trace *, count);1655Block_List worklist;1656int new_count = 0;16571658// Compact the traces.1659for (int i = 0; i < count; i++) {1660Trace *tr = traces[i];1661if (tr != NULL) {1662new_traces[new_count++] = tr;1663}1664}16651666// The entry block should be first on the new trace list.1667Trace *tr = trace(_cfg.get_root_block());1668assert(tr == new_traces[0], "entry trace misplaced");16691670// Sort the new trace list by frequency1671qsort(new_traces + 1, new_count - 1, sizeof(new_traces[0]), trace_frequency_order);16721673// Patch up the successor blocks1674_cfg.clear_blocks();1675for (int i = 0; i < new_count; i++) {1676Trace *tr = new_traces[i];1677if (tr != NULL) {1678tr->fixup_blocks(_cfg);1679}1680}1681}16821683// Order basic blocks based on frequency1684PhaseBlockLayout::PhaseBlockLayout(PhaseCFG &cfg)1685: Phase(BlockLayout)1686, _cfg(cfg) {1687ResourceMark rm;1688ResourceArea *area = Thread::current()->resource_area();16891690// List of traces1691int size = _cfg.number_of_blocks() + 1;1692traces = NEW_ARENA_ARRAY(area, Trace *, size);1693memset(traces, 0, size*sizeof(Trace*));1694next = NEW_ARENA_ARRAY(area, Block *, size);1695memset(next, 0, size*sizeof(Block *));1696prev = NEW_ARENA_ARRAY(area, Block *, size);1697memset(prev , 0, size*sizeof(Block *));16981699// List of edges1700edges = new GrowableArray<CFGEdge*>;17011702// Mapping block index --> block_trace1703uf = new UnionFind(size);1704uf->reset(size);17051706// Find edges and create traces.1707find_edges();17081709// Grow traces at their ends via most frequent edges.1710grow_traces();17111712// Merge one trace into another, but only at fall-through points.1713// This may make diamonds and other related shapes in a trace.1714merge_traces(true);17151716// Run merge again, allowing two traces to be catenated, even if1717// one does not fall through into the other. This appends loosely1718// related traces to be near each other.1719merge_traces(false);17201721// Re-order all the remaining traces by frequency1722reorder_traces(size);17231724assert(_cfg.number_of_blocks() >= (uint) (size - 1), "number of blocks can not shrink");1725}172617271728// Edge e completes a loop in a trace. If the target block is head of the1729// loop, rotate the loop block so that the loop ends in a conditional branch.1730bool Trace::backedge(CFGEdge *e) {1731bool loop_rotated = false;1732Block *src_block = e->from();1733Block *targ_block = e->to();17341735assert(last_block() == src_block, "loop discovery at back branch");1736if (first_block() == targ_block) {1737if (BlockLayoutRotateLoops && last_block()->num_fall_throughs() < 2) {1738// Find the last block in the trace that has a conditional1739// branch.1740Block *b;1741for (b = last_block(); b != NULL; b = prev(b)) {1742if (b->num_fall_throughs() == 2) {1743break;1744}1745}17461747if (b != last_block() && b != NULL) {1748loop_rotated = true;17491750// Rotate the loop by doing two-part linked-list surgery.1751append(first_block());1752break_loop_after(b);1753}1754}17551756// Backbranch to the top of a trace1757// Scroll forward through the trace from the targ_block. If we find1758// a loop head before another loop top, use the the loop head alignment.1759for (Block *b = targ_block; b != NULL; b = next(b)) {1760if (b->has_loop_alignment()) {1761break;1762}1763if (b->head()->is_Loop()) {1764targ_block = b;1765break;1766}1767}17681769first_block()->set_loop_alignment(targ_block);17701771} else {1772// That loop may already have a loop top (we're reaching it again1773// through the backedge of an outer loop)1774Block* b = prev(targ_block);1775bool has_top = targ_block->head()->is_Loop() && b->has_loop_alignment() && !b->head()->is_Loop();1776if (!has_top) {1777// Backbranch into the middle of a trace1778targ_block->set_loop_alignment(targ_block);1779}1780}17811782return loop_rotated;1783}17841785// push blocks onto the CFG list1786// ensure that blocks have the correct two-way branch sense1787void Trace::fixup_blocks(PhaseCFG &cfg) {1788Block *last = last_block();1789for (Block *b = first_block(); b != NULL; b = next(b)) {1790cfg.add_block(b);1791if (!b->is_connector()) {1792int nfallthru = b->num_fall_throughs();1793if (b != last) {1794if (nfallthru == 2) {1795// Ensure that the sense of the branch is correct1796Block *bnext = next(b);1797Block *bs0 = b->non_connector_successor(0);17981799MachNode *iff = b->get_node(b->number_of_nodes() - 3)->as_Mach();1800ProjNode *proj0 = b->get_node(b->number_of_nodes() - 2)->as_Proj();1801ProjNode *proj1 = b->get_node(b->number_of_nodes() - 1)->as_Proj();18021803if (bnext == bs0) {1804// Fall-thru case in succs[0], should be in succs[1]18051806// Flip targets in _succs map1807Block *tbs0 = b->_succs[0];1808Block *tbs1 = b->_succs[1];1809b->_succs.map( 0, tbs1 );1810b->_succs.map( 1, tbs0 );18111812// Flip projections to match targets1813b->map_node(proj1, b->number_of_nodes() - 2);1814b->map_node(proj0, b->number_of_nodes() - 1);1815}1816}1817}1818}1819}1820}182118221823