Path: blob/master/src/hotspot/share/opto/coalesce.cpp
40930 views
/*1* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "memory/allocation.inline.hpp"26#include "opto/block.hpp"27#include "opto/c2compiler.hpp"28#include "opto/cfgnode.hpp"29#include "opto/chaitin.hpp"30#include "opto/coalesce.hpp"31#include "opto/connode.hpp"32#include "opto/indexSet.hpp"33#include "opto/machnode.hpp"34#include "opto/matcher.hpp"35#include "opto/regmask.hpp"3637#ifndef PRODUCT38void PhaseCoalesce::dump(Node *n) const {39// Being a const function means I cannot use 'Find'40uint r = _phc._lrg_map.find(n);41tty->print("L%d/N%d ",r,n->_idx);42}4344void PhaseCoalesce::dump() const {45// I know I have a block layout now, so I can print blocks in a loop46for( uint i=0; i<_phc._cfg.number_of_blocks(); i++ ) {47uint j;48Block* b = _phc._cfg.get_block(i);49// Print a nice block header50tty->print("B%d: ",b->_pre_order);51for( j=1; j<b->num_preds(); j++ )52tty->print("B%d ", _phc._cfg.get_block_for_node(b->pred(j))->_pre_order);53tty->print("-> ");54for( j=0; j<b->_num_succs; j++ )55tty->print("B%d ",b->_succs[j]->_pre_order);56tty->print(" IDom: B%d/#%d\n", b->_idom ? b->_idom->_pre_order : 0, b->_dom_depth);57uint cnt = b->number_of_nodes();58for( j=0; j<cnt; j++ ) {59Node *n = b->get_node(j);60dump( n );61tty->print("\t%s\t",n->Name());6263// Dump the inputs64uint k; // Exit value of loop65for( k=0; k<n->req(); k++ ) // For all required inputs66if( n->in(k) ) dump( n->in(k) );67else tty->print("_ ");68int any_prec = 0;69for( ; k<n->len(); k++ ) // For all precedence inputs70if( n->in(k) ) {71if( !any_prec++ ) tty->print(" |");72dump( n->in(k) );73}7475// Dump node-specific info76n->dump_spec(tty);77tty->print("\n");7879}80tty->print("\n");81}82}83#endif8485// Combine the live ranges def'd by these 2 Nodes. N2 is an input to N1.86void PhaseCoalesce::combine_these_two(Node *n1, Node *n2) {87uint lr1 = _phc._lrg_map.find(n1);88uint lr2 = _phc._lrg_map.find(n2);89if( lr1 != lr2 && // Different live ranges already AND90!_phc._ifg->test_edge_sq( lr1, lr2 ) ) { // Do not interfere91LRG *lrg1 = &_phc.lrgs(lr1);92LRG *lrg2 = &_phc.lrgs(lr2);93// Not an oop->int cast; oop->oop, int->int, AND int->oop are OK.9495// Now, why is int->oop OK? We end up declaring a raw-pointer as an oop96// and in general that's a bad thing. However, int->oop conversions only97// happen at GC points, so the lifetime of the misclassified raw-pointer98// is from the CheckCastPP (that converts it to an oop) backwards up99// through a merge point and into the slow-path call, and around the100// diamond up to the heap-top check and back down into the slow-path call.101// The misclassified raw pointer is NOT live across the slow-path call,102// and so does not appear in any GC info, so the fact that it is103// misclassified is OK.104105if( (lrg1->_is_oop || !lrg2->_is_oop) && // not an oop->int cast AND106// Compatible final mask107lrg1->mask().overlap( lrg2->mask() ) ) {108// Merge larger into smaller.109if( lr1 > lr2 ) {110uint tmp = lr1; lr1 = lr2; lr2 = tmp;111Node *n = n1; n1 = n2; n2 = n;112LRG *ltmp = lrg1; lrg1 = lrg2; lrg2 = ltmp;113}114// Union lr2 into lr1115_phc.Union( n1, n2 );116if (lrg1->_maxfreq < lrg2->_maxfreq)117lrg1->_maxfreq = lrg2->_maxfreq;118// Merge in the IFG119_phc._ifg->Union( lr1, lr2 );120// Combine register restrictions121lrg1->AND(lrg2->mask());122}123}124}125126// Copy coalescing127void PhaseCoalesce::coalesce_driver() {128verify();129// Coalesce from high frequency to low130for (uint i = 0; i < _phc._cfg.number_of_blocks(); i++) {131coalesce(_phc._blks[i]);132}133}134135// I am inserting copies to come out of SSA form. In the general case, I am136// doing a parallel renaming. I'm in the Named world now, so I can't do a137// general parallel renaming. All the copies now use "names" (live-ranges)138// to carry values instead of the explicit use-def chains. Suppose I need to139// insert 2 copies into the same block. They copy L161->L128 and L128->L132.140// If I insert them in the wrong order then L128 will get clobbered before it141// can get used by the second copy. This cannot happen in the SSA model;142// direct use-def chains get me the right value. It DOES happen in the named143// model so I have to handle the reordering of copies.144//145// In general, I need to topo-sort the placed copies to avoid conflicts.146// Its possible to have a closed cycle of copies (e.g., recirculating the same147// values around a loop). In this case I need a temp to break the cycle.148void PhaseAggressiveCoalesce::insert_copy_with_overlap( Block *b, Node *copy, uint dst_name, uint src_name ) {149150// Scan backwards for the locations of the last use of the dst_name.151// I am about to clobber the dst_name, so the copy must be inserted152// after the last use. Last use is really first-use on a backwards scan.153uint i = b->end_idx()-1;154while(1) {155Node *n = b->get_node(i);156// Check for end of virtual copies; this is also the end of the157// parallel renaming effort.158if (n->_idx < _unique) {159break;160}161uint idx = n->is_Copy();162assert( idx || n->is_Con() || n->is_MachProj(), "Only copies during parallel renaming" );163if (idx && _phc._lrg_map.find(n->in(idx)) == dst_name) {164break;165}166i--;167}168uint last_use_idx = i;169170// Also search for any kill of src_name that exits the block.171// Since the copy uses src_name, I have to come before any kill.172uint kill_src_idx = b->end_idx();173// There can be only 1 kill that exits any block and that is174// the last kill. Thus it is the first kill on a backwards scan.175i = b->end_idx()-1;176while (1) {177Node *n = b->get_node(i);178// Check for end of virtual copies; this is also the end of the179// parallel renaming effort.180if (n->_idx < _unique) {181break;182}183assert( n->is_Copy() || n->is_Con() || n->is_MachProj(), "Only copies during parallel renaming" );184if (_phc._lrg_map.find(n) == src_name) {185kill_src_idx = i;186break;187}188i--;189}190// Need a temp? Last use of dst comes after the kill of src?191if (last_use_idx >= kill_src_idx) {192// Need to break a cycle with a temp193uint idx = copy->is_Copy();194Node *tmp = copy->clone();195uint max_lrg_id = _phc._lrg_map.max_lrg_id();196_phc.new_lrg(tmp, max_lrg_id);197_phc._lrg_map.set_max_lrg_id(max_lrg_id + 1);198199// Insert new temp between copy and source200tmp ->set_req(idx,copy->in(idx));201copy->set_req(idx,tmp);202// Save source in temp early, before source is killed203b->insert_node(tmp, kill_src_idx);204_phc._cfg.map_node_to_block(tmp, b);205last_use_idx++;206}207208// Insert just after last use209b->insert_node(copy, last_use_idx + 1);210}211212void PhaseAggressiveCoalesce::insert_copies( Matcher &matcher ) {213// We do LRGs compressing and fix a liveout data only here since the other214// place in Split() is guarded by the assert which we never hit.215_phc._lrg_map.compress_uf_map_for_nodes();216// Fix block's liveout data for compressed live ranges.217for (uint lrg = 1; lrg < _phc._lrg_map.max_lrg_id(); lrg++) {218uint compressed_lrg = _phc._lrg_map.find(lrg);219if (lrg != compressed_lrg) {220for (uint bidx = 0; bidx < _phc._cfg.number_of_blocks(); bidx++) {221IndexSet *liveout = _phc._live->live(_phc._cfg.get_block(bidx));222if (liveout->member(lrg)) {223liveout->remove(lrg);224liveout->insert(compressed_lrg);225}226}227}228}229230// All new nodes added are actual copies to replace virtual copies.231// Nodes with index less than '_unique' are original, non-virtual Nodes.232_unique = C->unique();233234for (uint i = 0; i < _phc._cfg.number_of_blocks(); i++) {235C->check_node_count(NodeLimitFudgeFactor, "out of nodes in coalesce");236if (C->failing()) return;237Block *b = _phc._cfg.get_block(i);238uint cnt = b->num_preds(); // Number of inputs to the Phi239240for( uint l = 1; l<b->number_of_nodes(); l++ ) {241Node *n = b->get_node(l);242243// Do not use removed-copies, use copied value instead244uint ncnt = n->req();245for( uint k = 1; k<ncnt; k++ ) {246Node *copy = n->in(k);247uint cidx = copy->is_Copy();248if( cidx ) {249Node *def = copy->in(cidx);250if (_phc._lrg_map.find(copy) == _phc._lrg_map.find(def)) {251n->set_req(k, def);252}253}254}255256// Remove any explicit copies that get coalesced.257uint cidx = n->is_Copy();258if( cidx ) {259Node *def = n->in(cidx);260if (_phc._lrg_map.find(n) == _phc._lrg_map.find(def)) {261n->replace_by(def);262n->set_req(cidx,NULL);263b->remove_node(l);264l--;265continue;266}267}268269if (n->is_Phi()) {270// Get the chosen name for the Phi271uint phi_name = _phc._lrg_map.find(n);272// Ignore the pre-allocated specials273if (!phi_name) {274continue;275}276// Check for mismatch inputs to Phi277for (uint j = 1; j < cnt; j++) {278Node *m = n->in(j);279uint src_name = _phc._lrg_map.find(m);280if (src_name != phi_name) {281Block *pred = _phc._cfg.get_block_for_node(b->pred(j));282Node *copy;283assert(!m->is_Con() || m->is_Mach(), "all Con must be Mach");284// Rematerialize constants instead of copying them.285// We do this only for immediate constants, we avoid constant table loads286// because that will unsafely extend the live range of the constant table base.287if (m->is_Mach() && m->as_Mach()->is_Con() && !m->as_Mach()->is_MachConstant() &&288m->as_Mach()->rematerialize()) {289copy = m->clone();290// Insert the copy in the predecessor basic block291pred->add_inst(copy);292// Copy any flags as well293_phc.clone_projs(pred, pred->end_idx(), m, copy, _phc._lrg_map);294} else {295uint ireg = m->ideal_reg();296if (ireg == 0 || ireg == Op_RegFlags) {297if (C->subsume_loads()) {298C->record_failure(C2Compiler::retry_no_subsuming_loads());299} else {300assert(false, "attempted to spill a non-spillable item: %d: %s, ireg = %u, spill_type: %s",301m->_idx, m->Name(), ireg, MachSpillCopyNode::spill_type(MachSpillCopyNode::PhiInput));302C->record_method_not_compilable("attempted to spill a non-spillable item");303}304return;305}306const RegMask *rm = C->matcher()->idealreg2spillmask[ireg];307copy = new MachSpillCopyNode(MachSpillCopyNode::PhiInput, m, *rm, *rm);308// Find a good place to insert. Kinda tricky, use a subroutine309insert_copy_with_overlap(pred,copy,phi_name,src_name);310}311// Insert the copy in the use-def chain312n->set_req(j, copy);313_phc._cfg.map_node_to_block(copy, pred);314// Extend ("register allocate") the names array for the copy.315_phc._lrg_map.extend(copy->_idx, phi_name);316} // End of if Phi names do not match317} // End of for all inputs to Phi318} else { // End of if Phi319320// Now check for 2-address instructions321uint idx;322if( n->is_Mach() && (idx=n->as_Mach()->two_adr()) ) {323// Get the chosen name for the Node324uint name = _phc._lrg_map.find(n);325assert (name, "no 2-address specials");326// Check for name mis-match on the 2-address input327Node *m = n->in(idx);328if (_phc._lrg_map.find(m) != name) {329Node *copy;330assert(!m->is_Con() || m->is_Mach(), "all Con must be Mach");331// At this point it is unsafe to extend live ranges (6550579).332// Rematerialize only constants as we do for Phi above.333if (m->is_Mach() && m->as_Mach()->is_Con() && !m->as_Mach()->is_MachConstant() &&334m->as_Mach()->rematerialize()) {335copy = m->clone();336// Insert the copy in the basic block, just before us337b->insert_node(copy, l++);338l += _phc.clone_projs(b, l, m, copy, _phc._lrg_map);339} else {340uint ireg = m->ideal_reg();341if (ireg == 0 || ireg == Op_RegFlags) {342assert(false, "attempted to spill a non-spillable item: %d: %s, ireg = %u, spill_type: %s",343m->_idx, m->Name(), ireg, MachSpillCopyNode::spill_type(MachSpillCopyNode::TwoAddress));344C->record_method_not_compilable("attempted to spill a non-spillable item");345return;346}347const RegMask *rm = C->matcher()->idealreg2spillmask[ireg];348copy = new MachSpillCopyNode(MachSpillCopyNode::TwoAddress, m, *rm, *rm);349// Insert the copy in the basic block, just before us350b->insert_node(copy, l++);351}352// Insert the copy in the use-def chain353n->set_req(idx, copy);354// Extend ("register allocate") the names array for the copy.355_phc._lrg_map.extend(copy->_idx, name);356_phc._cfg.map_node_to_block(copy, b);357}358359} // End of is two-adr360361// Insert a copy at a debug use for a lrg which has high frequency362if (b->_freq < OPTO_DEBUG_SPLIT_FREQ || _phc._cfg.is_uncommon(b)) {363// Walk the debug inputs to the node and check for lrg freq364JVMState* jvms = n->jvms();365uint debug_start = jvms ? jvms->debug_start() : 999999;366uint debug_end = jvms ? jvms->debug_end() : 999999;367for(uint inpidx = debug_start; inpidx < debug_end; inpidx++) {368// Do not split monitors; they are only needed for debug table369// entries and need no code.370if (jvms->is_monitor_use(inpidx)) {371continue;372}373Node *inp = n->in(inpidx);374uint nidx = _phc._lrg_map.live_range_id(inp);375LRG &lrg = lrgs(nidx);376377// If this lrg has a high frequency use/def378if( lrg._maxfreq >= _phc.high_frequency_lrg() ) {379// If the live range is also live out of this block (like it380// would be for a fast/slow idiom), the normal spill mechanism381// does an excellent job. If it is not live out of this block382// (like it would be for debug info to uncommon trap) splitting383// the live range now allows a better allocation in the high384// frequency blocks.385// Build_IFG_virtual has converted the live sets to386// live-IN info, not live-OUT info.387uint k;388for( k=0; k < b->_num_succs; k++ )389if( _phc._live->live(b->_succs[k])->member( nidx ) )390break; // Live in to some successor block?391if( k < b->_num_succs )392continue; // Live out; do not pre-split393// Split the lrg at this use394uint ireg = inp->ideal_reg();395if (ireg == 0 || ireg == Op_RegFlags) {396assert(false, "attempted to spill a non-spillable item: %d: %s, ireg = %u, spill_type: %s",397inp->_idx, inp->Name(), ireg, MachSpillCopyNode::spill_type(MachSpillCopyNode::DebugUse));398C->record_method_not_compilable("attempted to spill a non-spillable item");399return;400}401const RegMask *rm = C->matcher()->idealreg2spillmask[ireg];402Node* copy = new MachSpillCopyNode(MachSpillCopyNode::DebugUse, inp, *rm, *rm);403// Insert the copy in the use-def chain404n->set_req(inpidx, copy );405// Insert the copy in the basic block, just before us406b->insert_node(copy, l++);407// Extend ("register allocate") the names array for the copy.408uint max_lrg_id = _phc._lrg_map.max_lrg_id();409_phc.new_lrg(copy, max_lrg_id);410_phc._lrg_map.set_max_lrg_id(max_lrg_id + 1);411_phc._cfg.map_node_to_block(copy, b);412//tty->print_cr("Split a debug use in Aggressive Coalesce");413} // End of if high frequency use/def414} // End of for all debug inputs415} // End of if low frequency safepoint416417} // End of if Phi418419} // End of for all instructions420} // End of for all blocks421}422423424// Aggressive (but pessimistic) copy coalescing of a single block425426// The following coalesce pass represents a single round of aggressive427// pessimistic coalesce. "Aggressive" means no attempt to preserve428// colorability when coalescing. This occasionally means more spills, but429// it also means fewer rounds of coalescing for better code - and that means430// faster compiles.431432// "Pessimistic" means we do not hit the fixed point in one pass (and we are433// reaching for the least fixed point to boot). This is typically solved434// with a few more rounds of coalescing, but the compiler must run fast. We435// could optimistically coalescing everything touching PhiNodes together436// into one big live range, then check for self-interference. Everywhere437// the live range interferes with self it would have to be split. Finding438// the right split points can be done with some heuristics (based on439// expected frequency of edges in the live range). In short, it's a real440// research problem and the timeline is too short to allow such research.441// Further thoughts: (1) build the LR in a pass, (2) find self-interference442// in another pass, (3) per each self-conflict, split, (4) split by finding443// the low-cost cut (min-cut) of the LR, (5) edges in the LR are weighted444// according to the GCM algorithm (or just exec freq on CFG edges).445446void PhaseAggressiveCoalesce::coalesce( Block *b ) {447// Copies are still "virtual" - meaning we have not made them explicitly448// copies. Instead, Phi functions of successor blocks have mis-matched449// live-ranges. If I fail to coalesce, I'll have to insert a copy to line450// up the live-ranges. Check for Phis in successor blocks.451uint i;452for( i=0; i<b->_num_succs; i++ ) {453Block *bs = b->_succs[i];454// Find index of 'b' in 'bs' predecessors455uint j=1;456while (_phc._cfg.get_block_for_node(bs->pred(j)) != b) {457j++;458}459460// Visit all the Phis in successor block461for( uint k = 1; k<bs->number_of_nodes(); k++ ) {462Node *n = bs->get_node(k);463if( !n->is_Phi() ) break;464combine_these_two( n, n->in(j) );465}466} // End of for all successor blocks467468469// Check _this_ block for 2-address instructions and copies.470uint cnt = b->end_idx();471for( i = 1; i<cnt; i++ ) {472Node *n = b->get_node(i);473uint idx;474// 2-address instructions have a virtual Copy matching their input475// to their output476if (n->is_Mach() && (idx = n->as_Mach()->two_adr())) {477MachNode *mach = n->as_Mach();478combine_these_two(mach, mach->in(idx));479}480} // End of for all instructions in block481}482483PhaseConservativeCoalesce::PhaseConservativeCoalesce(PhaseChaitin &chaitin) : PhaseCoalesce(chaitin) {484_ulr.initialize(_phc._lrg_map.max_lrg_id());485}486487void PhaseConservativeCoalesce::verify() {488#ifdef ASSERT489_phc.set_was_low();490#endif491}492493void PhaseConservativeCoalesce::union_helper( Node *lr1_node, Node *lr2_node, uint lr1, uint lr2, Node *src_def, Node *dst_copy, Node *src_copy, Block *b, uint bindex ) {494// Join live ranges. Merge larger into smaller. Union lr2 into lr1 in the495// union-find tree496_phc.Union( lr1_node, lr2_node );497498// Single-def live range ONLY if both live ranges are single-def.499// If both are single def, then src_def powers one live range500// and def_copy powers the other. After merging, src_def powers501// the combined live range.502lrgs(lr1)._def = (lrgs(lr1).is_multidef() ||503lrgs(lr2).is_multidef() )504? NodeSentinel : src_def;505lrgs(lr2)._def = NULL; // No def for lrg 2506lrgs(lr2).Clear(); // Force empty mask for LRG 2507//lrgs(lr2)._size = 0; // Live-range 2 goes dead508lrgs(lr1)._is_oop |= lrgs(lr2)._is_oop;509lrgs(lr2)._is_oop = 0; // In particular, not an oop for GC info510511if (lrgs(lr1)._maxfreq < lrgs(lr2)._maxfreq)512lrgs(lr1)._maxfreq = lrgs(lr2)._maxfreq;513514// Copy original value instead. Intermediate copies go dead, and515// the dst_copy becomes useless.516int didx = dst_copy->is_Copy();517dst_copy->set_req( didx, src_def );518// Add copy to free list519// _phc.free_spillcopy(b->_nodes[bindex]);520assert( b->get_node(bindex) == dst_copy, "" );521dst_copy->replace_by( dst_copy->in(didx) );522dst_copy->set_req( didx, NULL);523b->remove_node(bindex);524if( bindex < b->_ihrp_index ) b->_ihrp_index--;525if( bindex < b->_fhrp_index ) b->_fhrp_index--;526527// Stretched lr1; add it to liveness of intermediate blocks528Block *b2 = _phc._cfg.get_block_for_node(src_copy);529while( b != b2 ) {530b = _phc._cfg.get_block_for_node(b->pred(1));531_phc._live->live(b)->insert(lr1);532}533}534535// Factored code from copy_copy that computes extra interferences from536// lengthening a live range by double-coalescing.537uint PhaseConservativeCoalesce::compute_separating_interferences(Node *dst_copy, Node *src_copy, Block *b, uint bindex, RegMask &rm, uint rm_size, uint reg_degree, uint lr1, uint lr2 ) {538539assert(!lrgs(lr1)._fat_proj, "cannot coalesce fat_proj");540assert(!lrgs(lr2)._fat_proj, "cannot coalesce fat_proj");541Node *prev_copy = dst_copy->in(dst_copy->is_Copy());542Block *b2 = b;543uint bindex2 = bindex;544while( 1 ) {545// Find previous instruction546bindex2--; // Chain backwards 1 instruction547while( bindex2 == 0 ) { // At block start, find prior block548assert( b2->num_preds() == 2, "cannot double coalesce across c-flow" );549b2 = _phc._cfg.get_block_for_node(b2->pred(1));550bindex2 = b2->end_idx()-1;551}552// Get prior instruction553assert(bindex2 < b2->number_of_nodes(), "index out of bounds");554Node *x = b2->get_node(bindex2);555if( x == prev_copy ) { // Previous copy in copy chain?556if( prev_copy == src_copy)// Found end of chain and all interferences557break; // So break out of loop558// Else work back one in copy chain559prev_copy = prev_copy->in(prev_copy->is_Copy());560} else { // Else collect interferences561uint lidx = _phc._lrg_map.find(x);562// Found another def of live-range being stretched?563if(lidx == lr1) {564return max_juint;565}566if(lidx == lr2) {567return max_juint;568}569570// If we attempt to coalesce across a bound def571if( lrgs(lidx).is_bound() ) {572// Do not let the coalesced LRG expect to get the bound color573rm.SUBTRACT( lrgs(lidx).mask() );574// Recompute rm_size575rm_size = rm.Size();576//if( rm._flags ) rm_size += 1000000;577if( reg_degree >= rm_size ) return max_juint;578}579if( rm.overlap(lrgs(lidx).mask()) ) {580// Insert lidx into union LRG; returns TRUE if actually inserted581if( _ulr.insert(lidx) ) {582// Infinite-stack neighbors do not alter colorability, as they583// can always color to some other color.584if( !lrgs(lidx).mask().is_AllStack() ) {585// If this coalesce will make any new neighbor uncolorable,586// do not coalesce.587if( lrgs(lidx).just_lo_degree() )588return max_juint;589// Bump our degree590if( ++reg_degree >= rm_size )591return max_juint;592} // End of if not infinite-stack neighbor593} // End of if actually inserted594} // End of if live range overlaps595} // End of else collect interferences for 1 node596} // End of while forever, scan back for interferences597return reg_degree;598}599600void PhaseConservativeCoalesce::update_ifg(uint lr1, uint lr2, IndexSet *n_lr1, IndexSet *n_lr2) {601// Some original neighbors of lr1 might have gone away602// because the constrained register mask prevented them.603// Remove lr1 from such neighbors.604uint neighbor = 0;605LRG &lrg1 = lrgs(lr1);606if (!n_lr1->is_empty()) {607IndexSetIterator one(n_lr1);608while ((neighbor = one.next()) != 0) {609if (!_ulr.member(neighbor)) {610if (_phc._ifg->neighbors(neighbor)->remove(lr1)) {611lrgs(neighbor).inc_degree(-lrg1.compute_degree(lrgs(neighbor)));612}613}614}615}616617618// lr2 is now called (coalesced into) lr1.619// Remove lr2 from the IFG.620LRG &lrg2 = lrgs(lr2);621if (!n_lr2->is_empty()) {622IndexSetIterator two(n_lr2);623while ((neighbor = two.next()) != 0) {624if (_phc._ifg->neighbors(neighbor)->remove(lr2)) {625lrgs(neighbor).inc_degree(-lrg2.compute_degree(lrgs(neighbor)));626}627}628}629630// Some neighbors of intermediate copies now interfere with the631// combined live range.632if (!_ulr.is_empty()) {633IndexSetIterator three(&_ulr);634while ((neighbor = three.next()) != 0) {635if (_phc._ifg->neighbors(neighbor)->insert(lr1)) {636lrgs(neighbor).inc_degree(lrg1.compute_degree(lrgs(neighbor)));637}638}639}640}641642static void record_bias( const PhaseIFG *ifg, int lr1, int lr2 ) {643// Tag copy bias here644if( !ifg->lrgs(lr1)._copy_bias )645ifg->lrgs(lr1)._copy_bias = lr2;646if( !ifg->lrgs(lr2)._copy_bias )647ifg->lrgs(lr2)._copy_bias = lr1;648}649650// See if I can coalesce a series of multiple copies together. I need the651// final dest copy and the original src copy. They can be the same Node.652// Compute the compatible register masks.653bool PhaseConservativeCoalesce::copy_copy(Node *dst_copy, Node *src_copy, Block *b, uint bindex) {654655if (!dst_copy->is_SpillCopy()) {656return false;657}658if (!src_copy->is_SpillCopy()) {659return false;660}661Node *src_def = src_copy->in(src_copy->is_Copy());662uint lr1 = _phc._lrg_map.find(dst_copy);663uint lr2 = _phc._lrg_map.find(src_def);664665// Same live ranges already?666if (lr1 == lr2) {667return false;668}669670// Interfere?671if (_phc._ifg->test_edge_sq(lr1, lr2)) {672return false;673}674675// Not an oop->int cast; oop->oop, int->int, AND int->oop are OK.676if (!lrgs(lr1)._is_oop && lrgs(lr2)._is_oop) { // not an oop->int cast677return false;678}679680// Coalescing between an aligned live range and a mis-aligned live range?681// No, no! Alignment changes how we count degree.682if (lrgs(lr1)._fat_proj != lrgs(lr2)._fat_proj) {683return false;684}685686// Sort; use smaller live-range number687Node *lr1_node = dst_copy;688Node *lr2_node = src_def;689if (lr1 > lr2) {690uint tmp = lr1; lr1 = lr2; lr2 = tmp;691lr1_node = src_def; lr2_node = dst_copy;692}693694// Check for compatibility of the 2 live ranges by695// intersecting their allowed register sets.696RegMask rm = lrgs(lr1).mask();697rm.AND(lrgs(lr2).mask());698// Number of bits free699uint rm_size = rm.Size();700701if (UseFPUForSpilling && rm.is_AllStack() ) {702// Don't coalesce when frequency difference is large703Block *dst_b = _phc._cfg.get_block_for_node(dst_copy);704Block *src_def_b = _phc._cfg.get_block_for_node(src_def);705if (src_def_b->_freq > 10*dst_b->_freq )706return false;707}708709// If we can use any stack slot, then effective size is infinite710if( rm.is_AllStack() ) rm_size += 1000000;711// Incompatible masks, no way to coalesce712if( rm_size == 0 ) return false;713714// Another early bail-out test is when we are double-coalescing and the715// 2 copies are separated by some control flow.716if( dst_copy != src_copy ) {717Block *src_b = _phc._cfg.get_block_for_node(src_copy);718Block *b2 = b;719while( b2 != src_b ) {720if( b2->num_preds() > 2 ){// Found merge-point721_phc._lost_opp_cflow_coalesce++;722// extra record_bias commented out because Chris believes it is not723// productive. Since we can record only 1 bias, we want to choose one724// that stands a chance of working and this one probably does not.725//record_bias( _phc._lrgs, lr1, lr2 );726return false; // To hard to find all interferences727}728b2 = _phc._cfg.get_block_for_node(b2->pred(1));729}730}731732// Union the two interference sets together into '_ulr'733uint reg_degree = _ulr.lrg_union( lr1, lr2, rm_size, _phc._ifg, rm );734735if( reg_degree >= rm_size ) {736record_bias( _phc._ifg, lr1, lr2 );737return false;738}739740// Now I need to compute all the interferences between dst_copy and741// src_copy. I'm not willing visit the entire interference graph, so742// I limit my search to things in dst_copy's block or in a straight743// line of previous blocks. I give up at merge points or when I get744// more interferences than my degree. I can stop when I find src_copy.745if( dst_copy != src_copy ) {746reg_degree = compute_separating_interferences(dst_copy, src_copy, b, bindex, rm, rm_size, reg_degree, lr1, lr2 );747if( reg_degree == max_juint ) {748record_bias( _phc._ifg, lr1, lr2 );749return false;750}751} // End of if dst_copy & src_copy are different752753754// ---- THE COMBINED LRG IS COLORABLE ----755756// YEAH - Now coalesce this copy away757assert( lrgs(lr1).num_regs() == lrgs(lr2).num_regs(), "" );758759IndexSet *n_lr1 = _phc._ifg->neighbors(lr1);760IndexSet *n_lr2 = _phc._ifg->neighbors(lr2);761762// Update the interference graph763update_ifg(lr1, lr2, n_lr1, n_lr2);764765_ulr.remove(lr1);766767// Uncomment the following code to trace Coalescing in great detail.768//769//if (false) {770// tty->cr();771// tty->print_cr("#######################################");772// tty->print_cr("union %d and %d", lr1, lr2);773// n_lr1->dump();774// n_lr2->dump();775// tty->print_cr("resulting set is");776// _ulr.dump();777//}778779// Replace n_lr1 with the new combined live range. _ulr will use780// n_lr1's old memory on the next iteration. n_lr2 is cleared to781// send its internal memory to the free list.782_ulr.swap(n_lr1);783_ulr.clear();784n_lr2->clear();785786lrgs(lr1).set_degree( _phc._ifg->effective_degree(lr1) );787lrgs(lr2).set_degree( 0 );788789// Join live ranges. Merge larger into smaller. Union lr2 into lr1 in the790// union-find tree791union_helper( lr1_node, lr2_node, lr1, lr2, src_def, dst_copy, src_copy, b, bindex );792// Combine register restrictions793lrgs(lr1).set_mask(rm);794lrgs(lr1).compute_set_mask_size();795lrgs(lr1)._cost += lrgs(lr2)._cost;796lrgs(lr1)._area += lrgs(lr2)._area;797798// While its uncommon to successfully coalesce live ranges that started out799// being not-lo-degree, it can happen. In any case the combined coalesced800// live range better Simplify nicely.801lrgs(lr1)._was_lo = 1;802803// kinda expensive to do all the time804//tty->print_cr("warning: slow verify happening");805//_phc._ifg->verify( &_phc );806return true;807}808809// Conservative (but pessimistic) copy coalescing of a single block810void PhaseConservativeCoalesce::coalesce( Block *b ) {811// Bail out on infrequent blocks812if (_phc._cfg.is_uncommon(b)) {813return;814}815// Check this block for copies.816for( uint i = 1; i<b->end_idx(); i++ ) {817// Check for actual copies on inputs. Coalesce a copy into its818// input if use and copy's input are compatible.819Node *copy1 = b->get_node(i);820uint idx1 = copy1->is_Copy();821if( !idx1 ) continue; // Not a copy822823if( copy_copy(copy1,copy1,b,i) ) {824i--; // Retry, same location in block825PhaseChaitin::_conserv_coalesce++; // Collect stats on success826continue;827}828}829}830831832