1 /*
   2  * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "libadt/vectset.hpp"
  27 #include "memory/allocation.inline.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"
  39 
  40 // Portions of code courtesy of Clifford Click
  41 
  42 // Optimization - Graph Style
  43 
  44 // To avoid float value underflow
  45 #define MIN_BLOCK_FREQUENCY 1.e-35f
  46 
  47 //----------------------------schedule_node_into_block-------------------------
  48 // Insert node n into block b. Look for projections of n and make sure they
  49 // are in b also.
  50 void PhaseCFG::schedule_node_into_block( Node *n, Block *b ) {
  51   // Set basic block of n, Add n to b,
  52   map_node_to_block(n, b);
  53   b->add_inst(n);
  54 
  55   // After Matching, nearly any old Node may have projections trailing it.
  56   // These are usually machine-dependent flags.  In any case, they might
  57   // float to another block below this one.  Move them up.
  58   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
  59     Node*  use  = n->fast_out(i);
  60     if (use->is_Proj()) {
  61       Block* buse = get_block_for_node(use);
  62       if (buse != b) {              // In wrong block?
  63         if (buse != NULL) {
  64           buse->find_remove(use);   // Remove from wrong block
  65         }
  66         map_node_to_block(use, b);
  67         b->add_inst(use);
  68       }
  69     }
  70   }
  71 }
  72 
  73 //----------------------------replace_block_proj_ctrl-------------------------
  74 // Nodes that have is_block_proj() nodes as their control need to use
  75 // the appropriate Region for their actual block as their control since
  76 // the projection will be in a predecessor block.
  77 void PhaseCFG::replace_block_proj_ctrl( Node *n ) {
  78   const Node *in0 = n->in(0);
  79   assert(in0 != NULL, "Only control-dependent");
  80   const Node *p = in0->is_block_proj();
  81   if (p != NULL && p != n) {    // Control from a block projection?
  82     assert(!n->pinned() || n->is_MachConstantBase(), "only pinned MachConstantBase node is expected here");
  83     // Find trailing Region
  84     Block *pb = get_block_for_node(in0); // Block-projection already has basic block
  85     uint j = 0;
  86     if (pb->_num_succs != 1) {  // More then 1 successor?
  87       // Search for successor
  88       uint max = pb->number_of_nodes();
  89       assert( max > 1, "" );
  90       uint start = max - pb->_num_succs;
  91       // Find which output path belongs to projection
  92       for (j = start; j < max; j++) {
  93         if( pb->get_node(j) == in0 )
  94           break;
  95       }
  96       assert( j < max, "must find" );
  97       // Change control to match head of successor basic block
  98       j -= start;
  99     }
 100     n->set_req(0, pb->_succs[j]->head());
 101   }
 102 }
 103 
 104 static bool is_dominator(Block* d, Block* n) {
 105   return d->dom_lca(n) == d;
 106 }
 107 
 108 //------------------------------schedule_pinned_nodes--------------------------
 109 // Set the basic block for Nodes pinned into blocks
 110 void PhaseCFG::schedule_pinned_nodes(VectorSet &visited) {
 111   // Allocate node stack of size C->live_nodes()+8 to avoid frequent realloc
 112   GrowableArray <Node *> spstack(C->live_nodes() + 8);
 113   spstack.push(_root);
 114   while (spstack.is_nonempty()) {
 115     Node* node = spstack.pop();
 116     if (!visited.test_set(node->_idx)) { // Test node and flag it as visited
 117       if (node->pinned() && !has_block(node)) {  // Pinned?  Nail it down!
 118         assert(node->in(0), "pinned Node must have Control");
 119         // Before setting block replace block_proj control edge
 120         replace_block_proj_ctrl(node);
 121         Node* input = node->in(0);
 122         while (!input->is_block_start()) {
 123           input = input->in(0);
 124         }
 125         Block* block = get_block_for_node(input); // Basic block of controlling input
 126         schedule_node_into_block(node, block);
 127       }
 128 
 129       // If the node has precedence edges (added when CastPP nodes are
 130       // removed in final_graph_reshaping), fix the control of the
 131       // node to cover the precedence edges and remove the
 132       // dependencies.
 133       Node* n = NULL;
 134       for (uint i = node->len()-1; i >= node->req(); i--) {
 135         Node* m = node->in(i);
 136         if (m == NULL) continue;
 137         // Skip the precedence edge if the test that guarded a CastPP:
 138         // - was optimized out during escape analysis
 139         // (OptimizePtrCompare): the CastPP's control isn't an end of
 140         // block.
 141         // - is moved in the branch of a dominating If: the control of
 142         // the CastPP is then a Region.
 143         if (m->is_block_proj() || m->is_block_start()) {
 144           node->rm_prec(i);
 145           if (n == NULL) {
 146             n = m;
 147           } else {
 148             Block* bn = get_block_for_node(n);
 149             Block* bm = get_block_for_node(m);
 150             assert(is_dominator(bn, bm) || is_dominator(bm, bn), "one must dominate the other");
 151             n = is_dominator(bn, bm) ? m : n;
 152           }
 153         }
 154       }
 155       if (n != NULL) {
 156         assert(node->in(0), "control should have been set");
 157         Block* bn = get_block_for_node(n);
 158         Block* bnode = get_block_for_node(node->in(0));
 159         assert(is_dominator(bn, bnode) || is_dominator(bnode, bn), "one must dominate the other");
 160         if (!is_dominator(bn, bnode)) {
 161           node->set_req(0, n);
 162         }
 163       }
 164 
 165       // process all inputs that are non NULL
 166       for (int i = node->req() - 1; i >= 0; --i) {
 167         if (node->in(i) != NULL) {
 168           spstack.push(node->in(i));
 169         }
 170       }
 171     }
 172   }
 173 }
 174 
 175 #ifdef ASSERT
 176 // Assert that new input b2 is dominated by all previous inputs.
 177 // Check this by by seeing that it is dominated by b1, the deepest
 178 // input observed until b2.
 179 static void assert_dom(Block* b1, Block* b2, Node* n, const PhaseCFG* cfg) {
 180   if (b1 == NULL)  return;
 181   assert(b1->_dom_depth < b2->_dom_depth, "sanity");
 182   Block* tmp = b2;
 183   while (tmp != b1 && tmp != NULL) {
 184     tmp = tmp->_idom;
 185   }
 186   if (tmp != b1) {
 187     // Detected an unschedulable graph.  Print some nice stuff and die.
 188     tty->print_cr("!!! Unschedulable graph !!!");
 189     for (uint j=0; j<n->len(); j++) { // For all inputs
 190       Node* inn = n->in(j); // Get input
 191       if (inn == NULL)  continue;  // Ignore NULL, missing inputs
 192       Block* inb = cfg->get_block_for_node(inn);
 193       tty->print("B%d idom=B%d depth=%2d ",inb->_pre_order,
 194                  inb->_idom ? inb->_idom->_pre_order : 0, inb->_dom_depth);
 195       inn->dump();
 196     }
 197     tty->print("Failing node: ");
 198     n->dump();
 199     assert(false, "unscheduable graph");
 200   }
 201 }
 202 #endif
 203 
 204 static Block* find_deepest_input(Node* n, const PhaseCFG* cfg) {
 205   // Find the last input dominated by all other inputs.
 206   Block* deepb           = NULL;        // Deepest block so far
 207   int    deepb_dom_depth = 0;
 208   for (uint k = 0; k < n->len(); k++) { // For all inputs
 209     Node* inn = n->in(k);               // Get input
 210     if (inn == NULL)  continue;         // Ignore NULL, missing inputs
 211     Block* inb = cfg->get_block_for_node(inn);
 212     assert(inb != NULL, "must already have scheduled this input");
 213     if (deepb_dom_depth < (int) inb->_dom_depth) {
 214       // The new inb must be dominated by the previous deepb.
 215       // The various inputs must be linearly ordered in the dom
 216       // tree, or else there will not be a unique deepest block.
 217       DEBUG_ONLY(assert_dom(deepb, inb, n, cfg));
 218       deepb = inb;                      // Save deepest block
 219       deepb_dom_depth = deepb->_dom_depth;
 220     }
 221   }
 222   assert(deepb != NULL, "must be at least one input to n");
 223   return deepb;
 224 }
 225 
 226 
 227 //------------------------------schedule_early---------------------------------
 228 // Find the earliest Block any instruction can be placed in.  Some instructions
 229 // are pinned into Blocks.  Unpinned instructions can appear in last block in
 230 // which all their inputs occur.
 231 bool PhaseCFG::schedule_early(VectorSet &visited, Node_List &roots) {
 232   // Allocate stack with enough space to avoid frequent realloc
 233   Node_Stack nstack(roots.Size() + 8);
 234   // _root will be processed among C->top() inputs
 235   roots.push(C->top());
 236   visited.set(C->top()->_idx);
 237 
 238   while (roots.size() != 0) {
 239     // Use local variables nstack_top_n & nstack_top_i to cache values
 240     // on stack's top.
 241     Node* parent_node = roots.pop();
 242     uint  input_index = 0;
 243 
 244     while (true) {
 245       if (input_index == 0) {
 246         // Fixup some control.  Constants without control get attached
 247         // to root and nodes that use is_block_proj() nodes should be attached
 248         // to the region that starts their block.
 249         const Node* control_input = parent_node->in(0);
 250         if (control_input != NULL) {
 251           replace_block_proj_ctrl(parent_node);
 252         } else {
 253           // Is a constant with NO inputs?
 254           if (parent_node->req() == 1) {
 255             parent_node->set_req(0, _root);
 256           }
 257         }
 258       }
 259 
 260       // First, visit all inputs and force them to get a block.  If an
 261       // input is already in a block we quit following inputs (to avoid
 262       // cycles). Instead we put that Node on a worklist to be handled
 263       // later (since IT'S inputs may not have a block yet).
 264 
 265       // Assume all n's inputs will be processed
 266       bool done = true;
 267 
 268       while (input_index < parent_node->len()) {
 269         Node* in = parent_node->in(input_index++);
 270         if (in == NULL) {
 271           continue;
 272         }
 273 
 274         int is_visited = visited.test_set(in->_idx);
 275         if (!has_block(in)) {
 276           if (is_visited) {
 277             return false;
 278           }
 279           // Save parent node and next input's index.
 280           nstack.push(parent_node, input_index);
 281           // Process current input now.
 282           parent_node = in;
 283           input_index = 0;
 284           // Not all n's inputs processed.
 285           done = false;
 286           break;
 287         } else if (!is_visited) {
 288           // Visit this guy later, using worklist
 289           roots.push(in);
 290         }
 291       }
 292 
 293       if (done) {
 294         // All of n's inputs have been processed, complete post-processing.
 295 
 296         // Some instructions are pinned into a block.  These include Region,
 297         // Phi, Start, Return, and other control-dependent instructions and
 298         // any projections which depend on them.
 299         if (!parent_node->pinned()) {
 300           // Set earliest legal block.
 301           Block* earliest_block = find_deepest_input(parent_node, this);
 302           map_node_to_block(parent_node, earliest_block);
 303         } else {
 304           assert(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");
 305         }
 306 
 307         if (nstack.is_empty()) {
 308           // Finished all nodes on stack.
 309           // Process next node on the worklist 'roots'.
 310           break;
 311         }
 312         // Get saved parent node and next input's index.
 313         parent_node = nstack.node();
 314         input_index = nstack.index();
 315         nstack.pop();
 316       }
 317     }
 318   }
 319   return true;
 320 }
 321 
 322 //------------------------------dom_lca----------------------------------------
 323 // Find least common ancestor in dominator tree
 324 // LCA is a current notion of LCA, to be raised above 'this'.
 325 // As a convenient boundary condition, return 'this' if LCA is NULL.
 326 // Find the LCA of those two nodes.
 327 Block* Block::dom_lca(Block* LCA) {
 328   if (LCA == NULL || LCA == this)  return this;
 329 
 330   Block* anc = this;
 331   while (anc->_dom_depth > LCA->_dom_depth)
 332     anc = anc->_idom;           // Walk up till anc is as high as LCA
 333 
 334   while (LCA->_dom_depth > anc->_dom_depth)
 335     LCA = LCA->_idom;           // Walk up till LCA is as high as anc
 336 
 337   while (LCA != anc) {          // Walk both up till they are the same
 338     LCA = LCA->_idom;
 339     anc = anc->_idom;
 340   }
 341 
 342   return LCA;
 343 }
 344 
 345 //--------------------------raise_LCA_above_use--------------------------------
 346 // We are placing a definition, and have been given a def->use edge.
 347 // The definition must dominate the use, so move the LCA upward in the
 348 // dominator tree to dominate the use.  If the use is a phi, adjust
 349 // the LCA only with the phi input paths which actually use this def.
 350 static Block* raise_LCA_above_use(Block* LCA, Node* use, Node* def, const PhaseCFG* cfg) {
 351   Block* buse = cfg->get_block_for_node(use);
 352   if (buse == NULL)    return LCA;   // Unused killing Projs have no use block
 353   if (!use->is_Phi())  return buse->dom_lca(LCA);
 354   uint pmax = use->req();       // Number of Phi inputs
 355   // Why does not this loop just break after finding the matching input to
 356   // the Phi?  Well...it's like this.  I do not have true def-use/use-def
 357   // chains.  Means I cannot distinguish, from the def-use direction, which
 358   // of many use-defs lead from the same use to the same def.  That is, this
 359   // Phi might have several uses of the same def.  Each use appears in a
 360   // different predecessor block.  But when I enter here, I cannot distinguish
 361   // which use-def edge I should find the predecessor block for.  So I find
 362   // them all.  Means I do a little extra work if a Phi uses the same value
 363   // more than once.
 364   for (uint j=1; j<pmax; j++) { // For all inputs
 365     if (use->in(j) == def) {    // Found matching input?
 366       Block* pred = cfg->get_block_for_node(buse->pred(j));
 367       LCA = pred->dom_lca(LCA);
 368     }
 369   }
 370   return LCA;
 371 }
 372 
 373 //----------------------------raise_LCA_above_marks----------------------------
 374 // Return a new LCA that dominates LCA and any of its marked predecessors.
 375 // Search all my parents up to 'early' (exclusive), looking for predecessors
 376 // which are marked with the given index.  Return the LCA (in the dom tree)
 377 // of all marked blocks.  If there are none marked, return the original
 378 // LCA.
 379 static Block* raise_LCA_above_marks(Block* LCA, node_idx_t mark, Block* early, const PhaseCFG* cfg) {
 380   Block_List worklist;
 381   worklist.push(LCA);
 382   while (worklist.size() > 0) {
 383     Block* mid = worklist.pop();
 384     if (mid == early)  continue;  // stop searching here
 385 
 386     // Test and set the visited bit.
 387     if (mid->raise_LCA_visited() == mark)  continue;  // already visited
 388 
 389     // Don't process the current LCA, otherwise the search may terminate early
 390     if (mid != LCA && mid->raise_LCA_mark() == mark) {
 391       // Raise the LCA.
 392       LCA = mid->dom_lca(LCA);
 393       if (LCA == early)  break;   // stop searching everywhere
 394       assert(early->dominates(LCA), "early is high enough");
 395       // Resume searching at that point, skipping intermediate levels.
 396       worklist.push(LCA);
 397       if (LCA == mid)
 398         continue; // Don't mark as visited to avoid early termination.
 399     } else {
 400       // Keep searching through this block's predecessors.
 401       for (uint j = 1, jmax = mid->num_preds(); j < jmax; j++) {
 402         Block* mid_parent = cfg->get_block_for_node(mid->pred(j));
 403         worklist.push(mid_parent);
 404       }
 405     }
 406     mid->set_raise_LCA_visited(mark);
 407   }
 408   return LCA;
 409 }
 410 
 411 //--------------------------memory_early_block--------------------------------
 412 // This is a variation of find_deepest_input, the heart of schedule_early.
 413 // Find the "early" block for a load, if we considered only memory and
 414 // address inputs, that is, if other data inputs were ignored.
 415 //
 416 // Because a subset of edges are considered, the resulting block will
 417 // be earlier (at a shallower dom_depth) than the true schedule_early
 418 // point of the node. We compute this earlier block as a more permissive
 419 // site for anti-dependency insertion, but only if subsume_loads is enabled.
 420 static Block* memory_early_block(Node* load, Block* early, const PhaseCFG* cfg) {
 421   Node* base;
 422   Node* index;
 423   Node* store = load->in(MemNode::Memory);
 424   load->as_Mach()->memory_inputs(base, index);
 425 
 426   assert(base != NodeSentinel && index != NodeSentinel,
 427          "unexpected base/index inputs");
 428 
 429   Node* mem_inputs[4];
 430   int mem_inputs_length = 0;
 431   if (base != NULL)  mem_inputs[mem_inputs_length++] = base;
 432   if (index != NULL) mem_inputs[mem_inputs_length++] = index;
 433   if (store != NULL) mem_inputs[mem_inputs_length++] = store;
 434 
 435   // In the comparision below, add one to account for the control input,
 436   // which may be null, but always takes up a spot in the in array.
 437   if (mem_inputs_length + 1 < (int) load->req()) {
 438     // This "load" has more inputs than just the memory, base and index inputs.
 439     // For purposes of checking anti-dependences, we need to start
 440     // from the early block of only the address portion of the instruction,
 441     // and ignore other blocks that may have factored into the wider
 442     // schedule_early calculation.
 443     if (load->in(0) != NULL) mem_inputs[mem_inputs_length++] = load->in(0);
 444 
 445     Block* deepb           = NULL;        // Deepest block so far
 446     int    deepb_dom_depth = 0;
 447     for (int i = 0; i < mem_inputs_length; i++) {
 448       Block* inb = cfg->get_block_for_node(mem_inputs[i]);
 449       if (deepb_dom_depth < (int) inb->_dom_depth) {
 450         // The new inb must be dominated by the previous deepb.
 451         // The various inputs must be linearly ordered in the dom
 452         // tree, or else there will not be a unique deepest block.
 453         DEBUG_ONLY(assert_dom(deepb, inb, load, cfg));
 454         deepb = inb;                      // Save deepest block
 455         deepb_dom_depth = deepb->_dom_depth;
 456       }
 457     }
 458     early = deepb;
 459   }
 460 
 461   return early;
 462 }
 463 
 464 //--------------------------insert_anti_dependences---------------------------
 465 // A load may need to witness memory that nearby stores can overwrite.
 466 // For each nearby store, either insert an "anti-dependence" edge
 467 // from the load to the store, or else move LCA upward to force the
 468 // load to (eventually) be scheduled in a block above the store.
 469 //
 470 // Do not add edges to stores on distinct control-flow paths;
 471 // only add edges to stores which might interfere.
 472 //
 473 // Return the (updated) LCA.  There will not be any possibly interfering
 474 // store between the load's "early block" and the updated LCA.
 475 // Any stores in the updated LCA will have new precedence edges
 476 // back to the load.  The caller is expected to schedule the load
 477 // in the LCA, in which case the precedence edges will make LCM
 478 // preserve anti-dependences.  The caller may also hoist the load
 479 // above the LCA, if it is not the early block.
 480 Block* PhaseCFG::insert_anti_dependences(Block* LCA, Node* load, bool verify) {
 481   assert(load->needs_anti_dependence_check(), "must be a load of some sort");
 482   assert(LCA != NULL, "");
 483   DEBUG_ONLY(Block* LCA_orig = LCA);
 484 
 485   // Compute the alias index.  Loads and stores with different alias indices
 486   // do not need anti-dependence edges.
 487   int load_alias_idx = C->get_alias_index(load->adr_type());
 488 #ifdef ASSERT
 489   if (load_alias_idx == Compile::AliasIdxBot && C->AliasLevel() > 0 &&
 490       (PrintOpto || VerifyAliases ||
 491        PrintMiscellaneous && (WizardMode || Verbose))) {
 492     // Load nodes should not consume all of memory.
 493     // Reporting a bottom type indicates a bug in adlc.
 494     // If some particular type of node validly consumes all of memory,
 495     // sharpen the preceding "if" to exclude it, so we can catch bugs here.
 496     tty->print_cr("*** Possible Anti-Dependence Bug:  Load consumes all of memory.");
 497     load->dump(2);
 498     if (VerifyAliases)  assert(load_alias_idx != Compile::AliasIdxBot, "");
 499   }
 500 #endif
 501   assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrComp),
 502          "String compare is only known 'load' that does not conflict with any stores");
 503   assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrEquals),
 504          "String equals is a 'load' that does not conflict with any stores");
 505   assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_StrIndexOf),
 506          "String indexOf is a 'load' that does not conflict with any stores");
 507   assert(load_alias_idx || (load->is_Mach() && load->as_Mach()->ideal_Opcode() == Op_AryEq),
 508          "Arrays equals is a 'load' that do not conflict with any stores");
 509 
 510   if (!C->alias_type(load_alias_idx)->is_rewritable()) {
 511     // It is impossible to spoil this load by putting stores before it,
 512     // because we know that the stores will never update the value
 513     // which 'load' must witness.
 514     return LCA;
 515   }
 516 
 517   node_idx_t load_index = load->_idx;
 518 
 519   // Note the earliest legal placement of 'load', as determined by
 520   // by the unique point in the dom tree where all memory effects
 521   // and other inputs are first available.  (Computed by schedule_early.)
 522   // For normal loads, 'early' is the shallowest place (dom graph wise)
 523   // to look for anti-deps between this load and any store.
 524   Block* early = get_block_for_node(load);
 525 
 526   // If we are subsuming loads, compute an "early" block that only considers
 527   // memory or address inputs. This block may be different than the
 528   // schedule_early block in that it could be at an even shallower depth in the
 529   // dominator tree, and allow for a broader discovery of anti-dependences.
 530   if (C->subsume_loads()) {
 531     early = memory_early_block(load, early, this);
 532   }
 533 
 534   ResourceArea *area = Thread::current()->resource_area();
 535   Node_List worklist_mem(area);     // prior memory state to store
 536   Node_List worklist_store(area);   // possible-def to explore
 537   Node_List worklist_visited(area); // visited mergemem nodes
 538   Node_List non_early_stores(area); // all relevant stores outside of early
 539   bool must_raise_LCA = false;
 540 
 541 #ifdef TRACK_PHI_INPUTS
 542   // %%% This extra checking fails because MergeMem nodes are not GVNed.
 543   // Provide "phi_inputs" to check if every input to a PhiNode is from the
 544   // original memory state.  This indicates a PhiNode for which should not
 545   // prevent the load from sinking.  For such a block, set_raise_LCA_mark
 546   // may be overly conservative.
 547   // Mechanism: count inputs seen for each Phi encountered in worklist_store.
 548   DEBUG_ONLY(GrowableArray<uint> phi_inputs(area, C->unique(),0,0));
 549 #endif
 550 
 551   // 'load' uses some memory state; look for users of the same state.
 552   // Recurse through MergeMem nodes to the stores that use them.
 553 
 554   // Each of these stores is a possible definition of memory
 555   // that 'load' needs to use.  We need to force 'load'
 556   // to occur before each such store.  When the store is in
 557   // the same block as 'load', we insert an anti-dependence
 558   // edge load->store.
 559 
 560   // The relevant stores "nearby" the load consist of a tree rooted
 561   // at initial_mem, with internal nodes of type MergeMem.
 562   // Therefore, the branches visited by the worklist are of this form:
 563   //    initial_mem -> (MergeMem ->)* store
 564   // The anti-dependence constraints apply only to the fringe of this tree.
 565 
 566   Node* initial_mem = load->in(MemNode::Memory);
 567   worklist_store.push(initial_mem);
 568   worklist_visited.push(initial_mem);
 569   worklist_mem.push(NULL);
 570   while (worklist_store.size() > 0) {
 571     // Examine a nearby store to see if it might interfere with our load.
 572     Node* mem   = worklist_mem.pop();
 573     Node* store = worklist_store.pop();
 574     uint op = store->Opcode();
 575 
 576     // MergeMems do not directly have anti-deps.
 577     // Treat them as internal nodes in a forward tree of memory states,
 578     // the leaves of which are each a 'possible-def'.
 579     if (store == initial_mem    // root (exclusive) of tree we are searching
 580         || op == Op_MergeMem    // internal node of tree we are searching
 581         ) {
 582       mem = store;   // It's not a possibly interfering store.
 583       if (store == initial_mem)
 584         initial_mem = NULL;  // only process initial memory once
 585 
 586       for (DUIterator_Fast imax, i = mem->fast_outs(imax); i < imax; i++) {
 587         store = mem->fast_out(i);
 588         if (store->is_MergeMem()) {
 589           // Be sure we don't get into combinatorial problems.
 590           // (Allow phis to be repeated; they can merge two relevant states.)
 591           uint j = worklist_visited.size();
 592           for (; j > 0; j--) {
 593             if (worklist_visited.at(j-1) == store)  break;
 594           }
 595           if (j > 0)  continue; // already on work list; do not repeat
 596           worklist_visited.push(store);
 597         }
 598         worklist_mem.push(mem);
 599         worklist_store.push(store);
 600       }
 601       continue;
 602     }
 603 
 604     if (op == Op_MachProj || op == Op_Catch)   continue;
 605     if (store->needs_anti_dependence_check())  continue;  // not really a store
 606 
 607     // Compute the alias index.  Loads and stores with different alias
 608     // indices do not need anti-dependence edges.  Wide MemBar's are
 609     // anti-dependent on everything (except immutable memories).
 610     const TypePtr* adr_type = store->adr_type();
 611     if (!C->can_alias(adr_type, load_alias_idx))  continue;
 612 
 613     // Most slow-path runtime calls do NOT modify Java memory, but
 614     // they can block and so write Raw memory.
 615     if (store->is_Mach()) {
 616       MachNode* mstore = store->as_Mach();
 617       if (load_alias_idx != Compile::AliasIdxRaw) {
 618         // Check for call into the runtime using the Java calling
 619         // convention (and from there into a wrapper); it has no
 620         // _method.  Can't do this optimization for Native calls because
 621         // they CAN write to Java memory.
 622         if (mstore->ideal_Opcode() == Op_CallStaticJava) {
 623           assert(mstore->is_MachSafePoint(), "");
 624           MachSafePointNode* ms = (MachSafePointNode*) mstore;
 625           assert(ms->is_MachCallJava(), "");
 626           MachCallJavaNode* mcj = (MachCallJavaNode*) ms;
 627           if (mcj->_method == NULL) {
 628             // These runtime calls do not write to Java visible memory
 629             // (other than Raw) and so do not require anti-dependence edges.
 630             continue;
 631           }
 632         }
 633         // Same for SafePoints: they read/write Raw but only read otherwise.
 634         // This is basically a workaround for SafePoints only defining control
 635         // instead of control + memory.
 636         if (mstore->ideal_Opcode() == Op_SafePoint)
 637           continue;
 638       } else {
 639         // Some raw memory, such as the load of "top" at an allocation,
 640         // can be control dependent on the previous safepoint. See
 641         // comments in GraphKit::allocate_heap() about control input.
 642         // Inserting an anti-dep between such a safepoint and a use
 643         // creates a cycle, and will cause a subsequent failure in
 644         // local scheduling.  (BugId 4919904)
 645         // (%%% How can a control input be a safepoint and not a projection??)
 646         if (mstore->ideal_Opcode() == Op_SafePoint && load->in(0) == mstore)
 647           continue;
 648       }
 649     }
 650 
 651     // Identify a block that the current load must be above,
 652     // or else observe that 'store' is all the way up in the
 653     // earliest legal block for 'load'.  In the latter case,
 654     // immediately insert an anti-dependence edge.
 655     Block* store_block = get_block_for_node(store);
 656     assert(store_block != NULL, "unused killing projections skipped above");
 657 
 658     if (store->is_Phi()) {
 659       // 'load' uses memory which is one (or more) of the Phi's inputs.
 660       // It must be scheduled not before the Phi, but rather before
 661       // each of the relevant Phi inputs.
 662       //
 663       // Instead of finding the LCA of all inputs to a Phi that match 'mem',
 664       // we mark each corresponding predecessor block and do a combined
 665       // hoisting operation later (raise_LCA_above_marks).
 666       //
 667       // Do not assert(store_block != early, "Phi merging memory after access")
 668       // PhiNode may be at start of block 'early' with backedge to 'early'
 669       DEBUG_ONLY(bool found_match = false);
 670       for (uint j = PhiNode::Input, jmax = store->req(); j < jmax; j++) {
 671         if (store->in(j) == mem) {   // Found matching input?
 672           DEBUG_ONLY(found_match = true);
 673           Block* pred_block = get_block_for_node(store_block->pred(j));
 674           if (pred_block != early) {
 675             // If any predecessor of the Phi matches the load's "early block",
 676             // we do not need a precedence edge between the Phi and 'load'
 677             // since the load will be forced into a block preceding the Phi.
 678             pred_block->set_raise_LCA_mark(load_index);
 679             assert(!LCA_orig->dominates(pred_block) ||
 680                    early->dominates(pred_block), "early is high enough");
 681             must_raise_LCA = true;
 682           } else {
 683             // anti-dependent upon PHI pinned below 'early', no edge needed
 684             LCA = early;             // but can not schedule below 'early'
 685           }
 686         }
 687       }
 688       assert(found_match, "no worklist bug");
 689 #ifdef TRACK_PHI_INPUTS
 690 #ifdef ASSERT
 691       // This assert asks about correct handling of PhiNodes, which may not
 692       // have all input edges directly from 'mem'. See BugId 4621264
 693       int num_mem_inputs = phi_inputs.at_grow(store->_idx,0) + 1;
 694       // Increment by exactly one even if there are multiple copies of 'mem'
 695       // coming into the phi, because we will run this block several times
 696       // if there are several copies of 'mem'.  (That's how DU iterators work.)
 697       phi_inputs.at_put(store->_idx, num_mem_inputs);
 698       assert(PhiNode::Input + num_mem_inputs < store->req(),
 699              "Expect at least one phi input will not be from original memory state");
 700 #endif //ASSERT
 701 #endif //TRACK_PHI_INPUTS
 702     } else if (store_block != early) {
 703       // 'store' is between the current LCA and earliest possible block.
 704       // Label its block, and decide later on how to raise the LCA
 705       // to include the effect on LCA of this store.
 706       // If this store's block gets chosen as the raised LCA, we
 707       // will find him on the non_early_stores list and stick him
 708       // with a precedence edge.
 709       // (But, don't bother if LCA is already raised all the way.)
 710       if (LCA != early) {
 711         store_block->set_raise_LCA_mark(load_index);
 712         must_raise_LCA = true;
 713         non_early_stores.push(store);
 714       }
 715     } else {
 716       // Found a possibly-interfering store in the load's 'early' block.
 717       // This means 'load' cannot sink at all in the dominator tree.
 718       // Add an anti-dep edge, and squeeze 'load' into the highest block.
 719       assert(store != load->in(0), "dependence cycle found");
 720       if (verify) {
 721         assert(store->find_edge(load) != -1, "missing precedence edge");
 722       } else {
 723         store->add_prec(load);
 724       }
 725       LCA = early;
 726       // This turns off the process of gathering non_early_stores.
 727     }
 728   }
 729   // (Worklist is now empty; all nearby stores have been visited.)
 730 
 731   // Finished if 'load' must be scheduled in its 'early' block.
 732   // If we found any stores there, they have already been given
 733   // precedence edges.
 734   if (LCA == early)  return LCA;
 735 
 736   // We get here only if there are no possibly-interfering stores
 737   // in the load's 'early' block.  Move LCA up above all predecessors
 738   // which contain stores we have noted.
 739   //
 740   // The raised LCA block can be a home to such interfering stores,
 741   // but its predecessors must not contain any such stores.
 742   //
 743   // The raised LCA will be a lower bound for placing the load,
 744   // preventing the load from sinking past any block containing
 745   // a store that may invalidate the memory state required by 'load'.
 746   if (must_raise_LCA)
 747     LCA = raise_LCA_above_marks(LCA, load->_idx, early, this);
 748   if (LCA == early)  return LCA;
 749 
 750   // Insert anti-dependence edges from 'load' to each store
 751   // in the non-early LCA block.
 752   // Mine the non_early_stores list for such stores.
 753   if (LCA->raise_LCA_mark() == load_index) {
 754     while (non_early_stores.size() > 0) {
 755       Node* store = non_early_stores.pop();
 756       Block* store_block = get_block_for_node(store);
 757       if (store_block == LCA) {
 758         // add anti_dependence from store to load in its own block
 759         assert(store != load->in(0), "dependence cycle found");
 760         if (verify) {
 761           assert(store->find_edge(load) != -1, "missing precedence edge");
 762         } else {
 763           store->add_prec(load);
 764         }
 765       } else {
 766         assert(store_block->raise_LCA_mark() == load_index, "block was marked");
 767         // Any other stores we found must be either inside the new LCA
 768         // or else outside the original LCA.  In the latter case, they
 769         // did not interfere with any use of 'load'.
 770         assert(LCA->dominates(store_block)
 771                || !LCA_orig->dominates(store_block), "no stray stores");
 772       }
 773     }
 774   }
 775 
 776   // Return the highest block containing stores; any stores
 777   // within that block have been given anti-dependence edges.
 778   return LCA;
 779 }
 780 
 781 // This class is used to iterate backwards over the nodes in the graph.
 782 
 783 class Node_Backward_Iterator {
 784 
 785 private:
 786   Node_Backward_Iterator();
 787 
 788 public:
 789   // Constructor for the iterator
 790   Node_Backward_Iterator(Node *root, VectorSet &visited, Node_List &stack, PhaseCFG &cfg);
 791 
 792   // Postincrement operator to iterate over the nodes
 793   Node *next();
 794 
 795 private:
 796   VectorSet   &_visited;
 797   Node_List   &_stack;
 798   PhaseCFG &_cfg;
 799 };
 800 
 801 // Constructor for the Node_Backward_Iterator
 802 Node_Backward_Iterator::Node_Backward_Iterator( Node *root, VectorSet &visited, Node_List &stack, PhaseCFG &cfg)
 803   : _visited(visited), _stack(stack), _cfg(cfg) {
 804   // The stack should contain exactly the root
 805   stack.clear();
 806   stack.push(root);
 807 
 808   // Clear the visited bits
 809   visited.Clear();
 810 }
 811 
 812 // Iterator for the Node_Backward_Iterator
 813 Node *Node_Backward_Iterator::next() {
 814 
 815   // If the _stack is empty, then just return NULL: finished.
 816   if ( !_stack.size() )
 817     return NULL;
 818 
 819   // '_stack' is emulating a real _stack.  The 'visit-all-users' loop has been
 820   // made stateless, so I do not need to record the index 'i' on my _stack.
 821   // Instead I visit all users each time, scanning for unvisited users.
 822   // I visit unvisited not-anti-dependence users first, then anti-dependent
 823   // children next.
 824   Node *self = _stack.pop();
 825 
 826   // I cycle here when I am entering a deeper level of recursion.
 827   // The key variable 'self' was set prior to jumping here.
 828   while( 1 ) {
 829 
 830     _visited.set(self->_idx);
 831 
 832     // Now schedule all uses as late as possible.
 833     const Node* src = self->is_Proj() ? self->in(0) : self;
 834     uint src_rpo = _cfg.get_block_for_node(src)->_rpo;
 835 
 836     // Schedule all nodes in a post-order visit
 837     Node *unvisited = NULL;  // Unvisited anti-dependent Node, if any
 838 
 839     // Scan for unvisited nodes
 840     for (DUIterator_Fast imax, i = self->fast_outs(imax); i < imax; i++) {
 841       // For all uses, schedule late
 842       Node* n = self->fast_out(i); // Use
 843 
 844       // Skip already visited children
 845       if ( _visited.test(n->_idx) )
 846         continue;
 847 
 848       // do not traverse backward control edges
 849       Node *use = n->is_Proj() ? n->in(0) : n;
 850       uint use_rpo = _cfg.get_block_for_node(use)->_rpo;
 851 
 852       if ( use_rpo < src_rpo )
 853         continue;
 854 
 855       // Phi nodes always precede uses in a basic block
 856       if ( use_rpo == src_rpo && use->is_Phi() )
 857         continue;
 858 
 859       unvisited = n;      // Found unvisited
 860 
 861       // Check for possible-anti-dependent
 862       if( !n->needs_anti_dependence_check() )
 863         break;            // Not visited, not anti-dep; schedule it NOW
 864     }
 865 
 866     // Did I find an unvisited not-anti-dependent Node?
 867     if ( !unvisited )
 868       break;                  // All done with children; post-visit 'self'
 869 
 870     // Visit the unvisited Node.  Contains the obvious push to
 871     // indicate I'm entering a deeper level of recursion.  I push the
 872     // old state onto the _stack and set a new state and loop (recurse).
 873     _stack.push(self);
 874     self = unvisited;
 875   } // End recursion loop
 876 
 877   return self;
 878 }
 879 
 880 //------------------------------ComputeLatenciesBackwards----------------------
 881 // Compute the latency of all the instructions.
 882 void PhaseCFG::compute_latencies_backwards(VectorSet &visited, Node_List &stack) {
 883 #ifndef PRODUCT
 884   if (trace_opto_pipelining())
 885     tty->print("\n#---- ComputeLatenciesBackwards ----\n");
 886 #endif
 887 
 888   Node_Backward_Iterator iter((Node *)_root, visited, stack, *this);
 889   Node *n;
 890 
 891   // Walk over all the nodes from last to first
 892   while (n = iter.next()) {
 893     // Set the latency for the definitions of this instruction
 894     partial_latency_of_defs(n);
 895   }
 896 } // end ComputeLatenciesBackwards
 897 
 898 //------------------------------partial_latency_of_defs------------------------
 899 // Compute the latency impact of this node on all defs.  This computes
 900 // a number that increases as we approach the beginning of the routine.
 901 void PhaseCFG::partial_latency_of_defs(Node *n) {
 902   // Set the latency for this instruction
 903 #ifndef PRODUCT
 904   if (trace_opto_pipelining()) {
 905     tty->print("# latency_to_inputs: node_latency[%d] = %d for node", n->_idx, get_latency_for_node(n));
 906     dump();
 907   }
 908 #endif
 909 
 910   if (n->is_Proj()) {
 911     n = n->in(0);
 912   }
 913 
 914   if (n->is_Root()) {
 915     return;
 916   }
 917 
 918   uint nlen = n->len();
 919   uint use_latency = get_latency_for_node(n);
 920   uint use_pre_order = get_block_for_node(n)->_pre_order;
 921 
 922   for (uint j = 0; j < nlen; j++) {
 923     Node *def = n->in(j);
 924 
 925     if (!def || def == n) {
 926       continue;
 927     }
 928 
 929     // Walk backwards thru projections
 930     if (def->is_Proj()) {
 931       def = def->in(0);
 932     }
 933 
 934 #ifndef PRODUCT
 935     if (trace_opto_pipelining()) {
 936       tty->print("#    in(%2d): ", j);
 937       def->dump();
 938     }
 939 #endif
 940 
 941     // If the defining block is not known, assume it is ok
 942     Block *def_block = get_block_for_node(def);
 943     uint def_pre_order = def_block ? def_block->_pre_order : 0;
 944 
 945     if ((use_pre_order <  def_pre_order) || (use_pre_order == def_pre_order && n->is_Phi())) {
 946       continue;
 947     }
 948 
 949     uint delta_latency = n->latency(j);
 950     uint current_latency = delta_latency + use_latency;
 951 
 952     if (get_latency_for_node(def) < current_latency) {
 953       set_latency_for_node(def, current_latency);
 954     }
 955 
 956 #ifndef PRODUCT
 957     if (trace_opto_pipelining()) {
 958       tty->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));
 959     }
 960 #endif
 961   }
 962 }
 963 
 964 //------------------------------latency_from_use-------------------------------
 965 // Compute the latency of a specific use
 966 int PhaseCFG::latency_from_use(Node *n, const Node *def, Node *use) {
 967   // If self-reference, return no latency
 968   if (use == n || use->is_Root()) {
 969     return 0;
 970   }
 971 
 972   uint def_pre_order = get_block_for_node(def)->_pre_order;
 973   uint latency = 0;
 974 
 975   // If the use is not a projection, then it is simple...
 976   if (!use->is_Proj()) {
 977 #ifndef PRODUCT
 978     if (trace_opto_pipelining()) {
 979       tty->print("#    out(): ");
 980       use->dump();
 981     }
 982 #endif
 983 
 984     uint use_pre_order = get_block_for_node(use)->_pre_order;
 985 
 986     if (use_pre_order < def_pre_order)
 987       return 0;
 988 
 989     if (use_pre_order == def_pre_order && use->is_Phi())
 990       return 0;
 991 
 992     uint nlen = use->len();
 993     uint nl = get_latency_for_node(use);
 994 
 995     for ( uint j=0; j<nlen; j++ ) {
 996       if (use->in(j) == n) {
 997         // Change this if we want local latencies
 998         uint ul = use->latency(j);
 999         uint  l = ul + nl;
1000         if (latency < l) latency = l;
1001 #ifndef PRODUCT
1002         if (trace_opto_pipelining()) {
1003           tty->print_cr("#      %d + edge_latency(%d) == %d -> %d, latency = %d",
1004                         nl, j, ul, l, latency);
1005         }
1006 #endif
1007       }
1008     }
1009   } else {
1010     // This is a projection, just grab the latency of the use(s)
1011     for (DUIterator_Fast jmax, j = use->fast_outs(jmax); j < jmax; j++) {
1012       uint l = latency_from_use(use, def, use->fast_out(j));
1013       if (latency < l) latency = l;
1014     }
1015   }
1016 
1017   return latency;
1018 }
1019 
1020 //------------------------------latency_from_uses------------------------------
1021 // Compute the latency of this instruction relative to all of it's uses.
1022 // This computes a number that increases as we approach the beginning of the
1023 // routine.
1024 void PhaseCFG::latency_from_uses(Node *n) {
1025   // Set the latency for this instruction
1026 #ifndef PRODUCT
1027   if (trace_opto_pipelining()) {
1028     tty->print("# latency_from_outputs: node_latency[%d] = %d for node", n->_idx, get_latency_for_node(n));
1029     dump();
1030   }
1031 #endif
1032   uint latency=0;
1033   const Node *def = n->is_Proj() ? n->in(0): n;
1034 
1035   for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
1036     uint l = latency_from_use(n, def, n->fast_out(i));
1037 
1038     if (latency < l) latency = l;
1039   }
1040 
1041   set_latency_for_node(n, latency);
1042 }
1043 
1044 //------------------------------hoist_to_cheaper_block-------------------------
1045 // Pick a block for node self, between early and LCA, that is a cheaper
1046 // alternative to LCA.
1047 Block* PhaseCFG::hoist_to_cheaper_block(Block* LCA, Block* early, Node* self) {
1048   const double delta = 1+PROB_UNLIKELY_MAG(4);
1049   Block* least       = LCA;
1050   double least_freq  = least->_freq;
1051   uint target        = get_latency_for_node(self);
1052   uint start_latency = get_latency_for_node(LCA->head());
1053   uint end_latency   = get_latency_for_node(LCA->get_node(LCA->end_idx()));
1054   bool in_latency    = (target <= start_latency);
1055   const Block* root_block = get_block_for_node(_root);
1056 
1057   // Turn off latency scheduling if scheduling is just plain off
1058   if (!C->do_scheduling())
1059     in_latency = true;
1060 
1061   // Do not hoist (to cover latency) instructions which target a
1062   // single register.  Hoisting stretches the live range of the
1063   // single register and may force spilling.
1064   MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL;
1065   if (mach && mach->out_RegMask().is_bound1() && mach->out_RegMask().is_NotEmpty())
1066     in_latency = true;
1067 
1068 #ifndef PRODUCT
1069   if (trace_opto_pipelining()) {
1070     tty->print("# Find cheaper block for latency %d: ", get_latency_for_node(self));
1071     self->dump();
1072     tty->print_cr("#   B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g",
1073       LCA->_pre_order,
1074       LCA->head()->_idx,
1075       start_latency,
1076       LCA->get_node(LCA->end_idx())->_idx,
1077       end_latency,
1078       least_freq);
1079   }
1080 #endif
1081 
1082   int cand_cnt = 0;  // number of candidates tried
1083 
1084   // Walk up the dominator tree from LCA (Lowest common ancestor) to
1085   // the earliest legal location.  Capture the least execution frequency.
1086   while (LCA != early) {
1087     LCA = LCA->_idom;         // Follow up the dominator tree
1088 
1089     if (LCA == NULL) {
1090       // Bailout without retry
1091       C->record_method_not_compilable("late schedule failed: LCA == NULL");
1092       return least;
1093     }
1094 
1095     // Don't hoist machine instructions to the root basic block
1096     if (mach && LCA == root_block)
1097       break;
1098 
1099     uint start_lat = get_latency_for_node(LCA->head());
1100     uint end_idx   = LCA->end_idx();
1101     uint end_lat   = get_latency_for_node(LCA->get_node(end_idx));
1102     double LCA_freq = LCA->_freq;
1103 #ifndef PRODUCT
1104     if (trace_opto_pipelining()) {
1105       tty->print_cr("#   B%d: start latency for [%4d]=%d, end latency for [%4d]=%d, freq=%g",
1106         LCA->_pre_order, LCA->head()->_idx, start_lat, end_idx, end_lat, LCA_freq);
1107     }
1108 #endif
1109     cand_cnt++;
1110     if (LCA_freq < least_freq              || // Better Frequency
1111         (StressGCM && Compile::randomized_select(cand_cnt)) || // Should be randomly accepted in stress mode
1112          (!StressGCM                    &&    // Otherwise, choose with latency
1113           !in_latency                   &&    // No block containing latency
1114           LCA_freq < least_freq * delta &&    // No worse frequency
1115           target >= end_lat             &&    // within latency range
1116           !self->is_iteratively_computed() )  // But don't hoist IV increments
1117              // because they may end up above other uses of their phi forcing
1118              // their result register to be different from their input.
1119        ) {
1120       least = LCA;            // Found cheaper block
1121       least_freq = LCA_freq;
1122       start_latency = start_lat;
1123       end_latency = end_lat;
1124       if (target <= start_lat)
1125         in_latency = true;
1126     }
1127   }
1128 
1129 #ifndef PRODUCT
1130   if (trace_opto_pipelining()) {
1131     tty->print_cr("#  Choose block B%d with start latency=%d and freq=%g",
1132       least->_pre_order, start_latency, least_freq);
1133   }
1134 #endif
1135 
1136   // See if the latency needs to be updated
1137   if (target < end_latency) {
1138 #ifndef PRODUCT
1139     if (trace_opto_pipelining()) {
1140       tty->print_cr("#  Change latency for [%4d] from %d to %d", self->_idx, target, end_latency);
1141     }
1142 #endif
1143     set_latency_for_node(self, end_latency);
1144     partial_latency_of_defs(self);
1145   }
1146 
1147   return least;
1148 }
1149 
1150 
1151 //------------------------------schedule_late-----------------------------------
1152 // Now schedule all codes as LATE as possible.  This is the LCA in the
1153 // dominator tree of all USES of a value.  Pick the block with the least
1154 // loop nesting depth that is lowest in the dominator tree.
1155 extern const char must_clone[];
1156 void PhaseCFG::schedule_late(VectorSet &visited, Node_List &stack) {
1157 #ifndef PRODUCT
1158   if (trace_opto_pipelining())
1159     tty->print("\n#---- schedule_late ----\n");
1160 #endif
1161 
1162   Node_Backward_Iterator iter((Node *)_root, visited, stack, *this);
1163   Node *self;
1164 
1165   // Walk over all the nodes from last to first
1166   while (self = iter.next()) {
1167     Block* early = get_block_for_node(self); // Earliest legal placement
1168 
1169     if (self->is_top()) {
1170       // Top node goes in bb #2 with other constants.
1171       // It must be special-cased, because it has no out edges.
1172       early->add_inst(self);
1173       continue;
1174     }
1175 
1176     // No uses, just terminate
1177     if (self->outcnt() == 0) {
1178       assert(self->is_MachProj(), "sanity");
1179       continue;                   // Must be a dead machine projection
1180     }
1181 
1182     // If node is pinned in the block, then no scheduling can be done.
1183     if( self->pinned() )          // Pinned in block?
1184       continue;
1185 
1186     MachNode* mach = self->is_Mach() ? self->as_Mach() : NULL;
1187     if (mach) {
1188       switch (mach->ideal_Opcode()) {
1189       case Op_CreateEx:
1190         // Don't move exception creation
1191         early->add_inst(self);
1192         continue;
1193         break;
1194       case Op_CheckCastPP:
1195         // Don't move CheckCastPP nodes away from their input, if the input
1196         // is a rawptr (5071820).
1197         Node *def = self->in(1);
1198         if (def != NULL && def->bottom_type()->base() == Type::RawPtr) {
1199           early->add_inst(self);
1200 #ifdef ASSERT
1201           _raw_oops.push(def);
1202 #endif
1203           continue;
1204         }
1205         break;
1206       }
1207     }
1208 
1209     // Gather LCA of all uses
1210     Block *LCA = NULL;
1211     {
1212       for (DUIterator_Fast imax, i = self->fast_outs(imax); i < imax; i++) {
1213         // For all uses, find LCA
1214         Node* use = self->fast_out(i);
1215         LCA = raise_LCA_above_use(LCA, use, self, this);
1216       }
1217     }  // (Hide defs of imax, i from rest of block.)
1218 
1219     // Place temps in the block of their use.  This isn't a
1220     // requirement for correctness but it reduces useless
1221     // interference between temps and other nodes.
1222     if (mach != NULL && mach->is_MachTemp()) {
1223       map_node_to_block(self, LCA);
1224       LCA->add_inst(self);
1225       continue;
1226     }
1227 
1228     // Check if 'self' could be anti-dependent on memory
1229     if (self->needs_anti_dependence_check()) {
1230       // Hoist LCA above possible-defs and insert anti-dependences to
1231       // defs in new LCA block.
1232       LCA = insert_anti_dependences(LCA, self);
1233     }
1234 
1235     if (early->_dom_depth > LCA->_dom_depth) {
1236       // Somehow the LCA has moved above the earliest legal point.
1237       // (One way this can happen is via memory_early_block.)
1238       if (C->subsume_loads() == true && !C->failing()) {
1239         // Retry with subsume_loads == false
1240         // If this is the first failure, the sentinel string will "stick"
1241         // to the Compile object, and the C2Compiler will see it and retry.
1242         C->record_failure(C2Compiler::retry_no_subsuming_loads());
1243       } else {
1244         // Bailout without retry when (early->_dom_depth > LCA->_dom_depth)
1245         C->record_method_not_compilable("late schedule failed: incorrect graph");
1246       }
1247       return;
1248     }
1249 
1250     // If there is no opportunity to hoist, then we're done.
1251     // In stress mode, try to hoist even the single operations.
1252     bool try_to_hoist = StressGCM || (LCA != early);
1253 
1254     // Must clone guys stay next to use; no hoisting allowed.
1255     // Also cannot hoist guys that alter memory or are otherwise not
1256     // allocatable (hoisting can make a value live longer, leading to
1257     // anti and output dependency problems which are normally resolved
1258     // by the register allocator giving everyone a different register).
1259     if (mach != NULL && must_clone[mach->ideal_Opcode()])
1260       try_to_hoist = false;
1261 
1262     Block* late = NULL;
1263     if (try_to_hoist) {
1264       // Now find the block with the least execution frequency.
1265       // Start at the latest schedule and work up to the earliest schedule
1266       // in the dominator tree.  Thus the Node will dominate all its uses.
1267       late = hoist_to_cheaper_block(LCA, early, self);
1268     } else {
1269       // Just use the LCA of the uses.
1270       late = LCA;
1271     }
1272 
1273     // Put the node into target block
1274     schedule_node_into_block(self, late);
1275 
1276 #ifdef ASSERT
1277     if (self->needs_anti_dependence_check()) {
1278       // since precedence edges are only inserted when we're sure they
1279       // are needed make sure that after placement in a block we don't
1280       // need any new precedence edges.
1281       verify_anti_dependences(late, self);
1282     }
1283 #endif
1284   } // Loop until all nodes have been visited
1285 
1286 } // end ScheduleLate
1287 
1288 //------------------------------GlobalCodeMotion-------------------------------
1289 void PhaseCFG::global_code_motion() {
1290   ResourceMark rm;
1291 
1292 #ifndef PRODUCT
1293   if (trace_opto_pipelining()) {
1294     tty->print("\n---- Start GlobalCodeMotion ----\n");
1295   }
1296 #endif
1297 
1298   // Initialize the node to block mapping for things on the proj_list
1299   for (uint i = 0; i < _matcher.number_of_projections(); i++) {
1300     unmap_node_from_block(_matcher.get_projection(i));
1301   }
1302 
1303   // Set the basic block for Nodes pinned into blocks
1304   Arena* arena = Thread::current()->resource_area();
1305   VectorSet visited(arena);
1306   schedule_pinned_nodes(visited);
1307 
1308   // Find the earliest Block any instruction can be placed in.  Some
1309   // instructions are pinned into Blocks.  Unpinned instructions can
1310   // appear in last block in which all their inputs occur.
1311   visited.Clear();
1312   Node_List stack(arena);
1313   // Pre-grow the list
1314   stack.map((C->live_nodes() >> 1) + 16, NULL);
1315   if (!schedule_early(visited, stack)) {
1316     // Bailout without retry
1317     C->record_method_not_compilable("early schedule failed");
1318     return;
1319   }
1320 
1321   // Build Def-Use edges.
1322   // Compute the latency information (via backwards walk) for all the
1323   // instructions in the graph
1324   _node_latency = new GrowableArray<uint>(); // resource_area allocation
1325 
1326   if (C->do_scheduling()) {
1327     compute_latencies_backwards(visited, stack);
1328   }
1329 
1330   // Now schedule all codes as LATE as possible.  This is the LCA in the
1331   // dominator tree of all USES of a value.  Pick the block with the least
1332   // loop nesting depth that is lowest in the dominator tree.
1333   // ( visited.Clear() called in schedule_late()->Node_Backward_Iterator() )
1334   schedule_late(visited, stack);
1335   if (C->failing()) {
1336     // schedule_late fails only when graph is incorrect.
1337     assert(!VerifyGraphEdges, "verification should have failed");
1338     return;
1339   }
1340 
1341 #ifndef PRODUCT
1342   if (trace_opto_pipelining()) {
1343     tty->print("\n---- Detect implicit null checks ----\n");
1344   }
1345 #endif
1346 
1347   // Detect implicit-null-check opportunities.  Basically, find NULL checks
1348   // with suitable memory ops nearby.  Use the memory op to do the NULL check.
1349   // I can generate a memory op if there is not one nearby.
1350   if (C->is_method_compilation()) {
1351     // By reversing the loop direction we get a very minor gain on mpegaudio.
1352     // Feel free to revert to a forward loop for clarity.
1353     // for( int i=0; i < (int)matcher._null_check_tests.size(); i+=2 ) {
1354     for (int i = _matcher._null_check_tests.size() - 2; i >= 0; i -= 2) {
1355       Node* proj = _matcher._null_check_tests[i];
1356       Node* val  = _matcher._null_check_tests[i + 1];
1357       Block* block = get_block_for_node(proj);
1358       implicit_null_check(block, proj, val, C->allowed_deopt_reasons());
1359       // The implicit_null_check will only perform the transformation
1360       // if the null branch is truly uncommon, *and* it leads to an
1361       // uncommon trap.  Combined with the too_many_traps guards
1362       // above, this prevents SEGV storms reported in 6366351,
1363       // by recompiling offending methods without this optimization.
1364     }
1365   }
1366 
1367   PhaseChaitin regalloc(C->unique(), *this, _matcher, true);
1368   ResourceArea live_arena;      // Arena for liveness
1369   ResourceMark rm_live(&live_arena);
1370   PhaseLive live(*this, regalloc._lrg_map.names(), &live_arena, true);
1371   PhaseIFG ifg(&live_arena);
1372   intptr_t *recalc_pressure_nodes = NULL;
1373 
1374   bool block_size_threshold_ok = false;
1375   if (OptoRegScheduling) {
1376     for (uint i = 0; i < number_of_blocks(); i++) {
1377       Block* block = get_block(i);
1378       if (block->number_of_nodes() > 10) {
1379         block_size_threshold_ok = true;
1380         break;
1381       }
1382     }
1383   }
1384 
1385   // Enabling the scheduler for register pressure plus finding blocks of size to schedule for it
1386   // is key to enabling this feature.
1387   if (OptoRegScheduling && block_size_threshold_ok) {
1388     regalloc.mark_ssa();
1389     Compile::TracePhase tp("computeLive", &timers[_t_computeLive]);
1390     rm_live.reset_to_mark();           // Reclaim working storage
1391     IndexSet::reset_memory(C, &live_arena);
1392     uint node_size = regalloc._lrg_map.max_lrg_id();
1393     ifg.init(node_size); // Empty IFG
1394     regalloc.set_ifg(ifg);
1395     regalloc.set_live(live);
1396     regalloc.gather_lrg_masks(false);    // Collect LRG masks
1397     live.compute(node_size); // Compute liveness
1398 
1399     recalc_pressure_nodes = NEW_RESOURCE_ARRAY(intptr_t, node_size);
1400     for (uint i = 0; i < node_size; i++) {
1401       recalc_pressure_nodes[i] = 0;
1402     }
1403   }
1404 
1405   _regalloc = &regalloc;
1406 
1407 #ifndef PRODUCT
1408   if (trace_opto_pipelining()) {
1409     tty->print("\n---- Start Local Scheduling ----\n");
1410   }
1411 #endif
1412 
1413   // Schedule locally.  Right now a simple topological sort.
1414   // Later, do a real latency aware scheduler.
1415   GrowableArray<int> ready_cnt(C->unique(), C->unique(), -1);
1416   visited.Clear();
1417   for (uint i = 0; i < number_of_blocks(); i++) {
1418     Block* block = get_block(i);
1419     if (!schedule_local(block, ready_cnt, visited, recalc_pressure_nodes)) {
1420       if (!C->failure_reason_is(C2Compiler::retry_no_subsuming_loads())) {
1421         C->record_method_not_compilable("local schedule failed");
1422       }
1423       _regalloc = NULL;
1424       return;
1425     }
1426   }
1427   _regalloc = NULL;
1428 
1429   // If we inserted any instructions between a Call and his CatchNode,
1430   // clone the instructions on all paths below the Catch.
1431   for (uint i = 0; i < number_of_blocks(); i++) {
1432     Block* block = get_block(i);
1433     call_catch_cleanup(block);
1434   }
1435 
1436 #ifndef PRODUCT
1437   if (trace_opto_pipelining()) {
1438     tty->print("\n---- After GlobalCodeMotion ----\n");
1439     for (uint i = 0; i < number_of_blocks(); i++) {
1440       Block* block = get_block(i);
1441       block->dump();
1442     }
1443   }
1444 #endif
1445   // Dead.
1446   _node_latency = (GrowableArray<uint> *)0xdeadbeef;
1447 }
1448 
1449 bool PhaseCFG::do_global_code_motion() {
1450 
1451   build_dominator_tree();
1452   if (C->failing()) {
1453     return false;
1454   }
1455 
1456   NOT_PRODUCT( C->verify_graph_edges(); )
1457 
1458   estimate_block_frequency();
1459 
1460   global_code_motion();
1461 
1462   if (C->failing()) {
1463     return false;
1464   }
1465 
1466   return true;
1467 }
1468 
1469 //------------------------------Estimate_Block_Frequency-----------------------
1470 // Estimate block frequencies based on IfNode probabilities.
1471 void PhaseCFG::estimate_block_frequency() {
1472 
1473   // Force conditional branches leading to uncommon traps to be unlikely,
1474   // not because we get to the uncommon_trap with less relative frequency,
1475   // but because an uncommon_trap typically causes a deopt, so we only get
1476   // there once.
1477   if (C->do_freq_based_layout()) {
1478     Block_List worklist;
1479     Block* root_blk = get_block(0);
1480     for (uint i = 1; i < root_blk->num_preds(); i++) {
1481       Block *pb = get_block_for_node(root_blk->pred(i));
1482       if (pb->has_uncommon_code()) {
1483         worklist.push(pb);
1484       }
1485     }
1486     while (worklist.size() > 0) {
1487       Block* uct = worklist.pop();
1488       if (uct == get_root_block()) {
1489         continue;
1490       }
1491       for (uint i = 1; i < uct->num_preds(); i++) {
1492         Block *pb = get_block_for_node(uct->pred(i));
1493         if (pb->_num_succs == 1) {
1494           worklist.push(pb);
1495         } else if (pb->num_fall_throughs() == 2) {
1496           pb->update_uncommon_branch(uct);
1497         }
1498       }
1499     }
1500   }
1501 
1502   // Create the loop tree and calculate loop depth.
1503   _root_loop = create_loop_tree();
1504   _root_loop->compute_loop_depth(0);
1505 
1506   // Compute block frequency of each block, relative to a single loop entry.
1507   _root_loop->compute_freq();
1508 
1509   // Adjust all frequencies to be relative to a single method entry
1510   _root_loop->_freq = 1.0;
1511   _root_loop->scale_freq();
1512 
1513   // Save outmost loop frequency for LRG frequency threshold
1514   _outer_loop_frequency = _root_loop->outer_loop_freq();
1515 
1516   // force paths ending at uncommon traps to be infrequent
1517   if (!C->do_freq_based_layout()) {
1518     Block_List worklist;
1519     Block* root_blk = get_block(0);
1520     for (uint i = 1; i < root_blk->num_preds(); i++) {
1521       Block *pb = get_block_for_node(root_blk->pred(i));
1522       if (pb->has_uncommon_code()) {
1523         worklist.push(pb);
1524       }
1525     }
1526     while (worklist.size() > 0) {
1527       Block* uct = worklist.pop();
1528       uct->_freq = PROB_MIN;
1529       for (uint i = 1; i < uct->num_preds(); i++) {
1530         Block *pb = get_block_for_node(uct->pred(i));
1531         if (pb->_num_succs == 1 && pb->_freq > PROB_MIN) {
1532           worklist.push(pb);
1533         }
1534       }
1535     }
1536   }
1537 
1538 #ifdef ASSERT
1539   for (uint i = 0; i < number_of_blocks(); i++) {
1540     Block* b = get_block(i);
1541     assert(b->_freq >= MIN_BLOCK_FREQUENCY, "Register Allocator requires meaningful block frequency");
1542   }
1543 #endif
1544 
1545 #ifndef PRODUCT
1546   if (PrintCFGBlockFreq) {
1547     tty->print_cr("CFG Block Frequencies");
1548     _root_loop->dump_tree();
1549     if (Verbose) {
1550       tty->print_cr("PhaseCFG dump");
1551       dump();
1552       tty->print_cr("Node dump");
1553       _root->dump(99999);
1554     }
1555   }
1556 #endif
1557 }
1558 
1559 //----------------------------create_loop_tree--------------------------------
1560 // Create a loop tree from the CFG
1561 CFGLoop* PhaseCFG::create_loop_tree() {
1562 
1563 #ifdef ASSERT
1564   assert(get_block(0) == get_root_block(), "first block should be root block");
1565   for (uint i = 0; i < number_of_blocks(); i++) {
1566     Block* block = get_block(i);
1567     // Check that _loop field are clear...we could clear them if not.
1568     assert(block->_loop == NULL, "clear _loop expected");
1569     // Sanity check that the RPO numbering is reflected in the _blocks array.
1570     // It doesn't have to be for the loop tree to be built, but if it is not,
1571     // then the blocks have been reordered since dom graph building...which
1572     // may question the RPO numbering
1573     assert(block->_rpo == i, "unexpected reverse post order number");
1574   }
1575 #endif
1576 
1577   int idct = 0;
1578   CFGLoop* root_loop = new CFGLoop(idct++);
1579 
1580   Block_List worklist;
1581 
1582   // Assign blocks to loops
1583   for(uint i = number_of_blocks() - 1; i > 0; i-- ) { // skip Root block
1584     Block* block = get_block(i);
1585 
1586     if (block->head()->is_Loop()) {
1587       Block* loop_head = block;
1588       assert(loop_head->num_preds() - 1 == 2, "loop must have 2 predecessors");
1589       Node* tail_n = loop_head->pred(LoopNode::LoopBackControl);
1590       Block* tail = get_block_for_node(tail_n);
1591 
1592       // Defensively filter out Loop nodes for non-single-entry loops.
1593       // For all reasonable loops, the head occurs before the tail in RPO.
1594       if (i <= tail->_rpo) {
1595 
1596         // The tail and (recursive) predecessors of the tail
1597         // are made members of a new loop.
1598 
1599         assert(worklist.size() == 0, "nonempty worklist");
1600         CFGLoop* nloop = new CFGLoop(idct++);
1601         assert(loop_head->_loop == NULL, "just checking");
1602         loop_head->_loop = nloop;
1603         // Add to nloop so push_pred() will skip over inner loops
1604         nloop->add_member(loop_head);
1605         nloop->push_pred(loop_head, LoopNode::LoopBackControl, worklist, this);
1606 
1607         while (worklist.size() > 0) {
1608           Block* member = worklist.pop();
1609           if (member != loop_head) {
1610             for (uint j = 1; j < member->num_preds(); j++) {
1611               nloop->push_pred(member, j, worklist, this);
1612             }
1613           }
1614         }
1615       }
1616     }
1617   }
1618 
1619   // Create a member list for each loop consisting
1620   // of both blocks and (immediate child) loops.
1621   for (uint i = 0; i < number_of_blocks(); i++) {
1622     Block* block = get_block(i);
1623     CFGLoop* lp = block->_loop;
1624     if (lp == NULL) {
1625       // Not assigned to a loop. Add it to the method's pseudo loop.
1626       block->_loop = root_loop;
1627       lp = root_loop;
1628     }
1629     if (lp == root_loop || block != lp->head()) { // loop heads are already members
1630       lp->add_member(block);
1631     }
1632     if (lp != root_loop) {
1633       if (lp->parent() == NULL) {
1634         // Not a nested loop. Make it a child of the method's pseudo loop.
1635         root_loop->add_nested_loop(lp);
1636       }
1637       if (block == lp->head()) {
1638         // Add nested loop to member list of parent loop.
1639         lp->parent()->add_member(lp);
1640       }
1641     }
1642   }
1643 
1644   return root_loop;
1645 }
1646 
1647 //------------------------------push_pred--------------------------------------
1648 void CFGLoop::push_pred(Block* blk, int i, Block_List& worklist, PhaseCFG* cfg) {
1649   Node* pred_n = blk->pred(i);
1650   Block* pred = cfg->get_block_for_node(pred_n);
1651   CFGLoop *pred_loop = pred->_loop;
1652   if (pred_loop == NULL) {
1653     // Filter out blocks for non-single-entry loops.
1654     // For all reasonable loops, the head occurs before the tail in RPO.
1655     if (pred->_rpo > head()->_rpo) {
1656       pred->_loop = this;
1657       worklist.push(pred);
1658     }
1659   } else if (pred_loop != this) {
1660     // Nested loop.
1661     while (pred_loop->_parent != NULL && pred_loop->_parent != this) {
1662       pred_loop = pred_loop->_parent;
1663     }
1664     // Make pred's loop be a child
1665     if (pred_loop->_parent == NULL) {
1666       add_nested_loop(pred_loop);
1667       // Continue with loop entry predecessor.
1668       Block* pred_head = pred_loop->head();
1669       assert(pred_head->num_preds() - 1 == 2, "loop must have 2 predecessors");
1670       assert(pred_head != head(), "loop head in only one loop");
1671       push_pred(pred_head, LoopNode::EntryControl, worklist, cfg);
1672     } else {
1673       assert(pred_loop->_parent == this && _parent == NULL, "just checking");
1674     }
1675   }
1676 }
1677 
1678 //------------------------------add_nested_loop--------------------------------
1679 // Make cl a child of the current loop in the loop tree.
1680 void CFGLoop::add_nested_loop(CFGLoop* cl) {
1681   assert(_parent == NULL, "no parent yet");
1682   assert(cl != this, "not my own parent");
1683   cl->_parent = this;
1684   CFGLoop* ch = _child;
1685   if (ch == NULL) {
1686     _child = cl;
1687   } else {
1688     while (ch->_sibling != NULL) { ch = ch->_sibling; }
1689     ch->_sibling = cl;
1690   }
1691 }
1692 
1693 //------------------------------compute_loop_depth-----------------------------
1694 // Store the loop depth in each CFGLoop object.
1695 // Recursively walk the children to do the same for them.
1696 void CFGLoop::compute_loop_depth(int depth) {
1697   _depth = depth;
1698   CFGLoop* ch = _child;
1699   while (ch != NULL) {
1700     ch->compute_loop_depth(depth + 1);
1701     ch = ch->_sibling;
1702   }
1703 }
1704 
1705 //------------------------------compute_freq-----------------------------------
1706 // Compute the frequency of each block and loop, relative to a single entry
1707 // into the dominating loop head.
1708 void CFGLoop::compute_freq() {
1709   // Bottom up traversal of loop tree (visit inner loops first.)
1710   // Set loop head frequency to 1.0, then transitively
1711   // compute frequency for all successors in the loop,
1712   // as well as for each exit edge.  Inner loops are
1713   // treated as single blocks with loop exit targets
1714   // as the successor blocks.
1715 
1716   // Nested loops first
1717   CFGLoop* ch = _child;
1718   while (ch != NULL) {
1719     ch->compute_freq();
1720     ch = ch->_sibling;
1721   }
1722   assert (_members.length() > 0, "no empty loops");
1723   Block* hd = head();
1724   hd->_freq = 1.0;
1725   for (int i = 0; i < _members.length(); i++) {
1726     CFGElement* s = _members.at(i);
1727     double freq = s->_freq;
1728     if (s->is_block()) {
1729       Block* b = s->as_Block();
1730       for (uint j = 0; j < b->_num_succs; j++) {
1731         Block* sb = b->_succs[j];
1732         update_succ_freq(sb, freq * b->succ_prob(j));
1733       }
1734     } else {
1735       CFGLoop* lp = s->as_CFGLoop();
1736       assert(lp->_parent == this, "immediate child");
1737       for (int k = 0; k < lp->_exits.length(); k++) {
1738         Block* eb = lp->_exits.at(k).get_target();
1739         double prob = lp->_exits.at(k).get_prob();
1740         update_succ_freq(eb, freq * prob);
1741       }
1742     }
1743   }
1744 
1745   // For all loops other than the outer, "method" loop,
1746   // sum and normalize the exit probability. The "method" loop
1747   // should keep the initial exit probability of 1, so that
1748   // inner blocks do not get erroneously scaled.
1749   if (_depth != 0) {
1750     // Total the exit probabilities for this loop.
1751     double exits_sum = 0.0f;
1752     for (int i = 0; i < _exits.length(); i++) {
1753       exits_sum += _exits.at(i).get_prob();
1754     }
1755 
1756     // Normalize the exit probabilities. Until now, the
1757     // probabilities estimate the possibility of exit per
1758     // a single loop iteration; afterward, they estimate
1759     // the probability of exit per loop entry.
1760     for (int i = 0; i < _exits.length(); i++) {
1761       Block* et = _exits.at(i).get_target();
1762       float new_prob = 0.0f;
1763       if (_exits.at(i).get_prob() > 0.0f) {
1764         new_prob = _exits.at(i).get_prob() / exits_sum;
1765       }
1766       BlockProbPair bpp(et, new_prob);
1767       _exits.at_put(i, bpp);
1768     }
1769 
1770     // Save the total, but guard against unreasonable probability,
1771     // as the value is used to estimate the loop trip count.
1772     // An infinite trip count would blur relative block
1773     // frequencies.
1774     if (exits_sum > 1.0f) exits_sum = 1.0;
1775     if (exits_sum < PROB_MIN) exits_sum = PROB_MIN;
1776     _exit_prob = exits_sum;
1777   }
1778 }
1779 
1780 //------------------------------succ_prob-------------------------------------
1781 // Determine the probability of reaching successor 'i' from the receiver block.
1782 float Block::succ_prob(uint i) {
1783   int eidx = end_idx();
1784   Node *n = get_node(eidx);  // Get ending Node
1785 
1786   int op = n->Opcode();
1787   if (n->is_Mach()) {
1788     if (n->is_MachNullCheck()) {
1789       // Can only reach here if called after lcm. The original Op_If is gone,
1790       // so we attempt to infer the probability from one or both of the
1791       // successor blocks.
1792       assert(_num_succs == 2, "expecting 2 successors of a null check");
1793       // If either successor has only one predecessor, then the
1794       // probability estimate can be derived using the
1795       // relative frequency of the successor and this block.
1796       if (_succs[i]->num_preds() == 2) {
1797         return _succs[i]->_freq / _freq;
1798       } else if (_succs[1-i]->num_preds() == 2) {
1799         return 1 - (_succs[1-i]->_freq / _freq);
1800       } else {
1801         // Estimate using both successor frequencies
1802         float freq = _succs[i]->_freq;
1803         return freq / (freq + _succs[1-i]->_freq);
1804       }
1805     }
1806     op = n->as_Mach()->ideal_Opcode();
1807   }
1808 
1809 
1810   // Switch on branch type
1811   switch( op ) {
1812   case Op_CountedLoopEnd:
1813   case Op_If: {
1814     assert (i < 2, "just checking");
1815     // Conditionals pass on only part of their frequency
1816     float prob  = n->as_MachIf()->_prob;
1817     assert(prob >= 0.0 && prob <= 1.0, "out of range probability");
1818     // If succ[i] is the FALSE branch, invert path info
1819     if( get_node(i + eidx + 1)->Opcode() == Op_IfFalse ) {
1820       return 1.0f - prob; // not taken
1821     } else {
1822       return prob; // taken
1823     }
1824   }
1825 
1826   case Op_Jump:
1827     // Divide the frequency between all successors evenly
1828     return 1.0f/_num_succs;
1829 
1830   case Op_Catch: {
1831     const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();
1832     if (ci->_con == CatchProjNode::fall_through_index) {
1833       // Fall-thru path gets the lion's share.
1834       return 1.0f - PROB_UNLIKELY_MAG(5)*_num_succs;
1835     } else {
1836       // Presume exceptional paths are equally unlikely
1837       return PROB_UNLIKELY_MAG(5);
1838     }
1839   }
1840 
1841   case Op_Root:
1842   case Op_Goto:
1843     // Pass frequency straight thru to target
1844     return 1.0f;
1845 
1846   case Op_NeverBranch:
1847     return 0.0f;
1848 
1849   case Op_TailCall:
1850   case Op_TailJump:
1851   case Op_Return:
1852   case Op_Halt:
1853   case Op_Rethrow:
1854     // Do not push out freq to root block
1855     return 0.0f;
1856 
1857   default:
1858     ShouldNotReachHere();
1859   }
1860 
1861   return 0.0f;
1862 }
1863 
1864 //------------------------------num_fall_throughs-----------------------------
1865 // Return the number of fall-through candidates for a block
1866 int Block::num_fall_throughs() {
1867   int eidx = end_idx();
1868   Node *n = get_node(eidx);  // Get ending Node
1869 
1870   int op = n->Opcode();
1871   if (n->is_Mach()) {
1872     if (n->is_MachNullCheck()) {
1873       // In theory, either side can fall-thru, for simplicity sake,
1874       // let's say only the false branch can now.
1875       return 1;
1876     }
1877     op = n->as_Mach()->ideal_Opcode();
1878   }
1879 
1880   // Switch on branch type
1881   switch( op ) {
1882   case Op_CountedLoopEnd:
1883   case Op_If:
1884     return 2;
1885 
1886   case Op_Root:
1887   case Op_Goto:
1888     return 1;
1889 
1890   case Op_Catch: {
1891     for (uint i = 0; i < _num_succs; i++) {
1892       const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();
1893       if (ci->_con == CatchProjNode::fall_through_index) {
1894         return 1;
1895       }
1896     }
1897     return 0;
1898   }
1899 
1900   case Op_Jump:
1901   case Op_NeverBranch:
1902   case Op_TailCall:
1903   case Op_TailJump:
1904   case Op_Return:
1905   case Op_Halt:
1906   case Op_Rethrow:
1907     return 0;
1908 
1909   default:
1910     ShouldNotReachHere();
1911   }
1912 
1913   return 0;
1914 }
1915 
1916 //------------------------------succ_fall_through-----------------------------
1917 // Return true if a specific successor could be fall-through target.
1918 bool Block::succ_fall_through(uint i) {
1919   int eidx = end_idx();
1920   Node *n = get_node(eidx);  // Get ending Node
1921 
1922   int op = n->Opcode();
1923   if (n->is_Mach()) {
1924     if (n->is_MachNullCheck()) {
1925       // In theory, either side can fall-thru, for simplicity sake,
1926       // let's say only the false branch can now.
1927       return get_node(i + eidx + 1)->Opcode() == Op_IfFalse;
1928     }
1929     op = n->as_Mach()->ideal_Opcode();
1930   }
1931 
1932   // Switch on branch type
1933   switch( op ) {
1934   case Op_CountedLoopEnd:
1935   case Op_If:
1936   case Op_Root:
1937   case Op_Goto:
1938     return true;
1939 
1940   case Op_Catch: {
1941     const CatchProjNode *ci = get_node(i + eidx + 1)->as_CatchProj();
1942     return ci->_con == CatchProjNode::fall_through_index;
1943   }
1944 
1945   case Op_Jump:
1946   case Op_NeverBranch:
1947   case Op_TailCall:
1948   case Op_TailJump:
1949   case Op_Return:
1950   case Op_Halt:
1951   case Op_Rethrow:
1952     return false;
1953 
1954   default:
1955     ShouldNotReachHere();
1956   }
1957 
1958   return false;
1959 }
1960 
1961 //------------------------------update_uncommon_branch------------------------
1962 // Update the probability of a two-branch to be uncommon
1963 void Block::update_uncommon_branch(Block* ub) {
1964   int eidx = end_idx();
1965   Node *n = get_node(eidx);  // Get ending Node
1966 
1967   int op = n->as_Mach()->ideal_Opcode();
1968 
1969   assert(op == Op_CountedLoopEnd || op == Op_If, "must be a If");
1970   assert(num_fall_throughs() == 2, "must be a two way branch block");
1971 
1972   // Which successor is ub?
1973   uint s;
1974   for (s = 0; s <_num_succs; s++) {
1975     if (_succs[s] == ub) break;
1976   }
1977   assert(s < 2, "uncommon successor must be found");
1978 
1979   // If ub is the true path, make the proability small, else
1980   // ub is the false path, and make the probability large
1981   bool invert = (get_node(s + eidx + 1)->Opcode() == Op_IfFalse);
1982 
1983   // Get existing probability
1984   float p = n->as_MachIf()->_prob;
1985 
1986   if (invert) p = 1.0 - p;
1987   if (p > PROB_MIN) {
1988     p = PROB_MIN;
1989   }
1990   if (invert) p = 1.0 - p;
1991 
1992   n->as_MachIf()->_prob = p;
1993 }
1994 
1995 //------------------------------update_succ_freq-------------------------------
1996 // Update the appropriate frequency associated with block 'b', a successor of
1997 // a block in this loop.
1998 void CFGLoop::update_succ_freq(Block* b, double freq) {
1999   if (b->_loop == this) {
2000     if (b == head()) {
2001       // back branch within the loop
2002       // Do nothing now, the loop carried frequency will be
2003       // adjust later in scale_freq().
2004     } else {
2005       // simple branch within the loop
2006       b->_freq += freq;
2007     }
2008   } else if (!in_loop_nest(b)) {
2009     // branch is exit from this loop
2010     BlockProbPair bpp(b, freq);
2011     _exits.append(bpp);
2012   } else {
2013     // branch into nested loop
2014     CFGLoop* ch = b->_loop;
2015     ch->_freq += freq;
2016   }
2017 }
2018 
2019 //------------------------------in_loop_nest-----------------------------------
2020 // Determine if block b is in the receiver's loop nest.
2021 bool CFGLoop::in_loop_nest(Block* b) {
2022   int depth = _depth;
2023   CFGLoop* b_loop = b->_loop;
2024   int b_depth = b_loop->_depth;
2025   if (depth == b_depth) {
2026     return true;
2027   }
2028   while (b_depth > depth) {
2029     b_loop = b_loop->_parent;
2030     b_depth = b_loop->_depth;
2031   }
2032   return b_loop == this;
2033 }
2034 
2035 //------------------------------scale_freq-------------------------------------
2036 // Scale frequency of loops and blocks by trip counts from outer loops
2037 // Do a top down traversal of loop tree (visit outer loops first.)
2038 void CFGLoop::scale_freq() {
2039   double loop_freq = _freq * trip_count();
2040   _freq = loop_freq;
2041   for (int i = 0; i < _members.length(); i++) {
2042     CFGElement* s = _members.at(i);
2043     double block_freq = s->_freq * loop_freq;
2044     if (g_isnan(block_freq) || block_freq < MIN_BLOCK_FREQUENCY)
2045       block_freq = MIN_BLOCK_FREQUENCY;
2046     s->_freq = block_freq;
2047   }
2048   CFGLoop* ch = _child;
2049   while (ch != NULL) {
2050     ch->scale_freq();
2051     ch = ch->_sibling;
2052   }
2053 }
2054 
2055 // Frequency of outer loop
2056 double CFGLoop::outer_loop_freq() const {
2057   if (_child != NULL) {
2058     return _child->_freq;
2059   }
2060   return _freq;
2061 }
2062 
2063 #ifndef PRODUCT
2064 //------------------------------dump_tree--------------------------------------
2065 void CFGLoop::dump_tree() const {
2066   dump();
2067   if (_child != NULL)   _child->dump_tree();
2068   if (_sibling != NULL) _sibling->dump_tree();
2069 }
2070 
2071 //------------------------------dump-------------------------------------------
2072 void CFGLoop::dump() const {
2073   for (int i = 0; i < _depth; i++) tty->print("   ");
2074   tty->print("%s: %d  trip_count: %6.0f freq: %6.0f\n",
2075              _depth == 0 ? "Method" : "Loop", _id, trip_count(), _freq);
2076   for (int i = 0; i < _depth; i++) tty->print("   ");
2077   tty->print("         members:");
2078   int k = 0;
2079   for (int i = 0; i < _members.length(); i++) {
2080     if (k++ >= 6) {
2081       tty->print("\n              ");
2082       for (int j = 0; j < _depth+1; j++) tty->print("   ");
2083       k = 0;
2084     }
2085     CFGElement *s = _members.at(i);
2086     if (s->is_block()) {
2087       Block *b = s->as_Block();
2088       tty->print(" B%d(%6.3f)", b->_pre_order, b->_freq);
2089     } else {
2090       CFGLoop* lp = s->as_CFGLoop();
2091       tty->print(" L%d(%6.3f)", lp->_id, lp->_freq);
2092     }
2093   }
2094   tty->print("\n");
2095   for (int i = 0; i < _depth; i++) tty->print("   ");
2096   tty->print("         exits:  ");
2097   k = 0;
2098   for (int i = 0; i < _exits.length(); i++) {
2099     if (k++ >= 7) {
2100       tty->print("\n              ");
2101       for (int j = 0; j < _depth+1; j++) tty->print("   ");
2102       k = 0;
2103     }
2104     Block *blk = _exits.at(i).get_target();
2105     double prob = _exits.at(i).get_prob();
2106     tty->print(" ->%d@%d%%", blk->_pre_order, (int)(prob*100));
2107   }
2108   tty->print("\n");
2109 }
2110 #endif