1 #ifdef USE_PRAGMA_IDENT_HDR
   2 #pragma ident "@(#)block.hpp    1.102 07/09/25 09:22:14 JVM"
   3 #endif
   4 /*
   5  * Copyright 1997-2008 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 // Optimization - Graph Style
  29 
  30 class Block;
  31 class CFGLoop;
  32 class MachCallNode;
  33 class Matcher;
  34 class RootNode;
  35 class VectorSet;
  36 struct Tarjan;
  37 
  38 //------------------------------Block_Array------------------------------------
  39 // Map dense integer indices to Blocks.  Uses classic doubling-array trick.
  40 // Abstractly provides an infinite array of Block*'s, initialized to NULL.
  41 // Note that the constructor just zeros things, and since I use Arena 
  42 // allocation I do not need a destructor to reclaim storage.
  43 class Block_Array : public ResourceObj {
  44   uint _size;                   // allocated size, as opposed to formal limit
  45   debug_only(uint _limit;)      // limit to formal domain
  46 protected:
  47   Block **_blocks;
  48   void grow( uint i );          // Grow array node to fit
  49 
  50 public:
  51   Arena *_arena;                // Arena to allocate in
  52 
  53   Block_Array(Arena *a) : _arena(a), _size(OptoBlockListSize) {
  54     debug_only(_limit=0);
  55     _blocks = NEW_ARENA_ARRAY( a, Block *, OptoBlockListSize );
  56     for( int i = 0; i < OptoBlockListSize; i++ ) {
  57       _blocks[i] = NULL;
  58     }
  59   }
  60   Block *lookup( uint i ) const // Lookup, or NULL for not mapped
  61   { return (i<Max()) ? _blocks[i] : (Block*)NULL; }
  62   Block *operator[] ( uint i ) const // Lookup, or assert for not mapped
  63   { assert( i < Max(), "oob" ); return _blocks[i]; }
  64   // Extend the mapping: index i maps to Block *n.
  65   void map( uint i, Block *n ) { if( i>=Max() ) grow(i); _blocks[i] = n; }
  66   uint Max() const { debug_only(return _limit); return _size; }
  67 };
  68 
  69 
  70 class Block_List : public Block_Array {
  71 public:
  72   uint _cnt;
  73   Block_List() : Block_Array(Thread::current()->resource_area()), _cnt(0) {}
  74   void push( Block *b ) { map(_cnt++,b); }
  75   Block *pop() { return _blocks[--_cnt]; }
  76   Block *rpop() { Block *b = _blocks[0]; _blocks[0]=_blocks[--_cnt]; return b;}
  77   void remove( uint i );
  78   void insert( uint i, Block *n );
  79   uint size() const { return _cnt; }
  80   void reset() { _cnt = 0; }
  81   void print();
  82 };
  83 
  84 
  85 class CFGElement : public ResourceObj {
  86  public:  
  87   float _freq; // Execution frequency (estimate)
  88 
  89   CFGElement() : _freq(0.0f) {}
  90   virtual bool is_block() { return false; }
  91   virtual bool is_loop()  { return false; }
  92   Block*   as_Block() { assert(is_block(), "must be block"); return (Block*)this; }
  93   CFGLoop* as_CFGLoop()  { assert(is_loop(),  "must be loop");  return (CFGLoop*)this;  }
  94 };
  95 
  96 //------------------------------Block------------------------------------------
  97 // This class defines a Basic Block.
  98 // Basic blocks are used during the output routines, and are not used during
  99 // any optimization pass.  They are created late in the game.
 100 class Block : public CFGElement {
 101  public:
 102   // Nodes in this block, in order
 103   Node_List _nodes;
 104 
 105   // Basic blocks have a Node which defines Control for all Nodes pinned in
 106   // this block.  This Node is a RegionNode.  Exception-causing Nodes
 107   // (division, subroutines) and Phi functions are always pinned.  Later,
 108   // every Node will get pinned to some block.
 109   Node *head() const { return _nodes[0]; }
 110 
 111   // CAUTION: num_preds() is ONE based, so that predecessor numbers match
 112   // input edges to Regions and Phis.
 113   uint num_preds() const { return head()->req(); }
 114   Node *pred(uint i) const { return head()->in(i); }
 115 
 116   // Array of successor blocks, same size as projs array
 117   Block_Array _succs;
 118 
 119   // Basic blocks have some number of Nodes which split control to all
 120   // following blocks.  These Nodes are always Projections.  The field in
 121   // the Projection and the block-ending Node determine which Block follows.
 122   uint _num_succs;
 123 
 124   // Basic blocks also carry all sorts of good old fashioned DFS information
 125   // used to find loops, loop nesting depth, dominators, etc.
 126   uint _pre_order;              // Pre-order DFS number
 127 
 128   // Dominator tree
 129   uint _dom_depth;              // Depth in dominator tree for fast LCA
 130   Block* _idom;                 // Immediate dominator block
 131 
 132   CFGLoop *_loop;               // Loop to which this block belongs
 133   uint _rpo;                    // Number in reverse post order walk 
 134 
 135   virtual bool is_block() { return true; }
 136   float succ_prob(uint i);      // return probability of i'th successor
 137   int num_fall_throughs();      // How many fall-through candidate this block has
 138   void update_uncommon_branch(Block* un); // Lower branch prob to uncommon code
 139   bool succ_fall_through(uint i); // Is successor "i" is a fall-through candidate
 140   Block* lone_fall_through();   // Return lone fall-through Block or null
 141 
 142   Block* dom_lca(Block* that);  // Compute LCA in dominator tree.
 143 #ifdef ASSERT
 144   bool dominates(Block* that) {
 145     int dom_diff = this->_dom_depth - that->_dom_depth;
 146     if (dom_diff > 0)  return false;
 147     for (; dom_diff < 0; dom_diff++)  that = that->_idom;
 148     return this == that;
 149   }
 150 #endif
 151 
 152   // Report the alignment required by this block.  Must be a power of 2.
 153   // The previous block will insert nops to get this alignment.
 154   uint code_alignment();
 155   uint compute_loop_alignment();
 156 
 157   // BLOCK_FREQUENCY is a sentinel to mark uses of constant block frequencies.
 158   // It is currently also used to scale such frequencies relative to 
 159   // FreqCountInvocations relative to the old value of 1500.
 160 #define BLOCK_FREQUENCY(f) ((f * (float) 1500) / FreqCountInvocations)
 161 
 162   // Register Pressure (estimate) for Splitting heuristic
 163   uint _reg_pressure;
 164   uint _ihrp_index;
 165   uint _freg_pressure;
 166   uint _fhrp_index;
 167 
 168   // Mark and visited bits for an LCA calculation in insert_anti_dependences.
 169   // Since they hold unique node indexes, they do not need reinitialization.
 170   node_idx_t _raise_LCA_mark;
 171   void    set_raise_LCA_mark(node_idx_t x)    { _raise_LCA_mark = x; }
 172   node_idx_t  raise_LCA_mark() const          { return _raise_LCA_mark; }
 173   node_idx_t _raise_LCA_visited;
 174   void    set_raise_LCA_visited(node_idx_t x) { _raise_LCA_visited = x; }
 175   node_idx_t  raise_LCA_visited() const       { return _raise_LCA_visited; }
 176 
 177   // Estimated size in bytes of first instructions in a loop. 
 178   uint _first_inst_size;
 179   uint first_inst_size() const     { return _first_inst_size; }
 180   void set_first_inst_size(uint s) { _first_inst_size = s; }
 181 
 182   // Compute the size of first instructions in this block.
 183   uint compute_first_inst_size(uint& sum_size, uint inst_cnt, PhaseRegAlloc* ra);
 184 
 185   // Compute alignment padding if the block needs it.
 186   // Align a loop if loop's padding is less or equal to padding limit
 187   // or the size of first instructions in the loop > padding.
 188   uint alignment_padding(int current_offset) {
 189     int block_alignment = code_alignment();
 190     int max_pad = block_alignment-relocInfo::addr_unit();
 191     if( max_pad > 0 ) {
 192       assert(is_power_of_2(max_pad+relocInfo::addr_unit()), "");
 193       int current_alignment = current_offset & max_pad;
 194       if( current_alignment != 0 ) {
 195         uint padding = (block_alignment-current_alignment) & max_pad;
 196         if( has_loop_alignment() &&
 197             padding > (uint)MaxLoopPad &&
 198             first_inst_size() <= padding ) {
 199           return 0;
 200         }
 201         return padding;
 202       }
 203     }
 204     return 0;
 205   }
 206 
 207   // Connector blocks. Connector blocks are basic blocks devoid of 
 208   // instructions, but may have relevant non-instruction Nodes, such as
 209   // Phis or MergeMems. Such blocks are discovered and marked during the
 210   // RemoveEmpty phase, and elided during Output.
 211   bool _connector;
 212   void set_connector() { _connector = true; }
 213   bool is_connector() const { return _connector; };
 214 
 215   // Loop_alignment will be set for blocks which are at the top of loops.
 216   // The block layout pass may rotate loops such that the loop head may not
 217   // be the sequentially first block of the loop encountered in the linear
 218   // list of blocks.  If the layout pass is not run, loop alignment is set
 219   // for each block which is the head of a loop.
 220   uint _loop_alignment;
 221   void set_loop_alignment(Block *loop_top) {
 222     uint new_alignment = loop_top->compute_loop_alignment();
 223     if (new_alignment > _loop_alignment) {
 224       _loop_alignment = new_alignment;
 225     }
 226   }
 227   uint loop_alignment() const { return _loop_alignment; }
 228   bool has_loop_alignment() const { return loop_alignment() > 0; }
 229 
 230   // Create a new Block with given head Node.
 231   // Creates the (empty) predecessor arrays.
 232   Block( Arena *a, Node *headnode ) 
 233     : CFGElement(),
 234       _nodes(a), 
 235       _succs(a), 
 236       _num_succs(0), 
 237       _pre_order(0), 
 238       _idom(0), 
 239       _loop(NULL), 
 240       _reg_pressure(0), 
 241       _ihrp_index(1), 
 242       _freg_pressure(0), 
 243       _fhrp_index(1), 
 244       _raise_LCA_mark(0),
 245       _raise_LCA_visited(0),
 246       _first_inst_size(999999),
 247       _connector(false),
 248       _loop_alignment(0) {
 249     _nodes.push(headnode);
 250   }
 251 
 252   // Index of 'end' Node
 253   uint end_idx() const {
 254     // %%%%% add a proj after every goto 
 255     // so (last->is_block_proj() != last) always, then simplify this code
 256     // This will not give correct end_idx for block 0 when it only contains root.
 257     int last_idx = _nodes.size() - 1;
 258     Node *last  = _nodes[last_idx];
 259     assert(last->is_block_proj() == last || last->is_block_proj() == _nodes[last_idx - _num_succs], "");
 260     return (last->is_block_proj() == last) ? last_idx : (last_idx - _num_succs);
 261   }
 262 
 263   // Basic blocks have a Node which ends them.  This Node determines which 
 264   // basic block follows this one in the program flow.  This Node is either an
 265   // IfNode, a GotoNode, a JmpNode, or a ReturnNode.
 266   Node *end() const { return _nodes[end_idx()]; }
 267 
 268   // Add an instruction to an existing block.  It must go after the head
 269   // instruction and before the end instruction.
 270   void add_inst( Node *n ) { _nodes.insert(end_idx(),n); }
 271   // Find node in block
 272   uint find_node( const Node *n ) const;
 273   // Find and remove n from block list
 274   void find_remove( const Node *n ); 
 275 
 276   // Schedule a call next in the block
 277   uint sched_call(Matcher &matcher, Block_Array &bbs, uint node_cnt, Node_List &worklist, int *ready_cnt, MachCallNode *mcall, VectorSet &next_call);
 278 
 279   // Perform basic-block local scheduling
 280   Node *select(PhaseCFG *cfg, Node_List &worklist, int *ready_cnt, VectorSet &next_call, uint sched_slot);
 281   void set_next_call( Node *n, VectorSet &next_call, Block_Array &bbs );
 282   void needed_for_next_call(Node *this_call, VectorSet &next_call, Block_Array &bbs);
 283   bool schedule_local(PhaseCFG *cfg, Matcher &m, int *ready_cnt, VectorSet &next_call);
 284   // Cleanup if any code lands between a Call and his Catch
 285   void call_catch_cleanup(Block_Array &bbs);
 286   // Detect implicit-null-check opportunities.  Basically, find NULL checks 
 287   // with suitable memory ops nearby.  Use the memory op to do the NULL check.
 288   // I can generate a memory op if there is not one nearby.
 289   void implicit_null_check(PhaseCFG *cfg, Node *proj, Node *val, int allowed_reasons);
 290 
 291   // Return the empty status of a block
 292   enum { not_empty, empty_with_goto, completely_empty };
 293   int is_Empty() const;
 294 
 295   // Forward through connectors
 296   Block* non_connector() {
 297     Block* s = this;
 298     while (s->is_connector()) {
 299       s = s->_succs[0];
 300     }
 301     return s;
 302   }
 303 
 304   // Return true if b is a successor of this block
 305   bool has_successor(Block* b) const {
 306     for (uint i = 0; i < _num_succs; i++ ) {
 307       if (non_connector_successor(i) == b) {
 308         return true;
 309       }
 310     }
 311     return false;
 312   }
 313 
 314   // Successor block, after forwarding through connectors
 315   Block* non_connector_successor(int i) const {
 316     return _succs[i]->non_connector();
 317   }
 318 
 319   // Examine block's code shape to predict if it is not commonly executed. 
 320   bool has_uncommon_code() const;
 321 
 322   // Use frequency calculations and code shape to predict if the block
 323   // is uncommon.
 324   bool is_uncommon( Block_Array &bbs ) const;
 325 
 326 #ifndef PRODUCT
 327   // Debugging print of basic block
 328   void dump_bidx(const Block* orig) const;
 329   void dump_pred(const Block_Array *bbs, Block* orig) const;
 330   void dump_head( const Block_Array *bbs ) const;
 331   void dump( ) const;
 332   void dump( const Block_Array *bbs ) const;
 333 #endif
 334 };
 335 
 336 
 337 //------------------------------PhaseCFG---------------------------------------
 338 // Build an array of Basic Block pointers, one per Node.
 339 class PhaseCFG : public Phase {
 340  private:
 341   // Build a proper looking cfg.  Return count of basic blocks
 342   uint build_cfg();
 343 
 344   // Perform DFS search.  
 345   // Setup 'vertex' as DFS to vertex mapping.  
 346   // Setup 'semi' as vertex to DFS mapping.  
 347   // Set 'parent' to DFS parent.             
 348   uint DFS( Tarjan *tarjan );
 349 
 350   // Helper function to insert a node into a block
 351   void schedule_node_into_block( Node *n, Block *b );
 352 
 353   // Set the basic block for pinned Nodes
 354   void schedule_pinned_nodes( VectorSet &visited );
 355 
 356   // I'll need a few machine-specific GotoNodes.  Clone from this one.
 357   MachNode *_goto;
 358 
 359   Block* insert_anti_dependences(Block* LCA, Node* load, bool verify = false);
 360   void verify_anti_dependences(Block* LCA, Node* load) {
 361     assert(LCA == _bbs[load->_idx], "should already be scheduled");
 362     insert_anti_dependences(LCA, load, true);
 363   }
 364 
 365  public:
 366   PhaseCFG( Arena *a, RootNode *r, Matcher &m );
 367 
 368   uint _num_blocks;             // Count of basic blocks
 369   Block_List _blocks;           // List of basic blocks  
 370   RootNode *_root;              // Root of whole program
 371   Block_Array _bbs;             // Map Nodes to owning Basic Block
 372   Block *_broot;                // Basic block of root
 373   uint _rpo_ctr;
 374   CFGLoop* _root_loop;
 375   
 376   // Per node latency estimation, valid only during GCM
 377   GrowableArray<uint> _node_latency;
 378 
 379 #ifndef PRODUCT
 380   bool _trace_opto_pipelining;  // tracing flag
 381 #endif
 382 
 383   // Build dominators
 384   void Dominators();
 385 
 386   // Estimate block frequencies based on IfNode probabilities
 387   void Estimate_Block_Frequency();
 388 
 389   // Global Code Motion.  See Click's PLDI95 paper.  Place Nodes in specific
 390   // basic blocks; i.e. _bbs now maps _idx for all Nodes to some Block.
 391   void GlobalCodeMotion( Matcher &m, uint unique, Node_List &proj_list );
 392  
 393   // Compute the (backwards) latency of a node from the uses
 394   void latency_from_uses(Node *n);
 395 
 396   // Compute the (backwards) latency of a node from a single use
 397   int latency_from_use(Node *n, const Node *def, Node *use);
 398 
 399   // Compute the (backwards) latency of a node from the uses of this instruction
 400   void partial_latency_of_defs(Node *n);
 401 
 402   // Schedule Nodes early in their basic blocks.
 403   bool schedule_early(VectorSet &visited, Node_List &roots);
 404 
 405   // For each node, find the latest block it can be scheduled into
 406   // and then select the cheapest block between the latest and earliest
 407   // block to place the node.
 408   void schedule_late(VectorSet &visited, Node_List &stack);
 409 
 410   // Pick a block between early and late that is a cheaper alternative
 411   // to late. Helper for schedule_late.
 412   Block* hoist_to_cheaper_block(Block* LCA, Block* early, Node* self);
 413 
 414   // Compute the instruction global latency with a backwards walk
 415   void ComputeLatenciesBackwards(VectorSet &visited, Node_List &stack);
 416 
 417   // Set loop alignment
 418   void set_loop_alignment();
 419 
 420   // Remove empty basic blocks
 421   void remove_empty();
 422   void fixup_flow();
 423   bool move_to_next(Block* bx, uint b_index);
 424   void move_to_end(Block* bx, uint b_index);
 425   void insert_goto_at(uint block_no, uint succ_no);
 426 
 427   // Check for NeverBranch at block end.  This needs to become a GOTO to the
 428   // true target.  NeverBranch are treated as a conditional branch that always
 429   // goes the same direction for most of the optimizer and are used to give a
 430   // fake exit path to infinite loops.  At this late stage they need to turn
 431   // into Goto's so that when you enter the infinite loop you indeed hang.
 432   void convert_NeverBranch_to_Goto(Block *b);
 433 
 434   CFGLoop* create_loop_tree();
 435 
 436   // Insert a node into a block, and update the _bbs
 437   void insert( Block *b, uint idx, Node *n ) { 
 438     b->_nodes.insert( idx, n ); 
 439     _bbs.map( n->_idx, b ); 
 440   } 
 441 
 442 #ifndef PRODUCT
 443   bool trace_opto_pipelining() const { return _trace_opto_pipelining; }
 444 
 445   // Debugging print of CFG
 446   void dump( ) const;           // CFG only
 447   void _dump_cfg( const Node *end, VectorSet &visited  ) const;
 448   void verify() const;
 449   void dump_headers();
 450 #else
 451   bool trace_opto_pipelining() const { return false; }
 452 #endif
 453 };
 454 
 455 
 456 //------------------------------UnionFind--------------------------------------
 457 // Map Block indices to a block-index for a cfg-cover.
 458 // Array lookup in the optimized case.
 459 class UnionFind : public ResourceObj {
 460   uint _cnt, _max;
 461   uint* _indices;
 462   ReallocMark _nesting;  // assertion check for reallocations
 463 public:
 464   UnionFind( uint max );
 465   void reset( uint max );  // Reset to identity map for [0..max]
 466 
 467   uint lookup( uint nidx ) const {
 468     return _indices[nidx];
 469   }
 470   uint operator[] (uint nidx) const { return lookup(nidx); }
 471 
 472   void map( uint from_idx, uint to_idx ) {
 473     assert( from_idx < _cnt, "oob" );
 474     _indices[from_idx] = to_idx;
 475   }
 476   void extend( uint from_idx, uint to_idx );
 477 
 478   uint Size() const { return _cnt; }
 479 
 480   uint Find( uint idx ) {
 481     assert( idx < 65536, "Must fit into uint");
 482     uint uf_idx = lookup(idx);
 483     return (uf_idx == idx) ? uf_idx : Find_compress(idx);
 484   }
 485   uint Find_compress( uint idx );
 486   uint Find_const( uint idx ) const;
 487   void Union( uint idx1, uint idx2 );
 488 
 489 };
 490 
 491 //----------------------------BlockProbPair---------------------------
 492 // Ordered pair of Node*.
 493 class BlockProbPair VALUE_OBJ_CLASS_SPEC {
 494 protected:
 495   Block* _target;      // block target
 496   float  _prob;        // probability of edge to block
 497 public:
 498   BlockProbPair() : _target(NULL), _prob(0.0) {}
 499   BlockProbPair(Block* b, float p) : _target(b), _prob(p) {}
 500 
 501   Block* get_target() const { return _target; }
 502   float get_prob() const { return _prob; }
 503 };
 504 
 505 //------------------------------CFGLoop-------------------------------------------
 506 class CFGLoop : public CFGElement {
 507   int _id;
 508   int _depth;
 509   CFGLoop *_parent;      // root of loop tree is the method level "pseudo" loop, it's parent is null
 510   CFGLoop *_sibling;     // null terminated list
 511   CFGLoop *_child;       // first child, use child's sibling to visit all immediately nested loops
 512   GrowableArray<CFGElement*> _members; // list of members of loop
 513   GrowableArray<BlockProbPair> _exits; // list of successor blocks and their probabilities
 514   float _exit_prob;       // probability any loop exit is taken on a single loop iteration
 515   void update_succ_freq(Block* b, float freq);
 516 
 517  public:
 518   CFGLoop(int id) : 
 519     CFGElement(), 
 520     _id(id), 
 521     _depth(0), 
 522     _parent(NULL), 
 523     _sibling(NULL), 
 524     _child(NULL), 
 525     _exit_prob(1.0f) {}
 526   CFGLoop* parent() { return _parent; }
 527   void push_pred(Block* blk, int i, Block_List& worklist, Block_Array& node_to_blk);
 528   void add_member(CFGElement *s) { _members.push(s); }
 529   void add_nested_loop(CFGLoop* cl);
 530   Block* head() {
 531     assert(_members.at(0)->is_block(), "head must be a block");
 532     Block* hd = _members.at(0)->as_Block();
 533     assert(hd->_loop == this, "just checking");
 534     assert(hd->head()->is_Loop(), "must begin with loop head node");
 535     return hd;
 536   }
 537   Block* backedge_block(); // Return the block on the backedge of the loop (else NULL)
 538   void compute_loop_depth(int depth);
 539   void compute_freq(); // compute frequency with loop assuming head freq 1.0f
 540   void scale_freq();   // scale frequency by loop trip count (including outer loops)
 541   bool in_loop_nest(Block* b);
 542   float trip_count() const { return 1.0f / _exit_prob; }
 543   virtual bool is_loop()  { return true; }
 544   int id() { return _id; }
 545 
 546 #ifndef PRODUCT
 547   void dump( ) const;
 548   void dump_tree() const;
 549 #endif
 550 };
 551 
 552 
 553 //----------------------------------CFGEdge------------------------------------
 554 // A edge between two basic blocks that will be embodied by a branch or a
 555 // fall-through.
 556 class CFGEdge : public ResourceObj {
 557  private:
 558   Block * _from;        // Source basic block
 559   Block * _to;          // Destination basic block
 560   float _freq;          // Execution frequency (estimate)
 561   int   _state;
 562   bool  _infrequent;
 563   int   _from_pct;
 564   int   _to_pct;
 565 
 566   // Private accessors
 567   int  from_pct() const { return _from_pct; }
 568   int  to_pct()   const { return _to_pct;   }
 569   int  from_infrequent() const { return from_pct() < BlockLayoutMinDiamondPercentage; }
 570   int  to_infrequent()   const { return to_pct()   < BlockLayoutMinDiamondPercentage; }
 571 
 572  public:
 573   enum {
 574     open,               // initial edge state; unprocessed
 575     connected,          // edge used to connect two traces together
 576     interior            // edge is interior to trace (could be backedge)
 577   };
 578 
 579   CFGEdge(Block *from, Block *to, float freq, int from_pct, int to_pct) :
 580     _from(from), _to(to), _freq(freq),
 581     _from_pct(from_pct), _to_pct(to_pct), _state(open) {
 582     _infrequent = from_infrequent() || to_infrequent();
 583   }
 584 
 585   float  freq() const { return _freq; }
 586   Block* from() const { return _from; }
 587   Block* to  () const { return _to;   }
 588   int  infrequent() const { return _infrequent; }
 589   int state() const { return _state; }
 590 
 591   void set_state(int state) { _state = state; }
 592 
 593 #ifndef PRODUCT
 594   void dump( ) const;
 595 #endif
 596 };
 597 
 598 
 599 //-----------------------------------Trace-------------------------------------
 600 // An ordered list of basic blocks.
 601 class Trace : public ResourceObj {
 602  private:
 603   uint _id;             // Unique Trace id (derived from initial block)
 604   Block ** _next_list;  // Array mapping index to next block
 605   Block ** _prev_list;  // Array mapping index to previous block
 606   Block * _first;       // First block in the trace
 607   Block * _last;        // Last block in the trace
 608 
 609   // Return the block that follows "b" in the trace.
 610   Block * next(Block *b) const { return _next_list[b->_pre_order]; }
 611   void set_next(Block *b, Block *n) const { _next_list[b->_pre_order] = n; }
 612 
 613   // Return the block that preceeds "b" in the trace.
 614   Block * prev(Block *b) const { return _prev_list[b->_pre_order]; }
 615   void set_prev(Block *b, Block *p) const { _prev_list[b->_pre_order] = p; }
 616 
 617   // We've discovered a loop in this trace. Reset last to be "b", and first as
 618   // the block following "b
 619   void break_loop_after(Block *b) {
 620     _last = b;
 621     _first = next(b);
 622     set_prev(_first, NULL);
 623     set_next(_last, NULL);
 624   }
 625 
 626  public:
 627 
 628   Trace(Block *b, Block **next_list, Block **prev_list) :
 629     _first(b),
 630     _last(b),
 631     _next_list(next_list),
 632     _prev_list(prev_list),
 633     _id(b->_pre_order) {
 634     set_next(b, NULL);
 635     set_prev(b, NULL);
 636   };
 637 
 638   // Return the id number
 639   uint id() const { return _id; }
 640   void set_id(uint id) { _id = id; }
 641 
 642   // Return the first block in the trace
 643   Block * first_block() const { return _first; }
 644 
 645   // Return the last block in the trace
 646   Block * last_block() const { return _last; }
 647 
 648   // Insert a trace in the middle of this one after b
 649   void insert_after(Block *b, Trace *tr) {
 650     set_next(tr->last_block(), next(b));
 651     if (next(b) != NULL) {
 652       set_prev(next(b), tr->last_block());
 653     }
 654 
 655     set_next(b, tr->first_block());
 656     set_prev(tr->first_block(), b);
 657 
 658     if (b == _last) {
 659       _last = tr->last_block();
 660     }
 661   }
 662 
 663   void insert_before(Block *b, Trace *tr) {
 664     Block *p = prev(b);
 665     assert(p != NULL, "use append instead");
 666     insert_after(p, tr);
 667   }
 668 
 669   // Append another trace to this one.
 670   void append(Trace *tr) {
 671     insert_after(_last, tr);
 672   }
 673 
 674   // Append a block at the end of this trace
 675   void append(Block *b) {
 676     set_next(_last, b);
 677     set_prev(b, _last);
 678     _last = b;
 679   }
 680 
 681   // Adjust the the blocks in this trace
 682   void fixup_blocks(PhaseCFG &cfg);
 683   bool backedge(CFGEdge *e);
 684 
 685 #ifndef PRODUCT
 686   void dump( ) const;
 687 #endif
 688 };
 689 
 690 //------------------------------PhaseBlockLayout-------------------------------
 691 // Rearrange blocks into some canonical order, based on edges and their frequencies
 692 class PhaseBlockLayout : public Phase {
 693   PhaseCFG &_cfg;               // Control flow graph
 694 
 695   GrowableArray<CFGEdge *> *edges;
 696   Trace **traces;
 697   Block **next;
 698   Block **prev;
 699   UnionFind *uf;
 700 
 701   // Given a block, find its encompassing Trace
 702   Trace * trace(Block *b) {
 703     return traces[uf->Find_compress(b->_pre_order)];
 704   }
 705  public:
 706   PhaseBlockLayout(PhaseCFG &cfg);
 707 
 708   void find_edges();
 709   void grow_traces();
 710   void merge_traces(bool loose_connections);
 711   void reorder_traces(int count);
 712   void union_traces(Trace* from, Trace* to);
 713 };