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