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