1 /*
   2  * Copyright (c) 2011, 2018, 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 "opto/loopnode.hpp"
  27 #include "opto/addnode.hpp"
  28 #include "opto/callnode.hpp"
  29 #include "opto/connode.hpp"
  30 #include "opto/convertnode.hpp"
  31 #include "opto/loopnode.hpp"
  32 #include "opto/matcher.hpp"
  33 #include "opto/mulnode.hpp"
  34 #include "opto/opaquenode.hpp"
  35 #include "opto/rootnode.hpp"
  36 #include "opto/subnode.hpp"
  37 #include <fenv.h>
  38 #include <math.h>
  39 
  40 /*
  41  * The general idea of Loop Predication is to insert a predicate on the entry
  42  * path to a loop, and raise a uncommon trap if the check of the condition fails.
  43  * The condition checks are promoted from inside the loop body, and thus
  44  * the checks inside the loop could be eliminated. Currently, loop predication
  45  * optimization has been applied to remove array range check and loop invariant
  46  * checks (such as null checks).
  47 */
  48 
  49 //-------------------------------register_control-------------------------
  50 void PhaseIdealLoop::register_control(Node* n, IdealLoopTree *loop, Node* pred) {
  51   assert(n->is_CFG(), "must be control node");
  52   _igvn.register_new_node_with_optimizer(n);
  53   loop->_body.push(n);
  54   set_loop(n, loop);
  55   // When called from beautify_loops() idom is not constructed yet.
  56   if (_idom != NULL) {
  57     set_idom(n, pred, dom_depth(pred));
  58   }
  59 }
  60 
  61 //------------------------------create_new_if_for_predicate------------------------
  62 // create a new if above the uct_if_pattern for the predicate to be promoted.
  63 //
  64 //          before                                after
  65 //        ----------                           ----------
  66 //           ctrl                                 ctrl
  67 //            |                                     |
  68 //            |                                     |
  69 //            v                                     v
  70 //           iff                                 new_iff
  71 //          /    \                                /      \
  72 //         /      \                              /        \
  73 //        v        v                            v          v
  74 //  uncommon_proj cont_proj                   if_uct     if_cont
  75 // \      |        |                           |          |
  76 //  \     |        |                           |          |
  77 //   v    v        v                           |          v
  78 //     rgn       loop                          |         iff
  79 //      |                                      |        /     \
  80 //      |                                      |       /       \
  81 //      v                                      |      v         v
  82 // uncommon_trap                               | uncommon_proj cont_proj
  83 //                                           \  \    |           |
  84 //                                            \  \   |           |
  85 //                                             v  v  v           v
  86 //                                               rgn           loop
  87 //                                                |
  88 //                                                |
  89 //                                                v
  90 //                                           uncommon_trap
  91 //
  92 //
  93 // We will create a region to guard the uct call if there is no one there.
  94 // The true projection (if_cont) of the new_iff is returned.
  95 // This code is also used to clone predicates to cloned loops.
  96 ProjNode* PhaseIdealLoop::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry,
  97                                                       Deoptimization::DeoptReason reason,
  98                                                       int opcode) {
  99   assert(cont_proj->is_uncommon_trap_if_pattern(reason), "must be a uct if pattern!");
 100   IfNode* iff = cont_proj->in(0)->as_If();
 101 
 102   ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con);
 103   Node     *rgn   = uncommon_proj->unique_ctrl_out();
 104   assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
 105 
 106   uint proj_index = 1; // region's edge corresponding to uncommon_proj
 107   if (!rgn->is_Region()) { // create a region to guard the call
 108     assert(rgn->is_Call(), "must be call uct");
 109     CallNode* call = rgn->as_Call();
 110     IdealLoopTree* loop = get_loop(call);
 111     rgn = new RegionNode(1);
 112     rgn->add_req(uncommon_proj);
 113     register_control(rgn, loop, uncommon_proj);
 114     _igvn.replace_input_of(call, 0, rgn);
 115     // When called from beautify_loops() idom is not constructed yet.
 116     if (_idom != NULL) {
 117       set_idom(call, rgn, dom_depth(rgn));
 118     }
 119     for (DUIterator_Fast imax, i = uncommon_proj->fast_outs(imax); i < imax; i++) {
 120       Node* n = uncommon_proj->fast_out(i);
 121       if (n->is_Load() || n->is_Store()) {
 122         _igvn.replace_input_of(n, 0, rgn);
 123         --i; --imax;
 124       }
 125     }
 126   } else {
 127     // Find region's edge corresponding to uncommon_proj
 128     for (; proj_index < rgn->req(); proj_index++)
 129       if (rgn->in(proj_index) == uncommon_proj) break;
 130     assert(proj_index < rgn->req(), "sanity");
 131   }
 132 
 133   Node* entry = iff->in(0);
 134   if (new_entry != NULL) {
 135     // Clonning the predicate to new location.
 136     entry = new_entry;
 137   }
 138   // Create new_iff
 139   IdealLoopTree* lp = get_loop(entry);
 140   IfNode* new_iff = NULL;
 141   if (opcode == Op_If) {
 142     new_iff = new IfNode(entry, iff->in(1), iff->_prob, iff->_fcnt);
 143   } else {
 144     assert(opcode == Op_RangeCheck, "no other if variant here");
 145     new_iff = new RangeCheckNode(entry, iff->in(1), iff->_prob, iff->_fcnt);
 146   }
 147   register_control(new_iff, lp, entry);
 148   Node *if_cont = new IfTrueNode(new_iff);
 149   Node *if_uct  = new IfFalseNode(new_iff);
 150   if (cont_proj->is_IfFalse()) {
 151     // Swap
 152     Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp;
 153   }
 154   register_control(if_cont, lp, new_iff);
 155   register_control(if_uct, get_loop(rgn), new_iff);
 156 
 157   // if_uct to rgn
 158   _igvn.hash_delete(rgn);
 159   rgn->add_req(if_uct);
 160   // When called from beautify_loops() idom is not constructed yet.
 161   if (_idom != NULL) {
 162     Node* ridom = idom(rgn);
 163     Node* nrdom = dom_lca_internal(ridom, new_iff);
 164     set_idom(rgn, nrdom, dom_depth(rgn));
 165   }
 166 
 167   // If rgn has phis add new edges which has the same
 168   // value as on original uncommon_proj pass.
 169   assert(rgn->in(rgn->req() -1) == if_uct, "new edge should be last");
 170   bool has_phi = false;
 171   for (DUIterator_Fast imax, i = rgn->fast_outs(imax); i < imax; i++) {
 172     Node* use = rgn->fast_out(i);
 173     if (use->is_Phi() && use->outcnt() > 0) {
 174       assert(use->in(0) == rgn, "");
 175       _igvn.rehash_node_delayed(use);
 176       use->add_req(use->in(proj_index));
 177       has_phi = true;
 178     }
 179   }
 180   assert(!has_phi || rgn->req() > 3, "no phis when region is created");
 181 
 182   if (new_entry == NULL) {
 183     // Attach if_cont to iff
 184     _igvn.replace_input_of(iff, 0, if_cont);
 185     if (_idom != NULL) {
 186       set_idom(iff, if_cont, dom_depth(iff));
 187     }
 188   }
 189   return if_cont->as_Proj();
 190 }
 191 
 192 //------------------------------create_new_if_for_predicate------------------------
 193 // Create a new if below new_entry for the predicate to be cloned (IGVN optimization)
 194 ProjNode* PhaseIterGVN::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry,
 195                                                     Deoptimization::DeoptReason reason,
 196                                                     int opcode) {
 197   assert(new_entry != 0, "only used for clone predicate");
 198   assert(cont_proj->is_uncommon_trap_if_pattern(reason), "must be a uct if pattern!");
 199   IfNode* iff = cont_proj->in(0)->as_If();
 200 
 201   ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con);
 202   Node     *rgn   = uncommon_proj->unique_ctrl_out();
 203   assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
 204 
 205   uint proj_index = 1; // region's edge corresponding to uncommon_proj
 206   if (!rgn->is_Region()) { // create a region to guard the call
 207     assert(rgn->is_Call(), "must be call uct");
 208     CallNode* call = rgn->as_Call();
 209     rgn = new RegionNode(1);
 210     register_new_node_with_optimizer(rgn);
 211     rgn->add_req(uncommon_proj);
 212     replace_input_of(call, 0, rgn);
 213   } else {
 214     // Find region's edge corresponding to uncommon_proj
 215     for (; proj_index < rgn->req(); proj_index++)
 216       if (rgn->in(proj_index) == uncommon_proj) break;
 217     assert(proj_index < rgn->req(), "sanity");
 218   }
 219 
 220   // Create new_iff in new location.
 221   IfNode* new_iff = NULL;
 222   if (opcode == Op_If) {
 223     new_iff = new IfNode(new_entry, iff->in(1), iff->_prob, iff->_fcnt);
 224   } else {
 225     assert(opcode == Op_RangeCheck, "no other if variant here");
 226     new_iff = new RangeCheckNode(new_entry, iff->in(1), iff->_prob, iff->_fcnt);
 227   }
 228 
 229   register_new_node_with_optimizer(new_iff);
 230   Node *if_cont = new IfTrueNode(new_iff);
 231   Node *if_uct  = new IfFalseNode(new_iff);
 232   if (cont_proj->is_IfFalse()) {
 233     // Swap
 234     Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp;
 235   }
 236   register_new_node_with_optimizer(if_cont);
 237   register_new_node_with_optimizer(if_uct);
 238 
 239   // if_uct to rgn
 240   hash_delete(rgn);
 241   rgn->add_req(if_uct);
 242 
 243   // If rgn has phis add corresponding new edges which has the same
 244   // value as on original uncommon_proj pass.
 245   assert(rgn->in(rgn->req() -1) == if_uct, "new edge should be last");
 246   bool has_phi = false;
 247   for (DUIterator_Fast imax, i = rgn->fast_outs(imax); i < imax; i++) {
 248     Node* use = rgn->fast_out(i);
 249     if (use->is_Phi() && use->outcnt() > 0) {
 250       rehash_node_delayed(use);
 251       use->add_req(use->in(proj_index));
 252       has_phi = true;
 253     }
 254   }
 255   assert(!has_phi || rgn->req() > 3, "no phis when region is created");
 256 
 257   return if_cont->as_Proj();
 258 }
 259 
 260 //--------------------------clone_predicate-----------------------
 261 ProjNode* PhaseIdealLoop::clone_predicate(ProjNode* predicate_proj, Node* new_entry,
 262                                           Deoptimization::DeoptReason reason,
 263                                           PhaseIdealLoop* loop_phase,
 264                                           PhaseIterGVN* igvn) {
 265   ProjNode* new_predicate_proj;
 266   if (loop_phase != NULL) {
 267     new_predicate_proj = loop_phase->create_new_if_for_predicate(predicate_proj, new_entry, reason, Op_If);
 268   } else {
 269     new_predicate_proj =       igvn->create_new_if_for_predicate(predicate_proj, new_entry, reason, Op_If);
 270   }
 271   IfNode* iff = new_predicate_proj->in(0)->as_If();
 272   Node* ctrl  = iff->in(0);
 273 
 274   // Match original condition since predicate's projections could be swapped.
 275   assert(predicate_proj->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
 276   Node* opq = new Opaque1Node(igvn->C, predicate_proj->in(0)->in(1)->in(1)->in(1));
 277   igvn->C->add_predicate_opaq(opq);
 278 
 279   Node* bol = new Conv2BNode(opq);
 280   if (loop_phase != NULL) {
 281     loop_phase->register_new_node(opq, ctrl);
 282     loop_phase->register_new_node(bol, ctrl);
 283   } else {
 284     igvn->register_new_node_with_optimizer(opq);
 285     igvn->register_new_node_with_optimizer(bol);
 286   }
 287   igvn->hash_delete(iff);
 288   iff->set_req(1, bol);
 289   return new_predicate_proj;
 290 }
 291 
 292 
 293 //--------------------------clone_loop_predicates-----------------------
 294 // Interface from IGVN
 295 Node* PhaseIterGVN::clone_loop_predicates(Node* old_entry, Node* new_entry, bool clone_limit_check) {
 296   return PhaseIdealLoop::clone_loop_predicates(old_entry, new_entry, clone_limit_check, NULL, this);
 297 }
 298 
 299 // Interface from PhaseIdealLoop
 300 Node* PhaseIdealLoop::clone_loop_predicates(Node* old_entry, Node* new_entry, bool clone_limit_check) {
 301   return clone_loop_predicates(old_entry, new_entry, clone_limit_check, this, &this->_igvn);
 302 }
 303 
 304 void PhaseIdealLoop::clone_loop_predicates_fix_mem(ProjNode* dom_proj , ProjNode* proj,
 305                                                    PhaseIdealLoop* loop_phase,
 306                                                    PhaseIterGVN* igvn) {
 307   if (!UseShenandoahGC) {
 308     return;
 309   }
 310   Compile* C = NULL;
 311   if (loop_phase != NULL) {
 312     igvn = &loop_phase->igvn();
 313   }
 314   C = igvn->C;
 315   ProjNode* other_dom_proj = dom_proj->in(0)->as_Multi()->proj_out(1-dom_proj->_con);
 316   Node* dom_r = other_dom_proj->unique_ctrl_out();
 317   if (dom_r->is_Region()) {
 318     assert(dom_r->unique_ctrl_out()->is_Call(), "unc expected");
 319     ProjNode* other_proj = proj->in(0)->as_Multi()->proj_out(1-proj->_con);
 320     Node* r = other_proj->unique_ctrl_out();
 321     assert(r->is_Region() && r->unique_ctrl_out()->is_Call(), "cloned predicate should have caused region to be added");
 322     for (DUIterator_Fast imax, i = dom_r->fast_outs(imax); i < imax; i++) {
 323       Node* dom_use = dom_r->fast_out(i);
 324       if (dom_use->is_Phi() && dom_use->bottom_type() == Type::MEMORY) {
 325         assert(dom_use->in(0) == dom_r, "");
 326         Node* phi = NULL;
 327         for (DUIterator_Fast jmax, j = r->fast_outs(jmax); j < jmax; j++) {
 328           Node* use = r->fast_out(j);
 329           if (use->is_Phi() && use->bottom_type() == Type::MEMORY &&
 330               use->adr_type() == dom_use->adr_type()) {
 331             assert(use->in(0) == r, "");
 332             assert(phi == NULL, "only one phi");
 333             phi = use;
 334           }
 335         }
 336         if (phi == NULL) {
 337           const TypePtr* adr_type = dom_use->adr_type();
 338           int alias = C->get_alias_index(adr_type);
 339           Node* call = r->unique_ctrl_out();
 340           Node* mem = call->in(TypeFunc::Memory);
 341           MergeMemNode* mm = NULL;
 342           if (mem->is_MergeMem()) {
 343             mm = mem->clone()->as_MergeMem();
 344             if (adr_type == TypePtr::BOTTOM) {
 345               mem = mem->as_MergeMem()->base_memory();
 346             } else {
 347               mem = mem->as_MergeMem()->memory_at(alias);
 348             }
 349           } else {
 350             mm = MergeMemNode::make(mem);
 351           }
 352           phi = PhiNode::make(r, mem, Type::MEMORY, adr_type);
 353           if (adr_type == TypePtr::BOTTOM) {
 354             mm->set_base_memory(phi);
 355           } else {
 356             mm->set_memory_at(alias, phi);
 357           }
 358           if (loop_phase != NULL) {
 359             loop_phase->register_new_node(mm, r);
 360             loop_phase->register_new_node(phi, r);
 361           } else {
 362             igvn->register_new_node_with_optimizer(mm);
 363             igvn->register_new_node_with_optimizer(phi);
 364           }
 365           igvn->replace_input_of(call, TypeFunc::Memory, mm);
 366         }
 367         igvn->replace_input_of(phi, r->req()-1, dom_use->in(dom_r->find_edge(other_dom_proj)));
 368       }
 369     }
 370   }
 371 }
 372 
 373 
 374 // Clone loop predicates to cloned loops (peeled, unswitched, split_if).
 375 Node* PhaseIdealLoop::clone_loop_predicates(Node* old_entry, Node* new_entry,
 376                                             bool clone_limit_check,
 377                                             PhaseIdealLoop* loop_phase,
 378                                             PhaseIterGVN* igvn) {
 379 #ifdef ASSERT
 380   if (new_entry == NULL || !(new_entry->is_Proj() || new_entry->is_Region() || new_entry->is_SafePoint())) {
 381     if (new_entry != NULL)
 382       new_entry->dump();
 383     assert(false, "not IfTrue, IfFalse, Region or SafePoint");
 384   }
 385 #endif
 386   // Search original predicates
 387   Node* entry = old_entry;
 388   ProjNode* limit_check_proj = NULL;
 389   limit_check_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
 390   if (limit_check_proj != NULL) {
 391     entry = skip_loop_predicates(entry);
 392   }
 393   ProjNode* profile_predicate_proj = NULL;
 394   ProjNode* predicate_proj = NULL;
 395   if (UseProfiledLoopPredicate) {
 396     profile_predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
 397     if (profile_predicate_proj != NULL) {
 398       entry = skip_loop_predicates(entry);
 399     }
 400   }
 401   if (UseLoopPredicate) {
 402     predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
 403   }
 404   if (predicate_proj != NULL) { // right pattern that can be used by loop predication
 405     // clone predicate
 406     ProjNode* proj = clone_predicate(predicate_proj, new_entry,
 407                                      Deoptimization::Reason_predicate,
 408                                      loop_phase, igvn);
 409     assert(proj != NULL, "IfTrue or IfFalse after clone predicate");
 410     new_entry = proj;
 411     if (TraceLoopPredicate) {
 412       tty->print("Loop Predicate cloned: ");
 413       debug_only( new_entry->in(0)->dump(); );
 414     }
 415     if (profile_predicate_proj != NULL) {
 416       // A node that produces memory may be out of loop and depend on
 417       // a profiled predicates. In that case the memory state at the
 418       // end of profiled predicates and at the end of predicates are
 419       // not the same. The cloned predicates are dominated by the
 420       // profiled predicates but may have the wrong memory
 421       // state. Update it.
 422       clone_loop_predicates_fix_mem(profile_predicate_proj, proj, loop_phase, igvn);
 423     }
 424   }
 425   if (profile_predicate_proj != NULL) { // right pattern that can be used by loop predication
 426     // clone predicate
 427     new_entry = clone_predicate(profile_predicate_proj, new_entry,
 428                                 Deoptimization::Reason_profile_predicate,
 429                                 loop_phase, igvn);
 430     assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone predicate");
 431     if (TraceLoopPredicate) {
 432       tty->print("Loop Predicate cloned: ");
 433       debug_only( new_entry->in(0)->dump(); );
 434     }
 435   }
 436   if (limit_check_proj != NULL && clone_limit_check) {
 437     // Clone loop limit check last to insert it before loop.
 438     // Don't clone a limit check which was already finalized
 439     // for this counted loop (only one limit check is needed).
 440     new_entry = clone_predicate(limit_check_proj, new_entry,
 441                                 Deoptimization::Reason_loop_limit_check,
 442                                 loop_phase, igvn);
 443     assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone limit check");
 444     if (TraceLoopLimitCheck) {
 445       tty->print("Loop Limit Check cloned: ");
 446       debug_only( new_entry->in(0)->dump(); )
 447     }
 448   }
 449   return new_entry;
 450 }
 451 
 452 //--------------------------skip_loop_predicates------------------------------
 453 // Skip related predicates.
 454 Node* PhaseIdealLoop::skip_loop_predicates(Node* entry) {
 455   IfNode* iff = entry->in(0)->as_If();
 456   ProjNode* uncommon_proj = iff->proj_out(1 - entry->as_Proj()->_con);
 457   Node* rgn = uncommon_proj->unique_ctrl_out();
 458   assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
 459   entry = entry->in(0)->in(0);
 460   while (entry != NULL && entry->is_Proj() && entry->in(0)->is_If()) {
 461     uncommon_proj = entry->in(0)->as_If()->proj_out(1 - entry->as_Proj()->_con);
 462     if (uncommon_proj->unique_ctrl_out() != rgn)
 463       break;
 464     entry = entry->in(0)->in(0);
 465   }
 466   return entry;
 467 }
 468 
 469 Node* PhaseIdealLoop::skip_all_loop_predicates(Node* entry) {
 470   Node* predicate = NULL;
 471   predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
 472   if (predicate != NULL) {
 473     entry = skip_loop_predicates(entry);
 474   }
 475   if (UseProfiledLoopPredicate) {
 476     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
 477     if (predicate != NULL) { // right pattern that can be used by loop predication
 478       entry = skip_loop_predicates(entry);
 479     }
 480   }
 481   if (UseLoopPredicate) {
 482     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
 483     if (predicate != NULL) { // right pattern that can be used by loop predication
 484       entry = skip_loop_predicates(entry);
 485     }
 486   }
 487   return entry;
 488 }
 489 
 490 //--------------------------find_predicate_insertion_point-------------------
 491 // Find a good location to insert a predicate
 492 ProjNode* PhaseIdealLoop::find_predicate_insertion_point(Node* start_c, Deoptimization::DeoptReason reason) {
 493   if (start_c == NULL || !start_c->is_Proj())
 494     return NULL;
 495   if (start_c->as_Proj()->is_uncommon_trap_if_pattern(reason)) {
 496     return start_c->as_Proj();
 497   }
 498   return NULL;
 499 }
 500 
 501 //--------------------------find_predicate------------------------------------
 502 // Find a predicate
 503 Node* PhaseIdealLoop::find_predicate(Node* entry) {
 504   Node* predicate = NULL;
 505   predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
 506   if (predicate != NULL) { // right pattern that can be used by loop predication
 507     return entry;
 508   }
 509   if (UseLoopPredicate) {
 510     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
 511     if (predicate != NULL) { // right pattern that can be used by loop predication
 512       return entry;
 513     }
 514   }
 515   if (UseProfiledLoopPredicate) {
 516     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
 517     if (predicate != NULL) { // right pattern that can be used by loop predication
 518       return entry;
 519     }
 520   }
 521   return NULL;
 522 }
 523 
 524 //------------------------------Invariance-----------------------------------
 525 // Helper class for loop_predication_impl to compute invariance on the fly and
 526 // clone invariants.
 527 class Invariance : public StackObj {
 528   VectorSet _visited, _invariant;
 529   Node_Stack _stack;
 530   VectorSet _clone_visited;
 531   Node_List _old_new; // map of old to new (clone)
 532   IdealLoopTree* _lpt;
 533   PhaseIdealLoop* _phase;
 534 
 535   // Helper function to set up the invariance for invariance computation
 536   // If n is a known invariant, set up directly. Otherwise, look up the
 537   // the possibility to push n onto the stack for further processing.
 538   void visit(Node* use, Node* n) {
 539     if (_lpt->is_invariant(n)) { // known invariant
 540       _invariant.set(n->_idx);
 541     } else if (!n->is_CFG()) {
 542       Node *n_ctrl = _phase->ctrl_or_self(n);
 543       Node *u_ctrl = _phase->ctrl_or_self(use); // self if use is a CFG
 544       if (_phase->is_dominator(n_ctrl, u_ctrl)) {
 545         _stack.push(n, n->in(0) == NULL ? 1 : 0);
 546       }
 547     }
 548   }
 549 
 550   // Compute invariance for "the_node" and (possibly) all its inputs recursively
 551   // on the fly
 552   void compute_invariance(Node* n) {
 553     assert(_visited.test(n->_idx), "must be");
 554     visit(n, n);
 555     while (_stack.is_nonempty()) {
 556       Node*  n = _stack.node();
 557       uint idx = _stack.index();
 558       if (idx == n->req()) { // all inputs are processed
 559         _stack.pop();
 560         // n is invariant if it's inputs are all invariant
 561         bool all_inputs_invariant = true;
 562         for (uint i = 0; i < n->req(); i++) {
 563           Node* in = n->in(i);
 564           if (in == NULL) continue;
 565           assert(_visited.test(in->_idx), "must have visited input");
 566           if (!_invariant.test(in->_idx)) { // bad guy
 567             all_inputs_invariant = false;
 568             break;
 569           }
 570         }
 571         if (all_inputs_invariant) {
 572           // If n's control is a predicate that was moved out of the
 573           // loop, it was marked invariant but n is only invariant if
 574           // it depends only on that test. Otherwise, unless that test
 575           // is out of the loop, it's not invariant.
 576           if (n->is_CFG() || n->depends_only_on_test() || n->in(0) == NULL || !_phase->is_member(_lpt, n->in(0))) {
 577             _invariant.set(n->_idx); // I am a invariant too
 578           }
 579         }
 580       } else { // process next input
 581         _stack.set_index(idx + 1);
 582         Node* m = n->in(idx);
 583         if (m != NULL && !_visited.test_set(m->_idx)) {
 584           visit(n, m);
 585         }
 586       }
 587     }
 588   }
 589 
 590   // Helper function to set up _old_new map for clone_nodes.
 591   // If n is a known invariant, set up directly ("clone" of n == n).
 592   // Otherwise, push n onto the stack for real cloning.
 593   void clone_visit(Node* n) {
 594     assert(_invariant.test(n->_idx), "must be invariant");
 595     if (_lpt->is_invariant(n)) { // known invariant
 596       _old_new.map(n->_idx, n);
 597     } else { // to be cloned
 598       assert(!n->is_CFG(), "should not see CFG here");
 599       _stack.push(n, n->in(0) == NULL ? 1 : 0);
 600     }
 601   }
 602 
 603   // Clone "n" and (possibly) all its inputs recursively
 604   void clone_nodes(Node* n, Node* ctrl) {
 605     clone_visit(n);
 606     while (_stack.is_nonempty()) {
 607       Node*  n = _stack.node();
 608       uint idx = _stack.index();
 609       if (idx == n->req()) { // all inputs processed, clone n!
 610         _stack.pop();
 611         // clone invariant node
 612         Node* n_cl = n->clone();
 613         _old_new.map(n->_idx, n_cl);
 614         _phase->register_new_node(n_cl, ctrl);
 615         for (uint i = 0; i < n->req(); i++) {
 616           Node* in = n_cl->in(i);
 617           if (in == NULL) continue;
 618           n_cl->set_req(i, _old_new[in->_idx]);
 619         }
 620       } else { // process next input
 621         _stack.set_index(idx + 1);
 622         Node* m = n->in(idx);
 623         if (m != NULL && !_clone_visited.test_set(m->_idx)) {
 624           clone_visit(m); // visit the input
 625         }
 626       }
 627     }
 628   }
 629 
 630  public:
 631   Invariance(Arena* area, IdealLoopTree* lpt) :
 632     _lpt(lpt), _phase(lpt->_phase),
 633     _visited(area), _invariant(area), _stack(area, 10 /* guess */),
 634     _clone_visited(area), _old_new(area)
 635   {
 636     LoopNode* head = _lpt->_head->as_Loop();
 637     Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
 638     if (entry->outcnt() != 1) {
 639       // If a node is pinned between the predicates and the loop
 640       // entry, we won't be able to move any node in the loop that
 641       // depends on it above it in a predicate. Mark all those nodes
 642       // as non loop invariatnt.
 643       Unique_Node_List wq;
 644       wq.push(entry);
 645       for (uint next = 0; next < wq.size(); ++next) {
 646         Node *n = wq.at(next);
 647         for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {
 648           Node* u = n->fast_out(i);
 649           if (!u->is_CFG()) {
 650             Node* c = _phase->get_ctrl(u);
 651             if (_lpt->is_member(_phase->get_loop(c)) || _phase->is_dominator(c, head)) {
 652               _visited.set(u->_idx);
 653               wq.push(u);
 654             }
 655           }
 656         }
 657       }
 658     }
 659   }
 660 
 661   // Map old to n for invariance computation and clone
 662   void map_ctrl(Node* old, Node* n) {
 663     assert(old->is_CFG() && n->is_CFG(), "must be");
 664     _old_new.map(old->_idx, n); // "clone" of old is n
 665     _invariant.set(old->_idx);  // old is invariant
 666     _clone_visited.set(old->_idx);
 667   }
 668 
 669   // Driver function to compute invariance
 670   bool is_invariant(Node* n) {
 671     if (!_visited.test_set(n->_idx))
 672       compute_invariance(n);
 673     return (_invariant.test(n->_idx) != 0);
 674   }
 675 
 676   // Driver function to clone invariant
 677   Node* clone(Node* n, Node* ctrl) {
 678     assert(ctrl->is_CFG(), "must be");
 679     assert(_invariant.test(n->_idx), "must be an invariant");
 680     if (!_clone_visited.test(n->_idx))
 681       clone_nodes(n, ctrl);
 682     return _old_new[n->_idx];
 683   }
 684 };
 685 
 686 //------------------------------is_range_check_if -----------------------------------
 687 // Returns true if the predicate of iff is in "scale*iv + offset u< load_range(ptr)" format
 688 // Note: this function is particularly designed for loop predication. We require load_range
 689 //       and offset to be loop invariant computed on the fly by "invar"
 690 bool IdealLoopTree::is_range_check_if(IfNode *iff, PhaseIdealLoop *phase, Invariance& invar) const {
 691   if (!is_loop_exit(iff)) {
 692     return false;
 693   }
 694   if (!iff->in(1)->is_Bool()) {
 695     return false;
 696   }
 697   const BoolNode *bol = iff->in(1)->as_Bool();
 698   if (bol->_test._test != BoolTest::lt) {
 699     return false;
 700   }
 701   if (!bol->in(1)->is_Cmp()) {
 702     return false;
 703   }
 704   const CmpNode *cmp = bol->in(1)->as_Cmp();
 705   if (cmp->Opcode() != Op_CmpU) {
 706     return false;
 707   }
 708   Node* range = cmp->in(2);
 709   if (range->Opcode() != Op_LoadRange && !iff->is_RangeCheck()) {
 710     const TypeInt* tint = phase->_igvn.type(range)->isa_int();
 711     if (tint == NULL || tint->empty() || tint->_lo < 0) {
 712       // Allow predication on positive values that aren't LoadRanges.
 713       // This allows optimization of loops where the length of the
 714       // array is a known value and doesn't need to be loaded back
 715       // from the array.
 716       return false;
 717     }
 718   }
 719   if (!invar.is_invariant(range)) {
 720     return false;
 721   }
 722   Node *iv     = _head->as_CountedLoop()->phi();
 723   int   scale  = 0;
 724   Node *offset = NULL;
 725   if (!phase->is_scaled_iv_plus_offset(cmp->in(1), iv, &scale, &offset)) {
 726     return false;
 727   }
 728   if (offset && !invar.is_invariant(offset)) { // offset must be invariant
 729     return false;
 730   }
 731   return true;
 732 }
 733 
 734 //------------------------------rc_predicate-----------------------------------
 735 // Create a range check predicate
 736 //
 737 // for (i = init; i < limit; i += stride) {
 738 //    a[scale*i+offset]
 739 // }
 740 //
 741 // Compute max(scale*i + offset) for init <= i < limit and build the predicate
 742 // as "max(scale*i + offset) u< a.length".
 743 //
 744 // There are two cases for max(scale*i + offset):
 745 // (1) stride*scale > 0
 746 //   max(scale*i + offset) = scale*(limit-stride) + offset
 747 // (2) stride*scale < 0
 748 //   max(scale*i + offset) = scale*init + offset
 749 BoolNode* PhaseIdealLoop::rc_predicate(IdealLoopTree *loop, Node* ctrl,
 750                                        int scale, Node* offset,
 751                                        Node* init, Node* limit, jint stride,
 752                                        Node* range, bool upper, bool &overflow) {
 753   jint con_limit  = (limit != NULL && limit->is_Con())  ? limit->get_int()  : 0;
 754   jint con_init   = init->is_Con()   ? init->get_int()   : 0;
 755   jint con_offset = offset->is_Con() ? offset->get_int() : 0;
 756 
 757   stringStream* predString = NULL;
 758   if (TraceLoopPredicate) {
 759     predString = new stringStream();
 760     predString->print("rc_predicate ");
 761   }
 762 
 763   overflow = false;
 764   Node* max_idx_expr = NULL;
 765   const TypeInt* idx_type = TypeInt::INT;
 766   if ((stride > 0) == (scale > 0) == upper) {
 767     guarantee(limit != NULL, "sanity");
 768     if (TraceLoopPredicate) {
 769       if (limit->is_Con()) {
 770         predString->print("(%d ", con_limit);
 771       } else {
 772         predString->print("(limit ");
 773       }
 774       predString->print("- %d) ", stride);
 775     }
 776     // Check if (limit - stride) may overflow
 777     const TypeInt* limit_type = _igvn.type(limit)->isa_int();
 778     jint limit_lo = limit_type->_lo;
 779     jint limit_hi = limit_type->_hi;
 780     if ((stride > 0 && (java_subtract(limit_lo, stride) < limit_lo)) ||
 781         (stride < 0 && (java_subtract(limit_hi, stride) > limit_hi))) {
 782       // No overflow possible
 783       ConINode* con_stride = _igvn.intcon(stride);
 784       set_ctrl(con_stride, C->root());
 785       max_idx_expr = new SubINode(limit, con_stride);
 786       idx_type = TypeInt::make(limit_lo - stride, limit_hi - stride, limit_type->_widen);
 787     } else {
 788       // May overflow
 789       overflow = true;
 790       limit = new ConvI2LNode(limit);
 791       register_new_node(limit, ctrl);
 792       ConLNode* con_stride = _igvn.longcon(stride);
 793       set_ctrl(con_stride, C->root());
 794       max_idx_expr = new SubLNode(limit, con_stride);
 795     }
 796     register_new_node(max_idx_expr, ctrl);
 797   } else {
 798     if (TraceLoopPredicate) {
 799       if (init->is_Con()) {
 800         predString->print("%d ", con_init);
 801       } else {
 802         predString->print("init ");
 803       }
 804     }
 805     idx_type = _igvn.type(init)->isa_int();
 806     max_idx_expr = init;
 807   }
 808 
 809   if (scale != 1) {
 810     ConNode* con_scale = _igvn.intcon(scale);
 811     set_ctrl(con_scale, C->root());
 812     if (TraceLoopPredicate) {
 813       predString->print("* %d ", scale);
 814     }
 815     // Check if (scale * max_idx_expr) may overflow
 816     const TypeInt* scale_type = TypeInt::make(scale);
 817     MulINode* mul = new MulINode(max_idx_expr, con_scale);
 818     idx_type = (TypeInt*)mul->mul_ring(idx_type, scale_type);
 819     if (overflow || TypeInt::INT->higher_equal(idx_type)) {
 820       // May overflow
 821       mul->destruct();
 822       if (!overflow) {
 823         max_idx_expr = new ConvI2LNode(max_idx_expr);
 824         register_new_node(max_idx_expr, ctrl);
 825       }
 826       overflow = true;
 827       con_scale = _igvn.longcon(scale);
 828       set_ctrl(con_scale, C->root());
 829       max_idx_expr = new MulLNode(max_idx_expr, con_scale);
 830     } else {
 831       // No overflow possible
 832       max_idx_expr = mul;
 833     }
 834     register_new_node(max_idx_expr, ctrl);
 835   }
 836 
 837   if (offset && (!offset->is_Con() || con_offset != 0)){
 838     if (TraceLoopPredicate) {
 839       if (offset->is_Con()) {
 840         predString->print("+ %d ", con_offset);
 841       } else {
 842         predString->print("+ offset");
 843       }
 844     }
 845     // Check if (max_idx_expr + offset) may overflow
 846     const TypeInt* offset_type = _igvn.type(offset)->isa_int();
 847     jint lo = java_add(idx_type->_lo, offset_type->_lo);
 848     jint hi = java_add(idx_type->_hi, offset_type->_hi);
 849     if (overflow || (lo > hi) ||
 850         ((idx_type->_lo & offset_type->_lo) < 0 && lo >= 0) ||
 851         ((~(idx_type->_hi | offset_type->_hi)) < 0 && hi < 0)) {
 852       // May overflow
 853       if (!overflow) {
 854         max_idx_expr = new ConvI2LNode(max_idx_expr);
 855         register_new_node(max_idx_expr, ctrl);
 856       }
 857       overflow = true;
 858       offset = new ConvI2LNode(offset);
 859       register_new_node(offset, ctrl);
 860       max_idx_expr = new AddLNode(max_idx_expr, offset);
 861     } else {
 862       // No overflow possible
 863       max_idx_expr = new AddINode(max_idx_expr, offset);
 864     }
 865     register_new_node(max_idx_expr, ctrl);
 866   }
 867 
 868   CmpNode* cmp = NULL;
 869   if (overflow) {
 870     // Integer expressions may overflow, do long comparison
 871     range = new ConvI2LNode(range);
 872     register_new_node(range, ctrl);
 873     cmp = new CmpULNode(max_idx_expr, range);
 874   } else {
 875     cmp = new CmpUNode(max_idx_expr, range);
 876   }
 877   register_new_node(cmp, ctrl);
 878   BoolNode* bol = new BoolNode(cmp, BoolTest::lt);
 879   register_new_node(bol, ctrl);
 880 
 881   if (TraceLoopPredicate) {
 882     predString->print_cr("<u range");
 883     tty->print("%s", predString->as_string());
 884   }
 885   return bol;
 886 }
 887 
 888 // Should loop predication look not only in the path from tail to head
 889 // but also in branches of the loop body?
 890 bool PhaseIdealLoop::loop_predication_should_follow_branches(IdealLoopTree *loop, ProjNode *predicate_proj, float& loop_trip_cnt) {
 891   if (!UseProfiledLoopPredicate) {
 892     return false;
 893   }
 894 
 895   if (predicate_proj == NULL) {
 896     return false;
 897   }
 898 
 899   LoopNode* head = loop->_head->as_Loop();
 900   bool follow_branches = true;
 901   IdealLoopTree* l = loop->_child;
 902   // For leaf loops and loops with a single inner loop
 903   while (l != NULL && follow_branches) {
 904     IdealLoopTree* child = l;
 905     if (child->_child != NULL &&
 906         child->_head->is_OuterStripMinedLoop()) {
 907       assert(child->_child->_next == NULL, "only one inner loop for strip mined loop");
 908       assert(child->_child->_head->is_CountedLoop() && child->_child->_head->as_CountedLoop()->is_strip_mined(), "inner loop should be strip mined");
 909       child = child->_child;
 910     }
 911     if (child->_child != NULL || child->_irreducible) {
 912       follow_branches = false;
 913     }
 914     l = l->_next;
 915   }
 916   if (follow_branches) {
 917     loop->compute_profile_trip_cnt(this);
 918     if (head->is_profile_trip_failed()) {
 919       follow_branches = false;
 920     } else {
 921       loop_trip_cnt = head->profile_trip_cnt();
 922       if (head->is_CountedLoop()) {
 923         CountedLoopNode* cl = head->as_CountedLoop();
 924         if (cl->phi() != NULL) {
 925           const TypeInt* t = _igvn.type(cl->phi())->is_int();
 926           float worst_case_trip_cnt = ((float)t->_hi - t->_lo) / ABS(cl->stride_con());
 927           if (worst_case_trip_cnt < loop_trip_cnt) {
 928             loop_trip_cnt = worst_case_trip_cnt;
 929           }
 930         }
 931       }
 932     }
 933   }
 934   return follow_branches;
 935 }
 936 
 937 // Compute probability of reaching some CFG node from a fixed
 938 // dominating CFG node
 939 class PathFrequency {
 940 private:
 941   Node* _dom; // frequencies are computed relative to this node
 942   Node_Stack _stack;
 943   GrowableArray<float> _freqs_stack; // keep track of intermediate result at regions
 944   GrowableArray<float> _freqs; // cache frequencies
 945   PhaseIdealLoop* _phase;
 946 
 947   void set_rounding(int mode) {
 948     // fesetround is broken on windows
 949     NOT_WINDOWS(fesetround(mode);)
 950   }
 951 
 952   void check_frequency(float f) {
 953     NOT_WINDOWS(assert(f <= 1 && f >= 0, "Incorrect frequency");)
 954   }
 955 
 956 public:
 957   PathFrequency(Node* dom, PhaseIdealLoop* phase)
 958     : _dom(dom), _stack(0), _phase(phase) {
 959   }
 960 
 961   float to(Node* n) {
 962     // post order walk on the CFG graph from n to _dom
 963     set_rounding(FE_TOWARDZERO); // make sure rounding doesn't push frequency above 1
 964     IdealLoopTree* loop = _phase->get_loop(_dom);
 965     Node* c = n;
 966     for (;;) {
 967       assert(_phase->get_loop(c) == loop, "have to be in the same loop");
 968       if (c == _dom || _freqs.at_grow(c->_idx, -1) >= 0) {
 969         float f = c == _dom ? 1 : _freqs.at(c->_idx);
 970         Node* prev = c;
 971         while (_stack.size() > 0 && prev == c) {
 972           Node* n = _stack.node();
 973           if (!n->is_Region()) {
 974             if (_phase->get_loop(n) != _phase->get_loop(n->in(0))) {
 975               // Found an inner loop: compute frequency of reaching this
 976               // exit from the loop head by looking at the number of
 977               // times each loop exit was taken
 978               IdealLoopTree* inner_loop = _phase->get_loop(n->in(0));
 979               LoopNode* inner_head = inner_loop->_head->as_Loop();
 980               assert(_phase->get_loop(n) == loop, "only 1 inner loop");
 981               if (inner_head->is_OuterStripMinedLoop()) {
 982                 inner_head->verify_strip_mined(1);
 983                 if (n->in(0) == inner_head->in(LoopNode::LoopBackControl)->in(0)) {
 984                   n = n->in(0)->in(0)->in(0);
 985                 }
 986                 inner_loop = inner_loop->_child;
 987                 inner_head = inner_loop->_head->as_Loop();
 988                 inner_head->verify_strip_mined(1);
 989               }
 990               set_rounding(FE_UPWARD);  // make sure rounding doesn't push frequency above 1
 991               float loop_exit_cnt = 0.0f;
 992               for (uint i = 0; i < inner_loop->_body.size(); i++) {
 993                 Node *n = inner_loop->_body[i];
 994                 float c = inner_loop->compute_profile_trip_cnt_helper(n);
 995                 loop_exit_cnt += c;
 996               }
 997               set_rounding(FE_TOWARDZERO);
 998               float cnt = -1;
 999               if (n->in(0)->is_If()) {
1000                 IfNode* iff = n->in(0)->as_If();
1001                 float p = n->in(0)->as_If()->_prob;
1002                 if (n->Opcode() == Op_IfFalse) {
1003                   p = 1 - p;
1004                 }
1005                 if (p > PROB_MIN) {
1006                   cnt = p * iff->_fcnt;
1007                 } else {
1008                   cnt = 0;
1009                 }
1010               } else {
1011                 assert(n->in(0)->is_Jump(), "unsupported node kind");
1012                 JumpNode* jmp = n->in(0)->as_Jump();
1013                 float p = n->in(0)->as_Jump()->_probs[n->as_JumpProj()->_con];
1014                 cnt = p * jmp->_fcnt;
1015               }
1016               float this_exit_f = cnt > 0 ? cnt / loop_exit_cnt : 0;
1017               check_frequency(this_exit_f);
1018               f = f * this_exit_f;
1019               check_frequency(f);
1020             } else {
1021               float p = -1;
1022               if (n->in(0)->is_If()) {
1023                 p = n->in(0)->as_If()->_prob;
1024                 if (n->Opcode() == Op_IfFalse) {
1025                   p = 1 - p;
1026                 }
1027               } else {
1028                 assert(n->in(0)->is_Jump(), "unsupported node kind");
1029                 p = n->in(0)->as_Jump()->_probs[n->as_JumpProj()->_con];
1030               }
1031               f = f * p;
1032               check_frequency(f);
1033             }
1034             _freqs.at_put_grow(n->_idx, (float)f, -1);
1035             _stack.pop();
1036           } else {
1037             float prev_f = _freqs_stack.pop();
1038             float new_f = f;
1039             f = new_f + prev_f;
1040             check_frequency(f);
1041             uint i = _stack.index();
1042             if (i < n->req()) {
1043               c = n->in(i);
1044               _stack.set_index(i+1);
1045               _freqs_stack.push(f);
1046             } else {
1047               _freqs.at_put_grow(n->_idx, f, -1);
1048               _stack.pop();
1049             }
1050           }
1051         }
1052         if (_stack.size() == 0) {
1053           set_rounding(FE_TONEAREST);
1054           check_frequency(f);
1055           return f;
1056         }
1057       } else if (c->is_Loop()) {
1058         ShouldNotReachHere();
1059         c = c->in(LoopNode::EntryControl);
1060       } else if (c->is_Region()) {
1061         _freqs_stack.push(0);
1062         _stack.push(c, 2);
1063         c = c->in(1);
1064       } else {
1065         if (c->is_IfProj()) {
1066           IfNode* iff = c->in(0)->as_If();
1067           if (iff->_prob == PROB_UNKNOWN) {
1068             // assume never taken
1069             _freqs.at_put_grow(c->_idx, 0, -1);
1070           } else if (_phase->get_loop(c) != _phase->get_loop(iff)) {
1071             if (iff->_fcnt == COUNT_UNKNOWN) {
1072               // assume never taken
1073               _freqs.at_put_grow(c->_idx, 0, -1);
1074             } else {
1075               // skip over loop
1076               _stack.push(c, 1);
1077               c = _phase->get_loop(c->in(0))->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl);
1078             }
1079           } else {
1080             _stack.push(c, 1);
1081             c = iff;
1082           }
1083         } else if (c->is_JumpProj()) {
1084           JumpNode* jmp = c->in(0)->as_Jump();
1085           if (_phase->get_loop(c) != _phase->get_loop(jmp)) {
1086             if (jmp->_fcnt == COUNT_UNKNOWN) {
1087               // assume never taken
1088               _freqs.at_put_grow(c->_idx, 0, -1);
1089             } else {
1090               // skip over loop
1091               _stack.push(c, 1);
1092               c = _phase->get_loop(c->in(0))->_head->as_Loop()->skip_strip_mined()->in(LoopNode::EntryControl);
1093             }
1094           } else {
1095             _stack.push(c, 1);
1096             c = jmp;
1097           }
1098         } else if (c->Opcode() == Op_CatchProj &&
1099                    c->in(0)->Opcode() == Op_Catch &&
1100                    c->in(0)->in(0)->is_Proj() &&
1101                    c->in(0)->in(0)->in(0)->is_Call()) {
1102           // assume exceptions are never thrown
1103           uint con = c->as_Proj()->_con;
1104           if (con == CatchProjNode::fall_through_index) {
1105             Node* call = c->in(0)->in(0)->in(0)->in(0);
1106             if (_phase->get_loop(call) != _phase->get_loop(c)) {
1107               _freqs.at_put_grow(c->_idx, 0, -1);
1108             } else {
1109               c = call;
1110             }
1111           } else {
1112             assert(con >= CatchProjNode::catch_all_index, "what else?");
1113             _freqs.at_put_grow(c->_idx, 0, -1);
1114           }
1115         } else if (c->unique_ctrl_out() == NULL && !c->is_If() && !c->is_Jump()) {
1116           ShouldNotReachHere();
1117         } else {
1118           c = c->in(0);
1119         }
1120       }
1121     }
1122     ShouldNotReachHere();
1123     return -1;
1124   }
1125 };
1126 
1127 void PhaseIdealLoop::loop_predication_follow_branches(Node *n, IdealLoopTree *loop, float loop_trip_cnt,
1128                                                       PathFrequency& pf, Node_Stack& stack, VectorSet& seen,
1129                                                       Node_List& if_proj_list) {
1130   assert(n->is_Region(), "start from a region");
1131   Node* tail = loop->tail();
1132   stack.push(n, 1);
1133   do {
1134     Node* c = stack.node();
1135     assert(c->is_Region() || c->is_IfProj(), "only region here");
1136     uint i = stack.index();
1137 
1138     if (i < c->req()) {
1139       stack.set_index(i+1);
1140       Node* in = c->in(i);
1141       while (!is_dominator(in, tail) && !seen.test_set(in->_idx)) {
1142         IdealLoopTree* in_loop = get_loop(in);
1143         if (in_loop != loop) {
1144           in = in_loop->_head->in(LoopNode::EntryControl);
1145         } else if (in->is_Region()) {
1146           stack.push(in, 1);
1147           break;
1148         } else if (in->is_IfProj() &&
1149                    in->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
1150                    (in->in(0)->Opcode() == Op_If ||
1151                     in->in(0)->Opcode() == Op_RangeCheck)) {
1152           if (pf.to(in) * loop_trip_cnt >= 1) {
1153             stack.push(in, 1);
1154           }
1155           in = in->in(0);
1156         } else {
1157           in = in->in(0);
1158         }
1159       }
1160     } else {
1161       if (c->is_IfProj()) {
1162         if_proj_list.push(c);
1163       }
1164       stack.pop();
1165     }
1166 
1167   } while (stack.size() > 0);
1168 }
1169 
1170 
1171 bool PhaseIdealLoop::loop_predication_impl_helper(IdealLoopTree *loop, ProjNode* proj, ProjNode *predicate_proj,
1172                                                   CountedLoopNode *cl, ConNode* zero, Invariance& invar,
1173                                                   Deoptimization::DeoptReason reason) {
1174   // Following are changed to nonnull when a predicate can be hoisted
1175   ProjNode* new_predicate_proj = NULL;
1176   IfNode*   iff  = proj->in(0)->as_If();
1177   Node*     test = iff->in(1);
1178   if (!test->is_Bool()){ //Conv2B, ...
1179     return false;
1180   }
1181   BoolNode* bol = test->as_Bool();
1182   if (invar.is_invariant(bol)) {
1183     // Invariant test
1184     new_predicate_proj = create_new_if_for_predicate(predicate_proj, NULL,
1185                                                      reason,
1186                                                      iff->Opcode());
1187     Node* ctrl = new_predicate_proj->in(0)->as_If()->in(0);
1188     BoolNode* new_predicate_bol = invar.clone(bol, ctrl)->as_Bool();
1189 
1190     // Negate test if necessary
1191     bool negated = false;
1192     if (proj->_con != predicate_proj->_con) {
1193       new_predicate_bol = new BoolNode(new_predicate_bol->in(1), new_predicate_bol->_test.negate());
1194       register_new_node(new_predicate_bol, ctrl);
1195       negated = true;
1196     }
1197     IfNode* new_predicate_iff = new_predicate_proj->in(0)->as_If();
1198     _igvn.hash_delete(new_predicate_iff);
1199     new_predicate_iff->set_req(1, new_predicate_bol);
1200 #ifndef PRODUCT
1201     if (TraceLoopPredicate) {
1202       tty->print("Predicate invariant if%s: %d ", negated ? " negated" : "", new_predicate_iff->_idx);
1203       loop->dump_head();
1204     } else if (TraceLoopOpts) {
1205       tty->print("Predicate IC ");
1206       loop->dump_head();
1207     }
1208 #endif
1209   } else if (cl != NULL && loop->is_range_check_if(iff, this, invar)) {
1210     // Range check for counted loops
1211     const Node*    cmp    = bol->in(1)->as_Cmp();
1212     Node*          idx    = cmp->in(1);
1213     assert(!invar.is_invariant(idx), "index is variant");
1214     Node* rng = cmp->in(2);
1215     assert(rng->Opcode() == Op_LoadRange || iff->is_RangeCheck() || _igvn.type(rng)->is_int()->_lo >= 0, "must be");
1216     assert(invar.is_invariant(rng), "range must be invariant");
1217     int scale    = 1;
1218     Node* offset = zero;
1219     bool ok = is_scaled_iv_plus_offset(idx, cl->phi(), &scale, &offset);
1220     assert(ok, "must be index expression");
1221 
1222     Node* init    = cl->init_trip();
1223     // Limit is not exact.
1224     // Calculate exact limit here.
1225     // Note, counted loop's test is '<' or '>'.
1226     Node* limit   = exact_limit(loop);
1227     int  stride   = cl->stride()->get_int();
1228 
1229     // Build if's for the upper and lower bound tests.  The
1230     // lower_bound test will dominate the upper bound test and all
1231     // cloned or created nodes will use the lower bound test as
1232     // their declared control.
1233 
1234     // Perform cloning to keep Invariance state correct since the
1235     // late schedule will place invariant things in the loop.
1236     Node *ctrl = predicate_proj->in(0)->as_If()->in(0);
1237     rng = invar.clone(rng, ctrl);
1238     if (offset && offset != zero) {
1239       assert(invar.is_invariant(offset), "offset must be loop invariant");
1240       offset = invar.clone(offset, ctrl);
1241     }
1242     // If predicate expressions may overflow in the integer range, longs are used.
1243     bool overflow = false;
1244 
1245     // Test the lower bound
1246     BoolNode* lower_bound_bol = rc_predicate(loop, ctrl, scale, offset, init, limit, stride, rng, false, overflow);
1247     // Negate test if necessary
1248     bool negated = false;
1249     if (proj->_con != predicate_proj->_con) {
1250       lower_bound_bol = new BoolNode(lower_bound_bol->in(1), lower_bound_bol->_test.negate());
1251       register_new_node(lower_bound_bol, ctrl);
1252       negated = true;
1253     }
1254     ProjNode* lower_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode());
1255     IfNode* lower_bound_iff = lower_bound_proj->in(0)->as_If();
1256     _igvn.hash_delete(lower_bound_iff);
1257     lower_bound_iff->set_req(1, lower_bound_bol);
1258     if (TraceLoopPredicate) tty->print_cr("lower bound check if: %s %d ", negated ? " negated" : "", lower_bound_iff->_idx);
1259 
1260     // Test the upper bound
1261     BoolNode* upper_bound_bol = rc_predicate(loop, lower_bound_proj, scale, offset, init, limit, stride, rng, true, overflow);
1262     negated = false;
1263     if (proj->_con != predicate_proj->_con) {
1264       upper_bound_bol = new BoolNode(upper_bound_bol->in(1), upper_bound_bol->_test.negate());
1265       register_new_node(upper_bound_bol, ctrl);
1266       negated = true;
1267     }
1268     ProjNode* upper_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode());
1269     assert(upper_bound_proj->in(0)->as_If()->in(0) == lower_bound_proj, "should dominate");
1270     IfNode* upper_bound_iff = upper_bound_proj->in(0)->as_If();
1271     _igvn.hash_delete(upper_bound_iff);
1272     upper_bound_iff->set_req(1, upper_bound_bol);
1273     if (TraceLoopPredicate) tty->print_cr("upper bound check if: %s %d ", negated ? " negated" : "", lower_bound_iff->_idx);
1274 
1275     // Fall through into rest of the clean up code which will move
1276     // any dependent nodes onto the upper bound test.
1277     new_predicate_proj = upper_bound_proj;
1278 
1279     if (iff->is_RangeCheck()) {
1280       new_predicate_proj = insert_skeleton_predicate(iff, loop, proj, predicate_proj, upper_bound_proj, scale, offset, init, limit, stride, rng, overflow, reason);
1281     }
1282 
1283 #ifndef PRODUCT
1284     if (TraceLoopOpts && !TraceLoopPredicate) {
1285       tty->print("Predicate RC ");
1286       loop->dump_head();
1287     }
1288 #endif
1289   } else {
1290     // Loop variant check (for example, range check in non-counted loop)
1291     // with uncommon trap.
1292     return false;
1293   }
1294   assert(new_predicate_proj != NULL, "sanity");
1295   // Success - attach condition (new_predicate_bol) to predicate if
1296   invar.map_ctrl(proj, new_predicate_proj); // so that invariance test can be appropriate
1297 
1298   // Eliminate the old If in the loop body
1299   dominated_by( new_predicate_proj, iff, proj->_con != new_predicate_proj->_con );
1300 
1301   C->set_major_progress();
1302   return true;
1303 }
1304 
1305 
1306 // After pre/main/post loops are created, we'll put a copy of some
1307 // range checks between the pre and main loop to validate the value
1308 // of the main loop induction variable. Make a copy of the predicates
1309 // here with an opaque node as a place holder for the value (will be
1310 // updated by PhaseIdealLoop::update_skeleton_predicate()).
1311 ProjNode* PhaseIdealLoop::insert_skeleton_predicate(IfNode* iff, IdealLoopTree *loop,
1312                                                     ProjNode* proj, ProjNode *predicate_proj,
1313                                                     ProjNode* upper_bound_proj,
1314                                                     int scale, Node* offset,
1315                                                     Node* init, Node* limit, jint stride,
1316                                                     Node* rng, bool &overflow,
1317                                                     Deoptimization::DeoptReason reason) {
1318   assert(proj->_con && predicate_proj->_con, "not a range check?");
1319   Node* opaque_init = new Opaque1Node(C, init);
1320   register_new_node(opaque_init, upper_bound_proj);
1321   BoolNode* bol = rc_predicate(loop, upper_bound_proj, scale, offset, opaque_init, limit, stride, rng, (stride > 0) != (scale > 0), overflow);
1322   Node* opaque_bol = new Opaque4Node(C, bol, _igvn.intcon(1)); // This will go away once loop opts are over
1323   register_new_node(opaque_bol, upper_bound_proj);
1324   ProjNode* new_proj = create_new_if_for_predicate(predicate_proj, NULL, reason, overflow ? Op_If : iff->Opcode());
1325   _igvn.replace_input_of(new_proj->in(0), 1, opaque_bol);
1326   assert(opaque_init->outcnt() > 0, "should be used");
1327   return new_proj;
1328 }
1329 
1330 //------------------------------ loop_predication_impl--------------------------
1331 // Insert loop predicates for null checks and range checks
1332 bool PhaseIdealLoop::loop_predication_impl(IdealLoopTree *loop) {
1333   if (!UseLoopPredicate) return false;
1334 
1335   if (!loop->_head->is_Loop()) {
1336     // Could be a simple region when irreducible loops are present.
1337     return false;
1338   }
1339   LoopNode* head = loop->_head->as_Loop();
1340 
1341   if (head->unique_ctrl_out()->Opcode() == Op_NeverBranch) {
1342     // do nothing for infinite loops
1343     return false;
1344   }
1345 
1346   if (head->is_OuterStripMinedLoop()) {
1347     return false;
1348   }
1349 
1350   CountedLoopNode *cl = NULL;
1351   if (head->is_valid_counted_loop()) {
1352     cl = head->as_CountedLoop();
1353     // do nothing for iteration-splitted loops
1354     if (!cl->is_normal_loop()) return false;
1355     // Avoid RCE if Counted loop's test is '!='.
1356     BoolTest::mask bt = cl->loopexit()->test_trip();
1357     if (bt != BoolTest::lt && bt != BoolTest::gt)
1358       cl = NULL;
1359   }
1360 
1361   Node* entry = head->skip_strip_mined()->in(LoopNode::EntryControl);
1362   ProjNode *loop_limit_proj = NULL;
1363   ProjNode *predicate_proj = NULL;
1364   ProjNode *profile_predicate_proj = NULL;
1365   // Loop limit check predicate should be near the loop.
1366   loop_limit_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_loop_limit_check);
1367   if (loop_limit_proj != NULL) {
1368     entry = skip_loop_predicates(loop_limit_proj);
1369   }
1370   bool has_profile_predicates = false;
1371   profile_predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_profile_predicate);
1372   if (profile_predicate_proj != NULL) {
1373     Node* n = skip_loop_predicates(entry);
1374     // Check if predicates were already added to the profile predicate
1375     // block
1376     if (n != entry->in(0)->in(0) || n->outcnt() != 1) {
1377       has_profile_predicates = true;
1378     }
1379     entry = n;
1380   }
1381   predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
1382 
1383   float loop_trip_cnt = -1;
1384   bool follow_branches = loop_predication_should_follow_branches(loop, profile_predicate_proj, loop_trip_cnt);
1385   assert(!follow_branches || loop_trip_cnt >= 0, "negative trip count?");
1386 
1387   if (predicate_proj == NULL && !follow_branches) {
1388 #ifndef PRODUCT
1389     if (TraceLoopPredicate) {
1390       tty->print("missing predicate:");
1391       loop->dump_head();
1392       head->dump(1);
1393     }
1394 #endif
1395     return false;
1396   }
1397   ConNode* zero = _igvn.intcon(0);
1398   set_ctrl(zero, C->root());
1399 
1400   ResourceArea *area = Thread::current()->resource_area();
1401   Invariance invar(area, loop);
1402 
1403   // Create list of if-projs such that a newer proj dominates all older
1404   // projs in the list, and they all dominate loop->tail()
1405   Node_List if_proj_list(area);
1406   Node_List regions(area);
1407   Node *current_proj = loop->tail(); //start from tail
1408 
1409 
1410   Node_List controls(area);
1411   while (current_proj != head) {
1412     if (loop == get_loop(current_proj) && // still in the loop ?
1413         current_proj->is_Proj()        && // is a projection  ?
1414         (current_proj->in(0)->Opcode() == Op_If ||
1415          current_proj->in(0)->Opcode() == Op_RangeCheck)) { // is a if projection ?
1416       if_proj_list.push(current_proj);
1417     }
1418     if (follow_branches &&
1419         current_proj->Opcode() == Op_Region &&
1420         loop == get_loop(current_proj)) {
1421       regions.push(current_proj);
1422     }
1423     current_proj = idom(current_proj);
1424   }
1425 
1426   bool hoisted = false; // true if at least one proj is promoted
1427 
1428   if (!has_profile_predicates) {
1429     while (if_proj_list.size() > 0) {
1430       Node* n = if_proj_list.pop();
1431 
1432       ProjNode* proj = n->as_Proj();
1433       IfNode*   iff  = proj->in(0)->as_If();
1434 
1435       CallStaticJavaNode* call = proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
1436       if (call == NULL) {
1437         if (loop->is_loop_exit(iff)) {
1438           // stop processing the remaining projs in the list because the execution of them
1439           // depends on the condition of "iff" (iff->in(1)).
1440           break;
1441         } else {
1442           // Both arms are inside the loop. There are two cases:
1443           // (1) there is one backward branch. In this case, any remaining proj
1444           //     in the if_proj list post-dominates "iff". So, the condition of "iff"
1445           //     does not determine the execution the remining projs directly, and we
1446           //     can safely continue.
1447           // (2) both arms are forwarded, i.e. a diamond shape. In this case, "proj"
1448           //     does not dominate loop->tail(), so it can not be in the if_proj list.
1449           continue;
1450         }
1451       }
1452       Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(call->uncommon_trap_request());
1453       if (reason == Deoptimization::Reason_predicate) {
1454         break;
1455       }
1456 
1457       if (predicate_proj != NULL) {
1458         hoisted = loop_predication_impl_helper(loop, proj, predicate_proj, cl, zero, invar, Deoptimization::Reason_predicate) | hoisted;
1459       }
1460     } // end while
1461   }
1462 
1463   Node_List if_proj_list_freq(area);
1464   if (follow_branches) {
1465     PathFrequency pf(loop->_head, this);
1466 
1467     // Some projections were skipped by regular predicates because of
1468     // an early loop exit. Try them with profile data.
1469     while (if_proj_list.size() > 0) {
1470       Node* proj = if_proj_list.pop();
1471       float f = pf.to(proj);
1472       if (proj->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
1473           f * loop_trip_cnt >= 1) {
1474         hoisted = loop_predication_impl_helper(loop, proj->as_Proj(), profile_predicate_proj, cl, zero, invar, Deoptimization::Reason_profile_predicate) | hoisted;
1475       }
1476     }
1477 
1478     // And look into all branches
1479     Node_Stack stack(0);
1480     VectorSet seen(Thread::current()->resource_area());
1481     while (regions.size() > 0) {
1482       Node* c = regions.pop();
1483       loop_predication_follow_branches(c, loop, loop_trip_cnt, pf, stack, seen, if_proj_list_freq);
1484     }
1485 
1486     for (uint i = 0; i < if_proj_list_freq.size(); i++) {
1487       ProjNode* proj = if_proj_list_freq.at(i)->as_Proj();
1488       hoisted = loop_predication_impl_helper(loop, proj, profile_predicate_proj, cl, zero, invar, Deoptimization::Reason_profile_predicate) | hoisted;
1489     }
1490   }
1491 
1492 #ifndef PRODUCT
1493   // report that the loop predication has been actually performed
1494   // for this loop
1495   if (TraceLoopPredicate && hoisted) {
1496     tty->print("Loop Predication Performed:");
1497     loop->dump_head();
1498   }
1499 #endif
1500 
1501   head->verify_strip_mined(1);
1502 
1503   return hoisted;
1504 }
1505 
1506 //------------------------------loop_predication--------------------------------
1507 // driver routine for loop predication optimization
1508 bool IdealLoopTree::loop_predication( PhaseIdealLoop *phase) {
1509   bool hoisted = false;
1510   // Recursively promote predicates
1511   if (_child) {
1512     hoisted = _child->loop_predication( phase);
1513   }
1514 
1515   // self
1516   if (!_irreducible && !tail()->is_top()) {
1517     hoisted |= phase->loop_predication_impl(this);
1518   }
1519 
1520   if (_next) { //sibling
1521     hoisted |= _next->loop_predication( phase);
1522   }
1523 
1524   return hoisted;
1525 }