src/share/vm/opto/loopPredicate.cpp

Mon, 02 May 2011 18:53:37 -0700

author
never
date
Mon, 02 May 2011 18:53:37 -0700
changeset 2868
2e038ad0c1d0
parent 2727
08eb13460b3a
child 2877
bad7ecd0b6ed
permissions
-rw-r--r--

7009361: JSR 292 Invalid value on stack on solaris-sparc with -Xcomp
Reviewed-by: kvn, twisti

     1 /*
     2  * Copyright (c) 2011, 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  */
    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/loopnode.hpp"
    31 #include "opto/mulnode.hpp"
    32 #include "opto/rootnode.hpp"
    33 #include "opto/subnode.hpp"
    35 /*
    36  * The general idea of Loop Predication is to insert a predicate on the entry
    37  * path to a loop, and raise a uncommon trap if the check of the condition fails.
    38  * The condition checks are promoted from inside the loop body, and thus
    39  * the checks inside the loop could be eliminated. Currently, loop predication
    40  * optimization has been applied to remove array range check and loop invariant
    41  * checks (such as null checks).
    42 */
    44 //-------------------------------is_uncommon_trap_proj----------------------------
    45 // Return true if proj is the form of "proj->[region->..]call_uct"
    46 bool PhaseIdealLoop::is_uncommon_trap_proj(ProjNode* proj, Deoptimization::DeoptReason reason) {
    47   int path_limit = 10;
    48   assert(proj, "invalid argument");
    49   Node* out = proj;
    50   for (int ct = 0; ct < path_limit; ct++) {
    51     out = out->unique_ctrl_out();
    52     if (out == NULL)
    53       return false;
    54     if (out->is_CallStaticJava()) {
    55       int req = out->as_CallStaticJava()->uncommon_trap_request();
    56       if (req != 0) {
    57         Deoptimization::DeoptReason trap_reason = Deoptimization::trap_request_reason(req);
    58         if (trap_reason == reason || reason == Deoptimization::Reason_none) {
    59            return true;
    60         }
    61       }
    62       return false; // don't do further after call
    63     }
    64     if (out->Opcode() != Op_Region)
    65       return false;
    66   }
    67   return false;
    68 }
    70 //-------------------------------is_uncommon_trap_if_pattern-------------------------
    71 // Return true  for "if(test)-> proj -> ...
    72 //                          |
    73 //                          V
    74 //                      other_proj->[region->..]call_uct"
    75 //
    76 // "must_reason_predicate" means the uct reason must be Reason_predicate
    77 bool PhaseIdealLoop::is_uncommon_trap_if_pattern(ProjNode *proj, Deoptimization::DeoptReason reason) {
    78   Node *in0 = proj->in(0);
    79   if (!in0->is_If()) return false;
    80   // Variation of a dead If node.
    81   if (in0->outcnt() < 2)  return false;
    82   IfNode* iff = in0->as_If();
    84   // we need "If(Conv2B(Opaque1(...)))" pattern for reason_predicate
    85   if (reason != Deoptimization::Reason_none) {
    86     if (iff->in(1)->Opcode() != Op_Conv2B ||
    87        iff->in(1)->in(1)->Opcode() != Op_Opaque1) {
    88       return false;
    89     }
    90   }
    92   ProjNode* other_proj = iff->proj_out(1-proj->_con)->as_Proj();
    93   if (is_uncommon_trap_proj(other_proj, reason)) {
    94     assert(reason == Deoptimization::Reason_none ||
    95            Compile::current()->is_predicate_opaq(iff->in(1)->in(1)), "should be on the list");
    96     return true;
    97   }
    98   return false;
    99 }
   101 //-------------------------------register_control-------------------------
   102 void PhaseIdealLoop::register_control(Node* n, IdealLoopTree *loop, Node* pred) {
   103   assert(n->is_CFG(), "must be control node");
   104   _igvn.register_new_node_with_optimizer(n);
   105   loop->_body.push(n);
   106   set_loop(n, loop);
   107   // When called from beautify_loops() idom is not constructed yet.
   108   if (_idom != NULL) {
   109     set_idom(n, pred, dom_depth(pred));
   110   }
   111 }
   113 //------------------------------create_new_if_for_predicate------------------------
   114 // create a new if above the uct_if_pattern for the predicate to be promoted.
   115 //
   116 //          before                                after
   117 //        ----------                           ----------
   118 //           ctrl                                 ctrl
   119 //            |                                     |
   120 //            |                                     |
   121 //            v                                     v
   122 //           iff                                 new_iff
   123 //          /    \                                /      \
   124 //         /      \                              /        \
   125 //        v        v                            v          v
   126 //  uncommon_proj cont_proj                   if_uct     if_cont
   127 // \      |        |                           |          |
   128 //  \     |        |                           |          |
   129 //   v    v        v                           |          v
   130 //     rgn       loop                          |         iff
   131 //      |                                      |        /     \
   132 //      |                                      |       /       \
   133 //      v                                      |      v         v
   134 // uncommon_trap                               | uncommon_proj cont_proj
   135 //                                           \  \    |           |
   136 //                                            \  \   |           |
   137 //                                             v  v  v           v
   138 //                                               rgn           loop
   139 //                                                |
   140 //                                                |
   141 //                                                v
   142 //                                           uncommon_trap
   143 //
   144 //
   145 // We will create a region to guard the uct call if there is no one there.
   146 // The true projecttion (if_cont) of the new_iff is returned.
   147 // This code is also used to clone predicates to clonned loops.
   148 ProjNode* PhaseIdealLoop::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry,
   149                                                       Deoptimization::DeoptReason reason) {
   150   assert(is_uncommon_trap_if_pattern(cont_proj, reason), "must be a uct if pattern!");
   151   IfNode* iff = cont_proj->in(0)->as_If();
   153   ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con);
   154   Node     *rgn   = uncommon_proj->unique_ctrl_out();
   155   assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
   157   uint proj_index = 1; // region's edge corresponding to uncommon_proj
   158   if (!rgn->is_Region()) { // create a region to guard the call
   159     assert(rgn->is_Call(), "must be call uct");
   160     CallNode* call = rgn->as_Call();
   161     IdealLoopTree* loop = get_loop(call);
   162     rgn = new (C, 1) RegionNode(1);
   163     rgn->add_req(uncommon_proj);
   164     register_control(rgn, loop, uncommon_proj);
   165     _igvn.hash_delete(call);
   166     call->set_req(0, rgn);
   167     // When called from beautify_loops() idom is not constructed yet.
   168     if (_idom != NULL) {
   169       set_idom(call, rgn, dom_depth(rgn));
   170     }
   171   } else {
   172     // Find region's edge corresponding to uncommon_proj
   173     for (; proj_index < rgn->req(); proj_index++)
   174       if (rgn->in(proj_index) == uncommon_proj) break;
   175     assert(proj_index < rgn->req(), "sanity");
   176   }
   178   Node* entry = iff->in(0);
   179   if (new_entry != NULL) {
   180     // Clonning the predicate to new location.
   181     entry = new_entry;
   182   }
   183   // Create new_iff
   184   IdealLoopTree* lp = get_loop(entry);
   185   IfNode *new_iff = iff->clone()->as_If();
   186   new_iff->set_req(0, entry);
   187   register_control(new_iff, lp, entry);
   188   Node *if_cont = new (C, 1) IfTrueNode(new_iff);
   189   Node *if_uct  = new (C, 1) IfFalseNode(new_iff);
   190   if (cont_proj->is_IfFalse()) {
   191     // Swap
   192     Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp;
   193   }
   194   register_control(if_cont, lp, new_iff);
   195   register_control(if_uct, get_loop(rgn), new_iff);
   197   // if_uct to rgn
   198   _igvn.hash_delete(rgn);
   199   rgn->add_req(if_uct);
   200   // When called from beautify_loops() idom is not constructed yet.
   201   if (_idom != NULL) {
   202     Node* ridom = idom(rgn);
   203     Node* nrdom = dom_lca(ridom, new_iff);
   204     set_idom(rgn, nrdom, dom_depth(rgn));
   205   }
   207   // If rgn has phis add new edges which has the same
   208   // value as on original uncommon_proj pass.
   209   assert(rgn->in(rgn->req() -1) == if_uct, "new edge should be last");
   210   bool has_phi = false;
   211   for (DUIterator_Fast imax, i = rgn->fast_outs(imax); i < imax; i++) {
   212     Node* use = rgn->fast_out(i);
   213     if (use->is_Phi() && use->outcnt() > 0) {
   214       assert(use->in(0) == rgn, "");
   215       _igvn.hash_delete(use);
   216       use->add_req(use->in(proj_index));
   217       _igvn._worklist.push(use);
   218       has_phi = true;
   219     }
   220   }
   221   assert(!has_phi || rgn->req() > 3, "no phis when region is created");
   223   if (new_entry == NULL) {
   224     // Attach if_cont to iff
   225     _igvn.hash_delete(iff);
   226     iff->set_req(0, if_cont);
   227     if (_idom != NULL) {
   228       set_idom(iff, if_cont, dom_depth(iff));
   229     }
   230   }
   231   return if_cont->as_Proj();
   232 }
   234 //------------------------------create_new_if_for_predicate------------------------
   235 // Create a new if below new_entry for the predicate to be cloned (IGVN optimization)
   236 ProjNode* PhaseIterGVN::create_new_if_for_predicate(ProjNode* cont_proj, Node* new_entry,
   237                                                     Deoptimization::DeoptReason reason) {
   238   assert(new_entry != 0, "only used for clone predicate");
   239   assert(PhaseIdealLoop::is_uncommon_trap_if_pattern(cont_proj, reason), "must be a uct if pattern!");
   240   IfNode* iff = cont_proj->in(0)->as_If();
   242   ProjNode *uncommon_proj = iff->proj_out(1 - cont_proj->_con);
   243   Node     *rgn   = uncommon_proj->unique_ctrl_out();
   244   assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
   246   uint proj_index = 1; // region's edge corresponding to uncommon_proj
   247   if (!rgn->is_Region()) { // create a region to guard the call
   248     assert(rgn->is_Call(), "must be call uct");
   249     CallNode* call = rgn->as_Call();
   250     rgn = new (C, 1) RegionNode(1);
   251     register_new_node_with_optimizer(rgn);
   252     rgn->add_req(uncommon_proj);
   253     hash_delete(call);
   254     call->set_req(0, rgn);
   255   } else {
   256     // Find region's edge corresponding to uncommon_proj
   257     for (; proj_index < rgn->req(); proj_index++)
   258       if (rgn->in(proj_index) == uncommon_proj) break;
   259     assert(proj_index < rgn->req(), "sanity");
   260   }
   262   // Create new_iff in new location.
   263   IfNode *new_iff = iff->clone()->as_If();
   264   new_iff->set_req(0, new_entry);
   266   register_new_node_with_optimizer(new_iff);
   267   Node *if_cont = new (C, 1) IfTrueNode(new_iff);
   268   Node *if_uct  = new (C, 1) IfFalseNode(new_iff);
   269   if (cont_proj->is_IfFalse()) {
   270     // Swap
   271     Node* tmp = if_uct; if_uct = if_cont; if_cont = tmp;
   272   }
   273   register_new_node_with_optimizer(if_cont);
   274   register_new_node_with_optimizer(if_uct);
   276   // if_uct to rgn
   277   hash_delete(rgn);
   278   rgn->add_req(if_uct);
   280   // If rgn has phis add corresponding new edges which has the same
   281   // value as on original uncommon_proj pass.
   282   assert(rgn->in(rgn->req() -1) == if_uct, "new edge should be last");
   283   bool has_phi = false;
   284   for (DUIterator_Fast imax, i = rgn->fast_outs(imax); i < imax; i++) {
   285     Node* use = rgn->fast_out(i);
   286     if (use->is_Phi() && use->outcnt() > 0) {
   287       hash_delete(use);
   288       use->add_req(use->in(proj_index));
   289       _worklist.push(use);
   290       has_phi = true;
   291     }
   292   }
   293   assert(!has_phi || rgn->req() > 3, "no phis when region is created");
   295   return if_cont->as_Proj();
   296 }
   298 //--------------------------clone_predicate-----------------------
   299 ProjNode* PhaseIdealLoop::clone_predicate(ProjNode* predicate_proj, Node* new_entry,
   300                                           Deoptimization::DeoptReason reason,
   301                                           PhaseIdealLoop* loop_phase,
   302                                           PhaseIterGVN* igvn) {
   303   ProjNode* new_predicate_proj;
   304   if (loop_phase != NULL) {
   305     new_predicate_proj = loop_phase->create_new_if_for_predicate(predicate_proj, new_entry, reason);
   306   } else {
   307     new_predicate_proj =       igvn->create_new_if_for_predicate(predicate_proj, new_entry, reason);
   308   }
   309   IfNode* iff = new_predicate_proj->in(0)->as_If();
   310   Node* ctrl  = iff->in(0);
   312   // Match original condition since predicate's projections could be swapped.
   313   assert(predicate_proj->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
   314   Node* opq = new (igvn->C, 2) Opaque1Node(igvn->C, predicate_proj->in(0)->in(1)->in(1)->in(1));
   315   igvn->C->add_predicate_opaq(opq);
   317   Node* bol = new (igvn->C, 2) Conv2BNode(opq);
   318   if (loop_phase != NULL) {
   319     loop_phase->register_new_node(opq, ctrl);
   320     loop_phase->register_new_node(bol, ctrl);
   321   } else {
   322     igvn->register_new_node_with_optimizer(opq);
   323     igvn->register_new_node_with_optimizer(bol);
   324   }
   325   igvn->hash_delete(iff);
   326   iff->set_req(1, bol);
   327   return new_predicate_proj;
   328 }
   330 //--------------------------move_predicate-----------------------
   331 // Cut predicate from old place and move it to new.
   332 ProjNode* PhaseIdealLoop::move_predicate(ProjNode* predicate_proj, Node* new_entry,
   333                                          Deoptimization::DeoptReason reason,
   334                                          PhaseIdealLoop* loop_phase,
   335                                          PhaseIterGVN* igvn) {
   336   assert(new_entry != NULL, "must be");
   337   assert(predicate_proj->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
   338   IfNode* iff = predicate_proj->in(0)->as_If();
   339   Node* old_entry = iff->in(0);
   341   // Cut predicate from old place.
   342   Node* old = predicate_proj;
   343   igvn->_worklist.push(old);
   344   for (DUIterator_Last imin, i = old->last_outs(imin); i >= imin; ) {
   345     Node* use = old->last_out(i);  // for each use...
   346     igvn->hash_delete(use);
   347     igvn->_worklist.push(use);
   348     // Update use-def info
   349     uint uses_found = 0;
   350     for (uint j = 0; j < use->req(); j++) {
   351       if (use->in(j) == old) {
   352         use->set_req(j, old_entry);
   353         uses_found++;
   354         if (loop_phase != NULL) {
   355           if (use->is_CFG()) {
   356             // When called from beautify_loops() idom is not constructed yet.
   357             if (loop_phase->_idom != NULL)
   358               loop_phase->set_idom(use, old_entry, loop_phase->dom_depth(use));
   359           } else {
   360             loop_phase->set_ctrl(use, old_entry);
   361           }
   362         }
   363       }
   364     }
   365     i -= uses_found;    // we deleted 1 or more copies of this edge
   366   }
   368   // Move predicate.
   369   igvn->hash_delete(iff);
   370   iff->set_req(0, new_entry);
   371   igvn->_worklist.push(iff);
   373   if (loop_phase != NULL) {
   374     // Fix up idom and ctrl.
   375     loop_phase->set_ctrl(iff->in(1), new_entry);
   376     loop_phase->set_ctrl(iff->in(1)->in(1), new_entry);
   377     // When called from beautify_loops() idom is not constructed yet.
   378     if (loop_phase->_idom != NULL)
   379       loop_phase->set_idom(iff, new_entry, loop_phase->dom_depth(iff));
   380   }
   382   return predicate_proj;
   383 }
   385 //--------------------------clone_loop_predicates-----------------------
   386 // Interface from IGVN
   387 Node* PhaseIterGVN::clone_loop_predicates(Node* old_entry, Node* new_entry) {
   388   return PhaseIdealLoop::clone_loop_predicates(old_entry, new_entry, false, NULL, this);
   389 }
   390 Node* PhaseIterGVN::move_loop_predicates(Node* old_entry, Node* new_entry) {
   391   return PhaseIdealLoop::clone_loop_predicates(old_entry, new_entry, true, NULL, this);
   392 }
   394 // Interface from PhaseIdealLoop
   395 Node* PhaseIdealLoop::clone_loop_predicates(Node* old_entry, Node* new_entry) {
   396   return clone_loop_predicates(old_entry, new_entry, false, this, &this->_igvn);
   397 }
   398 Node* PhaseIdealLoop::move_loop_predicates(Node* old_entry, Node* new_entry) {
   399   return clone_loop_predicates(old_entry, new_entry, true, this, &this->_igvn);
   400 }
   402 // Clone loop predicates to cloned loops (peeled, unswitched, split_if).
   403 Node* PhaseIdealLoop::clone_loop_predicates(Node* old_entry, Node* new_entry,
   404                                                 bool move_predicates,
   405                                                 PhaseIdealLoop* loop_phase,
   406                                                 PhaseIterGVN* igvn) {
   407 #ifdef ASSERT
   408   if (new_entry == NULL || !(new_entry->is_Proj() || new_entry->is_Region() || new_entry->is_SafePoint())) {
   409     if (new_entry != NULL)
   410       new_entry->dump();
   411     assert(false, "not IfTrue, IfFalse, Region or SafePoint");
   412   }
   413 #endif
   414   // Search original predicates
   415   Node* entry = old_entry;
   416   if (UseLoopPredicate) {
   417     ProjNode* predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
   418     if (predicate_proj != NULL) { // right pattern that can be used by loop predication
   419       assert(entry->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
   420       if (move_predicates) {
   421         new_entry =  move_predicate(predicate_proj, new_entry,
   422                                     Deoptimization::Reason_predicate,
   423                                     loop_phase, igvn);
   424         assert(new_entry == predicate_proj, "old predicate fall through projection");
   425       } else {
   426         // clone predicate
   427         new_entry = clone_predicate(predicate_proj, new_entry,
   428                                     Deoptimization::Reason_predicate,
   429                                     loop_phase, igvn);
   430         assert(new_entry != NULL && new_entry->is_Proj(), "IfTrue or IfFalse after clone predicate");
   431       }
   432       if (TraceLoopPredicate) {
   433         tty->print_cr("Loop Predicate %s: ", move_predicates ? "moved" : "cloned");
   434         debug_only( new_entry->in(0)->dump(); )
   435       }
   436     }
   437   }
   438   return new_entry;
   439 }
   441 //--------------------------eliminate_loop_predicates-----------------------
   442 void PhaseIdealLoop::eliminate_loop_predicates(Node* entry) {
   443   if (UseLoopPredicate) {
   444     ProjNode* predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
   445     if (predicate_proj != NULL) { // right pattern that can be used by loop predication
   446       Node* n = entry->in(0)->in(1)->in(1);
   447       assert(n->Opcode()==Op_Opaque1, "must be");
   448       // Remove Opaque1 node from predicates list.
   449       // IGVN will remove this predicate check.
   450       _igvn.replace_node(n, n->in(1));
   451     }
   452   }
   453 }
   455 //--------------------------skip_loop_predicates------------------------------
   456 // Skip related predicates.
   457 Node* PhaseIdealLoop::skip_loop_predicates(Node* entry) {
   458   Node* predicate = NULL;
   459   if (UseLoopPredicate) {
   460     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
   461     if (predicate != NULL) { // right pattern that can be used by loop predication
   462       assert(entry->is_Proj() && entry->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
   463       IfNode* iff = entry->in(0)->as_If();
   464       ProjNode* uncommon_proj = iff->proj_out(1 - entry->as_Proj()->_con);
   465       Node* rgn = uncommon_proj->unique_ctrl_out();
   466       assert(rgn->is_Region() || rgn->is_Call(), "must be a region or call uct");
   467       entry = entry->in(0)->in(0);
   468       while (entry != NULL && entry->is_Proj() && entry->in(0)->is_If()) {
   469         uncommon_proj = entry->in(0)->as_If()->proj_out(1 - entry->as_Proj()->_con);
   470         if (uncommon_proj->unique_ctrl_out() != rgn)
   471           break;
   472         entry = entry->in(0)->in(0);
   473       }
   474     }
   475   }
   476   return entry;
   477 }
   479 //--------------------------find_predicate_insertion_point-------------------
   480 // Find a good location to insert a predicate
   481 ProjNode* PhaseIdealLoop::find_predicate_insertion_point(Node* start_c, Deoptimization::DeoptReason reason) {
   482   if (start_c == NULL || !start_c->is_Proj())
   483     return NULL;
   484   if (is_uncommon_trap_if_pattern(start_c->as_Proj(), reason)) {
   485     return start_c->as_Proj();
   486   }
   487   return NULL;
   488 }
   490 //--------------------------find_predicate------------------------------------
   491 // Find a predicate
   492 Node* PhaseIdealLoop::find_predicate(Node* entry) {
   493   Node* predicate = NULL;
   494   if (UseLoopPredicate) {
   495     predicate = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
   496     if (predicate != NULL) { // right pattern that can be used by loop predication
   497       assert(entry->in(0)->in(1)->in(1)->Opcode()==Op_Opaque1, "must be");
   498       return entry;
   499     }
   500   }
   501   return NULL;
   502 }
   504 //------------------------------Invariance-----------------------------------
   505 // Helper class for loop_predication_impl to compute invariance on the fly and
   506 // clone invariants.
   507 class Invariance : public StackObj {
   508   VectorSet _visited, _invariant;
   509   Node_Stack _stack;
   510   VectorSet _clone_visited;
   511   Node_List _old_new; // map of old to new (clone)
   512   IdealLoopTree* _lpt;
   513   PhaseIdealLoop* _phase;
   515   // Helper function to set up the invariance for invariance computation
   516   // If n is a known invariant, set up directly. Otherwise, look up the
   517   // the possibility to push n onto the stack for further processing.
   518   void visit(Node* use, Node* n) {
   519     if (_lpt->is_invariant(n)) { // known invariant
   520       _invariant.set(n->_idx);
   521     } else if (!n->is_CFG()) {
   522       Node *n_ctrl = _phase->ctrl_or_self(n);
   523       Node *u_ctrl = _phase->ctrl_or_self(use); // self if use is a CFG
   524       if (_phase->is_dominator(n_ctrl, u_ctrl)) {
   525         _stack.push(n, n->in(0) == NULL ? 1 : 0);
   526       }
   527     }
   528   }
   530   // Compute invariance for "the_node" and (possibly) all its inputs recursively
   531   // on the fly
   532   void compute_invariance(Node* n) {
   533     assert(_visited.test(n->_idx), "must be");
   534     visit(n, n);
   535     while (_stack.is_nonempty()) {
   536       Node*  n = _stack.node();
   537       uint idx = _stack.index();
   538       if (idx == n->req()) { // all inputs are processed
   539         _stack.pop();
   540         // n is invariant if it's inputs are all invariant
   541         bool all_inputs_invariant = true;
   542         for (uint i = 0; i < n->req(); i++) {
   543           Node* in = n->in(i);
   544           if (in == NULL) continue;
   545           assert(_visited.test(in->_idx), "must have visited input");
   546           if (!_invariant.test(in->_idx)) { // bad guy
   547             all_inputs_invariant = false;
   548             break;
   549           }
   550         }
   551         if (all_inputs_invariant) {
   552           _invariant.set(n->_idx); // I am a invariant too
   553         }
   554       } else { // process next input
   555         _stack.set_index(idx + 1);
   556         Node* m = n->in(idx);
   557         if (m != NULL && !_visited.test_set(m->_idx)) {
   558           visit(n, m);
   559         }
   560       }
   561     }
   562   }
   564   // Helper function to set up _old_new map for clone_nodes.
   565   // If n is a known invariant, set up directly ("clone" of n == n).
   566   // Otherwise, push n onto the stack for real cloning.
   567   void clone_visit(Node* n) {
   568     assert(_invariant.test(n->_idx), "must be invariant");
   569     if (_lpt->is_invariant(n)) { // known invariant
   570       _old_new.map(n->_idx, n);
   571     } else { // to be cloned
   572       assert(!n->is_CFG(), "should not see CFG here");
   573       _stack.push(n, n->in(0) == NULL ? 1 : 0);
   574     }
   575   }
   577   // Clone "n" and (possibly) all its inputs recursively
   578   void clone_nodes(Node* n, Node* ctrl) {
   579     clone_visit(n);
   580     while (_stack.is_nonempty()) {
   581       Node*  n = _stack.node();
   582       uint idx = _stack.index();
   583       if (idx == n->req()) { // all inputs processed, clone n!
   584         _stack.pop();
   585         // clone invariant node
   586         Node* n_cl = n->clone();
   587         _old_new.map(n->_idx, n_cl);
   588         _phase->register_new_node(n_cl, ctrl);
   589         for (uint i = 0; i < n->req(); i++) {
   590           Node* in = n_cl->in(i);
   591           if (in == NULL) continue;
   592           n_cl->set_req(i, _old_new[in->_idx]);
   593         }
   594       } else { // process next input
   595         _stack.set_index(idx + 1);
   596         Node* m = n->in(idx);
   597         if (m != NULL && !_clone_visited.test_set(m->_idx)) {
   598           clone_visit(m); // visit the input
   599         }
   600       }
   601     }
   602   }
   604  public:
   605   Invariance(Arena* area, IdealLoopTree* lpt) :
   606     _lpt(lpt), _phase(lpt->_phase),
   607     _visited(area), _invariant(area), _stack(area, 10 /* guess */),
   608     _clone_visited(area), _old_new(area)
   609   {}
   611   // Map old to n for invariance computation and clone
   612   void map_ctrl(Node* old, Node* n) {
   613     assert(old->is_CFG() && n->is_CFG(), "must be");
   614     _old_new.map(old->_idx, n); // "clone" of old is n
   615     _invariant.set(old->_idx);  // old is invariant
   616     _clone_visited.set(old->_idx);
   617   }
   619   // Driver function to compute invariance
   620   bool is_invariant(Node* n) {
   621     if (!_visited.test_set(n->_idx))
   622       compute_invariance(n);
   623     return (_invariant.test(n->_idx) != 0);
   624   }
   626   // Driver function to clone invariant
   627   Node* clone(Node* n, Node* ctrl) {
   628     assert(ctrl->is_CFG(), "must be");
   629     assert(_invariant.test(n->_idx), "must be an invariant");
   630     if (!_clone_visited.test(n->_idx))
   631       clone_nodes(n, ctrl);
   632     return _old_new[n->_idx];
   633   }
   634 };
   636 //------------------------------is_range_check_if -----------------------------------
   637 // Returns true if the predicate of iff is in "scale*iv + offset u< load_range(ptr)" format
   638 // Note: this function is particularly designed for loop predication. We require load_range
   639 //       and offset to be loop invariant computed on the fly by "invar"
   640 bool IdealLoopTree::is_range_check_if(IfNode *iff, PhaseIdealLoop *phase, Invariance& invar) const {
   641   if (!is_loop_exit(iff)) {
   642     return false;
   643   }
   644   if (!iff->in(1)->is_Bool()) {
   645     return false;
   646   }
   647   const BoolNode *bol = iff->in(1)->as_Bool();
   648   if (bol->_test._test != BoolTest::lt) {
   649     return false;
   650   }
   651   if (!bol->in(1)->is_Cmp()) {
   652     return false;
   653   }
   654   const CmpNode *cmp = bol->in(1)->as_Cmp();
   655   if (cmp->Opcode() != Op_CmpU) {
   656     return false;
   657   }
   658   Node* range = cmp->in(2);
   659   if (range->Opcode() != Op_LoadRange) {
   660     const TypeInt* tint = phase->_igvn.type(range)->isa_int();
   661     if (!OptimizeFill || tint == NULL || tint->empty() || tint->_lo < 0) {
   662       // Allow predication on positive values that aren't LoadRanges.
   663       // This allows optimization of loops where the length of the
   664       // array is a known value and doesn't need to be loaded back
   665       // from the array.
   666       return false;
   667     }
   668   }
   669   if (!invar.is_invariant(range)) {
   670     return false;
   671   }
   672   Node *iv     = _head->as_CountedLoop()->phi();
   673   int   scale  = 0;
   674   Node *offset = NULL;
   675   if (!phase->is_scaled_iv_plus_offset(cmp->in(1), iv, &scale, &offset)) {
   676     return false;
   677   }
   678   if (offset && !invar.is_invariant(offset)) { // offset must be invariant
   679     return false;
   680   }
   681   return true;
   682 }
   684 //------------------------------rc_predicate-----------------------------------
   685 // Create a range check predicate
   686 //
   687 // for (i = init; i < limit; i += stride) {
   688 //    a[scale*i+offset]
   689 // }
   690 //
   691 // Compute max(scale*i + offset) for init <= i < limit and build the predicate
   692 // as "max(scale*i + offset) u< a.length".
   693 //
   694 // There are two cases for max(scale*i + offset):
   695 // (1) stride*scale > 0
   696 //   max(scale*i + offset) = scale*(limit-stride) + offset
   697 // (2) stride*scale < 0
   698 //   max(scale*i + offset) = scale*init + offset
   699 BoolNode* PhaseIdealLoop::rc_predicate(Node* ctrl,
   700                                        int scale, Node* offset,
   701                                        Node* init, Node* limit, Node* stride,
   702                                        Node* range, bool upper) {
   703   stringStream* predString = NULL;
   704   if (TraceLoopPredicate) {
   705     predString = new stringStream();
   706     predString->print("rc_predicate ");
   707   }
   709   Node* max_idx_expr  = init;
   710   int stride_con = stride->get_int();
   711   if ((stride_con > 0) == (scale > 0) == upper) {
   712     max_idx_expr = new (C, 3) SubINode(limit, stride);
   713     register_new_node(max_idx_expr, ctrl);
   714     if (TraceLoopPredicate) predString->print("(limit - stride) ");
   715   } else {
   716     if (TraceLoopPredicate) predString->print("init ");
   717   }
   719   if (scale != 1) {
   720     ConNode* con_scale = _igvn.intcon(scale);
   721     max_idx_expr = new (C, 3) MulINode(max_idx_expr, con_scale);
   722     register_new_node(max_idx_expr, ctrl);
   723     if (TraceLoopPredicate) predString->print("* %d ", scale);
   724   }
   726   if (offset && (!offset->is_Con() || offset->get_int() != 0)){
   727     max_idx_expr = new (C, 3) AddINode(max_idx_expr, offset);
   728     register_new_node(max_idx_expr, ctrl);
   729     if (TraceLoopPredicate)
   730       if (offset->is_Con()) predString->print("+ %d ", offset->get_int());
   731       else predString->print("+ offset ");
   732   }
   734   CmpUNode* cmp = new (C, 3) CmpUNode(max_idx_expr, range);
   735   register_new_node(cmp, ctrl);
   736   BoolNode* bol = new (C, 2) BoolNode(cmp, BoolTest::lt);
   737   register_new_node(bol, ctrl);
   739   if (TraceLoopPredicate) {
   740     predString->print_cr("<u range");
   741     tty->print(predString->as_string());
   742   }
   743   return bol;
   744 }
   746 //------------------------------ loop_predication_impl--------------------------
   747 // Insert loop predicates for null checks and range checks
   748 bool PhaseIdealLoop::loop_predication_impl(IdealLoopTree *loop) {
   749   if (!UseLoopPredicate) return false;
   751   if (!loop->_head->is_Loop()) {
   752     // Could be a simple region when irreducible loops are present.
   753     return false;
   754   }
   756   if (loop->_head->unique_ctrl_out()->Opcode() == Op_NeverBranch) {
   757     // do nothing for infinite loops
   758     return false;
   759   }
   761   CountedLoopNode *cl = NULL;
   762   if (loop->_head->is_CountedLoop()) {
   763     cl = loop->_head->as_CountedLoop();
   764     // do nothing for iteration-splitted loops
   765     if (!cl->is_normal_loop()) return false;
   766   }
   768   LoopNode *lpn  = loop->_head->as_Loop();
   769   Node* entry = lpn->in(LoopNode::EntryControl);
   771   ProjNode *predicate_proj = find_predicate_insertion_point(entry, Deoptimization::Reason_predicate);
   772   if (!predicate_proj) {
   773 #ifndef PRODUCT
   774     if (TraceLoopPredicate) {
   775       tty->print("missing predicate:");
   776       loop->dump_head();
   777       lpn->dump(1);
   778     }
   779 #endif
   780     return false;
   781   }
   782   ConNode* zero = _igvn.intcon(0);
   783   set_ctrl(zero, C->root());
   785   ResourceArea *area = Thread::current()->resource_area();
   786   Invariance invar(area, loop);
   788   // Create list of if-projs such that a newer proj dominates all older
   789   // projs in the list, and they all dominate loop->tail()
   790   Node_List if_proj_list(area);
   791   LoopNode *head  = loop->_head->as_Loop();
   792   Node *current_proj = loop->tail(); //start from tail
   793   while (current_proj != head) {
   794     if (loop == get_loop(current_proj) && // still in the loop ?
   795         current_proj->is_Proj()        && // is a projection  ?
   796         current_proj->in(0)->Opcode() == Op_If) { // is a if projection ?
   797       if_proj_list.push(current_proj);
   798     }
   799     current_proj = idom(current_proj);
   800   }
   802   bool hoisted = false; // true if at least one proj is promoted
   803   while (if_proj_list.size() > 0) {
   804     // Following are changed to nonnull when a predicate can be hoisted
   805     ProjNode* new_predicate_proj = NULL;
   807     ProjNode* proj = if_proj_list.pop()->as_Proj();
   808     IfNode*   iff  = proj->in(0)->as_If();
   810     if (!is_uncommon_trap_if_pattern(proj, Deoptimization::Reason_none)) {
   811       if (loop->is_loop_exit(iff)) {
   812         // stop processing the remaining projs in the list because the execution of them
   813         // depends on the condition of "iff" (iff->in(1)).
   814         break;
   815       } else {
   816         // Both arms are inside the loop. There are two cases:
   817         // (1) there is one backward branch. In this case, any remaining proj
   818         //     in the if_proj list post-dominates "iff". So, the condition of "iff"
   819         //     does not determine the execution the remining projs directly, and we
   820         //     can safely continue.
   821         // (2) both arms are forwarded, i.e. a diamond shape. In this case, "proj"
   822         //     does not dominate loop->tail(), so it can not be in the if_proj list.
   823         continue;
   824       }
   825     }
   827     Node*     test = iff->in(1);
   828     if (!test->is_Bool()){ //Conv2B, ...
   829       continue;
   830     }
   831     BoolNode* bol = test->as_Bool();
   832     if (invar.is_invariant(bol)) {
   833       // Invariant test
   834       new_predicate_proj = create_new_if_for_predicate(predicate_proj, NULL,
   835                                                        Deoptimization::Reason_predicate);
   836       Node* ctrl = new_predicate_proj->in(0)->as_If()->in(0);
   837       BoolNode* new_predicate_bol = invar.clone(bol, ctrl)->as_Bool();
   839       // Negate test if necessary
   840       bool negated = false;
   841       if (proj->_con != predicate_proj->_con) {
   842         new_predicate_bol = new (C, 2) BoolNode(new_predicate_bol->in(1), new_predicate_bol->_test.negate());
   843         register_new_node(new_predicate_bol, ctrl);
   844         negated = true;
   845       }
   846       IfNode* new_predicate_iff = new_predicate_proj->in(0)->as_If();
   847       _igvn.hash_delete(new_predicate_iff);
   848       new_predicate_iff->set_req(1, new_predicate_bol);
   849 #ifndef PRODUCT
   850       if (TraceLoopPredicate) {
   851         tty->print("Predicate invariant if%s: %d ", negated ? " negated" : "", new_predicate_iff->_idx);
   852         loop->dump_head();
   853       } else if (TraceLoopOpts) {
   854         tty->print("Predicate IC ");
   855         loop->dump_head();
   856       }
   857 #endif
   858     } else if (cl != NULL && loop->is_range_check_if(iff, this, invar)) {
   859       assert(proj->_con == predicate_proj->_con, "must match");
   861       // Range check for counted loops
   862       const Node*    cmp    = bol->in(1)->as_Cmp();
   863       Node*          idx    = cmp->in(1);
   864       assert(!invar.is_invariant(idx), "index is variant");
   865       assert(cmp->in(2)->Opcode() == Op_LoadRange || OptimizeFill, "must be");
   866       Node* rng = cmp->in(2);
   867       assert(invar.is_invariant(rng), "range must be invariant");
   868       int scale    = 1;
   869       Node* offset = zero;
   870       bool ok = is_scaled_iv_plus_offset(idx, cl->phi(), &scale, &offset);
   871       assert(ok, "must be index expression");
   873       Node* init    = cl->init_trip();
   874       Node* limit   = cl->limit();
   875       Node* stride  = cl->stride();
   877       // Build if's for the upper and lower bound tests.  The
   878       // lower_bound test will dominate the upper bound test and all
   879       // cloned or created nodes will use the lower bound test as
   880       // their declared control.
   881       ProjNode* lower_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, Deoptimization::Reason_predicate);
   882       ProjNode* upper_bound_proj = create_new_if_for_predicate(predicate_proj, NULL, Deoptimization::Reason_predicate);
   883       assert(upper_bound_proj->in(0)->as_If()->in(0) == lower_bound_proj, "should dominate");
   884       Node *ctrl = lower_bound_proj->in(0)->as_If()->in(0);
   886       // Perform cloning to keep Invariance state correct since the
   887       // late schedule will place invariant things in the loop.
   888       rng = invar.clone(rng, ctrl);
   889       if (offset && offset != zero) {
   890         assert(invar.is_invariant(offset), "offset must be loop invariant");
   891         offset = invar.clone(offset, ctrl);
   892       }
   894       // Test the lower bound
   895       Node*  lower_bound_bol = rc_predicate(ctrl, scale, offset, init, limit, stride, rng, false);
   896       IfNode* lower_bound_iff = lower_bound_proj->in(0)->as_If();
   897       _igvn.hash_delete(lower_bound_iff);
   898       lower_bound_iff->set_req(1, lower_bound_bol);
   899       if (TraceLoopPredicate) tty->print_cr("lower bound check if: %d", lower_bound_iff->_idx);
   901       // Test the upper bound
   902       Node* upper_bound_bol = rc_predicate(ctrl, scale, offset, init, limit, stride, rng, true);
   903       IfNode* upper_bound_iff = upper_bound_proj->in(0)->as_If();
   904       _igvn.hash_delete(upper_bound_iff);
   905       upper_bound_iff->set_req(1, upper_bound_bol);
   906       if (TraceLoopPredicate) tty->print_cr("upper bound check if: %d", lower_bound_iff->_idx);
   908       // Fall through into rest of the clean up code which will move
   909       // any dependent nodes onto the upper bound test.
   910       new_predicate_proj = upper_bound_proj;
   912 #ifndef PRODUCT
   913       if (TraceLoopOpts && !TraceLoopPredicate) {
   914         tty->print("Predicate RC ");
   915         loop->dump_head();
   916       }
   917 #endif
   918     } else {
   919       // Loop variant check (for example, range check in non-counted loop)
   920       // with uncommon trap.
   921       continue;
   922     }
   923     assert(new_predicate_proj != NULL, "sanity");
   924     // Success - attach condition (new_predicate_bol) to predicate if
   925     invar.map_ctrl(proj, new_predicate_proj); // so that invariance test can be appropriate
   927     // Eliminate the old If in the loop body
   928     dominated_by( new_predicate_proj, iff, proj->_con != new_predicate_proj->_con );
   930     hoisted = true;
   931     C->set_major_progress();
   932   } // end while
   934 #ifndef PRODUCT
   935   // report that the loop predication has been actually performed
   936   // for this loop
   937   if (TraceLoopPredicate && hoisted) {
   938     tty->print("Loop Predication Performed:");
   939     loop->dump_head();
   940   }
   941 #endif
   943   return hoisted;
   944 }
   946 //------------------------------loop_predication--------------------------------
   947 // driver routine for loop predication optimization
   948 bool IdealLoopTree::loop_predication( PhaseIdealLoop *phase) {
   949   bool hoisted = false;
   950   // Recursively promote predicates
   951   if (_child) {
   952     hoisted = _child->loop_predication( phase);
   953   }
   955   // self
   956   if (!_irreducible && !tail()->is_top()) {
   957     hoisted |= phase->loop_predication_impl(this);
   958   }
   960   if (_next) { //sibling
   961     hoisted |= _next->loop_predication( phase);
   962   }
   964   return hoisted;
   965 }

mercurial