/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "libadt/vectset.hpp"
#include "memory/allocation.inline.hpp"
#include "opto/cfgnode.hpp"
#include "opto/chaitin.hpp"
#include "opto/loopnode.hpp"
#include "opto/machnode.hpp"
#include "opto/matcher.hpp"
#include "opto/opcodes.hpp"
#include "opto/rootnode.hpp"
// Optimization - Graph Style
//-----------------------------------------------------------------------------
if( i < _size ) return;
if( !_size ) {
_size = 1;
}
}
//=============================================================================
Copy::conjoint_words_to_lower((HeapWord*)&_blocks[i+1], (HeapWord*)&_blocks[i], ((_cnt-i-1)*sizeof(Block*)));
pop(); // shrink list by one block
}
push(b); // grow list by one block
Copy::conjoint_words_to_higher((HeapWord*)&_blocks[i], (HeapWord*)&_blocks[i+1], ((_cnt-i-1)*sizeof(Block*)));
_blocks[i] = b;
}
#ifndef PRODUCT
void Block_List::print() {
}
}
#endif
//=============================================================================
// Check for Root block
if (_pre_order == 0) return CodeEntryAlignment;
// Check for Start block
// Check for loop alignment
if (has_loop_alignment()) return loop_alignment();
}
// Pre- and post-loops have low trip count so do not bother with
// NOPs for align loop head. The constants are hidden from tuning
// but only because my "divide by 4" heuristic surely gets nearly
// all possible gain (a "do not align at all" heuristic has a
// chance of getting a really tiny gain).
h->as_CountedLoop()->is_post_loop())) {
}
// Loops with low backedge frequency should not be aligned.
return unit_sz; // Loop does not loop, more often than not!
}
return OptoLoopAlignment; // Otherwise align loop head
}
return unit_sz; // no particular alignment
}
//-----------------------------------------------------------------------------
// Compute the size of first 'inst_cnt' instructions in this block.
// Return the number of instructions left to compute if the block has
// less then 'inst_cnt' instructions. Stop, and return 0 if sum_size
// exceeds OptoLoopAlignment.
PhaseRegAlloc* ra) {
if( inst_size > 0 ) {
inst_cnt--;
// Compute size of instructions which fit into fetch buffer only
// since all inst_cnt instructions will not fit even if we align them.
} else {
return 0;
}
}
}
return inst_cnt;
}
//-----------------------------------------------------------------------------
if( _nodes[i] == n )
return i;
}
return 0;
}
// Find and remove n from block list
}
//------------------------------is_Empty---------------------------------------
// Return empty status of a block. Empty blocks contain only the head, other
// ideal nodes, and an optional trailing goto.
// Root or start block is not considered empty
return not_empty;
}
int success_result = completely_empty;
// Check for ending goto
end_idx--;
}
// Unreachable blocks are considered empty
if (num_preds() <= 1) {
return success_result;
}
// Ideal nodes are allowable in empty blocks: skip them Only MachNodes
// turn directly into code, because only MachNodes have non-trivial
// emit() functions.
end_idx--;
}
// No room for any interesting instructions?
if (end_idx == 0) {
return success_result;
}
return not_empty;
}
//------------------------------has_uncommon_code------------------------------
// Return true if the block's code implies that it is likely to be
// executed infrequently. Check to see if the block ends in a Halt or
// a low probability call.
bool Block::has_uncommon_code() const {
if (en->is_MachGoto())
// This is true for slow-path stubs like new_{instance,array},
// slow_arraycopy, complete_monitor_locking, uncommon_trap.
// The magic number corresponds to the probability of an uncommon_trap,
// even though it is a count not a probability.
return true;
}
}
}
//------------------------------is_uncommon------------------------------------
// True if block is low enough frequency or guarded by a test which
// mostly does not go here.
// Initial blocks must never be moved, so are never uncommon.
// Check for way-low freq
// Look for code shape indicating uncommon_trap or slow path
if (has_uncommon_code()) return true;
const float epsilon = 0.05f;
uint uncommon_preds = 0;
uint freq_preds = 0;
// Check to see if this block follows its guard 1 time out of 10000
// or less.
//
// See list of magnitude-4 unlikely probabilities in cfgnode.hpp which
// we intend to be "uncommon", such as slow-path TLE allocation,
// predicted call failure, and uncommon trap triggers.
//
// Use an epsilon value of 5% to allow for variability in frequency
// predictions and floating point calculations. The net effect is
// that guard_factor is set to 9500.
//
// Ignore low-frequency blocks.
// The next check is (guard->_freq < 1.e-5 * 9500.).
} else {
freq_preds++;
}
}
}
if( num_preds() > 1 &&
// The block is uncommon if all preds are uncommon or
// it is uncommon for all frequent preds.
uncommon_for_freq_preds == freq_preds) ) {
return true;
}
return false;
}
//------------------------------dump-------------------------------------------
#ifndef PRODUCT
// Dump the original block's idx
}
}
if (is_connector()) {
}
} else {
}
}
// Print the basic block
// Print the incoming CFG edges and the outgoing CFG edges
for( uint i=0; i<_num_succs; i++ ) {
}
if( head()->is_block_start() ) {
if (bbs) {
} else {
while (!s->is_block_start())
s = s->in(0);
}
}
} else
// Print loop, if any
while (bx->is_connector()) {
}
// Dump any loop-specific bits, especially for CountedLoops.
} else if (has_loop_alignment()) {
}
if( Verbose || WizardMode ) {
}
}
}
#endif
//=============================================================================
//------------------------------PhaseCFG---------------------------------------
_bbs(a),
_root(r),
#ifndef PRODUCT
#endif
#ifdef ASSERT
, _raw_oops(a)
#endif
{
// I'll need a few machine-specific GotoNodes. Make an Ideal GotoNode,
// then Match it into a machine-specific Node. Then clone the machine
// Node on demand.
x->init_req(0, x);
_goto = m.match_tree(x);
// Build the CFG in Reverse Post Order
_num_blocks = build_cfg();
}
//------------------------------build_cfg--------------------------------------
// Build a proper looking CFG. Make every block begin with either a StartNode
// or a RegionNode. Make every block end with either a Goto, If or Return.
// The RootNode both starts and ends it's own block. Do this with a recursive
// backwards walk over the control edges.
// Allocate stack with enough space to avoid frequent realloc
while (nstack.is_nonempty()) {
// node and in's index from stack's top
// 'np' is _root (see above) or RegionNode, StartNode: we push on stack
// only nodes which point to the start of basic block (see below).
// idx > 0, except for the first node (_root) pushed on stack
// at the beginning when idx == 0.
// We will use the condition (idx == 0) later to end the build.
// Does the block end with a proper block-ending Node? One of Return,
// If or Goto? (This check should be done for visited nodes also).
if (x == NULL) { // Does not end right...
x = proj = g;
}
// Skip any control-pinned middle'in stuff
do {
proj = p; // Update pointer to last Control
p = p->in(0); // Move control forward
} while( !p->is_block_proj() &&
!p->is_block_start() );
// Make the block begin with one of Region or StartNode.
if( !p->is_block_start() ) {
p = r;
}
// 'p' now points to the start of this basic block
// Put self in array of basic blocks
if( x != p ) { // Only for root is x == p
}
// Now handle predecessors
++sum; // Count 1 for self block
// Check to see if p->in(i) is a "control-dependent" CFG edge -
// i.e., it splits at the source (via an IF or SWITCH) and merges
// at the destination (via a many-input Region).
// This breaks critical edges. The RegionNode to start the block
// will be added when <p,i> is pulled off the node stack
// Force a block on the control-dependent edge
p->set_req(i,g);
}
}
}
} else { // Post-processing visited nodes
// Check if it the fist node pushed on stack at the beginning.
if (idx == 0) break; // end of the build
// Find predecessor basic block
// Insert into nodes array, if not already there
// Map basic block of projection
}
// Insert self as a child of my predecessor block
"too many control users, not a CFG?" );
}
}
// Return number of basic blocks for all children and self
return sum;
}
//------------------------------insert_goto_at---------------------------------
// Inserts a goto & corresponding basic block between
// block[block_no] and its succ_no'th successor block
// get block with block_no
// get successor block succ_no
// Compute frequency of the new block. Do this before inserting
// new block in case succ_prob() needs to infer the probability from
// surrounding blocks.
// get ProjNode corresponding to the succ_no'th successor of the in block
// create region for basic block
// setup corresponding basic block
// add a goto node
// add it to the basic block
// hook up successor block
// remap successor's predecessors if necessary
}
// remap predecessor's successor to new block
// Set the frequency of the new block
// add new basic block to basic block list
_num_blocks++;
}
//------------------------------no_flip_branch---------------------------------
// Does this block end in a multiway branch that cannot have the default case
// flipped for another case?
static bool no_flip_branch( Block *b ) {
if( branch_idx < 1 ) return false;
return true;
if( bra->is_MachNullCheck() )
return true;
return true;
}
return false;
}
//------------------------------convert_NeverBranch_to_Goto--------------------
// Check for NeverBranch at block end. This needs to become a GOTO to the
// true target. NeverBranch are treated as a conditional branch that always
// goes the same direction for most of the optimizer and are used to give a
// fake exit path to infinite loops. At this late stage they need to turn
// into Goto's so that when you enter the infinite loop you indeed hang.
// Find true target
b->_num_succs = 1;
// remap successor's predecessors if necessary
uint j;
// Kill alternate exit path
break;
// Scan through block, yanking dead path from
// all regions and phis.
}
//------------------------------move_to_next-----------------------------------
// Helper function to move block bx to the slot following b_index. Return
// true if the move is successful, otherwise false
// Return false if bx is already scheduled.
return false;
}
// Find the current index of block bx on the block list
// If the previous block conditionally falls into bx, return false,
// because moving bx will create an extra jump.
return false;
}
}
}
// Reinsert bx just past block 'b'
return true;
}
//------------------------------move_to_end------------------------------------
// Move empty and uncommon blocks to the end.
int e = b->is_Empty();
if (e == Block::empty_with_goto) {
// Remove the goto, but leave the block.
}
// Mark this block as a connector block, which will cause it to be
// ignored in certain functions such as non_connector_successor().
b->set_connector();
}
// Move the empty block to the end, and don't recheck.
}
//---------------------------set_loop_alignment--------------------------------
// Set loop alignment for every block
void PhaseCFG::set_loop_alignment() {
b->set_loop_alignment(b);
}
}
}
//-----------------------------remove_empty------------------------------------
// Make empty basic blocks to be "connector" blocks, Move uncommon blocks
// to the end.
void PhaseCFG::remove_empty() {
// Move uncommon blocks to the end
if (b->is_connector()) break;
// Check for NeverBranch at block end. This needs to become a GOTO to the
// true target. NeverBranch are treated as a conditional branch that
// always goes the same direction for most of the optimizer and are used
// to give a fake exit path to infinite loops. At this late stage they
// need to turn into Goto's so that when you enter the infinite loop you
// indeed hang.
// Look for uncommon blocks and move to end.
if (!C->do_freq_based_layout()) {
if( b->is_uncommon(_bbs) ) {
move_to_end(b, i);
last--; // No longer check for being uncommon!
if( no_flip_branch(b) ) { // Fall-thru case must follow?
b = _blocks[i]; // Find the fall-thru block
move_to_end(b, i);
last--;
}
i--; // backup block counter post-increment
}
}
}
// Move empty blocks to the end
last = _num_blocks;
move_to_end(b, i);
last--;
i--;
}
} // End of for all blocks
}
//-----------------------------fixup_flow--------------------------------------
// Fix up the final control flow for basic blocks.
void PhaseCFG::fixup_flow() {
// Fixup final control flow for the blocks. Remove jump-to-next
// block. If neither arm of a IF follows the conditional branch, we
// have to add a second jump after the conditional. We place the
// TRUE branch target in succs[0] for both GOTOs and IFs.
for (uint i=0; i < _num_blocks; i++) {
b->_pre_order = i; // turn pre-order into block-index
// Connector blocks need no further processing.
if (b->is_connector()) {
"All connector blocks should sink to the end");
continue;
}
"Empty blocks should be connectors");
// Check for multi-way branches where I cannot negate the test to
// exchange the true and false targets.
if( no_flip_branch( b ) ) {
// Find fall through case - if must fall into its target
if (p->_con == 0) {
// successor j2 is fall through case
// but it is not the next block => insert a goto
insert_goto_at(i, j2);
}
// Put taken branch in slot 0
// Flip targets in succs map
}
break;
}
}
// Remove all CatchProjs
} else if (b->_num_succs == 1) {
// Block ends in a Goto?
// We fall into next block; remove the Goto
}
// Get opcode of 1st projection (matches _succs[0])
// Note: Since this basic block has 2 exits, the last 2 nodes must
// be projections (in any order), the 3rd last node must be
// the IfNode (we have excluded other 2-way exits such as
// CatchNodes already).
// Assert that proj0 and succs[0] match up. Similarly for proj1 and succs[1].
// Check for neither successor block following the current
// block ending in a conditional. If so, move one of the
// successors after the current one, provided that the
// successor was previously unscheduled, but moveable
// (i.e., all paths to it involve a branch).
// Choose the more common successor based on the probability
// of the conditional branch.
// _prob is the probability of taking the true path. Make
// p the probability of taking successor #1.
p = 1.0 - p;
}
// Prefer successor #1 if p > 0.5
if (p > PROB_FAIR) {
}
// Attempt the more common successor first
if (move_to_next(bx, i)) {
} else if (move_to_next(by, i)) {
}
}
// Check for conditional branching the wrong way. Negate
// conditional, if needed, so it falls into the following block
// and branches to the not-following block.
// Check for the next block being in succs[0]. We are going to branch
// to succs[0], so we want the fall-thru case as the next block in
// succs[1].
// Fall-thru case in succs[0], so flip targets in succs map
// Flip projection for each target
// Need a double-branch
// The existing conditional branch need not change.
// Add a unconditional branch to the false target.
// Alas, it must appear in its own block and adding a
// block this late in the game is complicated. Sigh.
insert_goto_at(i, 1);
}
// Make sure we TRUE branch to the target
}
} else {
// Multi-exit block, e.g. a switch statement
// But we don't need to do anything here
}
} // End of for all blocks
}
//------------------------------dump-------------------------------------------
#ifndef PRODUCT
assert( x, "not a CFG" );
// Do not visit this block again
// Skip through this block
const Node *p = x;
do {
p = p->in(0); // Move control forward
} while( !p->is_block_start() );
// Recursively visit
// Dump the block
}
for( uint i=0; i<_num_blocks; i++ )
} else { // Else do it with a DFS
}
}
void PhaseCFG::dump_headers() {
for( uint i = 0; i < _num_blocks; i++ ) {
}
}
#ifdef ASSERT
// Verify sane CFG
for (uint i = 0; i < _num_blocks; i++) {
uint j;
for (j = 0; j < cnt; j++) {
if (j >= 1 && n->is_Mach() &&
"CreateEx must be first instruction in block");
}
"must have block; constants for debug info ok");
// Verify that instructions in the block is in correct order.
// Uses must follow their definition if they are at the same block.
// Mostly done to check that MachSpillCopy nodes are placed correctly
// when CreateEx node is moved in build_ifg_physical().
// See (+++) comment in reg_split.cpp
bool is_loop = false;
if (n->is_Phi()) {
is_loop = true;
break; // Some kind of loop
}
}
}
}
}
}
}
j = b->end_idx();
while (b->_nodes[--j]->is_MachProj()) ;
}
}
#endif
}
#endif
//=============================================================================
//------------------------------UnionFind--------------------------------------
}
}
}
// Force the Union-Find mapping to be at least this large
// Initialize to be the ID mapping.
}
//------------------------------Find_compress----------------------------------
// Straight out of Tarjan's union-find algorithm
}
// Core of union-find algorithm: update chain of
// equivalences to be equal to the root.
}
return idx;
}
//------------------------------Find_const-------------------------------------
// Like Find above, but no path compress, so bad asymptotic behavior
// Off the end? This can happen during debugging dumps
// when data structures have not finished being updated.
}
return next;
}
//------------------------------Union------------------------------------------
// union 2 sets together.
}
#ifndef PRODUCT
if (e != NULL) {
}
}
}
for (int i = 0; i < count; i++) {
}
}
}
}
if (b->has_loop_alignment()) {
}
}
}
switch(state()) {
case connected:
break;
case open:
break;
case interior:
break;
}
if (infrequent()) {
}
}
#endif
//=============================================================================
//------------------------------edge_order-------------------------------------
// Comparison function for edges
}
}
//------------------------------trace_frequency_order--------------------------
// Comparison function for edges
// The trace of connector blocks goes at the end;
// we only expect one such trace
}
// Pull more frequently executed blocks to the beginning
}
return diff;
}
//------------------------------find_edges-------------------------------------
// Find edges of interest, i.e, those which can fall through. Presumes that
// edges which don't fall through are of low frequency and can be generally
// ignored. Initialize the list of traces.
void PhaseBlockLayout::find_edges()
{
// Walk the blocks, creating edges and Traces
uint i;
for (i = 0; i < _cfg._num_blocks; i++) {
// All connector blocks should be at the end of the list
if (b->is_connector()) break;
// If this block and the next one have a one-to-one successor
// predecessor relationship, simply append the next block
int nfallthru = b->num_fall_throughs();
while (nfallthru == 1 &&
b->succ_fall_through(0)) {
// Skip over single-entry connector blocks, we don't want to
// add them to the trace.
n = n->_succs[0];
}
// We see a merge point, so stop search for the next block
if (n->num_preds() != 1) break;
i++;
nfallthru = b->num_fall_throughs();
b = n;
}
if (nfallthru > 0) {
// Create a CFGEdge for each outgoing
// edge that could be a fall-through.
for (uint j = 0; j < b->_num_succs; j++ ) {
if (b->succ_fall_through(j)) {
}
}
}
}
// Group connector blocks into one trace
for (i++; i < _cfg._num_blocks; i++) {
}
}
//------------------------------union_traces----------------------------------
// Union two traces together in uf, and null out the trace in the list
{
// If from is greater than to, swap values to meet
// UnionFind guarantee.
if (updated_id > old_id) {
hi_id = updated_id;
// Fix up the trace ids
}
// Union the lower with the higher and remove the pointer
// to the higher.
}
//------------------------------grow_traces-------------------------------------
// Append traces together via the most frequently executed edges
void PhaseBlockLayout::grow_traces()
{
// Order the edges, and drive the growth of Traces via the most
// frequently executed edges.
// Don't grow traces along backedges?
if (!BlockLayoutRotateLoops) {
continue;
}
}
// If the edge in question can join two traces at their ends,
// append one trace to the other.
if (src_trace == targ_trace) {
if (targ_trace->backedge(e)) {
// Reset i to catch any newly eligible edge
// (Or we could remember the first "open" edge, and reset there)
i = 0;
}
}
}
}
}
//------------------------------merge_traces-----------------------------------
// Embed one trace into another, if the fork or join points are sufficiently
// balanced.
{
// Walk the edge list a another time, looking at unprocessed edges.
// Fold in diamonds
if (fall_thru_only) {
if (e->infrequent()) continue;
}
if (src_trace == targ_trace) {
// This may be a loop, but we can't do much about it.
continue;
}
if (fall_thru_only) {
// If the edge links the middle of two traces, we can't do anything.
// Mark the edge and continue.
if (!src_at_tail & !targ_at_start) {
continue;
}
// Don't grow traces along backedges?
continue;
}
// If both ends of the edge are available, why didn't we handle it earlier?
if (targ_at_start) {
// Insert the "targ" trace in the "src" trace if the insertion point
// is a two way branch.
// Better profitability check possible, but may not be worth it.
// Someday, see if the this "fork" has an associated "join";
// then make a policy on merging this trace at the fork or join.
// For example, other things being equal, it may be better to place this
// trace at the join point if the "src" trace ends in a two-way, but
// the insertion point is one-way.
} else if (src_at_tail) {
}
}
// Append traces, even without a fall-thru connection.
// But leave root entry at the beginning of the block list.
}
}
}
}
//----------------------------reorder_traces-----------------------------------
// Order the sequence of the traces in some desirable way, and fixup the
// jumps at the end of each block.
{
int new_count = 0;
// Compact the traces.
for (int i = 0; i < count; i++) {
}
}
// The entry block should be first on the new trace list.
// Sort the new trace list by frequency
// Patch up the successor blocks
_cfg._num_blocks = 0;
for (int i = 0; i < new_count; i++) {
}
}
}
//------------------------------PhaseBlockLayout-------------------------------
// Order basic blocks based on frequency
{
// List of traces
// List of edges
// Mapping block index --> block_trace
// Find edges and create traces.
find_edges();
// Grow traces at their ends via most frequent edges.
grow_traces();
// Merge one trace into another, but only at fall-through points.
// This may make diamonds and other related shapes in a trace.
merge_traces(true);
// Run merge again, allowing two traces to be catenated, even if
// one does not fall through into the other. This appends loosely
// related traces to be near each other.
merge_traces(false);
// Re-order all the remaining traces by frequency
}
//------------------------------backedge---------------------------------------
// Edge e completes a loop in a trace. If the target block is head of the
// loop, rotate the loop block so that the loop ends in a conditional branch.
bool loop_rotated = false;
if (first_block() == targ_block) {
// Find the last block in the trace that has a conditional
// branch.
Block *b;
if (b->num_fall_throughs() == 2) {
break;
}
}
if (b != last_block() && b != NULL) {
loop_rotated = true;
// Rotate the loop by doing two-part linked-list surgery.
append(first_block());
break_loop_after(b);
}
}
// Backbranch to the top of a trace
// Scroll forward through the trace from the targ_block. If we find
// a loop head before another loop top, use the the loop head alignment.
if (b->has_loop_alignment()) {
break;
}
targ_block = b;
break;
}
}
} else {
// Backbranch into the middle of a trace
}
return loop_rotated;
}
//------------------------------fixup_blocks-----------------------------------
// push blocks onto the CFG list
// ensure that blocks have the correct two-way branch sense
cfg._num_blocks++;
if (!b->is_connector()) {
int nfallthru = b->num_fall_throughs();
if (b != last) {
if (nfallthru == 2) {
// Ensure that the sense of the branch is correct
// Fall-thru case in succs[0], should be in succs[1]
// Flip targets in _succs map
// Flip projections to match targets
}
}
}
}
}
}