src/share/vm/c1/c1_Optimizer.cpp

Wed, 02 Feb 2011 11:35:26 -0500

author
bobv
date
Wed, 02 Feb 2011 11:35:26 -0500
changeset 2508
b92c45f2bc75
parent 2486
403dc4c1d7f5
child 2728
13bc79b5c9c8
permissions
-rw-r--r--

7016023: Enable building ARM and PPC from src/closed repository
Reviewed-by: dholmes, bdelsart

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

mercurial