Path: blob/master/src/hotspot/share/opto/block.hpp
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#ifndef SHARE_OPTO_BLOCK_HPP25#define SHARE_OPTO_BLOCK_HPP2627#include "opto/multnode.hpp"28#include "opto/node.hpp"29#include "opto/phase.hpp"30#include "utilities/powerOfTwo.hpp"3132// Optimization - Graph Style3334class Block;35class CFGLoop;36class MachCallNode;37class Matcher;38class RootNode;39class VectorSet;40class PhaseChaitin;41struct Tarjan;4243//------------------------------Block_Array------------------------------------44// Map dense integer indices to Blocks. Uses classic doubling-array trick.45// Abstractly provides an infinite array of Block*'s, initialized to NULL.46// Note that the constructor just zeros things, and since I use Arena47// allocation I do not need a destructor to reclaim storage.48class Block_Array : public ResourceObj {49friend class VMStructs;50uint _size; // allocated size, as opposed to formal limit51debug_only(uint _limit;) // limit to formal domain52Arena *_arena; // Arena to allocate in53protected:54Block **_blocks;55void grow( uint i ); // Grow array node to fit5657public:58Block_Array(Arena *a) : _size(OptoBlockListSize), _arena(a) {59debug_only(_limit=0);60_blocks = NEW_ARENA_ARRAY( a, Block *, OptoBlockListSize );61for( int i = 0; i < OptoBlockListSize; i++ ) {62_blocks[i] = NULL;63}64}65Block *lookup( uint i ) const // Lookup, or NULL for not mapped66{ return (i<Max()) ? _blocks[i] : (Block*)NULL; }67Block *operator[] ( uint i ) const // Lookup, or assert for not mapped68{ assert( i < Max(), "oob" ); return _blocks[i]; }69// Extend the mapping: index i maps to Block *n.70void map( uint i, Block *n ) { if( i>=Max() ) grow(i); _blocks[i] = n; }71uint Max() const { debug_only(return _limit); return _size; }72};737475class Block_List : public Block_Array {76friend class VMStructs;77public:78uint _cnt;79Block_List() : Block_Array(Thread::current()->resource_area()), _cnt(0) {}80void push( Block *b ) { map(_cnt++,b); }81Block *pop() { return _blocks[--_cnt]; }82Block *rpop() { Block *b = _blocks[0]; _blocks[0]=_blocks[--_cnt]; return b;}83void remove( uint i );84void insert( uint i, Block *n );85uint size() const { return _cnt; }86void reset() { _cnt = 0; }87void print();88};899091class CFGElement : public ResourceObj {92friend class VMStructs;93public:94double _freq; // Execution frequency (estimate)9596CFGElement() : _freq(0.0) {}97virtual bool is_block() { return false; }98virtual bool is_loop() { return false; }99Block* as_Block() { assert(is_block(), "must be block"); return (Block*)this; }100CFGLoop* as_CFGLoop() { assert(is_loop(), "must be loop"); return (CFGLoop*)this; }101};102103//------------------------------Block------------------------------------------104// This class defines a Basic Block.105// Basic blocks are used during the output routines, and are not used during106// any optimization pass. They are created late in the game.107class Block : public CFGElement {108friend class VMStructs;109110private:111// Nodes in this block, in order112Node_List _nodes;113114public:115116// Get the node at index 'at_index', if 'at_index' is out of bounds return NULL117Node* get_node(uint at_index) const {118return _nodes[at_index];119}120121// Get the number of nodes in this block122uint number_of_nodes() const {123return _nodes.size();124}125126// Map a node 'node' to index 'to_index' in the block, if the index is out of bounds the size of the node list is increased127void map_node(Node* node, uint to_index) {128_nodes.map(to_index, node);129}130131// Insert a node 'node' at index 'at_index', moving all nodes that are on a higher index one step, if 'at_index' is out of bounds we crash132void insert_node(Node* node, uint at_index) {133_nodes.insert(at_index, node);134}135136// Remove a node at index 'at_index'137void remove_node(uint at_index) {138_nodes.remove(at_index);139}140141// Push a node 'node' onto the node list142void push_node(Node* node) {143_nodes.push(node);144}145146// Pop the last node off the node list147Node* pop_node() {148return _nodes.pop();149}150151// Basic blocks have a Node which defines Control for all Nodes pinned in152// this block. This Node is a RegionNode. Exception-causing Nodes153// (division, subroutines) and Phi functions are always pinned. Later,154// every Node will get pinned to some block.155Node *head() const { return get_node(0); }156157// CAUTION: num_preds() is ONE based, so that predecessor numbers match158// input edges to Regions and Phis.159uint num_preds() const { return head()->req(); }160Node *pred(uint i) const { return head()->in(i); }161162// Array of successor blocks, same size as projs array163Block_Array _succs;164165// Basic blocks have some number of Nodes which split control to all166// following blocks. These Nodes are always Projections. The field in167// the Projection and the block-ending Node determine which Block follows.168uint _num_succs;169170// Basic blocks also carry all sorts of good old fashioned DFS information171// used to find loops, loop nesting depth, dominators, etc.172uint _pre_order; // Pre-order DFS number173174// Dominator tree175uint _dom_depth; // Depth in dominator tree for fast LCA176Block* _idom; // Immediate dominator block177178CFGLoop *_loop; // Loop to which this block belongs179uint _rpo; // Number in reverse post order walk180181virtual bool is_block() { return true; }182float succ_prob(uint i); // return probability of i'th successor183int num_fall_throughs(); // How many fall-through candidate this block has184void update_uncommon_branch(Block* un); // Lower branch prob to uncommon code185bool succ_fall_through(uint i); // Is successor "i" is a fall-through candidate186Block* lone_fall_through(); // Return lone fall-through Block or null187188Block* dom_lca(Block* that); // Compute LCA in dominator tree.189190bool dominates(Block* that) {191int dom_diff = this->_dom_depth - that->_dom_depth;192if (dom_diff > 0) return false;193for (; dom_diff < 0; dom_diff++) that = that->_idom;194return this == that;195}196197// Report the alignment required by this block. Must be a power of 2.198// The previous block will insert nops to get this alignment.199uint code_alignment() const;200uint compute_loop_alignment();201202// BLOCK_FREQUENCY is a sentinel to mark uses of constant block frequencies.203// It is currently also used to scale such frequencies relative to204// FreqCountInvocations relative to the old value of 1500.205#define BLOCK_FREQUENCY(f) ((f * (double) 1500) / FreqCountInvocations)206207// Register Pressure (estimate) for Splitting heuristic208uint _reg_pressure;209uint _ihrp_index;210uint _freg_pressure;211uint _fhrp_index;212213// Mark and visited bits for an LCA calculation in insert_anti_dependences.214// Since they hold unique node indexes, they do not need reinitialization.215node_idx_t _raise_LCA_mark;216void set_raise_LCA_mark(node_idx_t x) { _raise_LCA_mark = x; }217node_idx_t raise_LCA_mark() const { return _raise_LCA_mark; }218node_idx_t _raise_LCA_visited;219void set_raise_LCA_visited(node_idx_t x) { _raise_LCA_visited = x; }220node_idx_t raise_LCA_visited() const { return _raise_LCA_visited; }221222// Estimated size in bytes of first instructions in a loop.223uint _first_inst_size;224uint first_inst_size() const { return _first_inst_size; }225void set_first_inst_size(uint s) { _first_inst_size = s; }226227// Compute the size of first instructions in this block.228uint compute_first_inst_size(uint& sum_size, uint inst_cnt, PhaseRegAlloc* ra);229230// Compute alignment padding if the block needs it.231// Align a loop if loop's padding is less or equal to padding limit232// or the size of first instructions in the loop > padding.233uint alignment_padding(int current_offset) {234int block_alignment = code_alignment();235int max_pad = block_alignment-relocInfo::addr_unit();236if( max_pad > 0 ) {237assert(is_power_of_2(max_pad+relocInfo::addr_unit()), "");238int current_alignment = current_offset & max_pad;239if( current_alignment != 0 ) {240uint padding = (block_alignment-current_alignment) & max_pad;241if( has_loop_alignment() &&242padding > (uint)MaxLoopPad &&243first_inst_size() <= padding ) {244return 0;245}246return padding;247}248}249return 0;250}251252// Connector blocks. Connector blocks are basic blocks devoid of253// instructions, but may have relevant non-instruction Nodes, such as254// Phis or MergeMems. Such blocks are discovered and marked during the255// RemoveEmpty phase, and elided during Output.256bool _connector;257void set_connector() { _connector = true; }258bool is_connector() const { return _connector; };259260// Loop_alignment will be set for blocks which are at the top of loops.261// The block layout pass may rotate loops such that the loop head may not262// be the sequentially first block of the loop encountered in the linear263// list of blocks. If the layout pass is not run, loop alignment is set264// for each block which is the head of a loop.265uint _loop_alignment;266void set_loop_alignment(Block *loop_top) {267uint new_alignment = loop_top->compute_loop_alignment();268if (new_alignment > _loop_alignment) {269_loop_alignment = new_alignment;270}271}272uint loop_alignment() const { return _loop_alignment; }273bool has_loop_alignment() const { return loop_alignment() > 0; }274275// Create a new Block with given head Node.276// Creates the (empty) predecessor arrays.277Block( Arena *a, Node *headnode )278: CFGElement(),279_nodes(a),280_succs(a),281_num_succs(0),282_pre_order(0),283_idom(0),284_loop(NULL),285_reg_pressure(0),286_ihrp_index(1),287_freg_pressure(0),288_fhrp_index(1),289_raise_LCA_mark(0),290_raise_LCA_visited(0),291_first_inst_size(999999),292_connector(false),293_loop_alignment(0) {294_nodes.push(headnode);295}296297// Index of 'end' Node298uint end_idx() const {299// %%%%% add a proj after every goto300// so (last->is_block_proj() != last) always, then simplify this code301// This will not give correct end_idx for block 0 when it only contains root.302int last_idx = _nodes.size() - 1;303Node *last = _nodes[last_idx];304assert(last->is_block_proj() == last || last->is_block_proj() == _nodes[last_idx - _num_succs], "");305return (last->is_block_proj() == last) ? last_idx : (last_idx - _num_succs);306}307308// Basic blocks have a Node which ends them. This Node determines which309// basic block follows this one in the program flow. This Node is either an310// IfNode, a GotoNode, a JmpNode, or a ReturnNode.311Node *end() const { return _nodes[end_idx()]; }312313// Add an instruction to an existing block. It must go after the head314// instruction and before the end instruction.315void add_inst( Node *n ) { insert_node(n, end_idx()); }316// Find node in block. Fails if node not in block.317uint find_node( const Node *n ) const;318// Find and remove n from block list319void find_remove( const Node *n );320// Check whether the node is in the block.321bool contains (const Node *n) const;322323// Return the empty status of a block324enum { not_empty, empty_with_goto, completely_empty };325int is_Empty() const;326327// Forward through connectors328Block* non_connector() {329Block* s = this;330while (s->is_connector()) {331s = s->_succs[0];332}333return s;334}335336// Return true if b is a successor of this block337bool has_successor(Block* b) const {338for (uint i = 0; i < _num_succs; i++ ) {339if (non_connector_successor(i) == b) {340return true;341}342}343return false;344}345346// Successor block, after forwarding through connectors347Block* non_connector_successor(int i) const {348return _succs[i]->non_connector();349}350351// Examine block's code shape to predict if it is not commonly executed.352bool has_uncommon_code() const;353354#ifndef PRODUCT355// Debugging print of basic block356void dump_bidx(const Block* orig, outputStream* st = tty) const;357void dump_pred(const PhaseCFG* cfg, Block* orig, outputStream* st = tty) const;358void dump_head(const PhaseCFG* cfg, outputStream* st = tty) const;359void dump() const;360void dump(const PhaseCFG* cfg) const;361#endif362};363364365//------------------------------PhaseCFG---------------------------------------366// Build an array of Basic Block pointers, one per Node.367class PhaseCFG : public Phase {368friend class VMStructs;369private:370// Root of whole program371RootNode* _root;372373// The block containing the root node374Block* _root_block;375376// List of basic blocks that are created during CFG creation377Block_List _blocks;378379// Count of basic blocks380uint _number_of_blocks;381382// Arena for the blocks to be stored in383Arena* _block_arena;384385// Info used for scheduling386PhaseChaitin* _regalloc;387388// Register pressure heuristic used?389bool _scheduling_for_pressure;390391// The matcher for this compilation392Matcher& _matcher;393394// Map nodes to owning basic block395Block_Array _node_to_block_mapping;396397// Loop from the root398CFGLoop* _root_loop;399400// Outmost loop frequency401double _outer_loop_frequency;402403// Per node latency estimation, valid only during GCM404GrowableArray<uint>* _node_latency;405406// Build a proper looking cfg. Return count of basic blocks407uint build_cfg();408409// Build the dominator tree so that we know where we can move instructions410void build_dominator_tree();411412// Estimate block frequencies based on IfNode probabilities, so that we know where we want to move instructions413void estimate_block_frequency();414415// Global Code Motion. See Click's PLDI95 paper. Place Nodes in specific416// basic blocks; i.e. _node_to_block_mapping now maps _idx for all Nodes to some Block.417// Move nodes to ensure correctness from GVN and also try to move nodes out of loops.418void global_code_motion();419420// Schedule Nodes early in their basic blocks.421bool schedule_early(VectorSet &visited, Node_Stack &roots);422423// For each node, find the latest block it can be scheduled into424// and then select the cheapest block between the latest and earliest425// block to place the node.426void schedule_late(VectorSet &visited, Node_Stack &stack);427428// Compute the (backwards) latency of a node from a single use429int latency_from_use(Node *n, const Node *def, Node *use);430431// Compute the (backwards) latency of a node from the uses of this instruction432void partial_latency_of_defs(Node *n);433434// Compute the instruction global latency with a backwards walk435void compute_latencies_backwards(VectorSet &visited, Node_Stack &stack);436437// Pick a block between early and late that is a cheaper alternative438// to late. Helper for schedule_late.439Block* hoist_to_cheaper_block(Block* LCA, Block* early, Node* self);440441bool schedule_local(Block* block, GrowableArray<int>& ready_cnt, VectorSet& next_call, intptr_t* recacl_pressure_nodes);442void set_next_call(Block* block, Node* n, VectorSet& next_call);443void needed_for_next_call(Block* block, Node* this_call, VectorSet& next_call);444445// Perform basic-block local scheduling446Node* select(Block* block, Node_List& worklist, GrowableArray<int>& ready_cnt, VectorSet& next_call, uint sched_slot,447intptr_t* recacl_pressure_nodes);448void adjust_register_pressure(Node* n, Block* block, intptr_t *recalc_pressure_nodes, bool finalize_mode);449450// Schedule a call next in the block451uint sched_call(Block* block, uint node_cnt, Node_List& worklist, GrowableArray<int>& ready_cnt, MachCallNode* mcall, VectorSet& next_call);452453// Cleanup if any code lands between a Call and his Catch454void call_catch_cleanup(Block* block);455456Node* catch_cleanup_find_cloned_def(Block* use_blk, Node* def, Block* def_blk, int n_clone_idx);457void catch_cleanup_inter_block(Node *use, Block *use_blk, Node *def, Block *def_blk, int n_clone_idx);458459// Detect implicit-null-check opportunities. Basically, find NULL checks460// with suitable memory ops nearby. Use the memory op to do the NULL check.461// I can generate a memory op if there is not one nearby.462void implicit_null_check(Block* block, Node *proj, Node *val, int allowed_reasons);463464// Perform a Depth First Search (DFS).465// Setup 'vertex' as DFS to vertex mapping.466// Setup 'semi' as vertex to DFS mapping.467// Set 'parent' to DFS parent.468uint do_DFS(Tarjan* tarjan, uint rpo_counter);469470// Helper function to insert a node into a block471void schedule_node_into_block( Node *n, Block *b );472473void replace_block_proj_ctrl( Node *n );474475// Set the basic block for pinned Nodes476void schedule_pinned_nodes( VectorSet &visited );477478// I'll need a few machine-specific GotoNodes. Clone from this one.479// Used when building the CFG and creating end nodes for blocks.480MachNode* _goto;481482Block* insert_anti_dependences(Block* LCA, Node* load, bool verify = false);483void verify_anti_dependences(Block* LCA, Node* load) const {484assert(LCA == get_block_for_node(load), "should already be scheduled");485const_cast<PhaseCFG*>(this)->insert_anti_dependences(LCA, load, true);486}487488bool move_to_next(Block* bx, uint b_index);489void move_to_end(Block* bx, uint b_index);490491void insert_goto_at(uint block_no, uint succ_no);492493// Check for NeverBranch at block end. This needs to become a GOTO to the494// true target. NeverBranch are treated as a conditional branch that always495// goes the same direction for most of the optimizer and are used to give a496// fake exit path to infinite loops. At this late stage they need to turn497// into Goto's so that when you enter the infinite loop you indeed hang.498void convert_NeverBranch_to_Goto(Block *b);499500CFGLoop* create_loop_tree();501bool is_dominator(Node* dom_node, Node* node);502bool is_CFG(Node* n);503bool is_control_proj_or_safepoint(Node* n) const;504Block* find_block_for_node(Node* n) const;505bool is_dominating_control(Node* dom_ctrl, Node* n);506#ifndef PRODUCT507bool _trace_opto_pipelining; // tracing flag508#endif509510public:511PhaseCFG(Arena* arena, RootNode* root, Matcher& matcher);512513void set_latency_for_node(Node* node, int latency) {514_node_latency->at_put_grow(node->_idx, latency);515}516517uint get_latency_for_node(Node* node) {518return _node_latency->at_grow(node->_idx);519}520521// Get the outer most frequency522double get_outer_loop_frequency() const {523return _outer_loop_frequency;524}525526// Get the root node of the CFG527RootNode* get_root_node() const {528return _root;529}530531// Get the block of the root node532Block* get_root_block() const {533return _root_block;534}535536// Add a block at a position and moves the later ones one step537void add_block_at(uint pos, Block* block) {538_blocks.insert(pos, block);539_number_of_blocks++;540}541542// Adds a block to the top of the block list543void add_block(Block* block) {544_blocks.push(block);545_number_of_blocks++;546}547548// Clear the list of blocks549void clear_blocks() {550_blocks.reset();551_number_of_blocks = 0;552}553554// Get the block at position pos in _blocks555Block* get_block(uint pos) const {556return _blocks[pos];557}558559// Number of blocks560uint number_of_blocks() const {561return _number_of_blocks;562}563564// set which block this node should reside in565void map_node_to_block(const Node* node, Block* block) {566_node_to_block_mapping.map(node->_idx, block);567}568569// removes the mapping from a node to a block570void unmap_node_from_block(const Node* node) {571_node_to_block_mapping.map(node->_idx, NULL);572}573574// get the block in which this node resides575Block* get_block_for_node(const Node* node) const {576return _node_to_block_mapping[node->_idx];577}578579// does this node reside in a block; return true580bool has_block(const Node* node) const {581return (_node_to_block_mapping.lookup(node->_idx) != NULL);582}583584// Use frequency calculations and code shape to predict if the block585// is uncommon.586bool is_uncommon(const Block* block);587588#ifdef ASSERT589Unique_Node_List _raw_oops;590#endif591592// Do global code motion by first building dominator tree and estimate block frequency593// Returns true on success594bool do_global_code_motion();595596// Compute the (backwards) latency of a node from the uses597void latency_from_uses(Node *n);598599// Set loop alignment600void set_loop_alignment();601602// Remove empty basic blocks603void remove_empty_blocks();604Block *fixup_trap_based_check(Node *branch, Block *block, int block_pos, Block *bnext);605void fixup_flow();606607// Insert a node into a block at index and map the node to the block608void insert(Block *b, uint idx, Node *n) {609b->insert_node(n , idx);610map_node_to_block(n, b);611}612613// Check all nodes and postalloc_expand them if necessary.614void postalloc_expand(PhaseRegAlloc* _ra);615616#ifndef PRODUCT617bool trace_opto_pipelining() const { return _trace_opto_pipelining; }618619// Debugging print of CFG620void dump( ) const; // CFG only621void _dump_cfg( const Node *end, VectorSet &visited ) const;622void dump_headers();623#else624bool trace_opto_pipelining() const { return false; }625#endif626627// Check that block b is in the home loop (or an ancestor) of n, if n is a628// memory writer.629void verify_memory_writer_placement(const Block* b, const Node* n) const NOT_DEBUG_RETURN;630void verify() const NOT_DEBUG_RETURN;631};632633634//------------------------------UnionFind--------------------------------------635// Map Block indices to a block-index for a cfg-cover.636// Array lookup in the optimized case.637class UnionFind : public ResourceObj {638uint _cnt, _max;639uint* _indices;640ReallocMark _nesting; // assertion check for reallocations641public:642UnionFind( uint max );643void reset( uint max ); // Reset to identity map for [0..max]644645uint lookup( uint nidx ) const {646return _indices[nidx];647}648uint operator[] (uint nidx) const { return lookup(nidx); }649650void map( uint from_idx, uint to_idx ) {651assert( from_idx < _cnt, "oob" );652_indices[from_idx] = to_idx;653}654void extend( uint from_idx, uint to_idx );655656uint Size() const { return _cnt; }657658uint Find( uint idx ) {659assert( idx < 65536, "Must fit into uint");660uint uf_idx = lookup(idx);661return (uf_idx == idx) ? uf_idx : Find_compress(idx);662}663uint Find_compress( uint idx );664uint Find_const( uint idx ) const;665void Union( uint idx1, uint idx2 );666667};668669//----------------------------BlockProbPair---------------------------670// Ordered pair of Node*.671class BlockProbPair {672protected:673Block* _target; // block target674double _prob; // probability of edge to block675public:676BlockProbPair() : _target(NULL), _prob(0.0) {}677BlockProbPair(Block* b, double p) : _target(b), _prob(p) {}678679Block* get_target() const { return _target; }680double get_prob() const { return _prob; }681};682683//------------------------------CFGLoop-------------------------------------------684class CFGLoop : public CFGElement {685friend class VMStructs;686int _id;687int _depth;688CFGLoop *_parent; // root of loop tree is the method level "pseudo" loop, it's parent is null689CFGLoop *_sibling; // null terminated list690CFGLoop *_child; // first child, use child's sibling to visit all immediately nested loops691GrowableArray<CFGElement*> _members; // list of members of loop692GrowableArray<BlockProbPair> _exits; // list of successor blocks and their probabilities693double _exit_prob; // probability any loop exit is taken on a single loop iteration694void update_succ_freq(Block* b, double freq);695696public:697CFGLoop(int id) :698CFGElement(),699_id(id),700_depth(0),701_parent(NULL),702_sibling(NULL),703_child(NULL),704_exit_prob(1.0f) {}705CFGLoop* parent() { return _parent; }706void push_pred(Block* blk, int i, Block_List& worklist, PhaseCFG* cfg);707void add_member(CFGElement *s) { _members.push(s); }708void add_nested_loop(CFGLoop* cl);709Block* head() {710assert(_members.at(0)->is_block(), "head must be a block");711Block* hd = _members.at(0)->as_Block();712assert(hd->_loop == this, "just checking");713assert(hd->head()->is_Loop(), "must begin with loop head node");714return hd;715}716Block* backedge_block(); // Return the block on the backedge of the loop (else NULL)717void compute_loop_depth(int depth);718void compute_freq(); // compute frequency with loop assuming head freq 1.0f719void scale_freq(); // scale frequency by loop trip count (including outer loops)720double outer_loop_freq() const; // frequency of outer loop721bool in_loop_nest(Block* b);722double trip_count() const { return 1.0 / _exit_prob; }723virtual bool is_loop() { return true; }724int id() { return _id; }725int depth() { return _depth; }726727#ifndef PRODUCT728void dump( ) const;729void dump_tree() const;730#endif731};732733734//----------------------------------CFGEdge------------------------------------735// A edge between two basic blocks that will be embodied by a branch or a736// fall-through.737class CFGEdge : public ResourceObj {738friend class VMStructs;739private:740Block * _from; // Source basic block741Block * _to; // Destination basic block742double _freq; // Execution frequency (estimate)743int _state;744bool _infrequent;745int _from_pct;746int _to_pct;747748// Private accessors749int from_pct() const { return _from_pct; }750int to_pct() const { return _to_pct; }751int from_infrequent() const { return from_pct() < BlockLayoutMinDiamondPercentage; }752int to_infrequent() const { return to_pct() < BlockLayoutMinDiamondPercentage; }753754public:755enum {756open, // initial edge state; unprocessed757connected, // edge used to connect two traces together758interior // edge is interior to trace (could be backedge)759};760761CFGEdge(Block *from, Block *to, double freq, int from_pct, int to_pct) :762_from(from), _to(to), _freq(freq),763_state(open), _from_pct(from_pct), _to_pct(to_pct) {764_infrequent = from_infrequent() || to_infrequent();765}766767double freq() const { return _freq; }768Block* from() const { return _from; }769Block* to () const { return _to; }770int infrequent() const { return _infrequent; }771int state() const { return _state; }772773void set_state(int state) { _state = state; }774775#ifndef PRODUCT776void dump( ) const;777#endif778};779780781//-----------------------------------Trace-------------------------------------782// An ordered list of basic blocks.783class Trace : public ResourceObj {784private:785uint _id; // Unique Trace id (derived from initial block)786Block ** _next_list; // Array mapping index to next block787Block ** _prev_list; // Array mapping index to previous block788Block * _first; // First block in the trace789Block * _last; // Last block in the trace790791// Return the block that follows "b" in the trace.792Block * next(Block *b) const { return _next_list[b->_pre_order]; }793void set_next(Block *b, Block *n) const { _next_list[b->_pre_order] = n; }794795// Return the block that precedes "b" in the trace.796Block * prev(Block *b) const { return _prev_list[b->_pre_order]; }797void set_prev(Block *b, Block *p) const { _prev_list[b->_pre_order] = p; }798799// We've discovered a loop in this trace. Reset last to be "b", and first as800// the block following "b801void break_loop_after(Block *b) {802_last = b;803_first = next(b);804set_prev(_first, NULL);805set_next(_last, NULL);806}807808public:809810Trace(Block *b, Block **next_list, Block **prev_list) :811_id(b->_pre_order),812_next_list(next_list),813_prev_list(prev_list),814_first(b),815_last(b) {816set_next(b, NULL);817set_prev(b, NULL);818};819820// Return the id number821uint id() const { return _id; }822void set_id(uint id) { _id = id; }823824// Return the first block in the trace825Block * first_block() const { return _first; }826827// Return the last block in the trace828Block * last_block() const { return _last; }829830// Insert a trace in the middle of this one after b831void insert_after(Block *b, Trace *tr) {832set_next(tr->last_block(), next(b));833if (next(b) != NULL) {834set_prev(next(b), tr->last_block());835}836837set_next(b, tr->first_block());838set_prev(tr->first_block(), b);839840if (b == _last) {841_last = tr->last_block();842}843}844845void insert_before(Block *b, Trace *tr) {846Block *p = prev(b);847assert(p != NULL, "use append instead");848insert_after(p, tr);849}850851// Append another trace to this one.852void append(Trace *tr) {853insert_after(_last, tr);854}855856// Append a block at the end of this trace857void append(Block *b) {858set_next(_last, b);859set_prev(b, _last);860_last = b;861}862863// Adjust the the blocks in this trace864void fixup_blocks(PhaseCFG &cfg);865bool backedge(CFGEdge *e);866867#ifndef PRODUCT868void dump( ) const;869#endif870};871872//------------------------------PhaseBlockLayout-------------------------------873// Rearrange blocks into some canonical order, based on edges and their frequencies874class PhaseBlockLayout : public Phase {875friend class VMStructs;876PhaseCFG &_cfg; // Control flow graph877878GrowableArray<CFGEdge *> *edges;879Trace **traces;880Block **next;881Block **prev;882UnionFind *uf;883884// Given a block, find its encompassing Trace885Trace * trace(Block *b) {886return traces[uf->Find_compress(b->_pre_order)];887}888public:889PhaseBlockLayout(PhaseCFG &cfg);890891void find_edges();892void grow_traces();893void merge_traces(bool loose_connections);894void reorder_traces(int count);895void union_traces(Trace* from, Trace* to);896};897898#endif // SHARE_OPTO_BLOCK_HPP899900901