1 /*
   2  * Copyright (c) 2000, 2017, 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 "ci/ciTypeFlow.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "memory/resourceArea.hpp"
  29 #include "opto/addnode.hpp"
  30 #include "opto/castnode.hpp"
  31 #include "opto/cfgnode.hpp"
  32 #include "opto/connode.hpp"
  33 #include "opto/loopnode.hpp"
  34 #include "opto/phaseX.hpp"
  35 #include "opto/runtime.hpp"
  36 #include "opto/rootnode.hpp"
  37 #include "opto/subnode.hpp"
  38 
  39 // Portions of code courtesy of Clifford Click
  40 
  41 // Optimization - Graph Style
  42 
  43 
  44 #ifndef PRODUCT
  45 extern int explicit_null_checks_elided;
  46 #endif
  47 
  48 //=============================================================================
  49 //------------------------------Value------------------------------------------
  50 // Return a tuple for whichever arm of the IF is reachable
  51 const Type* IfNode::Value(PhaseGVN* phase) const {
  52   if( !in(0) ) return Type::TOP;
  53   if( phase->type(in(0)) == Type::TOP )
  54     return Type::TOP;
  55   const Type *t = phase->type(in(1));
  56   if( t == Type::TOP )          // data is undefined
  57     return TypeTuple::IFNEITHER; // unreachable altogether
  58   if( t == TypeInt::ZERO )      // zero, or false
  59     return TypeTuple::IFFALSE;  // only false branch is reachable
  60   if( t == TypeInt::ONE )       // 1, or true
  61     return TypeTuple::IFTRUE;   // only true branch is reachable
  62   assert( t == TypeInt::BOOL, "expected boolean type" );
  63 
  64   return TypeTuple::IFBOTH;     // No progress
  65 }
  66 
  67 const RegMask &IfNode::out_RegMask() const {
  68   return RegMask::Empty;
  69 }
  70 
  71 //------------------------------split_if---------------------------------------
  72 // Look for places where we merge constants, then test on the merged value.
  73 // If the IF test will be constant folded on the path with the constant, we
  74 // win by splitting the IF to before the merge point.
  75 static Node* split_if(IfNode *iff, PhaseIterGVN *igvn) {
  76   // I could be a lot more general here, but I'm trying to squeeze this
  77   // in before the Christmas '98 break so I'm gonna be kinda restrictive
  78   // on the patterns I accept.  CNC
  79 
  80   // Look for a compare of a constant and a merged value
  81   Node *i1 = iff->in(1);
  82   if( !i1->is_Bool() ) return NULL;
  83   BoolNode *b = i1->as_Bool();
  84   Node *cmp = b->in(1);
  85   if( !cmp->is_Cmp() ) return NULL;
  86   i1 = cmp->in(1);
  87   if( i1 == NULL || !i1->is_Phi() ) return NULL;
  88   PhiNode *phi = i1->as_Phi();
  89   if( phi->is_copy() ) return NULL;
  90   Node *con2 = cmp->in(2);
  91   if( !con2->is_Con() ) return NULL;
  92   // See that the merge point contains some constants
  93   Node *con1=NULL;
  94   uint i4;
  95   for( i4 = 1; i4 < phi->req(); i4++ ) {
  96     con1 = phi->in(i4);
  97     if( !con1 ) return NULL;    // Do not optimize partially collapsed merges
  98     if( con1->is_Con() ) break; // Found a constant
  99     // Also allow null-vs-not-null checks
 100     const TypePtr *tp = igvn->type(con1)->isa_ptr();
 101     if( tp && tp->_ptr == TypePtr::NotNull )
 102       break;
 103   }
 104   if( i4 >= phi->req() ) return NULL; // Found no constants
 105 
 106   igvn->C->set_has_split_ifs(true); // Has chance for split-if
 107 
 108   // Make sure that the compare can be constant folded away
 109   Node *cmp2 = cmp->clone();
 110   cmp2->set_req(1,con1);
 111   cmp2->set_req(2,con2);
 112   const Type *t = cmp2->Value(igvn);
 113   // This compare is dead, so whack it!
 114   igvn->remove_dead_node(cmp2);
 115   if( !t->singleton() ) return NULL;
 116 
 117   // No intervening control, like a simple Call
 118   Node *r = iff->in(0);
 119   if( !r->is_Region() ) return NULL;
 120   if (r->is_Loop() && r->in(LoopNode::LoopBackControl)->is_top()) return NULL; // going away anyway
 121   if( phi->region() != r ) return NULL;
 122   // No other users of the cmp/bool
 123   if (b->outcnt() != 1 || cmp->outcnt() != 1) {
 124     //tty->print_cr("many users of cmp/bool");
 125     return NULL;
 126   }
 127 
 128   // Make sure we can determine where all the uses of merged values go
 129   for (DUIterator_Fast jmax, j = r->fast_outs(jmax); j < jmax; j++) {
 130     Node* u = r->fast_out(j);
 131     if( u == r ) continue;
 132     if( u == iff ) continue;
 133     if( u->outcnt() == 0 ) continue; // use is dead & ignorable
 134     if( !u->is_Phi() ) {
 135       /*
 136       if( u->is_Start() ) {
 137         tty->print_cr("Region has inlined start use");
 138       } else {
 139         tty->print_cr("Region has odd use");
 140         u->dump(2);
 141       }*/
 142       return NULL;
 143     }
 144     if( u != phi ) {
 145       // CNC - do not allow any other merged value
 146       //tty->print_cr("Merging another value");
 147       //u->dump(2);
 148       return NULL;
 149     }
 150     // Make sure we can account for all Phi uses
 151     for (DUIterator_Fast kmax, k = u->fast_outs(kmax); k < kmax; k++) {
 152       Node* v = u->fast_out(k); // User of the phi
 153       // CNC - Allow only really simple patterns.
 154       // In particular I disallow AddP of the Phi, a fairly common pattern
 155       if (v == cmp) continue;  // The compare is OK
 156       if (v->is_ConstraintCast()) {
 157         // If the cast is derived from data flow edges, it may not have a control edge.
 158         // If so, it should be safe to split. But follow-up code can not deal with
 159         // this (l. 359). So skip.
 160         if (v->in(0) == NULL) {
 161           return NULL;
 162         }
 163         if (v->in(0)->in(0) == iff) {
 164           continue;               // CastPP/II of the IfNode is OK
 165         }
 166       }
 167       // Disabled following code because I cannot tell if exactly one
 168       // path dominates without a real dominator check. CNC 9/9/1999
 169       //uint vop = v->Opcode();
 170       //if( vop == Op_Phi ) {     // Phi from another merge point might be OK
 171       //  Node *r = v->in(0);     // Get controlling point
 172       //  if( !r ) return NULL;   // Degraded to a copy
 173       //  // Find exactly one path in (either True or False doms, but not IFF)
 174       //  int cnt = 0;
 175       //  for( uint i = 1; i < r->req(); i++ )
 176       //    if( r->in(i) && r->in(i)->in(0) == iff )
 177       //      cnt++;
 178       //  if( cnt == 1 ) continue; // Exactly one of True or False guards Phi
 179       //}
 180       if( !v->is_Call() ) {
 181         /*
 182         if( v->Opcode() == Op_AddP ) {
 183           tty->print_cr("Phi has AddP use");
 184         } else if( v->Opcode() == Op_CastPP ) {
 185           tty->print_cr("Phi has CastPP use");
 186         } else if( v->Opcode() == Op_CastII ) {
 187           tty->print_cr("Phi has CastII use");
 188         } else {
 189           tty->print_cr("Phi has use I cant be bothered with");
 190         }
 191         */
 192       }
 193       return NULL;
 194 
 195       /* CNC - Cut out all the fancy acceptance tests
 196       // Can we clone this use when doing the transformation?
 197       // If all uses are from Phis at this merge or constants, then YES.
 198       if( !v->in(0) && v != cmp ) {
 199         tty->print_cr("Phi has free-floating use");
 200         v->dump(2);
 201         return NULL;
 202       }
 203       for( uint l = 1; l < v->req(); l++ ) {
 204         if( (!v->in(l)->is_Phi() || v->in(l)->in(0) != r) &&
 205             !v->in(l)->is_Con() ) {
 206           tty->print_cr("Phi has use");
 207           v->dump(2);
 208           return NULL;
 209         } // End of if Phi-use input is neither Phi nor Constant
 210       } // End of for all inputs to Phi-use
 211       */
 212     } // End of for all uses of Phi
 213   } // End of for all uses of Region
 214 
 215   // Only do this if the IF node is in a sane state
 216   if (iff->outcnt() != 2)
 217     return NULL;
 218 
 219   // Got a hit!  Do the Mondo Hack!
 220   //
 221   //ABC  a1c   def   ghi            B     1     e     h   A C   a c   d f   g i
 222   // R - Phi - Phi - Phi            Rc - Phi - Phi - Phi   Rx - Phi - Phi - Phi
 223   //     cmp - 2                         cmp - 2               cmp - 2
 224   //       bool                            bool_c                bool_x
 225   //       if                               if_c                  if_x
 226   //      T  F                              T  F                  T  F
 227   // ..s..    ..t ..                   ..s..    ..t..        ..s..    ..t..
 228   //
 229   // Split the paths coming into the merge point into 2 separate groups of
 230   // merges.  On the left will be all the paths feeding constants into the
 231   // Cmp's Phi.  On the right will be the remaining paths.  The Cmp's Phi
 232   // will fold up into a constant; this will let the Cmp fold up as well as
 233   // all the control flow.  Below the original IF we have 2 control
 234   // dependent regions, 's' and 't'.  Now we will merge the two paths
 235   // just prior to 's' and 't' from the two IFs.  At least 1 path (and quite
 236   // likely 2 or more) will promptly constant fold away.
 237   PhaseGVN *phase = igvn;
 238 
 239   // Make a region merging constants and a region merging the rest
 240   uint req_c = 0;
 241   Node* predicate_proj = NULL;
 242   int nb_predicate_proj = 0;
 243   for (uint ii = 1; ii < r->req(); ii++) {
 244     if (phi->in(ii) == con1) {
 245       req_c++;
 246     }
 247     Node* proj = PhaseIdealLoop::find_predicate(r->in(ii));
 248     if (proj != NULL) {
 249       nb_predicate_proj++;
 250       predicate_proj = proj;
 251     }
 252   }
 253 
 254   // If all the defs of the phi are the same constant, we already have the desired end state.
 255   // Skip the split that would create empty phi and region nodes.
 256   if((r->req() - req_c) == 1) {
 257     return NULL;
 258   }
 259 
 260   if (nb_predicate_proj > 1) {
 261     // Can happen in case of loop unswitching and when the loop is
 262     // optimized out: it's not a loop anymore so we don't care about
 263     // predicates.
 264     assert(!r->is_Loop(), "this must not be a loop anymore");
 265     predicate_proj = NULL;
 266   }
 267   Node* predicate_c = NULL;
 268   Node* predicate_x = NULL;
 269   bool counted_loop = r->is_CountedLoop();
 270 
 271   Node *region_c = new RegionNode(req_c + 1);
 272   Node *phi_c    = con1;
 273   uint  len      = r->req();
 274   Node *region_x = new RegionNode(len - req_c);
 275   Node *phi_x    = PhiNode::make_blank(region_x, phi);
 276   for (uint i = 1, i_c = 1, i_x = 1; i < len; i++) {
 277     if (phi->in(i) == con1) {
 278       region_c->init_req( i_c++, r  ->in(i) );
 279       if (r->in(i) == predicate_proj)
 280         predicate_c = predicate_proj;
 281     } else {
 282       region_x->init_req( i_x,   r  ->in(i) );
 283       phi_x   ->init_req( i_x++, phi->in(i) );
 284       if (r->in(i) == predicate_proj)
 285         predicate_x = predicate_proj;
 286     }
 287   }
 288   if (predicate_c != NULL && (req_c > 1)) {
 289     assert(predicate_x == NULL, "only one predicate entry expected");
 290     predicate_c = NULL; // Do not clone predicate below merge point
 291   }
 292   if (predicate_x != NULL && ((len - req_c) > 2)) {
 293     assert(predicate_c == NULL, "only one predicate entry expected");
 294     predicate_x = NULL; // Do not clone predicate below merge point
 295   }
 296 
 297   // Register the new RegionNodes but do not transform them.  Cannot
 298   // transform until the entire Region/Phi conglomerate has been hacked
 299   // as a single huge transform.
 300   igvn->register_new_node_with_optimizer( region_c );
 301   igvn->register_new_node_with_optimizer( region_x );
 302   // Prevent the untimely death of phi_x.  Currently he has no uses.  He is
 303   // about to get one.  If this only use goes away, then phi_x will look dead.
 304   // However, he will be picking up some more uses down below.
 305   Node *hook = new Node(4);
 306   hook->init_req(0, phi_x);
 307   hook->init_req(1, phi_c);
 308   phi_x = phase->transform( phi_x );
 309 
 310   // Make the compare
 311   Node *cmp_c = phase->makecon(t);
 312   Node *cmp_x = cmp->clone();
 313   cmp_x->set_req(1,phi_x);
 314   cmp_x->set_req(2,con2);
 315   cmp_x = phase->transform(cmp_x);
 316   // Make the bool
 317   Node *b_c = phase->transform(new BoolNode(cmp_c,b->_test._test));
 318   Node *b_x = phase->transform(new BoolNode(cmp_x,b->_test._test));
 319   // Make the IfNode
 320   IfNode* iff_c = iff->clone()->as_If();
 321   iff_c->set_req(0, region_c);
 322   iff_c->set_req(1, b_c);
 323   igvn->set_type_bottom(iff_c);
 324   igvn->_worklist.push(iff_c);
 325   hook->init_req(2, iff_c);
 326 
 327   IfNode* iff_x = iff->clone()->as_If();
 328   iff_x->set_req(0, region_x);
 329   iff_x->set_req(1, b_x);
 330   igvn->set_type_bottom(iff_x);
 331   igvn->_worklist.push(iff_x);
 332   hook->init_req(3, iff_x);
 333 
 334   // Make the true/false arms
 335   Node *iff_c_t = phase->transform(new IfTrueNode (iff_c));
 336   Node *iff_c_f = phase->transform(new IfFalseNode(iff_c));
 337   if (predicate_c != NULL) {
 338     assert(predicate_x == NULL, "only one predicate entry expected");
 339     // Clone loop predicates to each path
 340     iff_c_t = igvn->clone_loop_predicates(predicate_c, iff_c_t, !counted_loop);
 341     iff_c_f = igvn->clone_loop_predicates(predicate_c, iff_c_f, !counted_loop);
 342   }
 343   Node *iff_x_t = phase->transform(new IfTrueNode (iff_x));
 344   Node *iff_x_f = phase->transform(new IfFalseNode(iff_x));
 345   if (predicate_x != NULL) {
 346     assert(predicate_c == NULL, "only one predicate entry expected");
 347     // Clone loop predicates to each path
 348     iff_x_t = igvn->clone_loop_predicates(predicate_x, iff_x_t, !counted_loop);
 349     iff_x_f = igvn->clone_loop_predicates(predicate_x, iff_x_f, !counted_loop);
 350   }
 351 
 352   // Merge the TRUE paths
 353   Node *region_s = new RegionNode(3);
 354   igvn->_worklist.push(region_s);
 355   region_s->init_req(1, iff_c_t);
 356   region_s->init_req(2, iff_x_t);
 357   igvn->register_new_node_with_optimizer( region_s );
 358 
 359   // Merge the FALSE paths
 360   Node *region_f = new RegionNode(3);
 361   igvn->_worklist.push(region_f);
 362   region_f->init_req(1, iff_c_f);
 363   region_f->init_req(2, iff_x_f);
 364   igvn->register_new_node_with_optimizer( region_f );
 365 
 366   igvn->hash_delete(cmp);// Remove soon-to-be-dead node from hash table.
 367   cmp->set_req(1,NULL);  // Whack the inputs to cmp because it will be dead
 368   cmp->set_req(2,NULL);
 369   // Check for all uses of the Phi and give them a new home.
 370   // The 'cmp' got cloned, but CastPP/IIs need to be moved.
 371   Node *phi_s = NULL;     // do not construct unless needed
 372   Node *phi_f = NULL;     // do not construct unless needed
 373   for (DUIterator_Last i2min, i2 = phi->last_outs(i2min); i2 >= i2min; --i2) {
 374     Node* v = phi->last_out(i2);// User of the phi
 375     igvn->rehash_node_delayed(v); // Have to fixup other Phi users
 376     uint vop = v->Opcode();
 377     Node *proj = NULL;
 378     if( vop == Op_Phi ) {       // Remote merge point
 379       Node *r = v->in(0);
 380       for (uint i3 = 1; i3 < r->req(); i3++)
 381         if (r->in(i3) && r->in(i3)->in(0) == iff) {
 382           proj = r->in(i3);
 383           break;
 384         }
 385     } else if( v->is_ConstraintCast() ) {
 386       proj = v->in(0);          // Controlling projection
 387     } else {
 388       assert( 0, "do not know how to handle this guy" );
 389     }
 390 
 391     Node *proj_path_data, *proj_path_ctrl;
 392     if( proj->Opcode() == Op_IfTrue ) {
 393       if( phi_s == NULL ) {
 394         // Only construct phi_s if needed, otherwise provides
 395         // interfering use.
 396         phi_s = PhiNode::make_blank(region_s,phi);
 397         phi_s->init_req( 1, phi_c );
 398         phi_s->init_req( 2, phi_x );
 399         hook->add_req(phi_s);
 400         phi_s = phase->transform(phi_s);
 401       }
 402       proj_path_data = phi_s;
 403       proj_path_ctrl = region_s;
 404     } else {
 405       if( phi_f == NULL ) {
 406         // Only construct phi_f if needed, otherwise provides
 407         // interfering use.
 408         phi_f = PhiNode::make_blank(region_f,phi);
 409         phi_f->init_req( 1, phi_c );
 410         phi_f->init_req( 2, phi_x );
 411         hook->add_req(phi_f);
 412         phi_f = phase->transform(phi_f);
 413       }
 414       proj_path_data = phi_f;
 415       proj_path_ctrl = region_f;
 416     }
 417 
 418     // Fixup 'v' for for the split
 419     if( vop == Op_Phi ) {       // Remote merge point
 420       uint i;
 421       for( i = 1; i < v->req(); i++ )
 422         if( v->in(i) == phi )
 423           break;
 424       v->set_req(i, proj_path_data );
 425     } else if( v->is_ConstraintCast() ) {
 426       v->set_req(0, proj_path_ctrl );
 427       v->set_req(1, proj_path_data );
 428     } else
 429       ShouldNotReachHere();
 430   }
 431 
 432   // Now replace the original iff's True/False with region_s/region_t.
 433   // This makes the original iff go dead.
 434   for (DUIterator_Last i3min, i3 = iff->last_outs(i3min); i3 >= i3min; --i3) {
 435     Node* p = iff->last_out(i3);
 436     assert( p->Opcode() == Op_IfTrue || p->Opcode() == Op_IfFalse, "" );
 437     Node *u = (p->Opcode() == Op_IfTrue) ? region_s : region_f;
 438     // Replace p with u
 439     igvn->add_users_to_worklist(p);
 440     for (DUIterator_Last lmin, l = p->last_outs(lmin); l >= lmin;) {
 441       Node* x = p->last_out(l);
 442       igvn->hash_delete(x);
 443       uint uses_found = 0;
 444       for( uint j = 0; j < x->req(); j++ ) {
 445         if( x->in(j) == p ) {
 446           x->set_req(j, u);
 447           uses_found++;
 448         }
 449       }
 450       l -= uses_found;    // we deleted 1 or more copies of this edge
 451     }
 452     igvn->remove_dead_node(p);
 453   }
 454 
 455   // Force the original merge dead
 456   igvn->hash_delete(r);
 457   // First, remove region's dead users.
 458   for (DUIterator_Last lmin, l = r->last_outs(lmin); l >= lmin;) {
 459     Node* u = r->last_out(l);
 460     if( u == r ) {
 461       r->set_req(0, NULL);
 462     } else {
 463       assert(u->outcnt() == 0, "only dead users");
 464       igvn->remove_dead_node(u);
 465     }
 466     l -= 1;
 467   }
 468   igvn->remove_dead_node(r);
 469 
 470   // Now remove the bogus extra edges used to keep things alive
 471   igvn->remove_dead_node( hook );
 472 
 473   // Must return either the original node (now dead) or a new node
 474   // (Do not return a top here, since that would break the uniqueness of top.)
 475   return new ConINode(TypeInt::ZERO);
 476 }
 477 
 478 // if this IfNode follows a range check pattern return the projection
 479 // for the failed path
 480 ProjNode* IfNode::range_check_trap_proj(int& flip_test, Node*& l, Node*& r) {
 481   if (outcnt() != 2) {
 482     return NULL;
 483   }
 484   Node* b = in(1);
 485   if (b == NULL || !b->is_Bool())  return NULL;
 486   BoolNode* bn = b->as_Bool();
 487   Node* cmp = bn->in(1);
 488   if (cmp == NULL)  return NULL;
 489   if (cmp->Opcode() != Op_CmpU)  return NULL;
 490 
 491   l = cmp->in(1);
 492   r = cmp->in(2);
 493   flip_test = 1;
 494   if (bn->_test._test == BoolTest::le) {
 495     l = cmp->in(2);
 496     r = cmp->in(1);
 497     flip_test = 2;
 498   } else if (bn->_test._test != BoolTest::lt) {
 499     return NULL;
 500   }
 501   if (l->is_top())  return NULL;   // Top input means dead test
 502   if (r->Opcode() != Op_LoadRange && !is_RangeCheck())  return NULL;
 503 
 504   // We have recognized one of these forms:
 505   //  Flip 1:  If (Bool[<] CmpU(l, LoadRange)) ...
 506   //  Flip 2:  If (Bool[<=] CmpU(LoadRange, l)) ...
 507 
 508   ProjNode* iftrap = proj_out(flip_test == 2 ? true : false);
 509   return iftrap;
 510 }
 511 
 512 
 513 //------------------------------is_range_check---------------------------------
 514 // Return 0 if not a range check.  Return 1 if a range check and set index and
 515 // offset.  Return 2 if we had to negate the test.  Index is NULL if the check
 516 // is versus a constant.
 517 int RangeCheckNode::is_range_check(Node* &range, Node* &index, jint &offset) {
 518   int flip_test = 0;
 519   Node* l = NULL;
 520   Node* r = NULL;
 521   ProjNode* iftrap = range_check_trap_proj(flip_test, l, r);
 522 
 523   if (iftrap == NULL) {
 524     return 0;
 525   }
 526 
 527   // Make sure it's a real range check by requiring an uncommon trap
 528   // along the OOB path.  Otherwise, it's possible that the user wrote
 529   // something which optimized to look like a range check but behaves
 530   // in some other way.
 531   if (iftrap->is_uncommon_trap_proj(Deoptimization::Reason_range_check) == NULL) {
 532     return 0;
 533   }
 534 
 535   // Look for index+offset form
 536   Node* ind = l;
 537   jint  off = 0;
 538   if (l->is_top()) {
 539     return 0;
 540   } else if (l->Opcode() == Op_AddI) {
 541     if ((off = l->in(1)->find_int_con(0)) != 0) {
 542       ind = l->in(2)->uncast();
 543     } else if ((off = l->in(2)->find_int_con(0)) != 0) {
 544       ind = l->in(1)->uncast();
 545     }
 546   } else if ((off = l->find_int_con(-1)) >= 0) {
 547     // constant offset with no variable index
 548     ind = NULL;
 549   } else {
 550     // variable index with no constant offset (or dead negative index)
 551     off = 0;
 552   }
 553 
 554   // Return all the values:
 555   index  = ind;
 556   offset = off;
 557   range  = r;
 558   return flip_test;
 559 }
 560 
 561 //------------------------------adjust_check-----------------------------------
 562 // Adjust (widen) a prior range check
 563 static void adjust_check(Node* proj, Node* range, Node* index,
 564                          int flip, jint off_lo, PhaseIterGVN* igvn) {
 565   PhaseGVN *gvn = igvn;
 566   // Break apart the old check
 567   Node *iff = proj->in(0);
 568   Node *bol = iff->in(1);
 569   if( bol->is_top() ) return;   // In case a partially dead range check appears
 570   // bail (or bomb[ASSERT/DEBUG]) if NOT projection-->IfNode-->BoolNode
 571   DEBUG_ONLY( if( !bol->is_Bool() ) { proj->dump(3); fatal("Expect projection-->IfNode-->BoolNode"); } )
 572   if( !bol->is_Bool() ) return;
 573 
 574   Node *cmp = bol->in(1);
 575   // Compute a new check
 576   Node *new_add = gvn->intcon(off_lo);
 577   if( index ) {
 578     new_add = off_lo ? gvn->transform(new AddINode( index, new_add )) : index;
 579   }
 580   Node *new_cmp = (flip == 1)
 581     ? new CmpUNode( new_add, range )
 582     : new CmpUNode( range, new_add );
 583   new_cmp = gvn->transform(new_cmp);
 584   // See if no need to adjust the existing check
 585   if( new_cmp == cmp ) return;
 586   // Else, adjust existing check
 587   Node *new_bol = gvn->transform( new BoolNode( new_cmp, bol->as_Bool()->_test._test ) );
 588   igvn->rehash_node_delayed( iff );
 589   iff->set_req_X( 1, new_bol, igvn );
 590 }
 591 
 592 //------------------------------up_one_dom-------------------------------------
 593 // Walk up the dominator tree one step.  Return NULL at root or true
 594 // complex merges.  Skips through small diamonds.
 595 Node* IfNode::up_one_dom(Node *curr, bool linear_only) {
 596   Node *dom = curr->in(0);
 597   if( !dom )                    // Found a Region degraded to a copy?
 598     return curr->nonnull_req(); // Skip thru it
 599 
 600   if( curr != dom )             // Normal walk up one step?
 601     return dom;
 602 
 603   // Use linear_only if we are still parsing, since we cannot
 604   // trust the regions to be fully filled in.
 605   if (linear_only)
 606     return NULL;
 607 
 608   if( dom->is_Root() )
 609     return NULL;
 610 
 611   // Else hit a Region.  Check for a loop header
 612   if( dom->is_Loop() )
 613     return dom->in(1);          // Skip up thru loops
 614 
 615   // Check for small diamonds
 616   Node *din1, *din2, *din3, *din4;
 617   if( dom->req() == 3 &&        // 2-path merge point
 618       (din1 = dom ->in(1)) &&   // Left  path exists
 619       (din2 = dom ->in(2)) &&   // Right path exists
 620       (din3 = din1->in(0)) &&   // Left  path up one
 621       (din4 = din2->in(0)) ) {  // Right path up one
 622     if( din3->is_Call() &&      // Handle a slow-path call on either arm
 623         (din3 = din3->in(0)) )
 624       din3 = din3->in(0);
 625     if( din4->is_Call() &&      // Handle a slow-path call on either arm
 626         (din4 = din4->in(0)) )
 627       din4 = din4->in(0);
 628     if( din3 == din4 && din3->is_If() )
 629       return din3;              // Skip around diamonds
 630   }
 631 
 632   // Give up the search at true merges
 633   return NULL;                  // Dead loop?  Or hit root?
 634 }
 635 
 636 
 637 //------------------------------filtered_int_type--------------------------------
 638 // Return a possibly more restrictive type for val based on condition control flow for an if
 639 const TypeInt* IfNode::filtered_int_type(PhaseGVN* gvn, Node *val, Node* if_proj) {
 640   assert(if_proj &&
 641          (if_proj->Opcode() == Op_IfTrue || if_proj->Opcode() == Op_IfFalse), "expecting an if projection");
 642   if (if_proj->in(0) && if_proj->in(0)->is_If()) {
 643     IfNode* iff = if_proj->in(0)->as_If();
 644     if (iff->in(1) && iff->in(1)->is_Bool()) {
 645       BoolNode* bol = iff->in(1)->as_Bool();
 646       if (bol->in(1) && bol->in(1)->is_Cmp()) {
 647         const CmpNode* cmp  = bol->in(1)->as_Cmp();
 648         if (cmp->in(1) == val) {
 649           const TypeInt* cmp2_t = gvn->type(cmp->in(2))->isa_int();
 650           if (cmp2_t != NULL) {
 651             jint lo = cmp2_t->_lo;
 652             jint hi = cmp2_t->_hi;
 653             BoolTest::mask msk = if_proj->Opcode() == Op_IfTrue ? bol->_test._test : bol->_test.negate();
 654             switch (msk) {
 655             case BoolTest::ne:
 656               // Can't refine type
 657               return NULL;
 658             case BoolTest::eq:
 659               return cmp2_t;
 660             case BoolTest::lt:
 661               lo = TypeInt::INT->_lo;
 662               if (hi - 1 < hi) {
 663                 hi = hi - 1;
 664               }
 665               break;
 666             case BoolTest::le:
 667               lo = TypeInt::INT->_lo;
 668               break;
 669             case BoolTest::gt:
 670               if (lo + 1 > lo) {
 671                 lo = lo + 1;
 672               }
 673               hi = TypeInt::INT->_hi;
 674               break;
 675             case BoolTest::ge:
 676               // lo unchanged
 677               hi = TypeInt::INT->_hi;
 678               break;
 679             default:
 680               break;
 681             }
 682             const TypeInt* rtn_t = TypeInt::make(lo, hi, cmp2_t->_widen);
 683             return rtn_t;
 684           }
 685         }
 686       }
 687     }
 688   }
 689   return NULL;
 690 }
 691 
 692 //------------------------------fold_compares----------------------------
 693 // See if a pair of CmpIs can be converted into a CmpU.  In some cases
 694 // the direction of this if is determined by the preceding if so it
 695 // can be eliminate entirely.
 696 //
 697 // Given an if testing (CmpI n v) check for an immediately control
 698 // dependent if that is testing (CmpI n v2) and has one projection
 699 // leading to this if and the other projection leading to a region
 700 // that merges one of this ifs control projections.
 701 //
 702 //                   If
 703 //                  / |
 704 //                 /  |
 705 //                /   |
 706 //              If    |
 707 //              /\    |
 708 //             /  \   |
 709 //            /    \  |
 710 //           /    Region
 711 //
 712 // Or given an if testing (CmpI n v) check for a dominating if that is
 713 // testing (CmpI n v2), both having one projection leading to an
 714 // uncommon trap. Allow Another independent guard in between to cover
 715 // an explicit range check:
 716 // if (index < 0 || index >= array.length) {
 717 // which may need a null check to guard the LoadRange
 718 //
 719 //                   If
 720 //                  / \
 721 //                 /   \
 722 //                /     \
 723 //              If      unc
 724 //              /\
 725 //             /  \
 726 //            /    \
 727 //           /      unc
 728 //
 729 
 730 // Is the comparison for this If suitable for folding?
 731 bool IfNode::cmpi_folds(PhaseIterGVN* igvn) {
 732   return in(1) != NULL &&
 733     in(1)->is_Bool() &&
 734     in(1)->in(1) != NULL &&
 735     in(1)->in(1)->Opcode() == Op_CmpI &&
 736     in(1)->in(1)->in(2) != NULL &&
 737     in(1)->in(1)->in(2) != igvn->C->top() &&
 738     (in(1)->as_Bool()->_test.is_less() ||
 739      in(1)->as_Bool()->_test.is_greater());
 740 }
 741 
 742 // Is a dominating control suitable for folding with this if?
 743 bool IfNode::is_ctrl_folds(Node* ctrl, PhaseIterGVN* igvn) {
 744   return ctrl != NULL &&
 745     ctrl->is_Proj() &&
 746     ctrl->in(0) != NULL &&
 747     ctrl->in(0)->Opcode() == Op_If &&
 748     ctrl->in(0)->outcnt() == 2 &&
 749     ctrl->in(0)->as_If()->cmpi_folds(igvn) &&
 750     // Must compare same value
 751     ctrl->in(0)->in(1)->in(1)->in(1) != NULL &&
 752     ctrl->in(0)->in(1)->in(1)->in(1) == in(1)->in(1)->in(1);
 753 }
 754 
 755 // Do this If and the dominating If share a region?
 756 bool IfNode::has_shared_region(ProjNode* proj, ProjNode*& success, ProjNode*& fail) {
 757   ProjNode* otherproj = proj->other_if_proj();
 758   Node* otherproj_ctrl_use = otherproj->unique_ctrl_out();
 759   RegionNode* region = (otherproj_ctrl_use != NULL && otherproj_ctrl_use->is_Region()) ? otherproj_ctrl_use->as_Region() : NULL;
 760   success = NULL;
 761   fail = NULL;
 762 
 763   if (otherproj->outcnt() == 1 && region != NULL && !region->has_phi()) {
 764     for (int i = 0; i < 2; i++) {
 765       ProjNode* proj = proj_out(i);
 766       if (success == NULL && proj->outcnt() == 1 && proj->unique_out() == region) {
 767         success = proj;
 768       } else if (fail == NULL) {
 769         fail = proj;
 770       } else {
 771         success = fail = NULL;
 772       }
 773     }
 774   }
 775   return success != NULL && fail != NULL;
 776 }
 777 
 778 // Return projection that leads to an uncommon trap if any
 779 ProjNode* IfNode::uncommon_trap_proj(CallStaticJavaNode*& call) const {
 780   for (int i = 0; i < 2; i++) {
 781     call = proj_out(i)->is_uncommon_trap_proj(Deoptimization::Reason_none);
 782     if (call != NULL) {
 783       return proj_out(i);
 784     }
 785   }
 786   return NULL;
 787 }
 788 
 789 // Do this If and the dominating If both branch out to an uncommon trap
 790 bool IfNode::has_only_uncommon_traps(ProjNode* proj, ProjNode*& success, ProjNode*& fail, PhaseIterGVN* igvn) {
 791   ProjNode* otherproj = proj->other_if_proj();
 792   CallStaticJavaNode* dom_unc = otherproj->is_uncommon_trap_proj(Deoptimization::Reason_none);
 793 
 794   if (otherproj->outcnt() == 1 && dom_unc != NULL) {
 795     // We need to re-execute the folded Ifs after deoptimization from the merged traps
 796     if (!dom_unc->jvms()->should_reexecute()) {
 797       return false;
 798     }
 799 
 800     CallStaticJavaNode* unc = NULL;
 801     ProjNode* unc_proj = uncommon_trap_proj(unc);
 802     if (unc_proj != NULL && unc_proj->outcnt() == 1) {
 803       if (dom_unc == unc) {
 804         // Allow the uncommon trap to be shared through a region
 805         RegionNode* r = unc->in(0)->as_Region();
 806         if (r->outcnt() != 2 || r->req() != 3 || r->find_edge(otherproj) == -1 || r->find_edge(unc_proj) == -1) {
 807           return false;
 808         }
 809         assert(r->has_phi() == NULL, "simple region shouldn't have a phi");
 810       } else if (dom_unc->in(0) != otherproj || unc->in(0) != unc_proj) {
 811         return false;
 812       }
 813 
 814       // Different methods and methods containing jsrs are not supported.
 815       ciMethod* method = unc->jvms()->method();
 816       ciMethod* dom_method = dom_unc->jvms()->method();
 817       if (method != dom_method || method->has_jsrs()) {
 818         return false;
 819       }
 820       // Check that both traps are in the same activation of the method (instead
 821       // of two activations being inlined through different call sites) by verifying
 822       // that the call stacks are equal for both JVMStates.
 823       JVMState* dom_caller = dom_unc->jvms()->caller();
 824       JVMState* caller = unc->jvms()->caller();
 825       if ((dom_caller == NULL) != (caller == NULL)) {
 826         // The current method must either be inlined into both dom_caller and
 827         // caller or must not be inlined at all (top method). Bail out otherwise.
 828         return false;
 829       } else if (dom_caller != NULL && !dom_caller->same_calls_as(caller)) {
 830         return false;
 831       }
 832       // Check that the bci of the dominating uncommon trap dominates the bci
 833       // of the dominated uncommon trap. Otherwise we may not re-execute
 834       // the dominated check after deoptimization from the merged uncommon trap.
 835       ciTypeFlow* flow = dom_method->get_flow_analysis();
 836       int bci = unc->jvms()->bci();
 837       int dom_bci = dom_unc->jvms()->bci();
 838       if (!flow->is_dominated_by(bci, dom_bci)) {
 839         return false;
 840       }
 841 
 842       // See merge_uncommon_traps: the reason of the uncommon trap
 843       // will be changed and the state of the dominating If will be
 844       // used. Checked that we didn't apply this transformation in a
 845       // previous compilation and it didn't cause too many traps
 846       if (!igvn->C->too_many_traps(dom_method, dom_bci, Deoptimization::Reason_unstable_fused_if) &&
 847           !igvn->C->too_many_traps(dom_method, dom_bci, Deoptimization::Reason_range_check)) {
 848         success = unc_proj;
 849         fail = unc_proj->other_if_proj();
 850         return true;
 851       }
 852     }
 853   }
 854   return false;
 855 }
 856 
 857 // Check that the 2 CmpI can be folded into as single CmpU and proceed with the folding
 858 bool IfNode::fold_compares_helper(ProjNode* proj, ProjNode* success, ProjNode* fail, PhaseIterGVN* igvn) {
 859   Node* this_cmp = in(1)->in(1);
 860   BoolNode* this_bool = in(1)->as_Bool();
 861   IfNode* dom_iff = proj->in(0)->as_If();
 862   BoolNode* dom_bool = dom_iff->in(1)->as_Bool();
 863   Node* lo = dom_iff->in(1)->in(1)->in(2);
 864   Node* hi = this_cmp->in(2);
 865   Node* n = this_cmp->in(1);
 866   ProjNode* otherproj = proj->other_if_proj();
 867 
 868   const TypeInt* lo_type = IfNode::filtered_int_type(igvn, n, otherproj);
 869   const TypeInt* hi_type = IfNode::filtered_int_type(igvn, n, success);
 870 
 871   BoolTest::mask lo_test = dom_bool->_test._test;
 872   BoolTest::mask hi_test = this_bool->_test._test;
 873   BoolTest::mask cond = hi_test;
 874 
 875   // convert:
 876   //
 877   //          dom_bool = x {<,<=,>,>=} a
 878   //                           / \
 879   //     proj = {True,False}  /   \ otherproj = {False,True}
 880   //                         /
 881   //        this_bool = x {<,<=} b
 882   //                       / \
 883   //  fail = {True,False} /   \ success = {False,True}
 884   //                     /
 885   //
 886   // (Second test guaranteed canonicalized, first one may not have
 887   // been canonicalized yet)
 888   //
 889   // into:
 890   //
 891   // cond = (x - lo) {<u,<=u,>u,>=u} adjusted_lim
 892   //                       / \
 893   //                 fail /   \ success
 894   //                     /
 895   //
 896 
 897   // Figure out which of the two tests sets the upper bound and which
 898   // sets the lower bound if any.
 899   Node* adjusted_lim = NULL;
 900   if (hi_type->_lo > lo_type->_hi && hi_type->_hi == max_jint && lo_type->_lo == min_jint) {
 901     assert((dom_bool->_test.is_less() && !proj->_con) ||
 902            (dom_bool->_test.is_greater() && proj->_con), "incorrect test");
 903     // this test was canonicalized
 904     assert(this_bool->_test.is_less() && fail->_con, "incorrect test");
 905 
 906     // this_bool = <
 907     //   dom_bool = >= (proj = True) or dom_bool = < (proj = False)
 908     //     x in [a, b[ on the fail (= True) projection, b > a-1 (because of hi_type->_lo > lo_type->_hi test above):
 909     //     lo = a, hi = b, adjusted_lim = b-a, cond = <u
 910     //   dom_bool = > (proj = True) or dom_bool = <= (proj = False)
 911     //     x in ]a, b[ on the fail (= True) projection, b > a:
 912     //     lo = a+1, hi = b, adjusted_lim = b-a-1, cond = <u
 913     // this_bool = <=
 914     //   dom_bool = >= (proj = True) or dom_bool = < (proj = False)
 915     //     x in [a, b] on the fail (= True) projection, b+1 > a-1:
 916     //     lo = a, hi = b, adjusted_lim = b-a+1, cond = <u
 917     //     lo = a, hi = b, adjusted_lim = b-a, cond = <=u doesn't work because b = a - 1 is possible, then b-a = -1
 918     //   dom_bool = > (proj = True) or dom_bool = <= (proj = False)
 919     //     x in ]a, b] on the fail (= True) projection b+1 > a:
 920     //     lo = a+1, hi = b, adjusted_lim = b-a, cond = <u
 921     //     lo = a+1, hi = b, adjusted_lim = b-a-1, cond = <=u doesn't work because a = b is possible, then b-a-1 = -1
 922 
 923     if (hi_test == BoolTest::lt) {
 924       if (lo_test == BoolTest::gt || lo_test == BoolTest::le) {
 925         lo = igvn->transform(new AddINode(lo, igvn->intcon(1)));
 926       }
 927     } else {
 928       assert(hi_test == BoolTest::le, "bad test");
 929       if (lo_test == BoolTest::ge || lo_test == BoolTest::lt) {
 930         adjusted_lim = igvn->transform(new SubINode(hi, lo));
 931         adjusted_lim = igvn->transform(new AddINode(adjusted_lim, igvn->intcon(1)));
 932         cond = BoolTest::lt;
 933       } else {
 934         assert(lo_test == BoolTest::gt || lo_test == BoolTest::le, "bad test");
 935         adjusted_lim = igvn->transform(new SubINode(hi, lo));
 936         lo = igvn->transform(new AddINode(lo, igvn->intcon(1)));
 937         cond = BoolTest::lt;
 938       }
 939     }
 940   } else if (lo_type->_lo > hi_type->_hi && lo_type->_hi == max_jint && hi_type->_lo == min_jint) {
 941 
 942     // this_bool = <
 943     //   dom_bool = < (proj = True) or dom_bool = >= (proj = False)
 944     //     x in [b, a[ on the fail (= False) projection, a > b-1 (because of lo_type->_lo > hi_type->_hi above):
 945     //     lo = b, hi = a, adjusted_lim = a-b, cond = >=u
 946     //   dom_bool = <= (proj = True) or dom_bool = > (proj = False)
 947     //     x in [b, a] on the fail (= False) projection, a+1 > b-1:
 948     //     lo = b, hi = a, adjusted_lim = a-b+1, cond = >=u
 949     //     lo = b, hi = a, adjusted_lim = a-b, cond = >u doesn't work because a = b - 1 is possible, then b-a = -1
 950     // this_bool = <=
 951     //   dom_bool = < (proj = True) or dom_bool = >= (proj = False)
 952     //     x in ]b, a[ on the fail (= False) projection, a > b:
 953     //     lo = b+1, hi = a, adjusted_lim = a-b-1, cond = >=u
 954     //   dom_bool = <= (proj = True) or dom_bool = > (proj = False)
 955     //     x in ]b, a] on the fail (= False) projection, a+1 > b:
 956     //     lo = b+1, hi = a, adjusted_lim = a-b, cond = >=u
 957     //     lo = b+1, hi = a, adjusted_lim = a-b-1, cond = >u doesn't work because a = b is possible, then b-a-1 = -1
 958 
 959     swap(lo, hi);
 960     swap(lo_type, hi_type);
 961     swap(lo_test, hi_test);
 962 
 963     assert((dom_bool->_test.is_less() && proj->_con) ||
 964            (dom_bool->_test.is_greater() && !proj->_con), "incorrect test");
 965     // this test was canonicalized
 966     assert(this_bool->_test.is_less() && !fail->_con, "incorrect test");
 967 
 968     cond = (hi_test == BoolTest::le || hi_test == BoolTest::gt) ? BoolTest::gt : BoolTest::ge;
 969 
 970     if (lo_test == BoolTest::lt) {
 971       if (hi_test == BoolTest::lt || hi_test == BoolTest::ge) {
 972         cond = BoolTest::ge;
 973       } else {
 974         assert(hi_test == BoolTest::le || hi_test == BoolTest::gt, "bad test");
 975         adjusted_lim = igvn->transform(new SubINode(hi, lo));
 976         adjusted_lim = igvn->transform(new AddINode(adjusted_lim, igvn->intcon(1)));
 977         cond = BoolTest::ge;
 978       }
 979     } else if (lo_test == BoolTest::le) {
 980       if (hi_test == BoolTest::lt || hi_test == BoolTest::ge) {
 981         lo = igvn->transform(new AddINode(lo, igvn->intcon(1)));
 982         cond = BoolTest::ge;
 983       } else {
 984         assert(hi_test == BoolTest::le || hi_test == BoolTest::gt, "bad test");
 985         adjusted_lim = igvn->transform(new SubINode(hi, lo));
 986         lo = igvn->transform(new AddINode(lo, igvn->intcon(1)));
 987         cond = BoolTest::ge;
 988       }
 989     }
 990   } else {
 991     const TypeInt* failtype  = filtered_int_type(igvn, n, proj);
 992     if (failtype != NULL) {
 993       const TypeInt* type2 = filtered_int_type(igvn, n, fail);
 994       if (type2 != NULL) {
 995         failtype = failtype->join(type2)->is_int();
 996         if (failtype->_lo > failtype->_hi) {
 997           // previous if determines the result of this if so
 998           // replace Bool with constant
 999           igvn->_worklist.push(in(1));
1000           igvn->replace_input_of(this, 1, igvn->intcon(success->_con));
1001           return true;
1002         }
1003       }
1004     }
1005     lo = NULL;
1006     hi = NULL;
1007   }
1008 
1009   if (lo && hi) {
1010     // Merge the two compares into a single unsigned compare by building (CmpU (n - lo) (hi - lo))
1011     Node* adjusted_val = igvn->transform(new SubINode(n,  lo));
1012     if (adjusted_lim == NULL) {
1013       adjusted_lim = igvn->transform(new SubINode(hi, lo));
1014     }
1015     Node* newcmp = igvn->transform(new CmpUNode(adjusted_val, adjusted_lim));
1016     Node* newbool = igvn->transform(new BoolNode(newcmp, cond));
1017 
1018     igvn->replace_input_of(dom_iff, 1, igvn->intcon(proj->_con));
1019     igvn->_worklist.push(in(1));
1020     igvn->replace_input_of(this, 1, newbool);
1021 
1022     return true;
1023   }
1024   return false;
1025 }
1026 
1027 // Merge the branches that trap for this If and the dominating If into
1028 // a single region that branches to the uncommon trap for the
1029 // dominating If
1030 Node* IfNode::merge_uncommon_traps(ProjNode* proj, ProjNode* success, ProjNode* fail, PhaseIterGVN* igvn) {
1031   Node* res = this;
1032   assert(success->in(0) == this, "bad projection");
1033 
1034   ProjNode* otherproj = proj->other_if_proj();
1035 
1036   CallStaticJavaNode* unc = success->is_uncommon_trap_proj(Deoptimization::Reason_none);
1037   CallStaticJavaNode* dom_unc = otherproj->is_uncommon_trap_proj(Deoptimization::Reason_none);
1038 
1039   if (unc != dom_unc) {
1040     Node* r = new RegionNode(3);
1041 
1042     r->set_req(1, otherproj);
1043     r->set_req(2, success);
1044     r = igvn->transform(r);
1045     assert(r->is_Region(), "can't go away");
1046 
1047     // Make both If trap at the state of the first If: once the CmpI
1048     // nodes are merged, if we trap we don't know which of the CmpI
1049     // nodes would have caused the trap so we have to restart
1050     // execution at the first one
1051     igvn->replace_input_of(dom_unc, 0, r);
1052     igvn->replace_input_of(unc, 0, igvn->C->top());
1053   }
1054   int trap_request = dom_unc->uncommon_trap_request();
1055   Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
1056   Deoptimization::DeoptAction action = Deoptimization::trap_request_action(trap_request);
1057 
1058   int flip_test = 0;
1059   Node* l = NULL;
1060   Node* r = NULL;
1061 
1062   if (success->in(0)->as_If()->range_check_trap_proj(flip_test, l, r) != NULL) {
1063     // If this looks like a range check, change the trap to
1064     // Reason_range_check so the compiler recognizes it as a range
1065     // check and applies the corresponding optimizations
1066     trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_range_check, action);
1067 
1068     improve_address_types(l, r, fail, igvn);
1069 
1070     res = igvn->transform(new RangeCheckNode(in(0), in(1), _prob, _fcnt));
1071   } else if (unc != dom_unc) {
1072     // If we trap we won't know what CmpI would have caused the trap
1073     // so use a special trap reason to mark this pair of CmpI nodes as
1074     // bad candidate for folding. On recompilation we won't fold them
1075     // and we may trap again but this time we'll know what branch
1076     // traps
1077     trap_request = Deoptimization::make_trap_request(Deoptimization::Reason_unstable_fused_if, action);
1078   }
1079   igvn->replace_input_of(dom_unc, TypeFunc::Parms, igvn->intcon(trap_request));
1080   return res;
1081 }
1082 
1083 // If we are turning 2 CmpI nodes into a CmpU that follows the pattern
1084 // of a rangecheck on index i, on 64 bit the compares may be followed
1085 // by memory accesses using i as index. In that case, the CmpU tells
1086 // us something about the values taken by i that can help the compiler
1087 // (see Compile::conv_I2X_index())
1088 void IfNode::improve_address_types(Node* l, Node* r, ProjNode* fail, PhaseIterGVN* igvn) {
1089 #ifdef _LP64
1090   ResourceMark rm;
1091   Node_Stack stack(2);
1092 
1093   assert(r->Opcode() == Op_LoadRange, "unexpected range check");
1094   const TypeInt* array_size = igvn->type(r)->is_int();
1095 
1096   stack.push(l, 0);
1097 
1098   while(stack.size() > 0) {
1099     Node* n = stack.node();
1100     uint start = stack.index();
1101 
1102     uint i = start;
1103     for (; i < n->outcnt(); i++) {
1104       Node* use = n->raw_out(i);
1105       if (stack.size() == 1) {
1106         if (use->Opcode() == Op_ConvI2L) {
1107           const TypeLong* bounds = use->as_Type()->type()->is_long();
1108           if (bounds->_lo <= array_size->_lo && bounds->_hi >= array_size->_hi &&
1109               (bounds->_lo != array_size->_lo || bounds->_hi != array_size->_hi)) {
1110             stack.set_index(i+1);
1111             stack.push(use, 0);
1112             break;
1113           }
1114         }
1115       } else if (use->is_Mem()) {
1116         Node* ctrl = use->in(0);
1117         for (int i = 0; i < 10 && ctrl != NULL && ctrl != fail; i++) {
1118           ctrl = up_one_dom(ctrl);
1119         }
1120         if (ctrl == fail) {
1121           Node* init_n = stack.node_at(1);
1122           assert(init_n->Opcode() == Op_ConvI2L, "unexpected first node");
1123           // Create a new narrow ConvI2L node that is dependent on the range check
1124           Node* new_n = igvn->C->conv_I2X_index(igvn, l, array_size, fail);
1125 
1126           // The type of the ConvI2L may be widen and so the new
1127           // ConvI2L may not be better than an existing ConvI2L
1128           if (new_n != init_n) {
1129             for (uint j = 2; j < stack.size(); j++) {
1130               Node* n = stack.node_at(j);
1131               Node* clone = n->clone();
1132               int rep = clone->replace_edge(init_n, new_n);
1133               assert(rep > 0, "can't find expected node?");
1134               clone = igvn->transform(clone);
1135               init_n = n;
1136               new_n = clone;
1137             }
1138             igvn->hash_delete(use);
1139             int rep = use->replace_edge(init_n, new_n);
1140             assert(rep > 0, "can't find expected node?");
1141             igvn->transform(use);
1142             if (init_n->outcnt() == 0) {
1143               igvn->_worklist.push(init_n);
1144             }
1145           }
1146         }
1147       } else if (use->in(0) == NULL && (igvn->type(use)->isa_long() ||
1148                                         igvn->type(use)->isa_ptr())) {
1149         stack.set_index(i+1);
1150         stack.push(use, 0);
1151         break;
1152       }
1153     }
1154     if (i == n->outcnt()) {
1155       stack.pop();
1156     }
1157   }
1158 #endif
1159 }
1160 
1161 bool IfNode::is_cmp_with_loadrange(ProjNode* proj) {
1162   if (in(1) != NULL &&
1163       in(1)->in(1) != NULL &&
1164       in(1)->in(1)->in(2) != NULL) {
1165     Node* other = in(1)->in(1)->in(2);
1166     if (other->Opcode() == Op_LoadRange &&
1167         ((other->in(0) != NULL && other->in(0) == proj) ||
1168          (other->in(0) == NULL &&
1169           other->in(2) != NULL &&
1170           other->in(2)->is_AddP() &&
1171           other->in(2)->in(1) != NULL &&
1172           other->in(2)->in(1)->Opcode() == Op_CastPP &&
1173           other->in(2)->in(1)->in(0) == proj))) {
1174       return true;
1175     }
1176   }
1177   return false;
1178 }
1179 
1180 bool IfNode::is_null_check(ProjNode* proj, PhaseIterGVN* igvn) {
1181   Node* other = in(1)->in(1)->in(2);
1182   if (other->in(MemNode::Address) != NULL &&
1183       proj->in(0)->in(1) != NULL &&
1184       proj->in(0)->in(1)->is_Bool() &&
1185       proj->in(0)->in(1)->in(1) != NULL &&
1186       proj->in(0)->in(1)->in(1)->Opcode() == Op_CmpP &&
1187       proj->in(0)->in(1)->in(1)->in(2) != NULL &&
1188       proj->in(0)->in(1)->in(1)->in(1) == other->in(MemNode::Address)->in(AddPNode::Address)->uncast() &&
1189       igvn->type(proj->in(0)->in(1)->in(1)->in(2)) == TypePtr::NULL_PTR) {
1190     return true;
1191   }
1192   return false;
1193 }
1194 
1195 // Check that the If that is in between the 2 integer comparisons has
1196 // no side effect
1197 bool IfNode::is_side_effect_free_test(ProjNode* proj, PhaseIterGVN* igvn) {
1198   if (proj != NULL &&
1199       proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none) &&
1200       proj->outcnt() <= 2) {
1201     if (proj->outcnt() == 1 ||
1202         // Allow simple null check from LoadRange
1203         (is_cmp_with_loadrange(proj) && is_null_check(proj, igvn))) {
1204       CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
1205       CallStaticJavaNode* dom_unc = proj->in(0)->in(0)->as_Proj()->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
1206 
1207       // reroute_side_effect_free_unc changes the state of this
1208       // uncommon trap to restart execution at the previous
1209       // CmpI. Check that this change in a previous compilation didn't
1210       // cause too many traps.
1211       int trap_request = unc->uncommon_trap_request();
1212       Deoptimization::DeoptReason reason = Deoptimization::trap_request_reason(trap_request);
1213 
1214       if (igvn->C->too_many_traps(dom_unc->jvms()->method(), dom_unc->jvms()->bci(), reason)) {
1215         return false;
1216       }
1217 
1218       return true;
1219     }
1220   }
1221   return false;
1222 }
1223 
1224 // Make the If between the 2 integer comparisons trap at the state of
1225 // the first If: the last CmpI is the one replaced by a CmpU and the
1226 // first CmpI is eliminated, so the test between the 2 CmpI nodes
1227 // won't be guarded by the first CmpI anymore. It can trap in cases
1228 // where the first CmpI would have prevented it from executing: on a
1229 // trap, we need to restart execution at the state of the first CmpI
1230 void IfNode::reroute_side_effect_free_unc(ProjNode* proj, ProjNode* dom_proj, PhaseIterGVN* igvn) {
1231   CallStaticJavaNode* dom_unc = dom_proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
1232   ProjNode* otherproj = proj->other_if_proj();
1233   CallStaticJavaNode* unc = proj->is_uncommon_trap_if_pattern(Deoptimization::Reason_none);
1234   Node* call_proj = dom_unc->unique_ctrl_out();
1235   Node* halt = call_proj->unique_ctrl_out();
1236 
1237   Node* new_unc = dom_unc->clone();
1238   call_proj = call_proj->clone();
1239   halt = halt->clone();
1240   Node* c = otherproj->clone();
1241 
1242   c = igvn->transform(c);
1243   new_unc->set_req(TypeFunc::Parms, unc->in(TypeFunc::Parms));
1244   new_unc->set_req(0, c);
1245   new_unc = igvn->transform(new_unc);
1246   call_proj->set_req(0, new_unc);
1247   call_proj = igvn->transform(call_proj);
1248   halt->set_req(0, call_proj);
1249   halt = igvn->transform(halt);
1250 
1251   igvn->replace_node(otherproj, igvn->C->top());
1252   igvn->C->root()->add_req(halt);
1253 }
1254 
1255 Node* IfNode::fold_compares(PhaseIterGVN* igvn) {
1256   if (Opcode() != Op_If) return NULL;
1257 
1258   if (cmpi_folds(igvn)) {
1259     Node* ctrl = in(0);
1260     if (is_ctrl_folds(ctrl, igvn) &&
1261         ctrl->outcnt() == 1) {
1262       // A integer comparison immediately dominated by another integer
1263       // comparison
1264       ProjNode* success = NULL;
1265       ProjNode* fail = NULL;
1266       ProjNode* dom_cmp = ctrl->as_Proj();
1267       if (has_shared_region(dom_cmp, success, fail) &&
1268           // Next call modifies graph so must be last
1269           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1270         return this;
1271       }
1272       if (has_only_uncommon_traps(dom_cmp, success, fail, igvn) &&
1273           // Next call modifies graph so must be last
1274           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1275         return merge_uncommon_traps(dom_cmp, success, fail, igvn);
1276       }
1277       return NULL;
1278     } else if (ctrl->in(0) != NULL &&
1279                ctrl->in(0)->in(0) != NULL) {
1280       ProjNode* success = NULL;
1281       ProjNode* fail = NULL;
1282       Node* dom = ctrl->in(0)->in(0);
1283       ProjNode* dom_cmp = dom->isa_Proj();
1284       ProjNode* other_cmp = ctrl->isa_Proj();
1285 
1286       // Check if it's an integer comparison dominated by another
1287       // integer comparison with another test in between
1288       if (is_ctrl_folds(dom, igvn) &&
1289           has_only_uncommon_traps(dom_cmp, success, fail, igvn) &&
1290           is_side_effect_free_test(other_cmp, igvn) &&
1291           // Next call modifies graph so must be last
1292           fold_compares_helper(dom_cmp, success, fail, igvn)) {
1293         reroute_side_effect_free_unc(other_cmp, dom_cmp, igvn);
1294         return merge_uncommon_traps(dom_cmp, success, fail, igvn);
1295       }
1296     }
1297   }
1298   return NULL;
1299 }
1300 
1301 //------------------------------remove_useless_bool----------------------------
1302 // Check for people making a useless boolean: things like
1303 // if( (x < y ? true : false) ) { ... }
1304 // Replace with if( x < y ) { ... }
1305 static Node *remove_useless_bool(IfNode *iff, PhaseGVN *phase) {
1306   Node *i1 = iff->in(1);
1307   if( !i1->is_Bool() ) return NULL;
1308   BoolNode *bol = i1->as_Bool();
1309 
1310   Node *cmp = bol->in(1);
1311   if( cmp->Opcode() != Op_CmpI ) return NULL;
1312 
1313   // Must be comparing against a bool
1314   const Type *cmp2_t = phase->type( cmp->in(2) );
1315   if( cmp2_t != TypeInt::ZERO &&
1316       cmp2_t != TypeInt::ONE )
1317     return NULL;
1318 
1319   // Find a prior merge point merging the boolean
1320   i1 = cmp->in(1);
1321   if( !i1->is_Phi() ) return NULL;
1322   PhiNode *phi = i1->as_Phi();
1323   if( phase->type( phi ) != TypeInt::BOOL )
1324     return NULL;
1325 
1326   // Check for diamond pattern
1327   int true_path = phi->is_diamond_phi();
1328   if( true_path == 0 ) return NULL;
1329 
1330   // Make sure that iff and the control of the phi are different. This
1331   // should really only happen for dead control flow since it requires
1332   // an illegal cycle.
1333   if (phi->in(0)->in(1)->in(0) == iff) return NULL;
1334 
1335   // phi->region->if_proj->ifnode->bool->cmp
1336   BoolNode *bol2 = phi->in(0)->in(1)->in(0)->in(1)->as_Bool();
1337 
1338   // Now get the 'sense' of the test correct so we can plug in
1339   // either iff2->in(1) or its complement.
1340   int flip = 0;
1341   if( bol->_test._test == BoolTest::ne ) flip = 1-flip;
1342   else if( bol->_test._test != BoolTest::eq ) return NULL;
1343   if( cmp2_t == TypeInt::ZERO ) flip = 1-flip;
1344 
1345   const Type *phi1_t = phase->type( phi->in(1) );
1346   const Type *phi2_t = phase->type( phi->in(2) );
1347   // Check for Phi(0,1) and flip
1348   if( phi1_t == TypeInt::ZERO ) {
1349     if( phi2_t != TypeInt::ONE ) return NULL;
1350     flip = 1-flip;
1351   } else {
1352     // Check for Phi(1,0)
1353     if( phi1_t != TypeInt::ONE  ) return NULL;
1354     if( phi2_t != TypeInt::ZERO ) return NULL;
1355   }
1356   if( true_path == 2 ) {
1357     flip = 1-flip;
1358   }
1359 
1360   Node* new_bol = (flip ? phase->transform( bol2->negate(phase) ) : bol2);
1361   assert(new_bol != iff->in(1), "must make progress");
1362   iff->set_req(1, new_bol);
1363   // Intervening diamond probably goes dead
1364   phase->C->set_major_progress();
1365   return iff;
1366 }
1367 
1368 static IfNode* idealize_test(PhaseGVN* phase, IfNode* iff);
1369 
1370 struct RangeCheck {
1371   Node* ctl;
1372   jint off;
1373 };
1374 
1375 Node* IfNode::Ideal_common(PhaseGVN *phase, bool can_reshape) {
1376   if (remove_dead_region(phase, can_reshape))  return this;
1377   // No Def-Use info?
1378   if (!can_reshape)  return NULL;
1379 
1380   // Don't bother trying to transform a dead if
1381   if (in(0)->is_top())  return NULL;
1382   // Don't bother trying to transform an if with a dead test
1383   if (in(1)->is_top())  return NULL;
1384   // Another variation of a dead test
1385   if (in(1)->is_Con())  return NULL;
1386   // Another variation of a dead if
1387   if (outcnt() < 2)  return NULL;
1388 
1389   // Canonicalize the test.
1390   Node* idt_if = idealize_test(phase, this);
1391   if (idt_if != NULL)  return idt_if;
1392 
1393   // Try to split the IF
1394   PhaseIterGVN *igvn = phase->is_IterGVN();
1395   Node *s = split_if(this, igvn);
1396   if (s != NULL)  return s;
1397 
1398   return NodeSentinel;
1399 }
1400 
1401 //------------------------------Ideal------------------------------------------
1402 // Return a node which is more "ideal" than the current node.  Strip out
1403 // control copies
1404 Node* IfNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1405   Node* res = Ideal_common(phase, can_reshape);
1406   if (res != NodeSentinel) {
1407     return res;
1408   }
1409 
1410   // Check for people making a useless boolean: things like
1411   // if( (x < y ? true : false) ) { ... }
1412   // Replace with if( x < y ) { ... }
1413   Node *bol2 = remove_useless_bool(this, phase);
1414   if( bol2 ) return bol2;
1415 
1416   if (in(0) == NULL) return NULL;     // Dead loop?
1417 
1418   PhaseIterGVN *igvn = phase->is_IterGVN();
1419   Node* result = fold_compares(igvn);
1420   if (result != NULL) {
1421     return result;
1422   }
1423 
1424   // Scan for an equivalent test
1425   Node *cmp;
1426   int dist = 0;               // Cutoff limit for search
1427   int op = Opcode();
1428   if( op == Op_If &&
1429       (cmp=in(1)->in(1))->Opcode() == Op_CmpP ) {
1430     if( cmp->in(2) != NULL && // make sure cmp is not already dead
1431         cmp->in(2)->bottom_type() == TypePtr::NULL_PTR ) {
1432       dist = 64;              // Limit for null-pointer scans
1433     } else {
1434       dist = 4;               // Do not bother for random pointer tests
1435     }
1436   } else {
1437     dist = 4;                 // Limit for random junky scans
1438   }
1439 
1440   Node* prev_dom = search_identical(dist);
1441 
1442   if (prev_dom == NULL) {
1443     return NULL;
1444   }
1445 
1446   // Replace dominated IfNode
1447   return dominated_by(prev_dom, igvn);
1448 }
1449 
1450 //------------------------------dominated_by-----------------------------------
1451 Node* IfNode::dominated_by(Node* prev_dom, PhaseIterGVN *igvn) {
1452 #ifndef PRODUCT
1453   if (TraceIterativeGVN) {
1454     tty->print("   Removing IfNode: "); this->dump();
1455   }
1456   if (VerifyOpto && !igvn->allow_progress()) {
1457     // Found an equivalent dominating test,
1458     // we can not guarantee reaching a fix-point for these during iterativeGVN
1459     // since intervening nodes may not change.
1460     return NULL;
1461   }
1462 #endif
1463 
1464   igvn->hash_delete(this);      // Remove self to prevent spurious V-N
1465   Node *idom = in(0);
1466   // Need opcode to decide which way 'this' test goes
1467   int prev_op = prev_dom->Opcode();
1468   Node *top = igvn->C->top(); // Shortcut to top
1469 
1470   // Loop predicates may have depending checks which should not
1471   // be skipped. For example, range check predicate has two checks
1472   // for lower and upper bounds.
1473   ProjNode* unc_proj = proj_out(1 - prev_dom->as_Proj()->_con)->as_Proj();
1474   if ((unc_proj != NULL) && (unc_proj->is_uncommon_trap_proj(Deoptimization::Reason_predicate) != NULL)) {
1475     prev_dom = idom;
1476   }
1477 
1478   // Now walk the current IfNode's projections.
1479   // Loop ends when 'this' has no more uses.
1480   for (DUIterator_Last imin, i = last_outs(imin); i >= imin; --i) {
1481     Node *ifp = last_out(i);     // Get IfTrue/IfFalse
1482     igvn->add_users_to_worklist(ifp);
1483     // Check which projection it is and set target.
1484     // Data-target is either the dominating projection of the same type
1485     // or TOP if the dominating projection is of opposite type.
1486     // Data-target will be used as the new control edge for the non-CFG
1487     // nodes like Casts and Loads.
1488     Node *data_target = (ifp->Opcode() == prev_op) ? prev_dom : top;
1489     // Control-target is just the If's immediate dominator or TOP.
1490     Node *ctrl_target = (ifp->Opcode() == prev_op) ?     idom : top;
1491 
1492     // For each child of an IfTrue/IfFalse projection, reroute.
1493     // Loop ends when projection has no more uses.
1494     for (DUIterator_Last jmin, j = ifp->last_outs(jmin); j >= jmin; --j) {
1495       Node* s = ifp->last_out(j);   // Get child of IfTrue/IfFalse
1496       if( !s->depends_only_on_test() ) {
1497         // Find the control input matching this def-use edge.
1498         // For Regions it may not be in slot 0.
1499         uint l;
1500         for( l = 0; s->in(l) != ifp; l++ ) { }
1501         igvn->replace_input_of(s, l, ctrl_target);
1502       } else {                      // Else, for control producers,
1503         igvn->replace_input_of(s, 0, data_target); // Move child to data-target
1504       }
1505     } // End for each child of a projection
1506 
1507     igvn->remove_dead_node(ifp);
1508   } // End for each IfTrue/IfFalse child of If
1509 
1510   // Kill the IfNode
1511   igvn->remove_dead_node(this);
1512 
1513   // Must return either the original node (now dead) or a new node
1514   // (Do not return a top here, since that would break the uniqueness of top.)
1515   return new ConINode(TypeInt::ZERO);
1516 }
1517 
1518 Node* IfNode::search_identical(int dist) {
1519   // Setup to scan up the CFG looking for a dominating test
1520   Node* dom = in(0);
1521   Node* prev_dom = this;
1522   int op = Opcode();
1523   // Search up the dominator tree for an If with an identical test
1524   while (dom->Opcode() != op    ||  // Not same opcode?
1525          dom->in(1)    != in(1) ||  // Not same input 1?
1526          (req() == 3 && dom->in(2) != in(2)) || // Not same input 2?
1527          prev_dom->in(0) != dom) {  // One path of test does not dominate?
1528     if (dist < 0) return NULL;
1529 
1530     dist--;
1531     prev_dom = dom;
1532     dom = up_one_dom(dom);
1533     if (!dom) return NULL;
1534   }
1535 
1536   // Check that we did not follow a loop back to ourselves
1537   if (this == dom) {
1538     return NULL;
1539   }
1540 
1541 #ifndef PRODUCT
1542   if (dist > 2) { // Add to count of NULL checks elided
1543     explicit_null_checks_elided++;
1544   }
1545 #endif
1546 
1547   return prev_dom;
1548 }
1549 
1550 //------------------------------Identity---------------------------------------
1551 // If the test is constant & we match, then we are the input Control
1552 Node* IfProjNode::Identity(PhaseGVN* phase) {
1553   // Can only optimize if cannot go the other way
1554   const TypeTuple *t = phase->type(in(0))->is_tuple();
1555   if (t == TypeTuple::IFNEITHER || (always_taken(t) &&
1556        // During parsing (GVN) we don't remove dead code aggressively.
1557        // Cut off dead branch and let PhaseRemoveUseless take care of it.
1558       (!phase->is_IterGVN() ||
1559        // During IGVN, first wait for the dead branch to be killed.
1560        // Otherwise, the IfNode's control will have two control uses (the IfNode
1561        // that doesn't go away because it still has uses and this branch of the
1562        // If) which breaks other optimizations. Node::has_special_unique_user()
1563        // will cause this node to be reprocessed once the dead branch is killed.
1564        in(0)->outcnt() == 1))) {
1565     // IfNode control
1566     return in(0)->in(0);
1567   }
1568   // no progress
1569   return this;
1570 }
1571 
1572 #ifndef PRODUCT
1573 //-------------------------------related---------------------------------------
1574 // An IfProjNode's related node set consists of its input (an IfNode) including
1575 // the IfNode's condition, plus all of its outputs at level 1. In compact mode,
1576 // the restrictions for IfNode apply (see IfNode::rel).
1577 void IfProjNode::related(GrowableArray<Node*> *in_rel, GrowableArray<Node*> *out_rel, bool compact) const {
1578   Node* ifNode = this->in(0);
1579   in_rel->append(ifNode);
1580   if (compact) {
1581     ifNode->collect_nodes(in_rel, 3, false, true);
1582   } else {
1583     ifNode->collect_nodes_in_all_data(in_rel, false);
1584   }
1585   this->collect_nodes(out_rel, -1, false, false);
1586 }
1587 
1588 //------------------------------dump_spec--------------------------------------
1589 void IfNode::dump_spec(outputStream *st) const {
1590   st->print("P=%f, C=%f",_prob,_fcnt);
1591 }
1592 
1593 //-------------------------------related---------------------------------------
1594 // For an IfNode, the set of related output nodes is just the output nodes till
1595 // depth 2, i.e, the IfTrue/IfFalse projection nodes plus the nodes they refer.
1596 // The related input nodes contain no control nodes, but all data nodes
1597 // pertaining to the condition. In compact mode, the input nodes are collected
1598 // up to a depth of 3.
1599 void IfNode::related(GrowableArray <Node *> *in_rel, GrowableArray <Node *> *out_rel, bool compact) const {
1600   if (compact) {
1601     this->collect_nodes(in_rel, 3, false, true);
1602   } else {
1603     this->collect_nodes_in_all_data(in_rel, false);
1604   }
1605   this->collect_nodes(out_rel, -2, false, false);
1606 }
1607 #endif
1608 
1609 //------------------------------idealize_test----------------------------------
1610 // Try to canonicalize tests better.  Peek at the Cmp/Bool/If sequence and
1611 // come up with a canonical sequence.  Bools getting 'eq', 'gt' and 'ge' forms
1612 // converted to 'ne', 'le' and 'lt' forms.  IfTrue/IfFalse get swapped as
1613 // needed.
1614 static IfNode* idealize_test(PhaseGVN* phase, IfNode* iff) {
1615   assert(iff->in(0) != NULL, "If must be live");
1616 
1617   if (iff->outcnt() != 2)  return NULL; // Malformed projections.
1618   Node* old_if_f = iff->proj_out(false);
1619   Node* old_if_t = iff->proj_out(true);
1620 
1621   // CountedLoopEnds want the back-control test to be TRUE, irregardless of
1622   // whether they are testing a 'gt' or 'lt' condition.  The 'gt' condition
1623   // happens in count-down loops
1624   if (iff->is_CountedLoopEnd())  return NULL;
1625   if (!iff->in(1)->is_Bool())  return NULL; // Happens for partially optimized IF tests
1626   BoolNode *b = iff->in(1)->as_Bool();
1627   BoolTest bt = b->_test;
1628   // Test already in good order?
1629   if( bt.is_canonical() )
1630     return NULL;
1631 
1632   // Flip test to be canonical.  Requires flipping the IfFalse/IfTrue and
1633   // cloning the IfNode.
1634   Node* new_b = phase->transform( new BoolNode(b->in(1), bt.negate()) );
1635   if( !new_b->is_Bool() ) return NULL;
1636   b = new_b->as_Bool();
1637 
1638   PhaseIterGVN *igvn = phase->is_IterGVN();
1639   assert( igvn, "Test is not canonical in parser?" );
1640 
1641   // The IF node never really changes, but it needs to be cloned
1642   iff = iff->clone()->as_If();
1643   iff->set_req(1, b);
1644   iff->_prob = 1.0-iff->_prob;
1645 
1646   Node *prior = igvn->hash_find_insert(iff);
1647   if( prior ) {
1648     igvn->remove_dead_node(iff);
1649     iff = (IfNode*)prior;
1650   } else {
1651     // Cannot call transform on it just yet
1652     igvn->set_type_bottom(iff);
1653   }
1654   igvn->_worklist.push(iff);
1655 
1656   // Now handle projections.  Cloning not required.
1657   Node* new_if_f = (Node*)(new IfFalseNode( iff ));
1658   Node* new_if_t = (Node*)(new IfTrueNode ( iff ));
1659 
1660   igvn->register_new_node_with_optimizer(new_if_f);
1661   igvn->register_new_node_with_optimizer(new_if_t);
1662   // Flip test, so flip trailing control
1663   igvn->replace_node(old_if_f, new_if_t);
1664   igvn->replace_node(old_if_t, new_if_f);
1665 
1666   // Progress
1667   return iff;
1668 }
1669 
1670 Node* RangeCheckNode::Ideal(PhaseGVN *phase, bool can_reshape) {
1671   Node* res = Ideal_common(phase, can_reshape);
1672   if (res != NodeSentinel) {
1673     return res;
1674   }
1675 
1676   PhaseIterGVN *igvn = phase->is_IterGVN();
1677   // Setup to scan up the CFG looking for a dominating test
1678   Node* prev_dom = this;
1679 
1680   // Check for range-check vs other kinds of tests
1681   Node* index1;
1682   Node* range1;
1683   jint offset1;
1684   int flip1 = is_range_check(range1, index1, offset1);
1685   if (flip1) {
1686     Node* dom = in(0);
1687     // Try to remove extra range checks.  All 'up_one_dom' gives up at merges
1688     // so all checks we inspect post-dominate the top-most check we find.
1689     // If we are going to fail the current check and we reach the top check
1690     // then we are guaranteed to fail, so just start interpreting there.
1691     // We 'expand' the top 3 range checks to include all post-dominating
1692     // checks.
1693 
1694     // The top 3 range checks seen
1695     const int NRC =3;
1696     RangeCheck prev_checks[NRC];
1697     int nb_checks = 0;
1698 
1699     // Low and high offsets seen so far
1700     jint off_lo = offset1;
1701     jint off_hi = offset1;
1702 
1703     bool found_immediate_dominator = false;
1704 
1705     // Scan for the top checks and collect range of offsets
1706     for (int dist = 0; dist < 999; dist++) { // Range-Check scan limit
1707       if (dom->Opcode() == Op_RangeCheck &&  // Not same opcode?
1708           prev_dom->in(0) == dom) { // One path of test does dominate?
1709         if (dom == this) return NULL; // dead loop
1710         // See if this is a range check
1711         Node* index2;
1712         Node* range2;
1713         jint offset2;
1714         int flip2 = dom->as_RangeCheck()->is_range_check(range2, index2, offset2);
1715         // See if this is a _matching_ range check, checking against
1716         // the same array bounds.
1717         if (flip2 == flip1 && range2 == range1 && index2 == index1 &&
1718             dom->outcnt() == 2) {
1719           if (nb_checks == 0 && dom->in(1) == in(1)) {
1720             // Found an immediately dominating test at the same offset.
1721             // This kind of back-to-back test can be eliminated locally,
1722             // and there is no need to search further for dominating tests.
1723             assert(offset2 == offset1, "Same test but different offsets");
1724             found_immediate_dominator = true;
1725             break;
1726           }
1727           // Gather expanded bounds
1728           off_lo = MIN2(off_lo,offset2);
1729           off_hi = MAX2(off_hi,offset2);
1730           // Record top NRC range checks
1731           prev_checks[nb_checks%NRC].ctl = prev_dom;
1732           prev_checks[nb_checks%NRC].off = offset2;
1733           nb_checks++;
1734         }
1735       }
1736       prev_dom = dom;
1737       dom = up_one_dom(dom);
1738       if (!dom) break;
1739     }
1740 
1741     if (!found_immediate_dominator) {
1742       // Attempt to widen the dominating range check to cover some later
1743       // ones.  Since range checks "fail" by uncommon-trapping to the
1744       // interpreter, widening a check can make us speculatively enter
1745       // the interpreter.  If we see range-check deopt's, do not widen!
1746       if (!phase->C->allow_range_check_smearing())  return NULL;
1747 
1748       // Didn't find prior covering check, so cannot remove anything.
1749       if (nb_checks == 0) {
1750         return NULL;
1751       }
1752       // Constant indices only need to check the upper bound.
1753       // Non-constant indices must check both low and high.
1754       int chk0 = (nb_checks - 1) % NRC;
1755       if (index1) {
1756         if (nb_checks == 1) {
1757           return NULL;
1758         } else {
1759           // If the top range check's constant is the min or max of
1760           // all constants we widen the next one to cover the whole
1761           // range of constants.
1762           RangeCheck rc0 = prev_checks[chk0];
1763           int chk1 = (nb_checks - 2) % NRC;
1764           RangeCheck rc1 = prev_checks[chk1];
1765           if (rc0.off == off_lo) {
1766             adjust_check(rc1.ctl, range1, index1, flip1, off_hi, igvn);
1767             prev_dom = rc1.ctl;
1768           } else if (rc0.off == off_hi) {
1769             adjust_check(rc1.ctl, range1, index1, flip1, off_lo, igvn);
1770             prev_dom = rc1.ctl;
1771           } else {
1772             // If the top test's constant is not the min or max of all
1773             // constants, we need 3 range checks. We must leave the
1774             // top test unchanged because widening it would allow the
1775             // accesses it protects to successfully read/write out of
1776             // bounds.
1777             if (nb_checks == 2) {
1778               return NULL;
1779             }
1780             int chk2 = (nb_checks - 3) % NRC;
1781             RangeCheck rc2 = prev_checks[chk2];
1782             // The top range check a+i covers interval: -a <= i < length-a
1783             // The second range check b+i covers interval: -b <= i < length-b
1784             if (rc1.off <= rc0.off) {
1785               // if b <= a, we change the second range check to:
1786               // -min_of_all_constants <= i < length-min_of_all_constants
1787               // Together top and second range checks now cover:
1788               // -min_of_all_constants <= i < length-a
1789               // which is more restrictive than -b <= i < length-b:
1790               // -b <= -min_of_all_constants <= i < length-a <= length-b
1791               // The third check is then changed to:
1792               // -max_of_all_constants <= i < length-max_of_all_constants
1793               // so 2nd and 3rd checks restrict allowed values of i to:
1794               // -min_of_all_constants <= i < length-max_of_all_constants
1795               adjust_check(rc1.ctl, range1, index1, flip1, off_lo, igvn);
1796               adjust_check(rc2.ctl, range1, index1, flip1, off_hi, igvn);
1797             } else {
1798               // if b > a, we change the second range check to:
1799               // -max_of_all_constants <= i < length-max_of_all_constants
1800               // Together top and second range checks now cover:
1801               // -a <= i < length-max_of_all_constants
1802               // which is more restrictive than -b <= i < length-b:
1803               // -b < -a <= i < length-max_of_all_constants <= length-b
1804               // The third check is then changed to:
1805               // -max_of_all_constants <= i < length-max_of_all_constants
1806               // so 2nd and 3rd checks restrict allowed values of i to:
1807               // -min_of_all_constants <= i < length-max_of_all_constants
1808               adjust_check(rc1.ctl, range1, index1, flip1, off_hi, igvn);
1809               adjust_check(rc2.ctl, range1, index1, flip1, off_lo, igvn);
1810             }
1811             prev_dom = rc2.ctl;
1812           }
1813         }
1814       } else {
1815         RangeCheck rc0 = prev_checks[chk0];
1816         // 'Widen' the offset of the 1st and only covering check
1817         adjust_check(rc0.ctl, range1, index1, flip1, off_hi, igvn);
1818         // Test is now covered by prior checks, dominate it out
1819         prev_dom = rc0.ctl;
1820       }
1821     }
1822   } else {
1823     prev_dom = search_identical(4);
1824 
1825     if (prev_dom == NULL) {
1826       return NULL;
1827     }
1828   }
1829 
1830   // Replace dominated IfNode
1831   return dominated_by(prev_dom, igvn);
1832 }