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