Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/opto/chaitin.hpp
32285 views
/*1* Copyright (c) 1997, 2013, 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_VM_OPTO_CHAITIN_HPP25#define SHARE_VM_OPTO_CHAITIN_HPP2627#include "code/vmreg.hpp"28#include "libadt/port.hpp"29#include "memory/resourceArea.hpp"30#include "opto/connode.hpp"31#include "opto/live.hpp"32#include "opto/matcher.hpp"33#include "opto/phase.hpp"34#include "opto/regalloc.hpp"35#include "opto/regmask.hpp"3637class LoopTree;38class MachCallNode;39class MachSafePointNode;40class Matcher;41class PhaseCFG;42class PhaseLive;43class PhaseRegAlloc;44class PhaseChaitin;4546#define OPTO_DEBUG_SPLIT_FREQ BLOCK_FREQUENCY(0.001)47#define OPTO_LRG_HIGH_FREQ BLOCK_FREQUENCY(0.25)4849//------------------------------LRG--------------------------------------------50// Live-RanGe structure.51class LRG : public ResourceObj {52friend class VMStructs;53public:54static const uint AllStack_size = 0xFFFFF; // This mask size is used to tell that the mask of this LRG supports stack positions55enum { SPILL_REG=29999 }; // Register number of a spilled LRG5657double _cost; // 2 for loads/1 for stores times block freq58double _area; // Sum of all simultaneously live values59double score() const; // Compute score from cost and area60double _maxfreq; // Maximum frequency of any def or use6162Node *_def; // Check for multi-def live ranges63#ifndef PRODUCT64GrowableArray<Node*>* _defs;65#endif6667uint _risk_bias; // Index of LRG which we want to avoid color68uint _copy_bias; // Index of LRG which we want to share color6970uint _next; // Index of next LRG in linked list71uint _prev; // Index of prev LRG in linked list72private:73uint _reg; // Chosen register; undefined if mask is plural74public:75// Return chosen register for this LRG. Error if the LRG is not bound to76// a single register.77OptoReg::Name reg() const { return OptoReg::Name(_reg); }78void set_reg( OptoReg::Name r ) { _reg = r; }7980private:81uint _eff_degree; // Effective degree: Sum of neighbors _num_regs82public:83int degree() const { assert( _degree_valid , "" ); return _eff_degree; }84// Degree starts not valid and any change to the IFG neighbor85// set makes it not valid.86void set_degree( uint degree ) {87_eff_degree = degree;88debug_only(_degree_valid = 1;)89assert(!_mask.is_AllStack() || (_mask.is_AllStack() && lo_degree()), "_eff_degree can't be bigger than AllStack_size - _num_regs if the mask supports stack registers");90}91// Made a change that hammered degree92void invalid_degree() { debug_only(_degree_valid=0;) }93// Incrementally modify degree. If it was correct, it should remain correct94void inc_degree( uint mod ) {95_eff_degree += mod;96assert(!_mask.is_AllStack() || (_mask.is_AllStack() && lo_degree()), "_eff_degree can't be bigger than AllStack_size - _num_regs if the mask supports stack registers");97}98// Compute the degree between 2 live ranges99int compute_degree( LRG &l ) const;100101private:102RegMask _mask; // Allowed registers for this LRG103uint _mask_size; // cache of _mask.Size();104public:105int compute_mask_size() const { return _mask.is_AllStack() ? AllStack_size : _mask.Size(); }106void set_mask_size( int size ) {107assert((size == (int)AllStack_size) || (size == (int)_mask.Size()), "");108_mask_size = size;109#ifdef ASSERT110_msize_valid=1;111if (_is_vector) {112assert(!_fat_proj, "sanity");113_mask.verify_sets(_num_regs);114} else if (_num_regs == 2 && !_fat_proj) {115_mask.verify_pairs();116}117#endif118}119void compute_set_mask_size() { set_mask_size(compute_mask_size()); }120int mask_size() const { assert( _msize_valid, "mask size not valid" );121return _mask_size; }122// Get the last mask size computed, even if it does not match the123// count of bits in the current mask.124int get_invalid_mask_size() const { return _mask_size; }125const RegMask &mask() const { return _mask; }126void set_mask( const RegMask &rm ) { _mask = rm; debug_only(_msize_valid=0;)}127void AND( const RegMask &rm ) { _mask.AND(rm); debug_only(_msize_valid=0;)}128void SUBTRACT( const RegMask &rm ) { _mask.SUBTRACT(rm); debug_only(_msize_valid=0;)}129void Clear() { _mask.Clear() ; debug_only(_msize_valid=1); _mask_size = 0; }130void Set_All() { _mask.Set_All(); debug_only(_msize_valid=1); _mask_size = RegMask::CHUNK_SIZE; }131void Insert( OptoReg::Name reg ) { _mask.Insert(reg); debug_only(_msize_valid=0;) }132void Remove( OptoReg::Name reg ) { _mask.Remove(reg); debug_only(_msize_valid=0;) }133void clear_to_pairs() { _mask.clear_to_pairs(); debug_only(_msize_valid=0;) }134void clear_to_sets() { _mask.clear_to_sets(_num_regs); debug_only(_msize_valid=0;) }135136// Number of registers this live range uses when it colors137private:138uint8 _num_regs; // 2 for Longs and Doubles, 1 for all else139// except _num_regs is kill count for fat_proj140public:141int num_regs() const { return _num_regs; }142void set_num_regs( int reg ) { assert( _num_regs == reg || !_num_regs, "" ); _num_regs = reg; }143144private:145// Number of physical registers this live range uses when it colors146// Architecture and register-set dependent147uint8 _reg_pressure;148public:149void set_reg_pressure(int i) { _reg_pressure = i; }150int reg_pressure() const { return _reg_pressure; }151152// How much 'wiggle room' does this live range have?153// How many color choices can it make (scaled by _num_regs)?154int degrees_of_freedom() const { return mask_size() - _num_regs; }155// Bound LRGs have ZERO degrees of freedom. We also count156// must_spill as bound.157bool is_bound () const { return _is_bound; }158// Negative degrees-of-freedom; even with no neighbors this159// live range must spill.160bool not_free() const { return degrees_of_freedom() < 0; }161// Is this live range of "low-degree"? Trivially colorable?162bool lo_degree () const { return degree() <= degrees_of_freedom(); }163// Is this live range just barely "low-degree"? Trivially colorable?164bool just_lo_degree () const { return degree() == degrees_of_freedom(); }165166uint _is_oop:1, // Live-range holds an oop167_is_float:1, // True if in float registers168_is_vector:1, // True if in vector registers169_was_spilled1:1, // True if prior spilling on def170_was_spilled2:1, // True if twice prior spilling on def171_is_bound:1, // live range starts life with no172// degrees of freedom.173_direct_conflict:1, // True if def and use registers in conflict174_must_spill:1, // live range has lost all degrees of freedom175// If _fat_proj is set, live range does NOT require aligned, adjacent176// registers and has NO interferences.177// If _fat_proj is clear, live range requires num_regs() to be a power of178// 2, and it requires registers to form an aligned, adjacent set.179_fat_proj:1, //180_was_lo:1, // Was lo-degree prior to coalesce181_msize_valid:1, // _mask_size cache valid182_degree_valid:1, // _degree cache valid183_has_copy:1, // Adjacent to some copy instruction184_at_risk:1; // Simplify says this guy is at risk to spill185186187// Alive if non-zero, dead if zero188bool alive() const { return _def != NULL; }189bool is_multidef() const { return _def == NodeSentinel; }190bool is_singledef() const { return _def != NodeSentinel; }191192#ifndef PRODUCT193void dump( ) const;194#endif195};196197//------------------------------IFG--------------------------------------------198// InterFerence Graph199// An undirected graph implementation. Created with a fixed number of200// vertices. Edges can be added & tested. Vertices can be removed, then201// added back later with all edges intact. Can add edges between one vertex202// and a list of other vertices. Can union vertices (and their edges)203// together. The IFG needs to be really really fast, and also fairly204// abstract! It needs abstraction so I can fiddle with the implementation to205// get even more speed.206class PhaseIFG : public Phase {207friend class VMStructs;208// Current implementation: a triangular adjacency list.209210// Array of adjacency-lists, indexed by live-range number211IndexSet *_adjs;212213// Assertion bit for proper use of Squaring214bool _is_square;215216// Live range structure goes here217LRG *_lrgs; // Array of LRG structures218219public:220// Largest live-range number221uint _maxlrg;222223Arena *_arena;224225// Keep track of inserted and deleted Nodes226VectorSet *_yanked;227228PhaseIFG( Arena *arena );229void init( uint maxlrg );230231// Add edge between a and b. Returns true if actually addded.232int add_edge( uint a, uint b );233234// Add edge between a and everything in the vector235void add_vector( uint a, IndexSet *vec );236237// Test for edge existance238int test_edge( uint a, uint b ) const;239240// Square-up matrix for faster Union241void SquareUp();242243// Return number of LRG neighbors244uint neighbor_cnt( uint a ) const { return _adjs[a].count(); }245// Union edges of b into a on Squared-up matrix246void Union( uint a, uint b );247// Test for edge in Squared-up matrix248int test_edge_sq( uint a, uint b ) const;249// Yank a Node and all connected edges from the IFG. Be prepared to250// re-insert the yanked Node in reverse order of yanking. Return a251// list of neighbors (edges) yanked.252IndexSet *remove_node( uint a );253// Reinsert a yanked Node254void re_insert( uint a );255// Return set of neighbors256IndexSet *neighbors( uint a ) const { return &_adjs[a]; }257258#ifndef PRODUCT259// Dump the IFG260void dump() const;261void stats() const;262void verify( const PhaseChaitin * ) const;263#endif264265//--------------- Live Range Accessors266LRG &lrgs(uint idx) const { assert(idx < _maxlrg, "oob"); return _lrgs[idx]; }267268// Compute and set effective degree. Might be folded into SquareUp().269void Compute_Effective_Degree();270271// Compute effective degree as the sum of neighbors' _sizes.272int effective_degree( uint lidx ) const;273};274275// The LiveRangeMap class is responsible for storing node to live range id mapping.276// Each node is mapped to a live range id (a virtual register). Nodes that are277// not considered for register allocation are given live range id 0.278class LiveRangeMap VALUE_OBJ_CLASS_SPEC {279280private:281282uint _max_lrg_id;283284// Union-find map. Declared as a short for speed.285// Indexed by live-range number, it returns the compacted live-range number286LRG_List _uf_map;287288// Map from Nodes to live ranges289LRG_List _names;290291// Straight out of Tarjan's union-find algorithm292uint find_compress(const Node *node) {293uint lrg_id = find_compress(_names.at(node->_idx));294_names.at_put(node->_idx, lrg_id);295return lrg_id;296}297298uint find_compress(uint lrg);299300public:301302const LRG_List& names() {303return _names;304}305306uint max_lrg_id() const {307return _max_lrg_id;308}309310void set_max_lrg_id(uint max_lrg_id) {311_max_lrg_id = max_lrg_id;312}313314uint size() const {315return _names.length();316}317318uint live_range_id(uint idx) const {319return _names.at(idx);320}321322uint live_range_id(const Node *node) const {323return _names.at(node->_idx);324}325326uint uf_live_range_id(uint lrg_id) const {327return _uf_map.at(lrg_id);328}329330void map(uint idx, uint lrg_id) {331_names.at_put(idx, lrg_id);332}333334void uf_map(uint dst_lrg_id, uint src_lrg_id) {335_uf_map.at_put(dst_lrg_id, src_lrg_id);336}337338void extend(uint idx, uint lrg_id) {339_names.at_put_grow(idx, lrg_id);340}341342void uf_extend(uint dst_lrg_id, uint src_lrg_id) {343_uf_map.at_put_grow(dst_lrg_id, src_lrg_id);344}345346LiveRangeMap(Arena* arena, uint unique)347: _names(arena, unique, unique, 0)348, _uf_map(arena, unique, unique, 0)349, _max_lrg_id(0) {}350351uint find_id( const Node *n ) {352uint retval = live_range_id(n);353assert(retval == find(n),"Invalid node to lidx mapping");354return retval;355}356357// Reset the Union-Find map to identity358void reset_uf_map(uint max_lrg_id);359360// Make all Nodes map directly to their final live range; no need for361// the Union-Find mapping after this call.362void compress_uf_map_for_nodes();363364uint find(uint lidx) {365uint uf_lidx = _uf_map.at(lidx);366return (uf_lidx == lidx) ? uf_lidx : find_compress(lidx);367}368369// Convert a Node into a Live Range Index - a lidx370uint find(const Node *node) {371uint lidx = live_range_id(node);372uint uf_lidx = _uf_map.at(lidx);373return (uf_lidx == lidx) ? uf_lidx : find_compress(node);374}375376// Like Find above, but no path compress, so bad asymptotic behavior377uint find_const(uint lrg) const;378379// Like Find above, but no path compress, so bad asymptotic behavior380uint find_const(const Node *node) const {381if(node->_idx >= (uint)_names.length()) {382return 0; // not mapped, usual for debug dump383}384return find_const(_names.at(node->_idx));385}386};387388//------------------------------Chaitin----------------------------------------389// Briggs-Chaitin style allocation, mostly.390class PhaseChaitin : public PhaseRegAlloc {391friend class VMStructs;392393int _trip_cnt;394int _alternate;395396LRG &lrgs(uint idx) const { return _ifg->lrgs(idx); }397PhaseLive *_live; // Liveness, used in the interference graph398PhaseIFG *_ifg; // Interference graph (for original chunk)399Node_List **_lrg_nodes; // Array of node; lists for lrgs which spill400VectorSet _spilled_once; // Nodes that have been spilled401VectorSet _spilled_twice; // Nodes that have been spilled twice402403// Combine the Live Range Indices for these 2 Nodes into a single live404// range. Future requests for any Node in either live range will405// return the live range index for the combined live range.406void Union( const Node *src, const Node *dst );407408void new_lrg( const Node *x, uint lrg );409410// Compact live ranges, removing unused ones. Return new maxlrg.411void compact();412413uint _lo_degree; // Head of lo-degree LRGs list414uint _lo_stk_degree; // Head of lo-stk-degree LRGs list415uint _hi_degree; // Head of hi-degree LRGs list416uint _simplified; // Linked list head of simplified LRGs417418// Helper functions for Split()419uint split_DEF( Node *def, Block *b, int loc, uint max, Node **Reachblock, Node **debug_defs, GrowableArray<uint> splits, int slidx );420uint split_USE( Node *def, Block *b, Node *use, uint useidx, uint max, bool def_down, bool cisc_sp, GrowableArray<uint> splits, int slidx );421422//------------------------------clone_projs------------------------------------423// After cloning some rematerialized instruction, clone any MachProj's that424// follow it. Example: Intel zero is XOR, kills flags. Sparc FP constants425// use G3 as an address temp.426int clone_projs(Block* b, uint idx, Node* orig, Node* copy, uint& max_lrg_id);427428int clone_projs(Block* b, uint idx, Node* orig, Node* copy, LiveRangeMap& lrg_map) {429uint max_lrg_id = lrg_map.max_lrg_id();430int found_projs = clone_projs(b, idx, orig, copy, max_lrg_id);431if (found_projs > 0) {432// max_lrg_id is updated during call above433lrg_map.set_max_lrg_id(max_lrg_id);434}435return found_projs;436}437438Node *split_Rematerialize(Node *def, Block *b, uint insidx, uint &maxlrg, GrowableArray<uint> splits,439int slidx, uint *lrg2reach, Node **Reachblock, bool walkThru);440// True if lidx is used before any real register is def'd in the block441bool prompt_use( Block *b, uint lidx );442Node *get_spillcopy_wide( Node *def, Node *use, uint uidx );443// Insert the spill at chosen location. Skip over any intervening Proj's or444// Phis. Skip over a CatchNode and projs, inserting in the fall-through block445// instead. Update high-pressure indices. Create a new live range.446void insert_proj( Block *b, uint i, Node *spill, uint maxlrg );447448bool is_high_pressure( Block *b, LRG *lrg, uint insidx );449450uint _oldphi; // Node index which separates pre-allocation nodes451452Block **_blks; // Array of blocks sorted by frequency for coalescing453454float _high_frequency_lrg; // Frequency at which LRG will be spilled for debug info455456#ifndef PRODUCT457bool _trace_spilling;458#endif459460public:461PhaseChaitin( uint unique, PhaseCFG &cfg, Matcher &matcher );462~PhaseChaitin() {}463464LiveRangeMap _lrg_map;465466// Do all the real work of allocate467void Register_Allocate();468469float high_frequency_lrg() const { return _high_frequency_lrg; }470471#ifndef PRODUCT472bool trace_spilling() const { return _trace_spilling; }473#endif474475private:476// De-SSA the world. Assign registers to Nodes. Use the same register for477// all inputs to a PhiNode, effectively coalescing live ranges. Insert478// copies as needed.479void de_ssa();480481// Add edge between reg and everything in the vector.482// Same as _ifg->add_vector(reg,live) EXCEPT use the RegMask483// information to trim the set of interferences. Return the484// count of edges added.485void interfere_with_live( uint reg, IndexSet *live );486// Count register pressure for asserts487uint count_int_pressure( IndexSet *liveout );488uint count_float_pressure( IndexSet *liveout );489490// Build the interference graph using virtual registers only.491// Used for aggressive coalescing.492void build_ifg_virtual( );493494// Build the interference graph using physical registers when available.495// That is, if 2 live ranges are simultaneously alive but in their496// acceptable register sets do not overlap, then they do not interfere.497uint build_ifg_physical( ResourceArea *a );498499// Gather LiveRanGe information, including register masks and base pointer/500// derived pointer relationships.501void gather_lrg_masks( bool mod_cisc_masks );502503// Force the bases of derived pointers to be alive at GC points.504bool stretch_base_pointer_live_ranges( ResourceArea *a );505// Helper to stretch above; recursively discover the base Node for506// a given derived Node. Easy for AddP-related machine nodes, but507// needs to be recursive for derived Phis.508Node *find_base_for_derived( Node **derived_base_map, Node *derived, uint &maxlrg );509510// Set the was-lo-degree bit. Conservative coalescing should not change the511// colorability of the graph. If any live range was of low-degree before512// coalescing, it should Simplify. This call sets the was-lo-degree bit.513void set_was_low();514515// Split live-ranges that must spill due to register conflicts (as opposed516// to capacity spills). Typically these are things def'd in a register517// and used on the stack or vice-versa.518void pre_spill();519520// Init LRG caching of degree, numregs. Init lo_degree list.521void cache_lrg_info( );522523// Simplify the IFG by removing LRGs of low degree with no copies524void Pre_Simplify();525526// Simplify the IFG by removing LRGs of low degree527void Simplify();528529// Select colors by re-inserting edges into the IFG.530// Return TRUE if any spills occurred.531uint Select( );532// Helper function for select which allows biased coloring533OptoReg::Name choose_color( LRG &lrg, int chunk );534// Helper function which implements biasing heuristic535OptoReg::Name bias_color( LRG &lrg, int chunk );536537// Split uncolorable live ranges538// Return new number of live ranges539uint Split(uint maxlrg, ResourceArea* split_arena);540541// Copy 'was_spilled'-edness from one Node to another.542void copy_was_spilled( Node *src, Node *dst );543// Set the 'spilled_once' or 'spilled_twice' flag on a node.544void set_was_spilled( Node *n );545546// Convert ideal spill-nodes into machine loads & stores547// Set C->failing when fixup spills could not complete, node limit exceeded.548void fixup_spills();549550// Post-Allocation peephole copy removal551void post_allocate_copy_removal();552Node *skip_copies( Node *c );553// Replace the old node with the current live version of that value554// and yank the old value if it's dead.555int replace_and_yank_if_dead( Node *old, OptoReg::Name nreg,556Block *current_block, Node_List& value, Node_List& regnd ) {557Node* v = regnd[nreg];558assert(v->outcnt() != 0, "no dead values");559old->replace_by(v);560return yank_if_dead(old, current_block, &value, ®nd);561}562563int yank_if_dead( Node *old, Block *current_block, Node_List *value, Node_List *regnd ) {564return yank_if_dead_recurse(old, old, current_block, value, regnd);565}566int yank_if_dead_recurse(Node *old, Node *orig_old, Block *current_block,567Node_List *value, Node_List *regnd);568int yank( Node *old, Block *current_block, Node_List *value, Node_List *regnd );569int elide_copy( Node *n, int k, Block *current_block, Node_List &value, Node_List ®nd, bool can_change_regs );570int use_prior_register( Node *copy, uint idx, Node *def, Block *current_block, Node_List &value, Node_List ®nd );571bool may_be_copy_of_callee( Node *def ) const;572573// If nreg already contains the same constant as val then eliminate it574bool eliminate_copy_of_constant(Node* val, Node* n,575Block *current_block, Node_List& value, Node_List ®nd,576OptoReg::Name nreg, OptoReg::Name nreg2);577// Extend the node to LRG mapping578void add_reference( const Node *node, const Node *old_node);579580// Record the first use of a def in the block for a register.581class RegDefUse {582Node* _def;583Node* _first_use;584public:585RegDefUse() : _def(NULL), _first_use(NULL) { }586Node* def() const { return _def; }587Node* first_use() const { return _first_use; }588589void update(Node* def, Node* use) {590if (_def != def) {591_def = def;592_first_use = use;593}594}595void clear() {596_def = NULL;597_first_use = NULL;598}599};600typedef GrowableArray<RegDefUse> RegToDefUseMap;601int possibly_merge_multidef(Node *n, uint k, Block *block, RegToDefUseMap& reg2defuse);602603// Merge nodes that are a part of a multidef lrg and produce the same value within a block.604void merge_multidefs();605606private:607608static int _final_loads, _final_stores, _final_copies, _final_memoves;609static double _final_load_cost, _final_store_cost, _final_copy_cost, _final_memove_cost;610static int _conserv_coalesce, _conserv_coalesce_pair;611static int _conserv_coalesce_trie, _conserv_coalesce_quad;612static int _post_alloc;613static int _lost_opp_pp_coalesce, _lost_opp_cflow_coalesce;614static int _used_cisc_instructions, _unused_cisc_instructions;615static int _allocator_attempts, _allocator_successes;616617#ifndef PRODUCT618static uint _high_pressure, _low_pressure;619620void dump() const;621void dump( const Node *n ) const;622void dump( const Block * b ) const;623void dump_degree_lists() const;624void dump_simplified() const;625void dump_lrg( uint lidx, bool defs_only) const;626void dump_lrg( uint lidx) const {627// dump defs and uses by default628dump_lrg(lidx, false);629}630void dump_bb( uint pre_order ) const;631632// Verify that base pointers and derived pointers are still sane633void verify_base_ptrs( ResourceArea *a ) const;634635void verify( ResourceArea *a, bool verify_ifg = false ) const;636637void dump_for_spill_split_recycle() const;638639public:640void dump_frame() const;641char *dump_register( const Node *n, char *buf ) const;642private:643static void print_chaitin_statistics();644#endif645friend class PhaseCoalesce;646friend class PhaseAggressiveCoalesce;647friend class PhaseConservativeCoalesce;648};649650#endif // SHARE_VM_OPTO_CHAITIN_HPP651652653