1 /*
   2  * Copyright (c) 1999, 2020, 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 "c1/c1_Canonicalizer.hpp"
  27 #include "c1/c1_Optimizer.hpp"
  28 #include "c1/c1_ValueMap.hpp"
  29 #include "c1/c1_ValueSet.hpp"
  30 #include "c1/c1_ValueStack.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "utilities/bitMap.inline.hpp"
  33 #include "compiler/compileLog.hpp"
  34 
  35 typedef GrowableArray<ValueSet*> ValueSetList;
  36 
  37 Optimizer::Optimizer(IR* ir) {
  38   assert(ir->is_valid(), "IR must be valid");
  39   _ir = ir;
  40 }
  41 
  42 class CE_Eliminator: public BlockClosure {
  43  private:
  44   IR* _hir;
  45   int _cee_count;                                // the number of CEs successfully eliminated
  46   int _ifop_count;                               // the number of IfOps successfully simplified
  47   int _has_substitution;
  48 
  49  public:
  50   CE_Eliminator(IR* hir) : _hir(hir), _cee_count(0), _ifop_count(0) {
  51     _has_substitution = false;
  52     _hir->iterate_preorder(this);
  53     if (_has_substitution) {
  54       // substituted some ifops/phis, so resolve the substitution
  55       SubstitutionResolver sr(_hir);
  56     }
  57 
  58     CompileLog* log = _hir->compilation()->log();
  59     if (log != NULL)
  60       log->set_context("optimize name='cee'");
  61   }
  62 
  63   ~CE_Eliminator() {
  64     CompileLog* log = _hir->compilation()->log();
  65     if (log != NULL)
  66       log->clear_context(); // skip marker if nothing was printed
  67   }
  68 
  69   int cee_count() const                          { return _cee_count; }
  70   int ifop_count() const                         { return _ifop_count; }
  71 
  72   void adjust_exception_edges(BlockBegin* block, BlockBegin* sux) {
  73     int e = sux->number_of_exception_handlers();
  74     for (int i = 0; i < e; i++) {
  75       BlockBegin* xhandler = sux->exception_handler_at(i);
  76       block->add_exception_handler(xhandler);
  77 
  78       assert(xhandler->is_predecessor(sux), "missing predecessor");
  79       if (sux->number_of_preds() == 0) {
  80         // sux is disconnected from graph so disconnect from exception handlers
  81         xhandler->remove_predecessor(sux);
  82       }
  83       if (!xhandler->is_predecessor(block)) {
  84         xhandler->add_predecessor(block);
  85       }
  86     }
  87   }
  88 
  89   virtual void block_do(BlockBegin* block);
  90 
  91  private:
  92   Value make_ifop(Value x, Instruction::Condition cond, Value y, Value tval, Value fval,
  93                   ValueStack* state_before, bool substitutability_check);
  94 };
  95 
  96 void CE_Eliminator::block_do(BlockBegin* block) {
  97   // 1) find conditional expression
  98   // check if block ends with an If
  99   If* if_ = block->end()->as_If();
 100   if (if_ == NULL) return;
 101 
 102   // check if If works on int or object types
 103   // (we cannot handle If's working on long, float or doubles yet,
 104   // since IfOp doesn't support them - these If's show up if cmp
 105   // operations followed by If's are eliminated)
 106   ValueType* if_type = if_->x()->type();
 107   if (!if_type->is_int() && !if_type->is_object()) return;
 108 
 109   BlockBegin* t_block = if_->tsux();
 110   BlockBegin* f_block = if_->fsux();
 111   Instruction* t_cur = t_block->next();
 112   Instruction* f_cur = f_block->next();
 113 
 114   // one Constant may be present between BlockBegin and BlockEnd
 115   Value t_const = NULL;
 116   Value f_const = NULL;
 117   if (t_cur->as_Constant() != NULL && !t_cur->can_trap()) {
 118     t_const = t_cur;
 119     t_cur = t_cur->next();
 120   }
 121   if (f_cur->as_Constant() != NULL && !f_cur->can_trap()) {
 122     f_const = f_cur;
 123     f_cur = f_cur->next();
 124   }
 125 
 126   // check if both branches end with a goto
 127   Goto* t_goto = t_cur->as_Goto();
 128   if (t_goto == NULL) return;
 129   Goto* f_goto = f_cur->as_Goto();
 130   if (f_goto == NULL) return;
 131 
 132   // check if both gotos merge into the same block
 133   BlockBegin* sux = t_goto->default_sux();
 134   if (sux != f_goto->default_sux()) return;
 135 
 136   // check if at least one word was pushed on sux_state
 137   // inlining depths must match
 138   ValueStack* if_state = if_->state();
 139   ValueStack* sux_state = sux->state();
 140   if (if_state->scope()->level() > sux_state->scope()->level()) {
 141     while (sux_state->scope() != if_state->scope()) {
 142       if_state = if_state->caller_state();
 143       assert(if_state != NULL, "states do not match up");
 144     }
 145   } else if (if_state->scope()->level() < sux_state->scope()->level()) {
 146     while (sux_state->scope() != if_state->scope()) {
 147       sux_state = sux_state->caller_state();
 148       assert(sux_state != NULL, "states do not match up");
 149     }
 150   }
 151 
 152   if (sux_state->stack_size() <= if_state->stack_size()) return;
 153 
 154   // check if phi function is present at end of successor stack and that
 155   // only this phi was pushed on the stack
 156   Value sux_phi = sux_state->stack_at(if_state->stack_size());
 157   if (sux_phi == NULL || sux_phi->as_Phi() == NULL || sux_phi->as_Phi()->block() != sux) return;
 158   if (sux_phi->type()->size() != sux_state->stack_size() - if_state->stack_size()) return;
 159 
 160   // get the values that were pushed in the true- and false-branch
 161   Value t_value = t_goto->state()->stack_at(if_state->stack_size());
 162   Value f_value = f_goto->state()->stack_at(if_state->stack_size());
 163 
 164   // backend does not support floats
 165   assert(t_value->type()->base() == f_value->type()->base(), "incompatible types");
 166   if (t_value->type()->is_float_kind()) return;
 167 
 168   // check that successor has no other phi functions but sux_phi
 169   // this can happen when t_block or f_block contained additonal stores to local variables
 170   // that are no longer represented by explicit instructions
 171   for_each_phi_fun(sux, phi,
 172                    if (phi != sux_phi) return;
 173                    );
 174   // true and false blocks can't have phis
 175   for_each_phi_fun(t_block, phi, return; );
 176   for_each_phi_fun(f_block, phi, return; );
 177 
 178   // Only replace safepoint gotos if state_before information is available (if is a safepoint)
 179   bool is_safepoint = if_->is_safepoint();
 180   if (!is_safepoint && (t_goto->is_safepoint() || f_goto->is_safepoint())) {
 181     return;
 182   }
 183 
 184   // 2) substitute conditional expression
 185   //    with an IfOp followed by a Goto
 186   // cut if_ away and get node before
 187   Instruction* cur_end = if_->prev();
 188 
 189   // append constants of true- and false-block if necessary
 190   // clone constants because original block must not be destroyed
 191   assert((t_value != f_const && f_value != t_const) || t_const == f_const, "mismatch");
 192   if (t_value == t_const) {
 193     t_value = new Constant(t_const->type());
 194     NOT_PRODUCT(t_value->set_printable_bci(if_->printable_bci()));
 195     cur_end = cur_end->set_next(t_value);
 196   }
 197   if (f_value == f_const) {
 198     f_value = new Constant(f_const->type());
 199     NOT_PRODUCT(f_value->set_printable_bci(if_->printable_bci()));
 200     cur_end = cur_end->set_next(f_value);
 201   }
 202 
 203   Value result = make_ifop(if_->x(), if_->cond(), if_->y(), t_value, f_value,
 204                            if_->state_before(), if_->substitutability_check());
 205   assert(result != NULL, "make_ifop must return a non-null instruction");
 206   if (!result->is_linked() && result->can_be_linked()) {
 207     NOT_PRODUCT(result->set_printable_bci(if_->printable_bci()));
 208     cur_end = cur_end->set_next(result);
 209   }
 210 
 211   // append Goto to successor
 212   ValueStack* state_before = if_->state_before();
 213   Goto* goto_ = new Goto(sux, state_before, is_safepoint);
 214 
 215   // prepare state for Goto
 216   ValueStack* goto_state = if_state;
 217   goto_state = goto_state->copy(ValueStack::StateAfter, goto_state->bci());
 218   goto_state->push(result->type(), result);
 219   assert(goto_state->is_same(sux_state), "states must match now");
 220   goto_->set_state(goto_state);
 221 
 222   cur_end = cur_end->set_next(goto_, goto_state->bci());
 223 
 224   // Adjust control flow graph
 225   BlockBegin::disconnect_edge(block, t_block);
 226   BlockBegin::disconnect_edge(block, f_block);
 227   if (t_block->number_of_preds() == 0) {
 228     BlockBegin::disconnect_edge(t_block, sux);
 229   }
 230   adjust_exception_edges(block, t_block);
 231   if (f_block->number_of_preds() == 0) {
 232     BlockBegin::disconnect_edge(f_block, sux);
 233   }
 234   adjust_exception_edges(block, f_block);
 235 
 236   // update block end
 237   block->set_end(goto_);
 238 
 239   // substitute the phi if possible
 240   if (sux_phi->as_Phi()->operand_count() == 1) {
 241     assert(sux_phi->as_Phi()->operand_at(0) == result, "screwed up phi");
 242     sux_phi->set_subst(result);
 243     _has_substitution = true;
 244   }
 245 
 246   // 3) successfully eliminated a conditional expression
 247   _cee_count++;
 248   if (PrintCEE) {
 249     tty->print_cr("%d. CEE in B%d (B%d B%d)", cee_count(), block->block_id(), t_block->block_id(), f_block->block_id());
 250     tty->print_cr("%d. IfOp in B%d", ifop_count(), block->block_id());
 251   }
 252 
 253   _hir->verify();
 254 }
 255 
 256 Value CE_Eliminator::make_ifop(Value x, Instruction::Condition cond, Value y, Value tval, Value fval,
 257                                ValueStack* state_before, bool substitutability_check) {
 258   if (!OptimizeIfOps) {
 259     return new IfOp(x, cond, y, tval, fval, state_before, substitutability_check);
 260   }
 261 
 262   tval = tval->subst();
 263   fval = fval->subst();
 264   if (tval == fval) {
 265     _ifop_count++;
 266     return tval;
 267   }
 268 
 269   x = x->subst();
 270   y = y->subst();
 271 
 272   Constant* y_const = y->as_Constant();
 273   if (y_const != NULL) {
 274     IfOp* x_ifop = x->as_IfOp();
 275     if (x_ifop != NULL) {                 // x is an ifop, y is a constant
 276       Constant* x_tval_const = x_ifop->tval()->subst()->as_Constant();
 277       Constant* x_fval_const = x_ifop->fval()->subst()->as_Constant();
 278 
 279       if (x_tval_const != NULL && x_fval_const != NULL) {
 280         Instruction::Condition x_ifop_cond = x_ifop->cond();
 281 
 282         Constant::CompareResult t_compare_res = x_tval_const->compare(cond, y_const);
 283         Constant::CompareResult f_compare_res = x_fval_const->compare(cond, y_const);
 284 
 285         // not_comparable here is a valid return in case we're comparing unloaded oop constants
 286         if (t_compare_res != Constant::not_comparable && f_compare_res != Constant::not_comparable) {
 287           Value new_tval = t_compare_res == Constant::cond_true ? tval : fval;
 288           Value new_fval = f_compare_res == Constant::cond_true ? tval : fval;
 289 
 290           _ifop_count++;
 291           if (new_tval == new_fval) {
 292             return new_tval;
 293           } else {
 294             return new IfOp(x_ifop->x(), x_ifop_cond, x_ifop->y(), new_tval, new_fval, state_before, substitutability_check);
 295           }
 296         }
 297       }
 298     } else {
 299       Constant* x_const = x->as_Constant();
 300       if (x_const != NULL) {         // x and y are constants
 301         Constant::CompareResult x_compare_res = x_const->compare(cond, y_const);
 302         // not_comparable here is a valid return in case we're comparing unloaded oop constants
 303         if (x_compare_res != Constant::not_comparable) {
 304           _ifop_count++;
 305           return x_compare_res == Constant::cond_true ? tval : fval;
 306         }
 307       }
 308     }
 309   }
 310   return new IfOp(x, cond, y, tval, fval, state_before, substitutability_check);
 311 }
 312 
 313 void Optimizer::eliminate_conditional_expressions() {
 314   // find conditional expressions & replace them with IfOps
 315   CE_Eliminator ce(ir());
 316 }
 317 
 318 class BlockMerger: public BlockClosure {
 319  private:
 320   IR* _hir;
 321   int _merge_count;              // the number of block pairs successfully merged
 322 
 323  public:
 324   BlockMerger(IR* hir)
 325   : _hir(hir)
 326   , _merge_count(0)
 327   {
 328     _hir->iterate_preorder(this);
 329     CompileLog* log = _hir->compilation()->log();
 330     if (log != NULL)
 331       log->set_context("optimize name='eliminate_blocks'");
 332   }
 333 
 334   ~BlockMerger() {
 335     CompileLog* log = _hir->compilation()->log();
 336     if (log != NULL)
 337       log->clear_context(); // skip marker if nothing was printed
 338   }
 339 
 340   bool try_merge(BlockBegin* block) {
 341     BlockEnd* end = block->end();
 342     if (end->as_Goto() != NULL) {
 343       assert(end->number_of_sux() == 1, "end must have exactly one successor");
 344       // Note: It would be sufficient to check for the number of successors (= 1)
 345       //       in order to decide if this block can be merged potentially. That
 346       //       would then also include switch statements w/ only a default case.
 347       //       However, in that case we would need to make sure the switch tag
 348       //       expression is executed if it can produce observable side effects.
 349       //       We should probably have the canonicalizer simplifying such switch
 350       //       statements and then we are sure we don't miss these merge opportunities
 351       //       here (was bug - gri 7/7/99).
 352       BlockBegin* sux = end->default_sux();
 353       if (sux->number_of_preds() == 1 && !sux->is_entry_block() && !end->is_safepoint()) {
 354         // merge the two blocks
 355 
 356 #ifdef ASSERT
 357         // verify that state at the end of block and at the beginning of sux are equal
 358         // no phi functions must be present at beginning of sux
 359         ValueStack* sux_state = sux->state();
 360         ValueStack* end_state = end->state();
 361 
 362         assert(end_state->scope() == sux_state->scope(), "scopes must match");
 363         assert(end_state->stack_size() == sux_state->stack_size(), "stack not equal");
 364         assert(end_state->locals_size() == sux_state->locals_size(), "locals not equal");
 365 
 366         int index;
 367         Value sux_value;
 368         for_each_stack_value(sux_state, index, sux_value) {
 369           assert(sux_value == end_state->stack_at(index), "stack not equal");
 370         }
 371         for_each_local_value(sux_state, index, sux_value) {
 372           Phi* sux_phi = sux_value->as_Phi();
 373           if (sux_phi != NULL && sux_phi->is_illegal()) continue;
 374           assert(sux_value == end_state->local_at(index), "locals not equal");
 375         }
 376         assert(sux_state->caller_state() == end_state->caller_state(), "caller not equal");
 377 #endif
 378 
 379         // find instruction before end & append first instruction of sux block
 380         Instruction* prev = end->prev();
 381         Instruction* next = sux->next();
 382         assert(prev->as_BlockEnd() == NULL, "must not be a BlockEnd");
 383         prev->set_next(next);
 384         prev->fixup_block_pointers();
 385         sux->disconnect_from_graph();
 386         block->set_end(sux->end());
 387         // add exception handlers of deleted block, if any
 388         for (int k = 0; k < sux->number_of_exception_handlers(); k++) {
 389           BlockBegin* xhandler = sux->exception_handler_at(k);
 390           block->add_exception_handler(xhandler);
 391 
 392           // also substitute predecessor of exception handler
 393           assert(xhandler->is_predecessor(sux), "missing predecessor");
 394           xhandler->remove_predecessor(sux);
 395           if (!xhandler->is_predecessor(block)) {
 396             xhandler->add_predecessor(block);
 397           }
 398         }
 399 
 400         // debugging output
 401         _merge_count++;
 402         if (PrintBlockElimination) {
 403           tty->print_cr("%d. merged B%d & B%d (stack size = %d)",
 404                         _merge_count, block->block_id(), sux->block_id(), sux->state()->stack_size());
 405         }
 406 
 407         _hir->verify();
 408 
 409         If* if_ = block->end()->as_If();
 410         if (if_) {
 411           IfOp* ifop    = if_->x()->as_IfOp();
 412           Constant* con = if_->y()->as_Constant();
 413           bool swapped = false;
 414           if (!con || !ifop) {
 415             ifop = if_->y()->as_IfOp();
 416             con  = if_->x()->as_Constant();
 417             swapped = true;
 418           }
 419           if (con && ifop && !ifop->substitutability_check()) {
 420             Constant* tval = ifop->tval()->as_Constant();
 421             Constant* fval = ifop->fval()->as_Constant();
 422             if (tval && fval) {
 423               // Find the instruction before if_, starting with ifop.
 424               // When if_ and ifop are not in the same block, prev
 425               // becomes NULL In such (rare) cases it is not
 426               // profitable to perform the optimization.
 427               Value prev = ifop;
 428               while (prev != NULL && prev->next() != if_) {
 429                 prev = prev->next();
 430               }
 431 
 432               if (prev != NULL) {
 433                 Instruction::Condition cond = if_->cond();
 434                 BlockBegin* tsux = if_->tsux();
 435                 BlockBegin* fsux = if_->fsux();
 436                 if (swapped) {
 437                   cond = Instruction::mirror(cond);
 438                 }
 439 
 440                 BlockBegin* tblock = tval->compare(cond, con, tsux, fsux);
 441                 BlockBegin* fblock = fval->compare(cond, con, tsux, fsux);
 442                 if (tblock != fblock && !if_->is_safepoint()) {
 443                   If* newif = new If(ifop->x(), ifop->cond(), false, ifop->y(),
 444                                      tblock, fblock, if_->state_before(), if_->is_safepoint(), ifop->substitutability_check());
 445                   newif->set_state(if_->state()->copy());
 446 
 447                   assert(prev->next() == if_, "must be guaranteed by above search");
 448                   NOT_PRODUCT(newif->set_printable_bci(if_->printable_bci()));
 449                   prev->set_next(newif);
 450                   block->set_end(newif);
 451 
 452                   _merge_count++;
 453                   if (PrintBlockElimination) {
 454                     tty->print_cr("%d. replaced If and IfOp at end of B%d with single If", _merge_count, block->block_id());
 455                   }
 456 
 457                   _hir->verify();
 458                 }
 459               }
 460             }
 461           }
 462         }
 463 
 464         return true;
 465       }
 466     }
 467     return false;
 468   }
 469 
 470   virtual void block_do(BlockBegin* block) {
 471     _hir->verify();
 472     // repeat since the same block may merge again
 473     while (try_merge(block)) {
 474       _hir->verify();
 475     }
 476   }
 477 };
 478 
 479 
 480 void Optimizer::eliminate_blocks() {
 481   // merge blocks if possible
 482   BlockMerger bm(ir());
 483 }
 484 
 485 
 486 class NullCheckEliminator;
 487 class NullCheckVisitor: public InstructionVisitor {
 488 private:
 489   NullCheckEliminator* _nce;
 490   NullCheckEliminator* nce() { return _nce; }
 491 
 492 public:
 493   NullCheckVisitor() {}
 494 
 495   void set_eliminator(NullCheckEliminator* nce) { _nce = nce; }
 496 
 497   void do_Phi            (Phi*             x);
 498   void do_Local          (Local*           x);
 499   void do_Constant       (Constant*        x);
 500   void do_LoadField      (LoadField*       x);
 501   void do_StoreField     (StoreField*      x);
 502   void do_ArrayLength    (ArrayLength*     x);
 503   void do_LoadIndexed    (LoadIndexed*     x);
 504   void do_StoreIndexed   (StoreIndexed*    x);
 505   void do_NegateOp       (NegateOp*        x);
 506   void do_ArithmeticOp   (ArithmeticOp*    x);
 507   void do_ShiftOp        (ShiftOp*         x);
 508   void do_LogicOp        (LogicOp*         x);
 509   void do_CompareOp      (CompareOp*       x);
 510   void do_IfOp           (IfOp*            x);
 511   void do_Convert        (Convert*         x);
 512   void do_NullCheck      (NullCheck*       x);
 513   void do_TypeCast       (TypeCast*        x);
 514   void do_Invoke         (Invoke*          x);
 515   void do_NewInstance    (NewInstance*     x);
 516   void do_NewInlineTypeInstance(NewInlineTypeInstance* x);
 517   void do_NewTypeArray   (NewTypeArray*    x);
 518   void do_NewObjectArray (NewObjectArray*  x);
 519   void do_NewMultiArray  (NewMultiArray*   x);
 520   void do_Deoptimize     (Deoptimize*      x);
 521   void do_CheckCast      (CheckCast*       x);
 522   void do_InstanceOf     (InstanceOf*      x);
 523   void do_MonitorEnter   (MonitorEnter*    x);
 524   void do_MonitorExit    (MonitorExit*     x);
 525   void do_Intrinsic      (Intrinsic*       x);
 526   void do_BlockBegin     (BlockBegin*      x);
 527   void do_Goto           (Goto*            x);
 528   void do_If             (If*              x);
 529   void do_TableSwitch    (TableSwitch*     x);
 530   void do_LookupSwitch   (LookupSwitch*    x);
 531   void do_Return         (Return*          x);
 532   void do_Throw          (Throw*           x);
 533   void do_Base           (Base*            x);
 534   void do_OsrEntry       (OsrEntry*        x);
 535   void do_ExceptionObject(ExceptionObject* x);
 536   void do_RoundFP        (RoundFP*         x);
 537   void do_UnsafeGet      (UnsafeGet*       x);
 538   void do_UnsafePut      (UnsafePut*       x);
 539   void do_UnsafeGetAndSet(UnsafeGetAndSet* x);
 540   void do_ProfileCall    (ProfileCall*     x);
 541   void do_ProfileReturnType (ProfileReturnType*  x);
 542   void do_ProfileACmpTypes(ProfileACmpTypes*  x);
 543   void do_ProfileInvoke  (ProfileInvoke*   x);
 544   void do_RuntimeCall    (RuntimeCall*     x);
 545   void do_MemBar         (MemBar*          x);
 546   void do_RangeCheckPredicate(RangeCheckPredicate* x);
 547 #ifdef ASSERT
 548   void do_Assert         (Assert*          x);
 549 #endif
 550 };
 551 
 552 
 553 // Because of a static contained within (for the purpose of iteration
 554 // over instructions), it is only valid to have one of these active at
 555 // a time
 556 class NullCheckEliminator: public ValueVisitor {
 557  private:
 558   Optimizer*        _opt;
 559 
 560   ValueSet*         _visitable_instructions;        // Visit each instruction only once per basic block
 561   BlockList*        _work_list;                   // Basic blocks to visit
 562 
 563   bool visitable(Value x) {
 564     assert(_visitable_instructions != NULL, "check");
 565     return _visitable_instructions->contains(x);
 566   }
 567   void mark_visited(Value x) {
 568     assert(_visitable_instructions != NULL, "check");
 569     _visitable_instructions->remove(x);
 570   }
 571   void mark_visitable(Value x) {
 572     assert(_visitable_instructions != NULL, "check");
 573     _visitable_instructions->put(x);
 574   }
 575   void clear_visitable_state() {
 576     assert(_visitable_instructions != NULL, "check");
 577     _visitable_instructions->clear();
 578   }
 579 
 580   ValueSet*         _set;                         // current state, propagated to subsequent BlockBegins
 581   ValueSetList      _block_states;                // BlockBegin null-check states for all processed blocks
 582   NullCheckVisitor  _visitor;
 583   NullCheck*        _last_explicit_null_check;
 584 
 585   bool set_contains(Value x)                      { assert(_set != NULL, "check"); return _set->contains(x); }
 586   void set_put     (Value x)                      { assert(_set != NULL, "check"); _set->put(x); }
 587   void set_remove  (Value x)                      { assert(_set != NULL, "check"); _set->remove(x); }
 588 
 589   BlockList* work_list()                          { return _work_list; }
 590 
 591   void iterate_all();
 592   void iterate_one(BlockBegin* block);
 593 
 594   ValueSet* state()                               { return _set; }
 595   void      set_state_from (ValueSet* state)      { _set->set_from(state); }
 596   ValueSet* state_for      (BlockBegin* block)    { return _block_states.at(block->block_id()); }
 597   void      set_state_for  (BlockBegin* block, ValueSet* stack) { _block_states.at_put(block->block_id(), stack); }
 598   // Returns true if caused a change in the block's state.
 599   bool      merge_state_for(BlockBegin* block,
 600                             ValueSet*   incoming_state);
 601 
 602  public:
 603   // constructor
 604   NullCheckEliminator(Optimizer* opt)
 605     : _opt(opt)
 606     , _work_list(new BlockList())
 607     , _set(new ValueSet())
 608     , _block_states(BlockBegin::number_of_blocks(), BlockBegin::number_of_blocks(), NULL)
 609     , _last_explicit_null_check(NULL) {
 610     _visitable_instructions = new ValueSet();
 611     _visitor.set_eliminator(this);
 612     CompileLog* log = _opt->ir()->compilation()->log();
 613     if (log != NULL)
 614       log->set_context("optimize name='null_check_elimination'");
 615   }
 616 
 617   ~NullCheckEliminator() {
 618     CompileLog* log = _opt->ir()->compilation()->log();
 619     if (log != NULL)
 620       log->clear_context(); // skip marker if nothing was printed
 621   }
 622 
 623   Optimizer*  opt()                               { return _opt; }
 624   IR*         ir ()                               { return opt()->ir(); }
 625 
 626   // Process a graph
 627   void iterate(BlockBegin* root);
 628 
 629   void visit(Value* f);
 630 
 631   // In some situations (like NullCheck(x); getfield(x)) the debug
 632   // information from the explicit NullCheck can be used to populate
 633   // the getfield, even if the two instructions are in different
 634   // scopes; this allows implicit null checks to be used but the
 635   // correct exception information to be generated. We must clear the
 636   // last-traversed NullCheck when we reach a potentially-exception-
 637   // throwing instruction, as well as in some other cases.
 638   void        set_last_explicit_null_check(NullCheck* check) { _last_explicit_null_check = check; }
 639   NullCheck*  last_explicit_null_check()                     { return _last_explicit_null_check; }
 640   Value       last_explicit_null_check_obj()                 { return (_last_explicit_null_check
 641                                                                          ? _last_explicit_null_check->obj()
 642                                                                          : NULL); }
 643   NullCheck*  consume_last_explicit_null_check() {
 644     _last_explicit_null_check->unpin(Instruction::PinExplicitNullCheck);
 645     _last_explicit_null_check->set_can_trap(false);
 646     return _last_explicit_null_check;
 647   }
 648   void        clear_last_explicit_null_check()               { _last_explicit_null_check = NULL; }
 649 
 650   // Handlers for relevant instructions
 651   // (separated out from NullCheckVisitor for clarity)
 652 
 653   // The basic contract is that these must leave the instruction in
 654   // the desired state; must not assume anything about the state of
 655   // the instruction. We make multiple passes over some basic blocks
 656   // and the last pass is the only one whose result is valid.
 657   void handle_AccessField     (AccessField* x);
 658   void handle_ArrayLength     (ArrayLength* x);
 659   void handle_LoadIndexed     (LoadIndexed* x);
 660   void handle_StoreIndexed    (StoreIndexed* x);
 661   void handle_NullCheck       (NullCheck* x);
 662   void handle_Invoke          (Invoke* x);
 663   void handle_NewInstance     (NewInstance* x);
 664   void handle_NewInlineTypeInstance(NewInlineTypeInstance* x);
 665   void handle_NewArray        (NewArray* x);
 666   void handle_AccessMonitor   (AccessMonitor* x);
 667   void handle_Intrinsic       (Intrinsic* x);
 668   void handle_ExceptionObject (ExceptionObject* x);
 669   void handle_Phi             (Phi* x);
 670   void handle_ProfileCall     (ProfileCall* x);
 671   void handle_ProfileReturnType (ProfileReturnType* x);
 672   void handle_ProfileACmpTypes(ProfileACmpTypes* x);
 673 };
 674 
 675 
 676 // NEEDS_CLEANUP
 677 // There may be other instructions which need to clear the last
 678 // explicit null check. Anything across which we can not hoist the
 679 // debug information for a NullCheck instruction must clear it. It
 680 // might be safer to pattern match "NullCheck ; {AccessField,
 681 // ArrayLength, LoadIndexed}" but it is more easily structured this way.
 682 // Should test to see performance hit of clearing it for all handlers
 683 // with empty bodies below. If it is negligible then we should leave
 684 // that in for safety, otherwise should think more about it.
 685 void NullCheckVisitor::do_Phi            (Phi*             x) { nce()->handle_Phi(x);      }
 686 void NullCheckVisitor::do_Local          (Local*           x) {}
 687 void NullCheckVisitor::do_Constant       (Constant*        x) { /* FIXME: handle object constants */ }
 688 void NullCheckVisitor::do_LoadField      (LoadField*       x) { nce()->handle_AccessField(x); }
 689 void NullCheckVisitor::do_StoreField     (StoreField*      x) { nce()->handle_AccessField(x); }
 690 void NullCheckVisitor::do_ArrayLength    (ArrayLength*     x) { nce()->handle_ArrayLength(x); }
 691 void NullCheckVisitor::do_LoadIndexed    (LoadIndexed*     x) { nce()->handle_LoadIndexed(x); }
 692 void NullCheckVisitor::do_StoreIndexed   (StoreIndexed*    x) { nce()->handle_StoreIndexed(x); }
 693 void NullCheckVisitor::do_NegateOp       (NegateOp*        x) {}
 694 void NullCheckVisitor::do_ArithmeticOp   (ArithmeticOp*    x) { if (x->can_trap()) nce()->clear_last_explicit_null_check(); }
 695 void NullCheckVisitor::do_ShiftOp        (ShiftOp*         x) {}
 696 void NullCheckVisitor::do_LogicOp        (LogicOp*         x) {}
 697 void NullCheckVisitor::do_CompareOp      (CompareOp*       x) {}
 698 void NullCheckVisitor::do_IfOp           (IfOp*            x) {}
 699 void NullCheckVisitor::do_Convert        (Convert*         x) {}
 700 void NullCheckVisitor::do_NullCheck      (NullCheck*       x) { nce()->handle_NullCheck(x); }
 701 void NullCheckVisitor::do_TypeCast       (TypeCast*        x) {}
 702 void NullCheckVisitor::do_Invoke         (Invoke*          x) { nce()->handle_Invoke(x); }
 703 void NullCheckVisitor::do_NewInstance    (NewInstance*     x) { nce()->handle_NewInstance(x); }
 704 void NullCheckVisitor::do_NewInlineTypeInstance(NewInlineTypeInstance* x) { nce()->handle_NewInlineTypeInstance(x); }
 705 void NullCheckVisitor::do_NewTypeArray   (NewTypeArray*    x) { nce()->handle_NewArray(x); }
 706 void NullCheckVisitor::do_NewObjectArray (NewObjectArray*  x) { nce()->handle_NewArray(x); }
 707 void NullCheckVisitor::do_NewMultiArray  (NewMultiArray*   x) { nce()->handle_NewArray(x); }
 708 void NullCheckVisitor::do_Deoptimize     (Deoptimize*      x) {}
 709 void NullCheckVisitor::do_CheckCast      (CheckCast*       x) { nce()->clear_last_explicit_null_check(); }
 710 void NullCheckVisitor::do_InstanceOf     (InstanceOf*      x) {}
 711 void NullCheckVisitor::do_MonitorEnter   (MonitorEnter*    x) { nce()->handle_AccessMonitor(x); }
 712 void NullCheckVisitor::do_MonitorExit    (MonitorExit*     x) { nce()->handle_AccessMonitor(x); }
 713 void NullCheckVisitor::do_Intrinsic      (Intrinsic*       x) { nce()->handle_Intrinsic(x);     }
 714 void NullCheckVisitor::do_BlockBegin     (BlockBegin*      x) {}
 715 void NullCheckVisitor::do_Goto           (Goto*            x) {}
 716 void NullCheckVisitor::do_If             (If*              x) {}
 717 void NullCheckVisitor::do_TableSwitch    (TableSwitch*     x) {}
 718 void NullCheckVisitor::do_LookupSwitch   (LookupSwitch*    x) {}
 719 void NullCheckVisitor::do_Return         (Return*          x) {}
 720 void NullCheckVisitor::do_Throw          (Throw*           x) { nce()->clear_last_explicit_null_check(); }
 721 void NullCheckVisitor::do_Base           (Base*            x) {}
 722 void NullCheckVisitor::do_OsrEntry       (OsrEntry*        x) {}
 723 void NullCheckVisitor::do_ExceptionObject(ExceptionObject* x) { nce()->handle_ExceptionObject(x); }
 724 void NullCheckVisitor::do_RoundFP        (RoundFP*         x) {}
 725 void NullCheckVisitor::do_UnsafeGet      (UnsafeGet*       x) {}
 726 void NullCheckVisitor::do_UnsafePut      (UnsafePut*       x) {}
 727 void NullCheckVisitor::do_UnsafeGetAndSet(UnsafeGetAndSet* x) {}
 728 void NullCheckVisitor::do_ProfileCall    (ProfileCall*     x) { nce()->clear_last_explicit_null_check();
 729                                                                 nce()->handle_ProfileCall(x); }
 730 void NullCheckVisitor::do_ProfileReturnType (ProfileReturnType* x) { nce()->handle_ProfileReturnType(x); }
 731 void NullCheckVisitor::do_ProfileInvoke  (ProfileInvoke*   x) {}
 732 void NullCheckVisitor::do_ProfileACmpTypes(ProfileACmpTypes* x) { nce()->handle_ProfileACmpTypes(x); }
 733 void NullCheckVisitor::do_RuntimeCall    (RuntimeCall*     x) {}
 734 void NullCheckVisitor::do_MemBar         (MemBar*          x) {}
 735 void NullCheckVisitor::do_RangeCheckPredicate(RangeCheckPredicate* x) {}
 736 #ifdef ASSERT
 737 void NullCheckVisitor::do_Assert         (Assert*          x) {}
 738 #endif
 739 
 740 void NullCheckEliminator::visit(Value* p) {
 741   assert(*p != NULL, "should not find NULL instructions");
 742   if (visitable(*p)) {
 743     mark_visited(*p);
 744     (*p)->visit(&_visitor);
 745   }
 746 }
 747 
 748 bool NullCheckEliminator::merge_state_for(BlockBegin* block, ValueSet* incoming_state) {
 749   ValueSet* state = state_for(block);
 750   if (state == NULL) {
 751     state = incoming_state->copy();
 752     set_state_for(block, state);
 753     return true;
 754   } else {
 755     bool changed = state->set_intersect(incoming_state);
 756     if (PrintNullCheckElimination && changed) {
 757       tty->print_cr("Block %d's null check state changed", block->block_id());
 758     }
 759     return changed;
 760   }
 761 }
 762 
 763 
 764 void NullCheckEliminator::iterate_all() {
 765   while (work_list()->length() > 0) {
 766     iterate_one(work_list()->pop());
 767   }
 768 }
 769 
 770 
 771 void NullCheckEliminator::iterate_one(BlockBegin* block) {
 772   clear_visitable_state();
 773   // clear out an old explicit null checks
 774   set_last_explicit_null_check(NULL);
 775 
 776   if (PrintNullCheckElimination) {
 777     tty->print_cr(" ...iterating block %d in null check elimination for %s::%s%s",
 778                   block->block_id(),
 779                   ir()->method()->holder()->name()->as_utf8(),
 780                   ir()->method()->name()->as_utf8(),
 781                   ir()->method()->signature()->as_symbol()->as_utf8());
 782   }
 783 
 784   // Create new state if none present (only happens at root)
 785   if (state_for(block) == NULL) {
 786     ValueSet* tmp_state = new ValueSet();
 787     set_state_for(block, tmp_state);
 788     // Initial state is that local 0 (receiver) is non-null for
 789     // non-static methods
 790     ValueStack* stack  = block->state();
 791     IRScope*    scope  = stack->scope();
 792     ciMethod*   method = scope->method();
 793     if (!method->is_static()) {
 794       Local* local0 = stack->local_at(0)->as_Local();
 795       assert(local0 != NULL, "must be");
 796       assert(local0->type() == objectType, "invalid type of receiver");
 797 
 798       if (local0 != NULL) {
 799         // Local 0 is used in this scope
 800         tmp_state->put(local0);
 801         if (PrintNullCheckElimination) {
 802           tty->print_cr("Local 0 (value %d) proven non-null upon entry", local0->id());
 803         }
 804       }
 805     }
 806   }
 807 
 808   // Must copy block's state to avoid mutating it during iteration
 809   // through the block -- otherwise "not-null" states can accidentally
 810   // propagate "up" through the block during processing of backward
 811   // branches and algorithm is incorrect (and does not converge)
 812   set_state_from(state_for(block));
 813 
 814   // allow visiting of Phis belonging to this block
 815   for_each_phi_fun(block, phi,
 816                    mark_visitable(phi);
 817                    );
 818 
 819   BlockEnd* e = block->end();
 820   assert(e != NULL, "incomplete graph");
 821   int i;
 822 
 823   // Propagate the state before this block into the exception
 824   // handlers.  They aren't true successors since we aren't guaranteed
 825   // to execute the whole block before executing them.  Also putting
 826   // them on first seems to help reduce the amount of iteration to
 827   // reach a fixed point.
 828   for (i = 0; i < block->number_of_exception_handlers(); i++) {
 829     BlockBegin* next = block->exception_handler_at(i);
 830     if (merge_state_for(next, state())) {
 831       if (!work_list()->contains(next)) {
 832         work_list()->push(next);
 833       }
 834     }
 835   }
 836 
 837   // Iterate through block, updating state.
 838   for (Instruction* instr = block; instr != NULL; instr = instr->next()) {
 839     // Mark instructions in this block as visitable as they are seen
 840     // in the instruction list.  This keeps the iteration from
 841     // visiting instructions which are references in other blocks or
 842     // visiting instructions more than once.
 843     mark_visitable(instr);
 844     if (instr->is_pinned() || instr->can_trap() || (instr->as_NullCheck() != NULL)) {
 845       mark_visited(instr);
 846       instr->input_values_do(this);
 847       instr->visit(&_visitor);
 848     }
 849   }
 850 
 851   // Propagate state to successors if necessary
 852   for (i = 0; i < e->number_of_sux(); i++) {
 853     BlockBegin* next = e->sux_at(i);
 854     if (merge_state_for(next, state())) {
 855       if (!work_list()->contains(next)) {
 856         work_list()->push(next);
 857       }
 858     }
 859   }
 860 }
 861 
 862 
 863 void NullCheckEliminator::iterate(BlockBegin* block) {
 864   work_list()->push(block);
 865   iterate_all();
 866 }
 867 
 868 void NullCheckEliminator::handle_AccessField(AccessField* x) {
 869   if (x->is_static()) {
 870     if (x->as_LoadField() != NULL) {
 871       // If the field is a non-null static final object field (as is
 872       // often the case for sun.misc.Unsafe), put this LoadField into
 873       // the non-null map
 874       ciField* field = x->field();
 875       if (field->is_constant()) {
 876         ciConstant field_val = field->constant_value();
 877         BasicType field_type = field_val.basic_type();
 878         if (is_reference_type(field_type)) {
 879           ciObject* obj_val = field_val.as_object();
 880           if (!obj_val->is_null_object()) {
 881             if (PrintNullCheckElimination) {
 882               tty->print_cr("AccessField %d proven non-null by static final non-null oop check",
 883                             x->id());
 884             }
 885             set_put(x);
 886           }
 887         }
 888       }
 889     }
 890     // Be conservative
 891     clear_last_explicit_null_check();
 892     return;
 893   }
 894 
 895   Value obj = x->obj();
 896   if (set_contains(obj)) {
 897     // Value is non-null => update AccessField
 898     if (last_explicit_null_check_obj() == obj && !x->needs_patching()) {
 899       x->set_explicit_null_check(consume_last_explicit_null_check());
 900       x->set_needs_null_check(true);
 901       if (PrintNullCheckElimination) {
 902         tty->print_cr("Folded NullCheck %d into AccessField %d's null check for value %d",
 903                       x->explicit_null_check()->id(), x->id(), obj->id());
 904       }
 905     } else {
 906       x->set_explicit_null_check(NULL);
 907       x->set_needs_null_check(false);
 908       if (PrintNullCheckElimination) {
 909         tty->print_cr("Eliminated AccessField %d's null check for value %d", x->id(), obj->id());
 910       }
 911     }
 912   } else {
 913     set_put(obj);
 914     if (PrintNullCheckElimination) {
 915       tty->print_cr("AccessField %d of value %d proves value to be non-null", x->id(), obj->id());
 916     }
 917     // Ensure previous passes do not cause wrong state
 918     x->set_needs_null_check(true);
 919     x->set_explicit_null_check(NULL);
 920   }
 921   clear_last_explicit_null_check();
 922 }
 923 
 924 
 925 void NullCheckEliminator::handle_ArrayLength(ArrayLength* x) {
 926   Value array = x->array();
 927   if (set_contains(array)) {
 928     // Value is non-null => update AccessArray
 929     if (last_explicit_null_check_obj() == array) {
 930       x->set_explicit_null_check(consume_last_explicit_null_check());
 931       x->set_needs_null_check(true);
 932       if (PrintNullCheckElimination) {
 933         tty->print_cr("Folded NullCheck %d into ArrayLength %d's null check for value %d",
 934                       x->explicit_null_check()->id(), x->id(), array->id());
 935       }
 936     } else {
 937       x->set_explicit_null_check(NULL);
 938       x->set_needs_null_check(false);
 939       if (PrintNullCheckElimination) {
 940         tty->print_cr("Eliminated ArrayLength %d's null check for value %d", x->id(), array->id());
 941       }
 942     }
 943   } else {
 944     set_put(array);
 945     if (PrintNullCheckElimination) {
 946       tty->print_cr("ArrayLength %d of value %d proves value to be non-null", x->id(), array->id());
 947     }
 948     // Ensure previous passes do not cause wrong state
 949     x->set_needs_null_check(true);
 950     x->set_explicit_null_check(NULL);
 951   }
 952   clear_last_explicit_null_check();
 953 }
 954 
 955 
 956 void NullCheckEliminator::handle_LoadIndexed(LoadIndexed* x) {
 957   Value array = x->array();
 958   if (set_contains(array)) {
 959     // Value is non-null => update AccessArray
 960     if (last_explicit_null_check_obj() == array) {
 961       x->set_explicit_null_check(consume_last_explicit_null_check());
 962       x->set_needs_null_check(true);
 963       if (PrintNullCheckElimination) {
 964         tty->print_cr("Folded NullCheck %d into LoadIndexed %d's null check for value %d",
 965                       x->explicit_null_check()->id(), x->id(), array->id());
 966       }
 967     } else {
 968       x->set_explicit_null_check(NULL);
 969       x->set_needs_null_check(false);
 970       if (PrintNullCheckElimination) {
 971         tty->print_cr("Eliminated LoadIndexed %d's null check for value %d", x->id(), array->id());
 972       }
 973     }
 974   } else {
 975     set_put(array);
 976     if (PrintNullCheckElimination) {
 977       tty->print_cr("LoadIndexed %d of value %d proves value to be non-null", x->id(), array->id());
 978     }
 979     // Ensure previous passes do not cause wrong state
 980     x->set_needs_null_check(true);
 981     x->set_explicit_null_check(NULL);
 982   }
 983   clear_last_explicit_null_check();
 984 }
 985 
 986 
 987 void NullCheckEliminator::handle_StoreIndexed(StoreIndexed* x) {
 988   Value array = x->array();
 989   if (set_contains(array)) {
 990     // Value is non-null => update AccessArray
 991     if (PrintNullCheckElimination) {
 992       tty->print_cr("Eliminated StoreIndexed %d's null check for value %d", x->id(), array->id());
 993     }
 994     x->set_needs_null_check(false);
 995   } else {
 996     set_put(array);
 997     if (PrintNullCheckElimination) {
 998       tty->print_cr("StoreIndexed %d of value %d proves value to be non-null", x->id(), array->id());
 999     }
1000     // Ensure previous passes do not cause wrong state
1001     x->set_needs_null_check(true);
1002   }
1003   clear_last_explicit_null_check();
1004 }
1005 
1006 
1007 void NullCheckEliminator::handle_NullCheck(NullCheck* x) {
1008   Value obj = x->obj();
1009   if (set_contains(obj)) {
1010     // Already proven to be non-null => this NullCheck is useless
1011     if (PrintNullCheckElimination) {
1012       tty->print_cr("Eliminated NullCheck %d for value %d", x->id(), obj->id());
1013     }
1014     // Don't unpin since that may shrink obj's live range and make it unavailable for debug info.
1015     // The code generator won't emit LIR for a NullCheck that cannot trap.
1016     x->set_can_trap(false);
1017   } else {
1018     // May be null => add to map and set last explicit NullCheck
1019     x->set_can_trap(true);
1020     // make sure it's pinned if it can trap
1021     x->pin(Instruction::PinExplicitNullCheck);
1022     set_put(obj);
1023     set_last_explicit_null_check(x);
1024     if (PrintNullCheckElimination) {
1025       tty->print_cr("NullCheck %d of value %d proves value to be non-null", x->id(), obj->id());
1026     }
1027   }
1028 }
1029 
1030 
1031 void NullCheckEliminator::handle_Invoke(Invoke* x) {
1032   if (!x->has_receiver()) {
1033     // Be conservative
1034     clear_last_explicit_null_check();
1035     return;
1036   }
1037 
1038   Value recv = x->receiver();
1039   if (!set_contains(recv)) {
1040     set_put(recv);
1041     if (PrintNullCheckElimination) {
1042       tty->print_cr("Invoke %d of value %d proves value to be non-null", x->id(), recv->id());
1043     }
1044   }
1045   clear_last_explicit_null_check();
1046 }
1047 
1048 
1049 void NullCheckEliminator::handle_NewInstance(NewInstance* x) {
1050   set_put(x);
1051   if (PrintNullCheckElimination) {
1052     tty->print_cr("NewInstance %d is non-null", x->id());
1053   }
1054 }
1055 
1056 void NullCheckEliminator::handle_NewInlineTypeInstance(NewInlineTypeInstance* x) {
1057   set_put(x);
1058   if (PrintNullCheckElimination) {
1059     tty->print_cr("NewInlineTypeInstance %d is non-null", x->id());
1060   }
1061 }
1062 
1063 
1064 void NullCheckEliminator::handle_NewArray(NewArray* x) {
1065   set_put(x);
1066   if (PrintNullCheckElimination) {
1067     tty->print_cr("NewArray %d is non-null", x->id());
1068   }
1069 }
1070 
1071 
1072 void NullCheckEliminator::handle_ExceptionObject(ExceptionObject* x) {
1073   set_put(x);
1074   if (PrintNullCheckElimination) {
1075     tty->print_cr("ExceptionObject %d is non-null", x->id());
1076   }
1077 }
1078 
1079 
1080 void NullCheckEliminator::handle_AccessMonitor(AccessMonitor* x) {
1081   Value obj = x->obj();
1082   if (set_contains(obj)) {
1083     // Value is non-null => update AccessMonitor
1084     if (PrintNullCheckElimination) {
1085       tty->print_cr("Eliminated AccessMonitor %d's null check for value %d", x->id(), obj->id());
1086     }
1087     x->set_needs_null_check(false);
1088   } else {
1089     set_put(obj);
1090     if (PrintNullCheckElimination) {
1091       tty->print_cr("AccessMonitor %d of value %d proves value to be non-null", x->id(), obj->id());
1092     }
1093     // Ensure previous passes do not cause wrong state
1094     x->set_needs_null_check(true);
1095   }
1096   clear_last_explicit_null_check();
1097 }
1098 
1099 
1100 void NullCheckEliminator::handle_Intrinsic(Intrinsic* x) {
1101   if (!x->has_receiver()) {
1102     if (x->id() == vmIntrinsics::_arraycopy) {
1103       for (int i = 0; i < x->number_of_arguments(); i++) {
1104         x->set_arg_needs_null_check(i, !set_contains(x->argument_at(i)));
1105       }
1106     }
1107 
1108     // Be conservative
1109     clear_last_explicit_null_check();
1110     return;
1111   }
1112 
1113   Value recv = x->receiver();
1114   if (set_contains(recv)) {
1115     // Value is non-null => update Intrinsic
1116     if (PrintNullCheckElimination) {
1117       tty->print_cr("Eliminated Intrinsic %d's null check for value %d", vmIntrinsics::as_int(x->id()), recv->id());
1118     }
1119     x->set_needs_null_check(false);
1120   } else {
1121     set_put(recv);
1122     if (PrintNullCheckElimination) {
1123       tty->print_cr("Intrinsic %d of value %d proves value to be non-null", vmIntrinsics::as_int(x->id()), recv->id());
1124     }
1125     // Ensure previous passes do not cause wrong state
1126     x->set_needs_null_check(true);
1127   }
1128   clear_last_explicit_null_check();
1129 }
1130 
1131 
1132 void NullCheckEliminator::handle_Phi(Phi* x) {
1133   int i;
1134   bool all_non_null = true;
1135   if (x->is_illegal()) {
1136     all_non_null = false;
1137   } else {
1138     for (i = 0; i < x->operand_count(); i++) {
1139       Value input = x->operand_at(i);
1140       if (!set_contains(input)) {
1141         all_non_null = false;
1142       }
1143     }
1144   }
1145 
1146   if (all_non_null) {
1147     // Value is non-null => update Phi
1148     if (PrintNullCheckElimination) {
1149       tty->print_cr("Eliminated Phi %d's null check for phifun because all inputs are non-null", x->id());
1150     }
1151     x->set_needs_null_check(false);
1152   } else if (set_contains(x)) {
1153     set_remove(x);
1154   }
1155 }
1156 
1157 void NullCheckEliminator::handle_ProfileCall(ProfileCall* x) {
1158   for (int i = 0; i < x->nb_profiled_args(); i++) {
1159     x->set_arg_needs_null_check(i, !set_contains(x->profiled_arg_at(i)));
1160   }
1161 }
1162 
1163 void NullCheckEliminator::handle_ProfileReturnType(ProfileReturnType* x) {
1164   x->set_needs_null_check(!set_contains(x->ret()));
1165 }
1166 
1167 void NullCheckEliminator::handle_ProfileACmpTypes(ProfileACmpTypes* x) {
1168   x->set_left_maybe_null(!set_contains(x->left()));
1169   x->set_right_maybe_null(!set_contains(x->right()));
1170 }
1171 
1172 void Optimizer::eliminate_null_checks() {
1173   ResourceMark rm;
1174 
1175   NullCheckEliminator nce(this);
1176 
1177   if (PrintNullCheckElimination) {
1178     tty->print_cr("Starting null check elimination for method %s::%s%s",
1179                   ir()->method()->holder()->name()->as_utf8(),
1180                   ir()->method()->name()->as_utf8(),
1181                   ir()->method()->signature()->as_symbol()->as_utf8());
1182   }
1183 
1184   // Apply to graph
1185   nce.iterate(ir()->start());
1186 
1187   // walk over the graph looking for exception
1188   // handlers and iterate over them as well
1189   int nblocks = BlockBegin::number_of_blocks();
1190   BlockList blocks(nblocks);
1191   boolArray visited_block(nblocks, nblocks, false);
1192 
1193   blocks.push(ir()->start());
1194   visited_block.at_put(ir()->start()->block_id(), true);
1195   for (int i = 0; i < blocks.length(); i++) {
1196     BlockBegin* b = blocks.at(i);
1197     // exception handlers need to be treated as additional roots
1198     for (int e = b->number_of_exception_handlers(); e-- > 0; ) {
1199       BlockBegin* excp = b->exception_handler_at(e);
1200       int id = excp->block_id();
1201       if (!visited_block.at(id)) {
1202         blocks.push(excp);
1203         visited_block.at_put(id, true);
1204         nce.iterate(excp);
1205       }
1206     }
1207     // traverse successors
1208     BlockEnd *end = b->end();
1209     for (int s = end->number_of_sux(); s-- > 0; ) {
1210       BlockBegin* next = end->sux_at(s);
1211       int id = next->block_id();
1212       if (!visited_block.at(id)) {
1213         blocks.push(next);
1214         visited_block.at_put(id, true);
1215       }
1216     }
1217   }
1218 
1219 
1220   if (PrintNullCheckElimination) {
1221     tty->print_cr("Done with null check elimination for method %s::%s%s",
1222                   ir()->method()->holder()->name()->as_utf8(),
1223                   ir()->method()->name()->as_utf8(),
1224                   ir()->method()->signature()->as_symbol()->as_utf8());
1225   }
1226 }
--- EOF ---