Path: blob/master/src/hotspot/share/opto/gcm.cpp
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#include "precompiled.hpp"25#include "libadt/vectset.hpp"26#include "memory/allocation.inline.hpp"27#include "memory/resourceArea.hpp"28#include "opto/block.hpp"29#include "opto/c2compiler.hpp"30#include "opto/callnode.hpp"31#include "opto/cfgnode.hpp"32#include "opto/machnode.hpp"33#include "opto/opcodes.hpp"34#include "opto/phaseX.hpp"35#include "opto/rootnode.hpp"36#include "opto/runtime.hpp"37#include "opto/chaitin.hpp"38#include "runtime/deoptimization.hpp"3940// Portions of code courtesy of Clifford Click4142// Optimization - Graph Style4344// To avoid float value underflow45#define MIN_BLOCK_FREQUENCY 1.e-35f4647//----------------------------schedule_node_into_block-------------------------48// Insert node n into block b. Look for projections of n and make sure they49// are in b also.50void PhaseCFG::schedule_node_into_block( Node *n, Block *b ) {51// Set basic block of n, Add n to b,52map_node_to_block(n, b);53b->add_inst(n);5455// After Matching, nearly any old Node may have projections trailing it.56// These are usually machine-dependent flags. In any case, they might57// float to another block below this one. Move them up.58for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {59Node* use = n->fast_out(i);60if (use->is_Proj()) {61Block* buse = get_block_for_node(use);62if (buse != b) { // In wrong block?63if (buse != NULL) {64buse->find_remove(use); // Remove from wrong block65}66map_node_to_block(use, b);67b->add_inst(use);68}69}70}71}7273//----------------------------replace_block_proj_ctrl-------------------------74// Nodes that have is_block_proj() nodes as their control need to use75// the appropriate Region for their actual block as their control since76// the projection will be in a predecessor block.77void PhaseCFG::replace_block_proj_ctrl( Node *n ) {78const Node *in0 = n->in(0);79assert(in0 != NULL, "Only control-dependent");80const Node *p = in0->is_block_proj();81if (p != NULL && p != n) { // Control from a block projection?82assert(!n->pinned() || n->is_MachConstantBase(), "only pinned MachConstantBase node is expected here");83// Find trailing Region84Block *pb = get_block_for_node(in0); // Block-projection already has basic block85uint j = 0;86if (pb->_num_succs != 1) { // More then 1 successor?87// Search for successor88uint max = pb->number_of_nodes();89assert( max > 1, "" );90uint start = max - pb->_num_succs;91// Find which output path belongs to projection92for (j = start; j < max; j++) {93if( pb->get_node(j) == in0 )94break;95}96assert( j < max, "must find" );97// Change control to match head of successor basic block98j -= start;99}100n->set_req(0, pb->_succs[j]->head());101}102}103104bool PhaseCFG::is_dominator(Node* dom_node, Node* node) {105assert(is_CFG(node) && is_CFG(dom_node), "node and dom_node must be CFG nodes");106if (dom_node == node) {107return true;108}109Block* d = find_block_for_node(dom_node);110Block* n = find_block_for_node(node);111assert(n != NULL && d != NULL, "blocks must exist");112113if (d == n) {114if (dom_node->is_block_start()) {115return true;116}117if (node->is_block_start()) {118return false;119}120if (dom_node->is_block_proj()) {121return false;122}123if (node->is_block_proj()) {124return true;125}126127assert(is_control_proj_or_safepoint(node), "node must be control projection or safepoint");128assert(is_control_proj_or_safepoint(dom_node), "dom_node must be control projection or safepoint");129130// Neither 'node' nor 'dom_node' is a block start or block projection.131// Check if 'dom_node' is above 'node' in the control graph.132if (is_dominating_control(dom_node, node)) {133return true;134}135136#ifdef ASSERT137// If 'dom_node' does not dominate 'node' then 'node' has to dominate 'dom_node'138if (!is_dominating_control(node, dom_node)) {139node->dump();140dom_node->dump();141assert(false, "neither dom_node nor node dominates the other");142}143#endif144145return false;146}147return d->dom_lca(n) == d;148}149150bool PhaseCFG::is_CFG(Node* n) {151return n->is_block_proj() || n->is_block_start() || is_control_proj_or_safepoint(n);152}153154bool PhaseCFG::is_control_proj_or_safepoint(Node* n) const {155bool result = (n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_SafePoint) || (n->is_Proj() && n->as_Proj()->bottom_type() == Type::CONTROL);156assert(!result || (n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_SafePoint)157|| (n->is_Proj() && n->as_Proj()->_con == 0), "If control projection, it must be projection 0");158return result;159}160161Block* PhaseCFG::find_block_for_node(Node* n) const {162if (n->is_block_start() || n->is_block_proj()) {163return get_block_for_node(n);164} else {165// Walk the control graph up if 'n' is not a block start nor a block projection. In this case 'n' must be166// an unmatched control projection or a not yet matched safepoint precedence edge in the middle of a block.167assert(is_control_proj_or_safepoint(n), "must be control projection or safepoint");168Node* ctrl = n->in(0);169while (!ctrl->is_block_start()) {170ctrl = ctrl->in(0);171}172return get_block_for_node(ctrl);173}174}175176// Walk up the control graph from 'n' and check if 'dom_ctrl' is found.177bool PhaseCFG::is_dominating_control(Node* dom_ctrl, Node* n) {178Node* ctrl = n->in(0);179while (!ctrl->is_block_start()) {180if (ctrl == dom_ctrl) {181return true;182}183ctrl = ctrl->in(0);184}185return false;186}187188189//------------------------------schedule_pinned_nodes--------------------------190// Set the basic block for Nodes pinned into blocks191void PhaseCFG::schedule_pinned_nodes(VectorSet &visited) {192// Allocate node stack of size C->live_nodes()+8 to avoid frequent realloc193GrowableArray <Node*> spstack(C->live_nodes() + 8);194spstack.push(_root);195while (spstack.is_nonempty()) {196Node* node = spstack.pop();197if (!visited.test_set(node->_idx)) { // Test node and flag it as visited198if (node->pinned() && !has_block(node)) { // Pinned? Nail it down!199assert(node->in(0), "pinned Node must have Control");200// Before setting block replace block_proj control edge201replace_block_proj_ctrl(node);202Node* input = node->in(0);203while (!input->is_block_start()) {204input = input->in(0);205}206Block* block = get_block_for_node(input); // Basic block of controlling input207schedule_node_into_block(node, block);208}209210// If the node has precedence edges (added when CastPP nodes are211// removed in final_graph_reshaping), fix the control of the212// node to cover the precedence edges and remove the213// dependencies.214Node* n = NULL;215for (uint i = node->len()-1; i >= node->req(); i--) {216Node* m = node->in(i);217if (m == NULL) continue;218219// Only process precedence edges that are CFG nodes. Safepoints and control projections can be in the middle of a block220if (is_CFG(m)) {221node->rm_prec(i);222if (n == NULL) {223n = m;224} else {225assert(is_dominator(n, m) || is_dominator(m, n), "one must dominate the other");226n = is_dominator(n, m) ? m : n;227}228} else {229assert(node->is_Mach(), "sanity");230assert(node->as_Mach()->ideal_Opcode() == Op_StoreCM, "must be StoreCM node");231}232}233if (n != NULL) {234assert(node->in(0), "control should have been set");235assert(is_dominator(n, node->in(0)) || is_dominator(node->in(0), n), "one must dominate the other");236if (!is_dominator(n, node->in(0))) {237node->set_req(0, n);238}239}240241// process all inputs that are non NULL242for (int i = node->req()-1; i >= 0; --i) {243if (node->in(i) != NULL) {244spstack.push(node->in(i));245}246}247}248}249}250251#ifdef ASSERT252// Assert that new input b2 is dominated by all previous inputs.253// Check this by by seeing that it is dominated by b1, the deepest254// input observed until b2.255static void assert_dom(Block* b1, Block* b2, Node* n, const PhaseCFG* cfg) {256if (b1 == NULL) return;257assert(b1->_dom_depth < b2->_dom_depth, "sanity");258Block* tmp = b2;259while (tmp != b1 && tmp != NULL) {260tmp = tmp->_idom;261}262if (tmp != b1) {263// Detected an unschedulable graph. Print some nice stuff and die.264tty->print_cr("!!! Unschedulable graph !!!");265for (uint j=0; j<n->len(); j++) { // For all inputs266Node* inn = n->in(j); // Get input267if (inn == NULL) continue; // Ignore NULL, missing inputs268Block* inb = cfg->get_block_for_node(inn);269tty->print("B%d idom=B%d depth=%2d ",inb->_pre_order,270inb->_idom ? inb->_idom->_pre_order : 0, inb->_dom_depth);271inn->dump();272}273tty->print("Failing node: ");274n->dump();275assert(false, "unscheduable graph");276}277}278#endif279280static Block* find_deepest_input(Node* n, const PhaseCFG* cfg) {281// Find the last input dominated by all other inputs.282Block* deepb = NULL; // Deepest block so far283int deepb_dom_depth = 0;284for (uint k = 0; k < n->len(); k++) { // For all inputs285Node* inn = n->in(k); // Get input286if (inn == NULL) continue; // Ignore NULL, missing inputs287Block* inb = cfg->get_block_for_node(inn);288assert(inb != NULL, "must already have scheduled this input");289if (deepb_dom_depth < (int) inb->_dom_depth) {290// The new inb must be dominated by the previous deepb.291// The various inputs must be linearly ordered in the dom292// tree, or else there will not be a unique deepest block.293DEBUG_ONLY(assert_dom(deepb, inb, n, cfg));294deepb = inb; // Save deepest block295deepb_dom_depth = deepb->_dom_depth;296}297}298assert(deepb != NULL, "must be at least one input to n");299return deepb;300}301302303//------------------------------schedule_early---------------------------------304// Find the earliest Block any instruction can be placed in. Some instructions305// are pinned into Blocks. Unpinned instructions can appear in last block in306// which all their inputs occur.307bool PhaseCFG::schedule_early(VectorSet &visited, Node_Stack &roots) {308// Allocate stack with enough space to avoid frequent realloc309Node_Stack nstack(roots.size() + 8);310// _root will be processed among C->top() inputs311roots.push(C->top(), 0);312visited.set(C->top()->_idx);313314while (roots.size() != 0) {315// Use local variables nstack_top_n & nstack_top_i to cache values316// on stack's top.317Node* parent_node = roots.node();318uint input_index = 0;319roots.pop();320321while (true) {322if (input_index == 0) {323// Fixup some control. Constants without control get attached324// to root and nodes that use is_block_proj() nodes should be attached325// to the region that starts their block.326const Node* control_input = parent_node->in(0);327if (control_input != NULL) {328replace_block_proj_ctrl(parent_node);329} else {330// Is a constant with NO inputs?331if (parent_node->req() == 1) {332parent_node->set_req(0, _root);333}334}335}336337// First, visit all inputs and force them to get a block. If an338// input is already in a block we quit following inputs (to avoid339// cycles). Instead we put that Node on a worklist to be handled340// later (since IT'S inputs may not have a block yet).341342// Assume all n's inputs will be processed343bool done = true;344345while (input_index < parent_node->len()) {346Node* in = parent_node->in(input_index++);347if (in == NULL) {348continue;349}350351int is_visited = visited.test_set(in->_idx);352if (!has_block(in)) {353if (is_visited) {354assert(false, "graph should be schedulable");355return false;356}357// Save parent node and next input's index.358nstack.push(parent_node, input_index);359// Process current input now.360parent_node = in;361input_index = 0;362// Not all n's inputs processed.363done = false;364break;365} else if (!is_visited) {366// Visit this guy later, using worklist367roots.push(in, 0);368}369}370371if (done) {372// All of n's inputs have been processed, complete post-processing.373374// Some instructions are pinned into a block. These include Region,375// Phi, Start, Return, and other control-dependent instructions and376// any projections which depend on them.377if (!parent_node->pinned()) {378// Set earliest legal block.379Block* earliest_block = find_deepest_input(parent_node, this);380map_node_to_block(parent_node, earliest_block);381} else {382assert(get_block_for_node(parent_node) == get_block_for_node(parent_node->in(0)), "Pinned Node should be at the same block as its control edge");383}384385if (nstack.is_empty()) {386// Finished all nodes on stack.387// Process next node on the worklist 'roots'.388break;389}390// Get saved parent node and next input's index.391parent_node = nstack.node();392input_index = nstack.index();393nstack.pop();394}395}396}397return true;398}399400//------------------------------dom_lca----------------------------------------401// Find least common ancestor in dominator tree402// LCA is a current notion of LCA, to be raised above 'this'.403// As a convenient boundary condition, return 'this' if LCA is NULL.404// Find the LCA of those two nodes.405Block* Block::dom_lca(Block* LCA) {406if (LCA == NULL || LCA == this) return this;407408Block* anc = this;409while (anc->_dom_depth > LCA->_dom_depth)410anc = anc->_idom; // Walk up till anc is as high as LCA411412while (LCA->_dom_depth > anc->_dom_depth)413LCA = LCA->_idom; // Walk up till LCA is as high as anc414415while (LCA != anc) { // Walk both up till they are the same416LCA = LCA->_idom;417anc = anc->_idom;418}419420return LCA;421}422423//--------------------------raise_LCA_above_use--------------------------------424// We are placing a definition, and have been given a def->use edge.425// The definition must dominate the use, so move the LCA upward in the426// dominator tree to dominate the use. If the use is a phi, adjust427// the LCA only with the phi input paths which actually use this def.428static Block* raise_LCA_above_use(Block* LCA, Node* use, Node* def, const PhaseCFG* cfg) {429Block* buse = cfg->get_block_for_node(use);430if (buse == NULL) return LCA; // Unused killing Projs have no use block431if (!use->is_Phi()) return buse->dom_lca(LCA);432uint pmax = use->req(); // Number of Phi inputs433// Why does not this loop just break after finding the matching input to434// the Phi? Well...it's like this. I do not have true def-use/use-def435// chains. Means I cannot distinguish, from the def-use direction, which436// of many use-defs lead from the same use to the same def. That is, this437// Phi might have several uses of the same def. Each use appears in a438// different predecessor block. But when I enter here, I cannot distinguish439// which use-def edge I should find the predecessor block for. So I find440// them all. Means I do a little extra work if a Phi uses the same value441// more than once.442for (uint j=1; j<pmax; j++) { // For all inputs443if (use->in(j) == def) { // Found matching input?444Block* pred = cfg->get_block_for_node(buse->pred(j));445LCA = pred->dom_lca(LCA);446}447}448return LCA;449}450451//----------------------------raise_LCA_above_marks----------------------------452// Return a new LCA that dominates LCA and any of its marked predecessors.453// Search all my parents up to 'early' (exclusive), looking for predecessors454// which are marked with the given index. Return the LCA (in the dom tree)455// of all marked blocks. If there are none marked, return the original456// LCA.457static Block* raise_LCA_above_marks(Block* LCA, node_idx_t mark, Block* early, const PhaseCFG* cfg) {458Block_List worklist;459worklist.push(LCA);460while (worklist.size() > 0) {461Block* mid = worklist.pop();462if (mid == early) continue; // stop searching here463464// Test and set the visited bit.465if (mid->raise_LCA_visited() == mark) continue; // already visited466467// Don't process the current LCA, otherwise the search may terminate early468if (mid != LCA && mid->raise_LCA_mark() == mark) {469// Raise the LCA.470LCA = mid->dom_lca(LCA);471if (LCA == early) break; // stop searching everywhere472assert(early->dominates(LCA), "early is high enough");473// Resume searching at that point, skipping intermediate levels.474worklist.push(LCA);475if (LCA == mid)476continue; // Don't mark as visited to avoid early termination.477} else {478// Keep searching through this block's predecessors.479for (uint j = 1, jmax = mid->num_preds(); j < jmax; j++) {480Block* mid_parent = cfg->get_block_for_node(mid->pred(j));481worklist.push(mid_parent);482}483}484mid->set_raise_LCA_visited(mark);485}486return LCA;487}488489//--------------------------memory_early_block--------------------------------490// This is a variation of find_deepest_input, the heart of schedule_early.491// Find the "early" block for a load, if we considered only memory and492// address inputs, that is, if other data inputs were ignored.493//494// Because a subset of edges are considered, the resulting block will495// be earlier (at a shallower dom_depth) than the true schedule_early496// point of the node. We compute this earlier block as a more permissive497// site for anti-dependency insertion, but only if subsume_loads is enabled.498static Block* memory_early_block(Node* load, Block* early, const PhaseCFG* cfg) {499Node* base;500Node* index;501Node* store = load->in(MemNode::Memory);502load->as_Mach()->memory_inputs(base, index);503504assert(base != NodeSentinel && index != NodeSentinel,505"unexpected base/index inputs");506507Node* mem_inputs[4];508int mem_inputs_length = 0;509if (base != NULL) mem_inputs[mem_inputs_length++] = base;510if (index != NULL) mem_inputs[mem_inputs_length++] = index;511if (store != NULL) mem_inputs[mem_inputs_length++] = store;512513// In the comparision below, add one to account for the control input,514// which may be null, but always takes up a spot in the in array.515if (mem_inputs_length + 1 < (int) load->req()) {516// This "load" has more inputs than just the memory, base and index inputs.517// For purposes of checking anti-dependences, we need to start518// from the early block of only the address portion of the instruction,519// and ignore other blocks that may have factored into the wider520// schedule_early calculation.521if (load->in(0) != NULL) mem_inputs[mem_inputs_length++] = load->in(0);522523Block* deepb = NULL; // Deepest block so far524int deepb_dom_depth = 0;525for (int i = 0; i < mem_inputs_length; i++) {526Block* inb = cfg->get_block_for_node(mem_inputs[i]);527if (deepb_dom_depth < (int) inb->_dom_depth) {528// The new inb must be dominated by the previous deepb.529// The various inputs must be linearly ordered in the dom530// tree, or else there will not be a unique deepest block.531DEBUG_ONLY(assert_dom(deepb, inb, load, cfg));532deepb = inb; // Save deepest block533deepb_dom_depth = deepb->_dom_depth;534}535}536early = deepb;537}538539return early;540}541542//--------------------------insert_anti_dependences---------------------------543// A load may need to witness memory that nearby stores can overwrite.544// For each nearby store, either insert an "anti-dependence" edge545// from the load to the store, or else move LCA upward to force the546// load to (eventually) be scheduled in a block above the store.547//548// Do not add edges to stores on distinct control-flow paths;549// only add edges to stores which might interfere.550//551// Return the (updated) LCA. There will not be any possibly interfering552// store between the load's "early block" and the updated LCA.553// Any stores in the updated LCA will have new precedence edges554// back to the load. The caller is expected to schedule the load555// in the LCA, in which case the precedence edges will make LCM556// preserve anti-dependences. The caller may also hoist the load557// above the LCA, if it is not the early block.558Block* PhaseCFG::insert_anti_dependences(Block* LCA, Node* load, bool verify) {559assert(load->needs_anti_dependence_check(), "must be a load of some sort");560assert(LCA != NULL, "");561DEBUG_ONLY(Block* LCA_orig = LCA);562563// Compute the alias index. Loads and stores with different alias indices564// do not need anti-dependence edges.565int load_alias_idx = C->get_alias_index(load->adr_type());566#ifdef ASSERT567assert(Compile::AliasIdxTop <= load_alias_idx && load_alias_idx < C->num_alias_types(), "Invalid alias index");568if (load_alias_idx == Compile::AliasIdxBot && C->AliasLevel() > 0 &&569(PrintOpto || VerifyAliases ||570(PrintMiscellaneous && (WizardMode || Verbose)))) {571// Load nodes should not consume all of memory.572// Reporting a bottom type indicates a bug in adlc.573// If some particular type of node validly consumes all of memory,574// sharpen the preceding "if" to exclude it, so we can catch bugs here.575tty->print_cr("*** Possible Anti-Dependence Bug: Load consumes all of memory.");576load->dump(2);577if (VerifyAliases) assert(load_alias_idx != Compile::AliasIdxBot, "");578}579#endif580581if (!C->alias_type(load_alias_idx)->is_rewritable()) {582// It is impossible to spoil this load by putting stores before it,583// because we know that the stores will never update the value584// which 'load' must witness.585return LCA;586}587588node_idx_t load_index = load->_idx;589590// Note the earliest legal placement of 'load', as determined by591// by the unique point in the dom tree where all memory effects592// and other inputs are first available. (Computed by schedule_early.)593// For normal loads, 'early' is the shallowest place (dom graph wise)594// to look for anti-deps between this load and any store.595Block* early = get_block_for_node(load);596597// If we are subsuming loads, compute an "early" block that only considers598// memory or address inputs. This block may be different than the599// schedule_early block in that it could be at an even shallower depth in the600// dominator tree, and allow for a broader discovery of anti-dependences.601if (C->subsume_loads()) {602early = memory_early_block(load, early, this);603}604605ResourceArea *area = Thread::current()->resource_area();606Node_List worklist_mem(area); // prior memory state to store607Node_List worklist_store(area); // possible-def to explore608Node_List worklist_visited(area); // visited mergemem nodes609Node_List non_early_stores(area); // all relevant stores outside of early610bool must_raise_LCA = false;611612// 'load' uses some memory state; look for users of the same state.613// Recurse through MergeMem nodes to the stores that use them.614615// Each of these stores is a possible definition of memory616// that 'load' needs to use. We need to force 'load'617// to occur before each such store. When the store is in618// the same block as 'load', we insert an anti-dependence619// edge load->store.620621// The relevant stores "nearby" the load consist of a tree rooted622// at initial_mem, with internal nodes of type MergeMem.623// Therefore, the branches visited by the worklist are of this form:624// initial_mem -> (MergeMem ->)* store625// The anti-dependence constraints apply only to the fringe of this tree.626627Node* initial_mem = load->in(MemNode::Memory);628worklist_store.push(initial_mem);629worklist_visited.push(initial_mem);630worklist_mem.push(NULL);631while (worklist_store.size() > 0) {632// Examine a nearby store to see if it might interfere with our load.633Node* mem = worklist_mem.pop();634Node* store = worklist_store.pop();635uint op = store->Opcode();636637// MergeMems do not directly have anti-deps.638// Treat them as internal nodes in a forward tree of memory states,639// the leaves of which are each a 'possible-def'.640if (store == initial_mem // root (exclusive) of tree we are searching641|| op == Op_MergeMem // internal node of tree we are searching642) {643mem = store; // It's not a possibly interfering store.644if (store == initial_mem)645initial_mem = NULL; // only process initial memory once646647for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {648store = mem->fast_out(i);649if (store->is_MergeMem()) {650// Be sure we don't get into combinatorial problems.651// (Allow phis to be repeated; they can merge two relevant states.)652uint j = worklist_visited.size();653for (; j > 0; j--) {654if (worklist_visited.at(j-1) == store) break;655}656if (j > 0) continue; // already on work list; do not repeat657worklist_visited.push(store);658}659worklist_mem.push(mem);660worklist_store.push(store);661}662continue;663}664665if (op == Op_MachProj || op == Op_Catch) continue;666if (store->needs_anti_dependence_check()) continue; // not really a store667668// Compute the alias index. Loads and stores with different alias669// indices do not need anti-dependence edges. Wide MemBar's are670// anti-dependent on everything (except immutable memories).671const TypePtr* adr_type = store->adr_type();672if (!C->can_alias(adr_type, load_alias_idx)) continue;673674// Most slow-path runtime calls do NOT modify Java memory, but675// they can block and so write Raw memory.676if (store->is_Mach()) {677MachNode* mstore = store->as_Mach();678if (load_alias_idx != Compile::AliasIdxRaw) {679// Check for call into the runtime using the Java calling680// convention (and from there into a wrapper); it has no681// _method. Can't do this optimization for Native calls because682// they CAN write to Java memory.683if (mstore->ideal_Opcode() == Op_CallStaticJava) {684assert(mstore->is_MachSafePoint(), "");685MachSafePointNode* ms = (MachSafePointNode*) mstore;686assert(ms->is_MachCallJava(), "");687MachCallJavaNode* mcj = (MachCallJavaNode*) ms;688if (mcj->_method == NULL) {689// These runtime calls do not write to Java visible memory690// (other than Raw) and so do not require anti-dependence edges.691continue;692}693}694// Same for SafePoints: they read/write Raw but only read otherwise.695// This is basically a workaround for SafePoints only defining control696// instead of control + memory.697if (mstore->ideal_Opcode() == Op_SafePoint)698continue;699} else {700// Some raw memory, such as the load of "top" at an allocation,701// can be control dependent on the previous safepoint. See702// comments in GraphKit::allocate_heap() about control input.703// Inserting an anti-dep between such a safepoint and a use704// creates a cycle, and will cause a subsequent failure in705// local scheduling. (BugId 4919904)706// (%%% How can a control input be a safepoint and not a projection??)707if (mstore->ideal_Opcode() == Op_SafePoint && load->in(0) == mstore)708continue;709}710}711712// Identify a block that the current load must be above,713// or else observe that 'store' is all the way up in the714// earliest legal block for 'load'. In the latter case,715// immediately insert an anti-dependence edge.716Block* store_block = get_block_for_node(store);717assert(store_block != NULL, "unused killing projections skipped above");718719if (store->is_Phi()) {720// Loop-phis need to raise load before input. (Other phis are treated721// as store below.)722//723// 'load' uses memory which is one (or more) of the Phi's inputs.724// It must be scheduled not before the Phi, but rather before725// each of the relevant Phi inputs.726//727// Instead of finding the LCA of all inputs to a Phi that match 'mem',728// we mark each corresponding predecessor block and do a combined729// hoisting operation later (raise_LCA_above_marks).730//731// Do not assert(store_block != early, "Phi merging memory after access")732// PhiNode may be at start of block 'early' with backedge to 'early'733DEBUG_ONLY(bool found_match = false);734for (uint j = PhiNode::Input, jmax = store->req(); j < jmax; j++) {735if (store->in(j) == mem) { // Found matching input?736DEBUG_ONLY(found_match = true);737Block* pred_block = get_block_for_node(store_block->pred(j));738if (pred_block != early) {739// If any predecessor of the Phi matches the load's "early block",740// we do not need a precedence edge between the Phi and 'load'741// since the load will be forced into a block preceding the Phi.742pred_block->set_raise_LCA_mark(load_index);743assert(!LCA_orig->dominates(pred_block) ||744early->dominates(pred_block), "early is high enough");745must_raise_LCA = true;746} else {747// anti-dependent upon PHI pinned below 'early', no edge needed748LCA = early; // but can not schedule below 'early'749}750}751}752assert(found_match, "no worklist bug");753} else if (store_block != early) {754// 'store' is between the current LCA and earliest possible block.755// Label its block, and decide later on how to raise the LCA756// to include the effect on LCA of this store.757// If this store's block gets chosen as the raised LCA, we758// will find him on the non_early_stores list and stick him759// with a precedence edge.760// (But, don't bother if LCA is already raised all the way.)761if (LCA != early) {762store_block->set_raise_LCA_mark(load_index);763must_raise_LCA = true;764non_early_stores.push(store);765}766} else {767// Found a possibly-interfering store in the load's 'early' block.768// This means 'load' cannot sink at all in the dominator tree.769// Add an anti-dep edge, and squeeze 'load' into the highest block.770assert(store != load->find_exact_control(load->in(0)), "dependence cycle found");771if (verify) {772#ifdef ASSERT773// We expect an anti-dependence edge from 'load' to 'store', except when774// implicit_null_check() has hoisted 'store' above its early block to775// perform an implicit null check, and 'load' is placed in the null776// block. In this case it is safe to ignore the anti-dependence, as the777// null block is only reached if 'store' tries to write to null.778Block* store_null_block = NULL;779Node* store_null_check = store->find_out_with(Op_MachNullCheck);780if (store_null_check != NULL) {781Node* if_true = store_null_check->find_out_with(Op_IfTrue);782assert(if_true != NULL, "null check without null projection");783Node* null_block_region = if_true->find_out_with(Op_Region);784assert(null_block_region != NULL, "null check without null region");785store_null_block = get_block_for_node(null_block_region);786}787#endif788assert(LCA == store_null_block || store->find_edge(load) != -1,789"missing precedence edge");790} else {791store->add_prec(load);792}793LCA = early;794// This turns off the process of gathering non_early_stores.795}796}797// (Worklist is now empty; all nearby stores have been visited.)798799// Finished if 'load' must be scheduled in its 'early' block.800// If we found any stores there, they have already been given801// precedence edges.802if (LCA == early) return LCA;803804// We get here only if there are no possibly-interfering stores805// in the load's 'early' block. Move LCA up above all predecessors806// which contain stores we have noted.807//808// The raised LCA block can be a home to such interfering stores,809// but its predecessors must not contain any such stores.810//811// The raised LCA will be a lower bound for placing the load,812// preventing the load from sinking past any block containing813// a store that may invalidate the memory state required by 'load'.814if (must_raise_LCA)815LCA = raise_LCA_above_marks(LCA, load->_idx, early, this);816if (LCA == early) return LCA;817818// Insert anti-dependence edges from 'load' to each store819// in the non-early LCA block.820// Mine the non_early_stores list for such stores.821if (LCA->raise_LCA_mark() == load_index) {822while (non_early_stores.size() > 0) {823Node* store = non_early_stores.pop();824Block* store_block = get_block_for_node(store);825if (store_block == LCA) {826// add anti_dependence from store to load in its own block827assert(store != load->find_exact_control(load->in(0)), "dependence cycle found");828if (verify) {829assert(store->find_edge(load) != -1, "missing precedence edge");830} else {831store->add_prec(load);832}833} else {834assert(store_block->raise_LCA_mark() == load_index, "block was marked");835// Any other stores we found must be either inside the new LCA836// or else outside the original LCA. In the latter case, they837// did not interfere with any use of 'load'.838assert(LCA->dominates(store_block)839|| !LCA_orig->dominates(store_block), "no stray stores");840}841}842}843844// Return the highest block containing stores; any stores845// within that block have been given anti-dependence edges.846return LCA;847}848849// This class is used to iterate backwards over the nodes in the graph.850851class Node_Backward_Iterator {852853private:854Node_Backward_Iterator();855856public:857// Constructor for the iterator858Node_Backward_Iterator(Node *root, VectorSet &visited, Node_Stack &stack, PhaseCFG &cfg);859860// Postincrement operator to iterate over the nodes861Node *next();862863private:864VectorSet &_visited;865Node_Stack &_stack;866PhaseCFG &_cfg;867};868869// Constructor for the Node_Backward_Iterator870Node_Backward_Iterator::Node_Backward_Iterator( Node *root, VectorSet &visited, Node_Stack &stack, PhaseCFG &cfg)871: _visited(visited), _stack(stack), _cfg(cfg) {872// The stack should contain exactly the root873stack.clear();874stack.push(root, root->outcnt());875876// Clear the visited bits877visited.clear();878}879880// Iterator for the Node_Backward_Iterator881Node *Node_Backward_Iterator::next() {882883// If the _stack is empty, then just return NULL: finished.884if ( !_stack.size() )885return NULL;886887// I visit unvisited not-anti-dependence users first, then anti-dependent888// children next. I iterate backwards to support removal of nodes.889// The stack holds states consisting of 3 values:890// current Def node, flag which indicates 1st/2nd pass, index of current out edge891Node *self = (Node*)(((uintptr_t)_stack.node()) & ~1);892bool iterate_anti_dep = (((uintptr_t)_stack.node()) & 1);893uint idx = MIN2(_stack.index(), self->outcnt()); // Support removal of nodes.894_stack.pop();895896// I cycle here when I am entering a deeper level of recursion.897// The key variable 'self' was set prior to jumping here.898while( 1 ) {899900_visited.set(self->_idx);901902// Now schedule all uses as late as possible.903const Node* src = self->is_Proj() ? self->in(0) : self;904uint src_rpo = _cfg.get_block_for_node(src)->_rpo;905906// Schedule all nodes in a post-order visit907Node *unvisited = NULL; // Unvisited anti-dependent Node, if any908909// Scan for unvisited nodes910while (idx > 0) {911// For all uses, schedule late912Node* n = self->raw_out(--idx); // Use913914// Skip already visited children915if ( _visited.test(n->_idx) )916continue;917918// do not traverse backward control edges919Node *use = n->is_Proj() ? n->in(0) : n;920uint use_rpo = _cfg.get_block_for_node(use)->_rpo;921922if ( use_rpo < src_rpo )923continue;924925// Phi nodes always precede uses in a basic block926if ( use_rpo == src_rpo && use->is_Phi() )927continue;928929unvisited = n; // Found unvisited930931// Check for possible-anti-dependent932// 1st pass: No such nodes, 2nd pass: Only such nodes.933if (n->needs_anti_dependence_check() == iterate_anti_dep) {934unvisited = n; // Found unvisited935break;936}937}938939// Did I find an unvisited not-anti-dependent Node?940if (!unvisited) {941if (!iterate_anti_dep) {942// 2nd pass: Iterate over nodes which needs_anti_dependence_check.943iterate_anti_dep = true;944idx = self->outcnt();945continue;946}947break; // All done with children; post-visit 'self'948}949950// Visit the unvisited Node. Contains the obvious push to951// indicate I'm entering a deeper level of recursion. I push the952// old state onto the _stack and set a new state and loop (recurse).953_stack.push((Node*)((uintptr_t)self | (uintptr_t)iterate_anti_dep), idx);954self = unvisited;955iterate_anti_dep = false;956idx = self->outcnt();957} // End recursion loop958959return self;960}961962//------------------------------ComputeLatenciesBackwards----------------------963// Compute the latency of all the instructions.964void PhaseCFG::compute_latencies_backwards(VectorSet &visited, Node_Stack &stack) {965#ifndef PRODUCT966if (trace_opto_pipelining())967tty->print("\n#---- ComputeLatenciesBackwards ----\n");968#endif969970Node_Backward_Iterator iter((Node *)_root, visited, stack, *this);971Node *n;972973// Walk over all the nodes from last to first974while ((n = iter.next())) {975// Set the latency for the definitions of this instruction976partial_latency_of_defs(n);977}978} // end ComputeLatenciesBackwards979980//------------------------------partial_latency_of_defs------------------------981// Compute the latency impact of this node on all defs. This computes982// a number that increases as we approach the beginning of the routine.983void PhaseCFG::partial_latency_of_defs(Node *n) {984// Set the latency for this instruction985#ifndef PRODUCT986if (trace_opto_pipelining()) {987tty->print("# latency_to_inputs: node_latency[%d] = %d for node", n->_idx, get_latency_for_node(n));988dump();989}990#endif991992if (n->is_Proj()) {993n = n->in(0);994}995996if (n->is_Root()) {997return;998}9991000uint nlen = n->len();1001uint use_latency = get_latency_for_node(n);1002uint use_pre_order = get_block_for_node(n)->_pre_order;10031004for (uint j = 0; j < nlen; j++) {1005Node *def = n->in(j);10061007if (!def || def == n) {1008continue;1009}10101011// Walk backwards thru projections1012if (def->is_Proj()) {1013def = def->in(0);1014}10151016#ifndef PRODUCT1017if (trace_opto_pipelining()) {1018tty->print("# in(%2d): ", j);1019def->dump();1020}1021#endif10221023// If the defining block is not known, assume it is ok1024Block *def_block = get_block_for_node(def);1025uint def_pre_order = def_block ? def_block->_pre_order : 0;10261027if ((use_pre_order < def_pre_order) || (use_pre_order == def_pre_order && n->is_Phi())) {1028continue;1029}10301031uint delta_latency = n->latency(j);1032uint current_latency = delta_latency + use_latency;10331034if (get_latency_for_node(def) < current_latency) {1035set_latency_for_node(def, current_latency);1036}10371038#ifndef PRODUCT1039if (trace_opto_pipelining()) {1040tty->print_cr("# %d + edge_latency(%d) == %d -> %d, node_latency[%d] = %d", use_latency, j, delta_latency, current_latency, def->_idx, get_latency_for_node(def));1041}1042#endif1043}1044}10451046//------------------------------latency_from_use-------------------------------1047// Compute the latency of a specific use1048int PhaseCFG::latency_from_use(Node *n, const Node *def, Node *use) {1049// If self-reference, return no latency1050if (use == n || use->is_Root()) {1051return 0;1052}10531054uint def_pre_order = get_block_for_node(def)->_pre_order;1055uint latency = 0;10561057// If the use is not a projection, then it is simple...1058if (!use->is_Proj()) {1059#ifndef PRODUCT1060if (trace_opto_pipelining()) {1061tty->print("# out(): ");1062use->dump();1063}1064#endif10651066uint use_pre_order = get_block_for_node(use)->_pre_order;10671068if (use_pre_order < def_pre_order)1069return 0;10701071if (use_pre_order == def_pre_order && use->is_Phi())1072return 0;10731074uint nlen = use->len();1075uint nl = get_latency_for_node(use);10761077for ( uint j=0; j<nlen; j++ ) {1078if (use->in(j) == n) {1079// Change this if we want local latencies1080uint ul = use->latency(j);1081uint l = ul + nl;1082if (latency < l) latency = l;1083#ifndef PRODUCT1084if (trace_opto_pipelining()) {1085tty->print_cr("# %d + edge_latency(%d) == %d -> %d, latency = %d",1086nl, j, ul, l, latency);1087}1088#endif1089}1090}1091} else {1092// This is a projection, just grab the latency of the use(s)1093for (DUIterator_Fast jmax, j = use->fast_outs(jmax); j < jmax; j++) {1094uint l = latency_from_use(use, def, use->fast_out(j));1095if (latency < l) latency = l;1096}1097}10981099return latency;1100}11011102//------------------------------latency_from_uses------------------------------1103// Compute the latency of this instruction relative to all of it's uses.1104// This computes a number that increases as we approach the beginning of the1105// routine.1106void PhaseCFG::latency_from_uses(Node *n) {1107// Set the latency for this instruction1108#ifndef PRODUCT1109if (trace_opto_pipelining()) {1110tty->print("# latency_from_outputs: node_latency[%d] = %d for node", n->_idx, get_latency_for_node(n));1111dump();1112}1113#endif1114uint latency=0;1115const Node *def = n->is_Proj() ? n->in(0): n;11161117for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {1118uint l = latency_from_use(n, def, n->fast_out(i));11191120if (latency < l) latency = l;1121}11221123set_latency_for_node(n, latency);1124}11251126//------------------------------hoist_to_cheaper_block-------------------------1127// Pick a block for node self, between early and LCA, that is a cheaper1128// alternative to LCA.1129Block* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) {1130const double delta = 1+PROB_UNLIKELY_MAG(4);1131Block* least = LCA;1132double least_freq = least->_freq;1133uint target = get_latency_for_node(self);1134uint start_latency = get_latency_for_node(LCA->head());1135uint end_latency = get_latency_for_node(LCA->get_node(LCA->end_idx()));1136bool in_latency = (target <= start_latency);1137const Block* root_block = get_block_for_node(_root);11381139// Turn off latency scheduling if scheduling is just plain off1140if (!C->do_scheduling())1141in_latency = true;11421143// Do not hoist (to cover latency) instructions which target a1144// single register. Hoisting stretches the live range of the1145// single register and may force spilling.1146MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL;1147if (mach && mach->out_RegMask().is_bound1() && mach->out_RegMask().is_NotEmpty())1148in_latency = true;11491150#ifndef PRODUCT1151if (trace_opto_pipelining()) {1152tty->print("# Find cheaper block for latency %d: ", get_latency_for_node(self));1153self->dump();1154tty->print_cr("# B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g",1155LCA->_pre_order,1156LCA->head()->_idx,1157start_latency,1158LCA->get_node(LCA->end_idx())->_idx,1159end_latency,1160least_freq);1161}1162#endif11631164int cand_cnt = 0; // number of candidates tried11651166// Walk up the dominator tree from LCA (Lowest common ancestor) to1167// the earliest legal location. Capture the least execution frequency.1168while (LCA != early) {1169LCA = LCA->_idom; // Follow up the dominator tree11701171if (LCA == NULL) {1172// Bailout without retry1173assert(false, "graph should be schedulable");1174C->record_method_not_compilable("late schedule failed: LCA == NULL");1175return least;1176}11771178// Don't hoist machine instructions to the root basic block1179if (mach && LCA == root_block)1180break;11811182if (self->is_memory_writer() &&1183(LCA->_loop->depth() > early->_loop->depth())) {1184// LCA is an invalid placement for a memory writer: choosing it would1185// cause memory interference, as illustrated in schedule_late().1186continue;1187}1188verify_memory_writer_placement(LCA, self);11891190uint start_lat = get_latency_for_node(LCA->head());1191uint end_idx = LCA->end_idx();1192uint end_lat = get_latency_for_node(LCA->get_node(end_idx));1193double LCA_freq = LCA->_freq;1194#ifndef PRODUCT1195if (trace_opto_pipelining()) {1196tty->print_cr("# B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g",1197LCA->_pre_order, LCA->head()->_idx, start_lat, end_idx, end_lat, LCA_freq);1198}1199#endif1200cand_cnt++;1201if (LCA_freq < least_freq || // Better Frequency1202(StressGCM && C->randomized_select(cand_cnt)) || // Should be randomly accepted in stress mode1203(!StressGCM && // Otherwise, choose with latency1204!in_latency && // No block containing latency1205LCA_freq < least_freq * delta && // No worse frequency1206target >= end_lat && // within latency range1207!self->is_iteratively_computed() ) // But don't hoist IV increments1208// because they may end up above other uses of their phi forcing1209// their result register to be different from their input.1210) {1211least = LCA; // Found cheaper block1212least_freq = LCA_freq;1213start_latency = start_lat;1214end_latency = end_lat;1215if (target <= start_lat)1216in_latency = true;1217}1218}12191220#ifndef PRODUCT1221if (trace_opto_pipelining()) {1222tty->print_cr("# Choose block B%d with start latency=%d and freq=%g",1223least->_pre_order, start_latency, least_freq);1224}1225#endif12261227// See if the latency needs to be updated1228if (target < end_latency) {1229#ifndef PRODUCT1230if (trace_opto_pipelining()) {1231tty->print_cr("# Change latency for [%4d] from %d to %d", self->_idx, target, end_latency);1232}1233#endif1234set_latency_for_node(self, end_latency);1235partial_latency_of_defs(self);1236}12371238return least;1239}124012411242//------------------------------schedule_late-----------------------------------1243// Now schedule all codes as LATE as possible. This is the LCA in the1244// dominator tree of all USES of a value. Pick the block with the least1245// loop nesting depth that is lowest in the dominator tree.1246extern const char must_clone[];1247void PhaseCFG::schedule_late(VectorSet &visited, Node_Stack &stack) {1248#ifndef PRODUCT1249if (trace_opto_pipelining())1250tty->print("\n#---- schedule_late ----\n");1251#endif12521253Node_Backward_Iterator iter((Node *)_root, visited, stack, *this);1254Node *self;12551256// Walk over all the nodes from last to first1257while ((self = iter.next())) {1258Block* early = get_block_for_node(self); // Earliest legal placement12591260if (self->is_top()) {1261// Top node goes in bb #2 with other constants.1262// It must be special-cased, because it has no out edges.1263early->add_inst(self);1264continue;1265}12661267// No uses, just terminate1268if (self->outcnt() == 0) {1269assert(self->is_MachProj(), "sanity");1270continue; // Must be a dead machine projection1271}12721273// If node is pinned in the block, then no scheduling can be done.1274if( self->pinned() ) // Pinned in block?1275continue;12761277#ifdef ASSERT1278// Assert that memory writers (e.g. stores) have a "home" block (the block1279// given by their control input), and that this block corresponds to their1280// earliest possible placement. This guarantees that1281// hoist_to_cheaper_block() will always have at least one valid choice.1282if (self->is_memory_writer()) {1283assert(find_block_for_node(self->in(0)) == early,1284"The home of a memory writer must also be its earliest placement");1285}1286#endif12871288MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL;1289if (mach) {1290switch (mach->ideal_Opcode()) {1291case Op_CreateEx:1292// Don't move exception creation1293early->add_inst(self);1294continue;1295break;1296case Op_CheckCastPP: {1297// Don't move CheckCastPP nodes away from their input, if the input1298// is a rawptr (5071820).1299Node *def = self->in(1);1300if (def != NULL && def->bottom_type()->base() == Type::RawPtr) {1301early->add_inst(self);1302#ifdef ASSERT1303_raw_oops.push(def);1304#endif1305continue;1306}1307break;1308}1309default:1310break;1311}1312if (C->has_irreducible_loop() && self->is_memory_writer()) {1313// If the CFG is irreducible, place memory writers in their home block.1314// This prevents hoist_to_cheaper_block() from accidentally placing such1315// nodes into deeper loops, as in the following example:1316//1317// Home placement of store in B1 (loop L1):1318//1319// B1 (L1):1320// m1 <- ..1321// m2 <- store m1, ..1322// B2 (L2):1323// jump B21324// B3 (L1):1325// .. <- .. m2, ..1326//1327// Wrong "hoisting" of store to B2 (in loop L2, child of L1):1328//1329// B1 (L1):1330// m1 <- ..1331// B2 (L2):1332// m2 <- store m1, ..1333// # Wrong: m1 and m2 interfere at this point.1334// jump B21335// B3 (L1):1336// .. <- .. m2, ..1337//1338// This "hoist inversion" can happen due to different factors such as1339// inaccurate estimation of frequencies for irreducible CFGs, and loops1340// with always-taken exits in reducible CFGs. In the reducible case,1341// hoist inversion is prevented by discarding invalid blocks (those in1342// deeper loops than the home block). In the irreducible case, the1343// invalid blocks cannot be identified due to incomplete loop nesting1344// information, hence a conservative solution is taken.1345#ifndef PRODUCT1346if (trace_opto_pipelining()) {1347tty->print_cr("# Irreducible loops: schedule in home block B%d:",1348early->_pre_order);1349self->dump();1350}1351#endif1352schedule_node_into_block(self, early);1353continue;1354}1355}13561357// Gather LCA of all uses1358Block *LCA = NULL;1359{1360for (DUIterator_Fast imax, i = self->fast_outs(imax); i < imax; i++) {1361// For all uses, find LCA1362Node* use = self->fast_out(i);1363LCA = raise_LCA_above_use(LCA, use, self, this);1364}1365guarantee(LCA != NULL, "There must be a LCA");1366} // (Hide defs of imax, i from rest of block.)13671368// Place temps in the block of their use. This isn't a1369// requirement for correctness but it reduces useless1370// interference between temps and other nodes.1371if (mach != NULL && mach->is_MachTemp()) {1372map_node_to_block(self, LCA);1373LCA->add_inst(self);1374continue;1375}13761377// Check if 'self' could be anti-dependent on memory1378if (self->needs_anti_dependence_check()) {1379// Hoist LCA above possible-defs and insert anti-dependences to1380// defs in new LCA block.1381LCA = insert_anti_dependences(LCA, self);1382}13831384if (early->_dom_depth > LCA->_dom_depth) {1385// Somehow the LCA has moved above the earliest legal point.1386// (One way this can happen is via memory_early_block.)1387if (C->subsume_loads() == true && !C->failing()) {1388// Retry with subsume_loads == false1389// If this is the first failure, the sentinel string will "stick"1390// to the Compile object, and the C2Compiler will see it and retry.1391C->record_failure(C2Compiler::retry_no_subsuming_loads());1392} else {1393// Bailout without retry when (early->_dom_depth > LCA->_dom_depth)1394assert(false, "graph should be schedulable");1395C->record_method_not_compilable("late schedule failed: incorrect graph");1396}1397return;1398}13991400if (self->is_memory_writer()) {1401// If the LCA of a memory writer is a descendant of its home loop, hoist1402// it into a valid placement.1403while (LCA->_loop->depth() > early->_loop->depth()) {1404LCA = LCA->_idom;1405}1406assert(LCA != NULL, "a valid LCA must exist");1407verify_memory_writer_placement(LCA, self);1408}14091410// If there is no opportunity to hoist, then we're done.1411// In stress mode, try to hoist even the single operations.1412bool try_to_hoist = StressGCM || (LCA != early);14131414// Must clone guys stay next to use; no hoisting allowed.1415// Also cannot hoist guys that alter memory or are otherwise not1416// allocatable (hoisting can make a value live longer, leading to1417// anti and output dependency problems which are normally resolved1418// by the register allocator giving everyone a different register).1419if (mach != NULL && must_clone[mach->ideal_Opcode()])1420try_to_hoist = false;14211422Block* late = NULL;1423if (try_to_hoist) {1424// Now find the block with the least execution frequency.1425// Start at the latest schedule and work up to the earliest schedule1426// in the dominator tree. Thus the Node will dominate all its uses.1427late = hoist_to_cheaper_block(LCA, early, self);1428} else {1429// Just use the LCA of the uses.1430late = LCA;1431}14321433// Put the node into target block1434schedule_node_into_block(self, late);14351436#ifdef ASSERT1437if (self->needs_anti_dependence_check()) {1438// since precedence edges are only inserted when we're sure they1439// are needed make sure that after placement in a block we don't1440// need any new precedence edges.1441verify_anti_dependences(late, self);1442}1443#endif1444} // Loop until all nodes have been visited14451446} // end ScheduleLate14471448//------------------------------GlobalCodeMotion-------------------------------1449void PhaseCFG::global_code_motion() {1450ResourceMark rm;14511452#ifndef PRODUCT1453if (trace_opto_pipelining()) {1454tty->print("\n---- Start GlobalCodeMotion ----\n");1455}1456#endif14571458// Initialize the node to block mapping for things on the proj_list1459for (uint i = 0; i < _matcher.number_of_projections(); i++) {1460unmap_node_from_block(_matcher.get_projection(i));1461}14621463// Set the basic block for Nodes pinned into blocks1464VectorSet visited;1465schedule_pinned_nodes(visited);14661467// Find the earliest Block any instruction can be placed in. Some1468// instructions are pinned into Blocks. Unpinned instructions can1469// appear in last block in which all their inputs occur.1470visited.clear();1471Node_Stack stack((C->live_nodes() >> 2) + 16); // pre-grow1472if (!schedule_early(visited, stack)) {1473// Bailout without retry1474C->record_method_not_compilable("early schedule failed");1475return;1476}14771478// Build Def-Use edges.1479// Compute the latency information (via backwards walk) for all the1480// instructions in the graph1481_node_latency = new GrowableArray<uint>(); // resource_area allocation14821483if (C->do_scheduling()) {1484compute_latencies_backwards(visited, stack);1485}14861487// Now schedule all codes as LATE as possible. This is the LCA in the1488// dominator tree of all USES of a value. Pick the block with the least1489// loop nesting depth that is lowest in the dominator tree.1490// ( visited.clear() called in schedule_late()->Node_Backward_Iterator() )1491schedule_late(visited, stack);1492if (C->failing()) {1493return;1494}14951496#ifndef PRODUCT1497if (trace_opto_pipelining()) {1498tty->print("\n---- Detect implicit null checks ----\n");1499}1500#endif15011502// Detect implicit-null-check opportunities. Basically, find NULL checks1503// with suitable memory ops nearby. Use the memory op to do the NULL check.1504// I can generate a memory op if there is not one nearby.1505if (C->is_method_compilation()) {1506// By reversing the loop direction we get a very minor gain on mpegaudio.1507// Feel free to revert to a forward loop for clarity.1508// for( int i=0; i < (int)matcher._null_check_tests.size(); i+=2 ) {1509for (int i = _matcher._null_check_tests.size() - 2; i >= 0; i -= 2) {1510Node* proj = _matcher._null_check_tests[i];1511Node* val = _matcher._null_check_tests[i + 1];1512Block* block = get_block_for_node(proj);1513implicit_null_check(block, proj, val, C->allowed_deopt_reasons());1514// The implicit_null_check will only perform the transformation1515// if the null branch is truly uncommon, *and* it leads to an1516// uncommon trap. Combined with the too_many_traps guards1517// above, this prevents SEGV storms reported in 6366351,1518// by recompiling offending methods without this optimization.1519}1520}15211522bool block_size_threshold_ok = false;1523intptr_t *recalc_pressure_nodes = NULL;1524if (OptoRegScheduling) {1525for (uint i = 0; i < number_of_blocks(); i++) {1526Block* block = get_block(i);1527if (block->number_of_nodes() > 10) {1528block_size_threshold_ok = true;1529break;1530}1531}1532}15331534// Enabling the scheduler for register pressure plus finding blocks of size to schedule for it1535// is key to enabling this feature.1536PhaseChaitin regalloc(C->unique(), *this, _matcher, true);1537ResourceArea live_arena(mtCompiler); // Arena for liveness1538ResourceMark rm_live(&live_arena);1539PhaseLive live(*this, regalloc._lrg_map.names(), &live_arena, true);1540PhaseIFG ifg(&live_arena);1541if (OptoRegScheduling && block_size_threshold_ok) {1542regalloc.mark_ssa();1543Compile::TracePhase tp("computeLive", &timers[_t_computeLive]);1544rm_live.reset_to_mark(); // Reclaim working storage1545IndexSet::reset_memory(C, &live_arena);1546uint node_size = regalloc._lrg_map.max_lrg_id();1547ifg.init(node_size); // Empty IFG1548regalloc.set_ifg(ifg);1549regalloc.set_live(live);1550regalloc.gather_lrg_masks(false); // Collect LRG masks1551live.compute(node_size); // Compute liveness15521553recalc_pressure_nodes = NEW_RESOURCE_ARRAY(intptr_t, node_size);1554for (uint i = 0; i < node_size; i++) {1555recalc_pressure_nodes[i] = 0;1556}1557}1558_regalloc = ®alloc;15591560#ifndef PRODUCT1561if (trace_opto_pipelining()) {1562tty->print("\n---- Start Local Scheduling ----\n");1563}1564#endif15651566// Schedule locally. Right now a simple topological sort.1567// Later, do a real latency aware scheduler.1568GrowableArray<int> ready_cnt(C->unique(), C->unique(), -1);1569visited.reset();1570for (uint i = 0; i < number_of_blocks(); i++) {1571Block* block = get_block(i);1572if (!schedule_local(block, ready_cnt, visited, recalc_pressure_nodes)) {1573if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {1574C->record_method_not_compilable("local schedule failed");1575}1576_regalloc = NULL;1577return;1578}1579}1580_regalloc = NULL;15811582// If we inserted any instructions between a Call and his CatchNode,1583// clone the instructions on all paths below the Catch.1584for (uint i = 0; i < number_of_blocks(); i++) {1585Block* block = get_block(i);1586call_catch_cleanup(block);1587}15881589#ifndef PRODUCT1590if (trace_opto_pipelining()) {1591tty->print("\n---- After GlobalCodeMotion ----\n");1592for (uint i = 0; i < number_of_blocks(); i++) {1593Block* block = get_block(i);1594block->dump();1595}1596}1597#endif1598// Dead.1599_node_latency = (GrowableArray<uint> *)((intptr_t)0xdeadbeef);1600}16011602bool PhaseCFG::do_global_code_motion() {16031604build_dominator_tree();1605if (C->failing()) {1606return false;1607}16081609NOT_PRODUCT( C->verify_graph_edges(); )16101611estimate_block_frequency();16121613global_code_motion();16141615if (C->failing()) {1616return false;1617}16181619return true;1620}16211622//------------------------------Estimate_Block_Frequency-----------------------1623// Estimate block frequencies based on IfNode probabilities.1624void PhaseCFG::estimate_block_frequency() {16251626// Force conditional branches leading to uncommon traps to be unlikely,1627// not because we get to the uncommon_trap with less relative frequency,1628// but because an uncommon_trap typically causes a deopt, so we only get1629// there once.1630if (C->do_freq_based_layout()) {1631Block_List worklist;1632Block* root_blk = get_block(0);1633for (uint i = 1; i < root_blk->num_preds(); i++) {1634Block *pb = get_block_for_node(root_blk->pred(i));1635if (pb->has_uncommon_code()) {1636worklist.push(pb);1637}1638}1639while (worklist.size() > 0) {1640Block* uct = worklist.pop();1641if (uct == get_root_block()) {1642continue;1643}1644for (uint i = 1; i < uct->num_preds(); i++) {1645Block *pb = get_block_for_node(uct->pred(i));1646if (pb->_num_succs == 1) {1647worklist.push(pb);1648} else if (pb->num_fall_throughs() == 2) {1649pb->update_uncommon_branch(uct);1650}1651}1652}1653}16541655// Create the loop tree and calculate loop depth.1656_root_loop = create_loop_tree();1657_root_loop->compute_loop_depth(0);16581659// Compute block frequency of each block, relative to a single loop entry.1660_root_loop->compute_freq();16611662// Adjust all frequencies to be relative to a single method entry1663_root_loop->_freq = 1.0;1664_root_loop->scale_freq();16651666// Save outmost loop frequency for LRG frequency threshold1667_outer_loop_frequency = _root_loop->outer_loop_freq();16681669// force paths ending at uncommon traps to be infrequent1670if (!C->do_freq_based_layout()) {1671Block_List worklist;1672Block* root_blk = get_block(0);1673for (uint i = 1; i < root_blk->num_preds(); i++) {1674Block *pb = get_block_for_node(root_blk->pred(i));1675if (pb->has_uncommon_code()) {1676worklist.push(pb);1677}1678}1679while (worklist.size() > 0) {1680Block* uct = worklist.pop();1681uct->_freq = PROB_MIN;1682for (uint i = 1; i < uct->num_preds(); i++) {1683Block *pb = get_block_for_node(uct->pred(i));1684if (pb->_num_succs == 1 && pb->_freq > PROB_MIN) {1685worklist.push(pb);1686}1687}1688}1689}16901691#ifdef ASSERT1692for (uint i = 0; i < number_of_blocks(); i++) {1693Block* b = get_block(i);1694assert(b->_freq >= MIN_BLOCK_FREQUENCY, "Register Allocator requires meaningful block frequency");1695}1696#endif16971698#ifndef PRODUCT1699if (PrintCFGBlockFreq) {1700tty->print_cr("CFG Block Frequencies");1701_root_loop->dump_tree();1702if (Verbose) {1703tty->print_cr("PhaseCFG dump");1704dump();1705tty->print_cr("Node dump");1706_root->dump(99999);1707}1708}1709#endif1710}17111712//----------------------------create_loop_tree--------------------------------1713// Create a loop tree from the CFG1714CFGLoop* PhaseCFG::create_loop_tree() {17151716#ifdef ASSERT1717assert(get_block(0) == get_root_block(), "first block should be root block");1718for (uint i = 0; i < number_of_blocks(); i++) {1719Block* block = get_block(i);1720// Check that _loop field are clear...we could clear them if not.1721assert(block->_loop == NULL, "clear _loop expected");1722// Sanity check that the RPO numbering is reflected in the _blocks array.1723// It doesn't have to be for the loop tree to be built, but if it is not,1724// then the blocks have been reordered since dom graph building...which1725// may question the RPO numbering1726assert(block->_rpo == i, "unexpected reverse post order number");1727}1728#endif17291730int idct = 0;1731CFGLoop* root_loop = new CFGLoop(idct++);17321733Block_List worklist;17341735// Assign blocks to loops1736for(uint i = number_of_blocks() - 1; i > 0; i-- ) { // skip Root block1737Block* block = get_block(i);17381739if (block->head()->is_Loop()) {1740Block* loop_head = block;1741assert(loop_head->num_preds() - 1 == 2, "loop must have 2 predecessors");1742Node* tail_n = loop_head->pred(LoopNode::LoopBackControl);1743Block* tail = get_block_for_node(tail_n);17441745// Defensively filter out Loop nodes for non-single-entry loops.1746// For all reasonable loops, the head occurs before the tail in RPO.1747if (i <= tail->_rpo) {17481749// The tail and (recursive) predecessors of the tail1750// are made members of a new loop.17511752assert(worklist.size() == 0, "nonempty worklist");1753CFGLoop* nloop = new CFGLoop(idct++);1754assert(loop_head->_loop == NULL, "just checking");1755loop_head->_loop = nloop;1756// Add to nloop so push_pred() will skip over inner loops1757nloop->add_member(loop_head);1758nloop->push_pred(loop_head, LoopNode::LoopBackControl, worklist, this);17591760while (worklist.size() > 0) {1761Block* member = worklist.pop();1762if (member != loop_head) {1763for (uint j = 1; j < member->num_preds(); j++) {1764nloop->push_pred(member, j, worklist, this);1765}1766}1767}1768}1769}1770}17711772// Create a member list for each loop consisting1773// of both blocks and (immediate child) loops.1774for (uint i = 0; i < number_of_blocks(); i++) {1775Block* block = get_block(i);1776CFGLoop* lp = block->_loop;1777if (lp == NULL) {1778// Not assigned to a loop. Add it to the method's pseudo loop.1779block->_loop = root_loop;1780lp = root_loop;1781}1782if (lp == root_loop || block != lp->head()) { // loop heads are already members1783lp->add_member(block);1784}1785if (lp != root_loop) {1786if (lp->parent() == NULL) {1787// Not a nested loop. Make it a child of the method's pseudo loop.1788root_loop->add_nested_loop(lp);1789}1790if (block == lp->head()) {1791// Add nested loop to member list of parent loop.1792lp->parent()->add_member(lp);1793}1794}1795}17961797return root_loop;1798}17991800//------------------------------push_pred--------------------------------------1801void CFGLoop::push_pred(Block* blk, int i, Block_List& worklist, PhaseCFG* cfg) {1802Node* pred_n = blk->pred(i);1803Block* pred = cfg->get_block_for_node(pred_n);1804CFGLoop *pred_loop = pred->_loop;1805if (pred_loop == NULL) {1806// Filter out blocks for non-single-entry loops.1807// For all reasonable loops, the head occurs before the tail in RPO.1808if (pred->_rpo > head()->_rpo) {1809pred->_loop = this;1810worklist.push(pred);1811}1812} else if (pred_loop != this) {1813// Nested loop.1814while (pred_loop->_parent != NULL && pred_loop->_parent != this) {1815pred_loop = pred_loop->_parent;1816}1817// Make pred's loop be a child1818if (pred_loop->_parent == NULL) {1819add_nested_loop(pred_loop);1820// Continue with loop entry predecessor.1821Block* pred_head = pred_loop->head();1822assert(pred_head->num_preds() - 1 == 2, "loop must have 2 predecessors");1823assert(pred_head != head(), "loop head in only one loop");1824push_pred(pred_head, LoopNode::EntryControl, worklist, cfg);1825} else {1826assert(pred_loop->_parent == this && _parent == NULL, "just checking");1827}1828}1829}18301831//------------------------------add_nested_loop--------------------------------1832// Make cl a child of the current loop in the loop tree.1833void CFGLoop::add_nested_loop(CFGLoop* cl) {1834assert(_parent == NULL, "no parent yet");1835assert(cl != this, "not my own parent");1836cl->_parent = this;1837CFGLoop* ch = _child;1838if (ch == NULL) {1839_child = cl;1840} else {1841while (ch->_sibling != NULL) { ch = ch->_sibling; }1842ch->_sibling = cl;1843}1844}18451846//------------------------------compute_loop_depth-----------------------------1847// Store the loop depth in each CFGLoop object.1848// Recursively walk the children to do the same for them.1849void CFGLoop::compute_loop_depth(int depth) {1850_depth = depth;1851CFGLoop* ch = _child;1852while (ch != NULL) {1853ch->compute_loop_depth(depth + 1);1854ch = ch->_sibling;1855}1856}18571858//------------------------------compute_freq-----------------------------------1859// Compute the frequency of each block and loop, relative to a single entry1860// into the dominating loop head.1861void CFGLoop::compute_freq() {1862// Bottom up traversal of loop tree (visit inner loops first.)1863// Set loop head frequency to 1.0, then transitively1864// compute frequency for all successors in the loop,1865// as well as for each exit edge. Inner loops are1866// treated as single blocks with loop exit targets1867// as the successor blocks.18681869// Nested loops first1870CFGLoop* ch = _child;1871while (ch != NULL) {1872ch->compute_freq();1873ch = ch->_sibling;1874}1875assert (_members.length() > 0, "no empty loops");1876Block* hd = head();1877hd->_freq = 1.0;1878for (int i = 0; i < _members.length(); i++) {1879CFGElement* s = _members.at(i);1880double freq = s->_freq;1881if (s->is_block()) {1882Block* b = s->as_Block();1883for (uint j = 0; j < b->_num_succs; j++) {1884Block* sb = b->_succs[j];1885update_succ_freq(sb, freq * b->succ_prob(j));1886}1887} else {1888CFGLoop* lp = s->as_CFGLoop();1889assert(lp->_parent == this, "immediate child");1890for (int k = 0; k < lp->_exits.length(); k++) {1891Block* eb = lp->_exits.at(k).get_target();1892double prob = lp->_exits.at(k).get_prob();1893update_succ_freq(eb, freq * prob);1894}1895}1896}18971898// For all loops other than the outer, "method" loop,1899// sum and normalize the exit probability. The "method" loop1900// should keep the initial exit probability of 1, so that1901// inner blocks do not get erroneously scaled.1902if (_depth != 0) {1903// Total the exit probabilities for this loop.1904double exits_sum = 0.0f;1905for (int i = 0; i < _exits.length(); i++) {1906exits_sum += _exits.at(i).get_prob();1907}19081909// Normalize the exit probabilities. Until now, the1910// probabilities estimate the possibility of exit per1911// a single loop iteration; afterward, they estimate1912// the probability of exit per loop entry.1913for (int i = 0; i < _exits.length(); i++) {1914Block* et = _exits.at(i).get_target();1915float new_prob = 0.0f;1916if (_exits.at(i).get_prob() > 0.0f) {1917new_prob = _exits.at(i).get_prob() / exits_sum;1918}1919BlockProbPair bpp(et, new_prob);1920_exits.at_put(i, bpp);1921}19221923// Save the total, but guard against unreasonable probability,1924// as the value is used to estimate the loop trip count.1925// An infinite trip count would blur relative block1926// frequencies.1927if (exits_sum > 1.0f) exits_sum = 1.0;1928if (exits_sum < PROB_MIN) exits_sum = PROB_MIN;1929_exit_prob = exits_sum;1930}1931}19321933//------------------------------succ_prob-------------------------------------1934// Determine the probability of reaching successor 'i' from the receiver block.1935float Block::succ_prob(uint i) {1936int eidx = end_idx();1937Node *n = get_node(eidx); // Get ending Node19381939int op = n->Opcode();1940if (n->is_Mach()) {1941if (n->is_MachNullCheck()) {1942// Can only reach here if called after lcm. The original Op_If is gone,1943// so we attempt to infer the probability from one or both of the1944// successor blocks.1945assert(_num_succs == 2, "expecting 2 successors of a null check");1946// If either successor has only one predecessor, then the1947// probability estimate can be derived using the1948// relative frequency of the successor and this block.1949if (_succs[i]->num_preds() == 2) {1950return _succs[i]->_freq / _freq;1951} else if (_succs[1-i]->num_preds() == 2) {1952return 1 - (_succs[1-i]->_freq / _freq);1953} else {1954// Estimate using both successor frequencies1955float freq = _succs[i]->_freq;1956return freq / (freq + _succs[1-i]->_freq);1957}1958}1959op = n->as_Mach()->ideal_Opcode();1960}196119621963// Switch on branch type1964switch( op ) {1965case Op_CountedLoopEnd:1966case Op_If: {1967assert (i < 2, "just checking");1968// Conditionals pass on only part of their frequency1969float prob = n->as_MachIf()->_prob;1970assert(prob >= 0.0 && prob <= 1.0, "out of range probability");1971// If succ[i] is the FALSE branch, invert path info1972if( get_node(i + eidx + 1)->Opcode() == Op_IfFalse ) {1973return 1.0f - prob; // not taken1974} else {1975return prob; // taken1976}1977}19781979case Op_Jump:1980return n->as_MachJump()->_probs[get_node(i + eidx + 1)->as_JumpProj()->_con];19811982case Op_Catch: {1983const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();1984if (ci->_con == CatchProjNode::fall_through_index) {1985// Fall-thru path gets the lion's share.1986return 1.0f - PROB_UNLIKELY_MAG(5)*_num_succs;1987} else {1988// Presume exceptional paths are equally unlikely1989return PROB_UNLIKELY_MAG(5);1990}1991}19921993case Op_Root:1994case Op_Goto:1995// Pass frequency straight thru to target1996return 1.0f;19971998case Op_NeverBranch:1999return 0.0f;20002001case Op_TailCall:2002case Op_TailJump:2003case Op_Return:2004case Op_Halt:2005case Op_Rethrow:2006// Do not push out freq to root block2007return 0.0f;20082009default:2010ShouldNotReachHere();2011}20122013return 0.0f;2014}20152016//------------------------------num_fall_throughs-----------------------------2017// Return the number of fall-through candidates for a block2018int Block::num_fall_throughs() {2019int eidx = end_idx();2020Node *n = get_node(eidx); // Get ending Node20212022int op = n->Opcode();2023if (n->is_Mach()) {2024if (n->is_MachNullCheck()) {2025// In theory, either side can fall-thru, for simplicity sake,2026// let's say only the false branch can now.2027return 1;2028}2029op = n->as_Mach()->ideal_Opcode();2030}20312032// Switch on branch type2033switch( op ) {2034case Op_CountedLoopEnd:2035case Op_If:2036return 2;20372038case Op_Root:2039case Op_Goto:2040return 1;20412042case Op_Catch: {2043for (uint i = 0; i < _num_succs; i++) {2044const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();2045if (ci->_con == CatchProjNode::fall_through_index) {2046return 1;2047}2048}2049return 0;2050}20512052case Op_Jump:2053case Op_NeverBranch:2054case Op_TailCall:2055case Op_TailJump:2056case Op_Return:2057case Op_Halt:2058case Op_Rethrow:2059return 0;20602061default:2062ShouldNotReachHere();2063}20642065return 0;2066}20672068//------------------------------succ_fall_through-----------------------------2069// Return true if a specific successor could be fall-through target.2070bool Block::succ_fall_through(uint i) {2071int eidx = end_idx();2072Node *n = get_node(eidx); // Get ending Node20732074int op = n->Opcode();2075if (n->is_Mach()) {2076if (n->is_MachNullCheck()) {2077// In theory, either side can fall-thru, for simplicity sake,2078// let's say only the false branch can now.2079return get_node(i + eidx + 1)->Opcode() == Op_IfFalse;2080}2081op = n->as_Mach()->ideal_Opcode();2082}20832084// Switch on branch type2085switch( op ) {2086case Op_CountedLoopEnd:2087case Op_If:2088case Op_Root:2089case Op_Goto:2090return true;20912092case Op_Catch: {2093const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();2094return ci->_con == CatchProjNode::fall_through_index;2095}20962097case Op_Jump:2098case Op_NeverBranch:2099case Op_TailCall:2100case Op_TailJump:2101case Op_Return:2102case Op_Halt:2103case Op_Rethrow:2104return false;21052106default:2107ShouldNotReachHere();2108}21092110return false;2111}21122113//------------------------------update_uncommon_branch------------------------2114// Update the probability of a two-branch to be uncommon2115void Block::update_uncommon_branch(Block* ub) {2116int eidx = end_idx();2117Node *n = get_node(eidx); // Get ending Node21182119int op = n->as_Mach()->ideal_Opcode();21202121assert(op == Op_CountedLoopEnd || op == Op_If, "must be a If");2122assert(num_fall_throughs() == 2, "must be a two way branch block");21232124// Which successor is ub?2125uint s;2126for (s = 0; s <_num_succs; s++) {2127if (_succs[s] == ub) break;2128}2129assert(s < 2, "uncommon successor must be found");21302131// If ub is the true path, make the proability small, else2132// ub is the false path, and make the probability large2133bool invert = (get_node(s + eidx + 1)->Opcode() == Op_IfFalse);21342135// Get existing probability2136float p = n->as_MachIf()->_prob;21372138if (invert) p = 1.0 - p;2139if (p > PROB_MIN) {2140p = PROB_MIN;2141}2142if (invert) p = 1.0 - p;21432144n->as_MachIf()->_prob = p;2145}21462147//------------------------------update_succ_freq-------------------------------2148// Update the appropriate frequency associated with block 'b', a successor of2149// a block in this loop.2150void CFGLoop::update_succ_freq(Block* b, double freq) {2151if (b->_loop == this) {2152if (b == head()) {2153// back branch within the loop2154// Do nothing now, the loop carried frequency will be2155// adjust later in scale_freq().2156} else {2157// simple branch within the loop2158b->_freq += freq;2159}2160} else if (!in_loop_nest(b)) {2161// branch is exit from this loop2162BlockProbPair bpp(b, freq);2163_exits.append(bpp);2164} else {2165// branch into nested loop2166CFGLoop* ch = b->_loop;2167ch->_freq += freq;2168}2169}21702171//------------------------------in_loop_nest-----------------------------------2172// Determine if block b is in the receiver's loop nest.2173bool CFGLoop::in_loop_nest(Block* b) {2174int depth = _depth;2175CFGLoop* b_loop = b->_loop;2176int b_depth = b_loop->_depth;2177if (depth == b_depth) {2178return true;2179}2180while (b_depth > depth) {2181b_loop = b_loop->_parent;2182b_depth = b_loop->_depth;2183}2184return b_loop == this;2185}21862187//------------------------------scale_freq-------------------------------------2188// Scale frequency of loops and blocks by trip counts from outer loops2189// Do a top down traversal of loop tree (visit outer loops first.)2190void CFGLoop::scale_freq() {2191double loop_freq = _freq * trip_count();2192_freq = loop_freq;2193for (int i = 0; i < _members.length(); i++) {2194CFGElement* s = _members.at(i);2195double block_freq = s->_freq * loop_freq;2196if (g_isnan(block_freq) || block_freq < MIN_BLOCK_FREQUENCY)2197block_freq = MIN_BLOCK_FREQUENCY;2198s->_freq = block_freq;2199}2200CFGLoop* ch = _child;2201while (ch != NULL) {2202ch->scale_freq();2203ch = ch->_sibling;2204}2205}22062207// Frequency of outer loop2208double CFGLoop::outer_loop_freq() const {2209if (_child != NULL) {2210return _child->_freq;2211}2212return _freq;2213}22142215#ifndef PRODUCT2216//------------------------------dump_tree--------------------------------------2217void CFGLoop::dump_tree() const {2218dump();2219if (_child != NULL) _child->dump_tree();2220if (_sibling != NULL) _sibling->dump_tree();2221}22222223//------------------------------dump-------------------------------------------2224void CFGLoop::dump() const {2225for (int i = 0; i < _depth; i++) tty->print(" ");2226tty->print("%s: %d trip_count: %6.0f freq: %6.0f\n",2227_depth == 0 ? "Method" : "Loop", _id, trip_count(), _freq);2228for (int i = 0; i < _depth; i++) tty->print(" ");2229tty->print(" members:");2230int k = 0;2231for (int i = 0; i < _members.length(); i++) {2232if (k++ >= 6) {2233tty->print("\n ");2234for (int j = 0; j < _depth+1; j++) tty->print(" ");2235k = 0;2236}2237CFGElement *s = _members.at(i);2238if (s->is_block()) {2239Block *b = s->as_Block();2240tty->print(" B%d(%6.3f)", b->_pre_order, b->_freq);2241} else {2242CFGLoop* lp = s->as_CFGLoop();2243tty->print(" L%d(%6.3f)", lp->_id, lp->_freq);2244}2245}2246tty->print("\n");2247for (int i = 0; i < _depth; i++) tty->print(" ");2248tty->print(" exits: ");2249k = 0;2250for (int i = 0; i < _exits.length(); i++) {2251if (k++ >= 7) {2252tty->print("\n ");2253for (int j = 0; j < _depth+1; j++) tty->print(" ");2254k = 0;2255}2256Block *blk = _exits.at(i).get_target();2257double prob = _exits.at(i).get_prob();2258tty->print(" ->%d@%d%%", blk->_pre_order, (int)(prob*100));2259}2260tty->print("\n");2261}2262#endif226322642265