ciTypeFlow.cpp revision 0:a61af66fc99e
1/*
2 * Copyright 2000-2007 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/_ciTypeFlow.cpp.incl"
27
28// ciTypeFlow::JsrSet
29//
30// A JsrSet represents some set of JsrRecords.  This class
31// is used to record a set of all jsr routines which we permit
32// execution to return (ret) from.
33//
34// During abstract interpretation, JsrSets are used to determine
35// whether two paths which reach a given block are unique, and
36// should be cloned apart, or are compatible, and should merge
37// together.
38
39// ------------------------------------------------------------------
40// ciTypeFlow::JsrSet::JsrSet
41ciTypeFlow::JsrSet::JsrSet(Arena* arena, int default_len) {
42  if (arena != NULL) {
43    // Allocate growable array in Arena.
44    _set = new (arena) GrowableArray<JsrRecord*>(arena, default_len, 0, NULL);
45  } else {
46    // Allocate growable array in current ResourceArea.
47    _set = new GrowableArray<JsrRecord*>(4, 0, NULL, false);
48  }
49}
50
51// ------------------------------------------------------------------
52// ciTypeFlow::JsrSet::copy_into
53void ciTypeFlow::JsrSet::copy_into(JsrSet* jsrs) {
54  int len = size();
55  jsrs->_set->clear();
56  for (int i = 0; i < len; i++) {
57    jsrs->_set->append(_set->at(i));
58  }
59}
60
61// ------------------------------------------------------------------
62// ciTypeFlow::JsrSet::is_compatible_with
63//
64// !!!! MISGIVINGS ABOUT THIS... disregard
65//
66// Is this JsrSet compatible with some other JsrSet?
67//
68// In set-theoretic terms, a JsrSet can be viewed as a partial function
69// from entry addresses to return addresses.  Two JsrSets A and B are
70// compatible iff
71//
72//   For any x,
73//   A(x) defined and B(x) defined implies A(x) == B(x)
74//
75// Less formally, two JsrSets are compatible when they have identical
76// return addresses for any entry addresses they share in common.
77bool ciTypeFlow::JsrSet::is_compatible_with(JsrSet* other) {
78  // Walk through both sets in parallel.  If the same entry address
79  // appears in both sets, then the return address must match for
80  // the sets to be compatible.
81  int size1 = size();
82  int size2 = other->size();
83
84  // Special case.  If nothing is on the jsr stack, then there can
85  // be no ret.
86  if (size2 == 0) {
87    return true;
88  } else if (size1 != size2) {
89    return false;
90  } else {
91    for (int i = 0; i < size1; i++) {
92      JsrRecord* record1 = record_at(i);
93      JsrRecord* record2 = other->record_at(i);
94      if (record1->entry_address() != record2->entry_address() ||
95          record1->return_address() != record2->return_address()) {
96        return false;
97      }
98    }
99    return true;
100  }
101
102#if 0
103  int pos1 = 0;
104  int pos2 = 0;
105  int size1 = size();
106  int size2 = other->size();
107  while (pos1 < size1 && pos2 < size2) {
108    JsrRecord* record1 = record_at(pos1);
109    JsrRecord* record2 = other->record_at(pos2);
110    int entry1 = record1->entry_address();
111    int entry2 = record2->entry_address();
112    if (entry1 < entry2) {
113      pos1++;
114    } else if (entry1 > entry2) {
115      pos2++;
116    } else {
117      if (record1->return_address() == record2->return_address()) {
118        pos1++;
119        pos2++;
120      } else {
121        // These two JsrSets are incompatible.
122        return false;
123      }
124    }
125  }
126  // The two JsrSets agree.
127  return true;
128#endif
129}
130
131// ------------------------------------------------------------------
132// ciTypeFlow::JsrSet::insert_jsr_record
133//
134// Insert the given JsrRecord into the JsrSet, maintaining the order
135// of the set and replacing any element with the same entry address.
136void ciTypeFlow::JsrSet::insert_jsr_record(JsrRecord* record) {
137  int len = size();
138  int entry = record->entry_address();
139  int pos = 0;
140  for ( ; pos < len; pos++) {
141    JsrRecord* current = record_at(pos);
142    if (entry == current->entry_address()) {
143      // Stomp over this entry.
144      _set->at_put(pos, record);
145      assert(size() == len, "must be same size");
146      return;
147    } else if (entry < current->entry_address()) {
148      break;
149    }
150  }
151
152  // Insert the record into the list.
153  JsrRecord* swap = record;
154  JsrRecord* temp = NULL;
155  for ( ; pos < len; pos++) {
156    temp = _set->at(pos);
157    _set->at_put(pos, swap);
158    swap = temp;
159  }
160  _set->append(swap);
161  assert(size() == len+1, "must be larger");
162}
163
164// ------------------------------------------------------------------
165// ciTypeFlow::JsrSet::remove_jsr_record
166//
167// Remove the JsrRecord with the given return address from the JsrSet.
168void ciTypeFlow::JsrSet::remove_jsr_record(int return_address) {
169  int len = size();
170  for (int i = 0; i < len; i++) {
171    if (record_at(i)->return_address() == return_address) {
172      // We have found the proper entry.  Remove it from the
173      // JsrSet and exit.
174      for (int j = i+1; j < len ; j++) {
175        _set->at_put(j-1, _set->at(j));
176      }
177      _set->trunc_to(len-1);
178      assert(size() == len-1, "must be smaller");
179      return;
180    }
181  }
182  assert(false, "verify: returning from invalid subroutine");
183}
184
185// ------------------------------------------------------------------
186// ciTypeFlow::JsrSet::apply_control
187//
188// Apply the effect of a control-flow bytecode on the JsrSet.  The
189// only bytecodes that modify the JsrSet are jsr and ret.
190void ciTypeFlow::JsrSet::apply_control(ciTypeFlow* analyzer,
191                                       ciBytecodeStream* str,
192                                       ciTypeFlow::StateVector* state) {
193  Bytecodes::Code code = str->cur_bc();
194  if (code == Bytecodes::_jsr) {
195    JsrRecord* record =
196      analyzer->make_jsr_record(str->get_dest(), str->next_bci());
197    insert_jsr_record(record);
198  } else if (code == Bytecodes::_jsr_w) {
199    JsrRecord* record =
200      analyzer->make_jsr_record(str->get_far_dest(), str->next_bci());
201    insert_jsr_record(record);
202  } else if (code == Bytecodes::_ret) {
203    Cell local = state->local(str->get_index());
204    ciType* return_address = state->type_at(local);
205    assert(return_address->is_return_address(), "verify: wrong type");
206    if (size() == 0) {
207      // Ret-state underflow:  Hit a ret w/o any previous jsrs.  Bail out.
208      // This can happen when a loop is inside a finally clause (4614060).
209      analyzer->record_failure("OSR in finally clause");
210      return;
211    }
212    remove_jsr_record(return_address->as_return_address()->bci());
213  }
214}
215
216#ifndef PRODUCT
217// ------------------------------------------------------------------
218// ciTypeFlow::JsrSet::print_on
219void ciTypeFlow::JsrSet::print_on(outputStream* st) const {
220  st->print("{ ");
221  int num_elements = size();
222  if (num_elements > 0) {
223    int i = 0;
224    for( ; i < num_elements - 1; i++) {
225      _set->at(i)->print_on(st);
226      st->print(", ");
227    }
228    _set->at(i)->print_on(st);
229    st->print(" ");
230  }
231  st->print("}");
232}
233#endif
234
235// ciTypeFlow::StateVector
236//
237// A StateVector summarizes the type information at some point in
238// the program.
239
240// ------------------------------------------------------------------
241// ciTypeFlow::StateVector::type_meet
242//
243// Meet two types.
244//
245// The semi-lattice of types use by this analysis are modeled on those
246// of the verifier.  The lattice is as follows:
247//
248//        top_type() >= all non-extremal types >= bottom_type
249//                             and
250//   Every primitive type is comparable only with itself.  The meet of
251//   reference types is determined by their kind: instance class,
252//   interface, or array class.  The meet of two types of the same
253//   kind is their least common ancestor.  The meet of two types of
254//   different kinds is always java.lang.Object.
255ciType* ciTypeFlow::StateVector::type_meet_internal(ciType* t1, ciType* t2, ciTypeFlow* analyzer) {
256  assert(t1 != t2, "checked in caller");
257  if (t1->equals(top_type())) {
258    return t2;
259  } else if (t2->equals(top_type())) {
260    return t1;
261  } else if (t1->is_primitive_type() || t2->is_primitive_type()) {
262    // Special case null_type.  null_type meet any reference type T
263    // is T.  null_type meet null_type is null_type.
264    if (t1->equals(null_type())) {
265      if (!t2->is_primitive_type() || t2->equals(null_type())) {
266        return t2;
267      }
268    } else if (t2->equals(null_type())) {
269      if (!t1->is_primitive_type()) {
270        return t1;
271      }
272    }
273
274    // At least one of the two types is a non-top primitive type.
275    // The other type is not equal to it.  Fall to bottom.
276    return bottom_type();
277  } else {
278    // Both types are non-top non-primitive types.  That is,
279    // both types are either instanceKlasses or arrayKlasses.
280    ciKlass* object_klass = analyzer->env()->Object_klass();
281    ciKlass* k1 = t1->as_klass();
282    ciKlass* k2 = t2->as_klass();
283    if (k1->equals(object_klass) || k2->equals(object_klass)) {
284      return object_klass;
285    } else if (!k1->is_loaded() || !k2->is_loaded()) {
286      // Unloaded classes fall to java.lang.Object at a merge.
287      return object_klass;
288    } else if (k1->is_interface() != k2->is_interface()) {
289      // When an interface meets a non-interface, we get Object;
290      // This is what the verifier does.
291      return object_klass;
292    } else if (k1->is_array_klass() || k2->is_array_klass()) {
293      // When an array meets a non-array, we get Object.
294      // When objArray meets typeArray, we also get Object.
295      // And when typeArray meets different typeArray, we again get Object.
296      // But when objArray meets objArray, we look carefully at element types.
297      if (k1->is_obj_array_klass() && k2->is_obj_array_klass()) {
298        // Meet the element types, then construct the corresponding array type.
299        ciKlass* elem1 = k1->as_obj_array_klass()->element_klass();
300        ciKlass* elem2 = k2->as_obj_array_klass()->element_klass();
301        ciKlass* elem  = type_meet_internal(elem1, elem2, analyzer)->as_klass();
302        // Do an easy shortcut if one type is a super of the other.
303        if (elem == elem1) {
304          assert(k1 == ciObjArrayKlass::make(elem), "shortcut is OK");
305          return k1;
306        } else if (elem == elem2) {
307          assert(k2 == ciObjArrayKlass::make(elem), "shortcut is OK");
308          return k2;
309        } else {
310          return ciObjArrayKlass::make(elem);
311        }
312      } else {
313        return object_klass;
314      }
315    } else {
316      // Must be two plain old instance klasses.
317      assert(k1->is_instance_klass(), "previous cases handle non-instances");
318      assert(k2->is_instance_klass(), "previous cases handle non-instances");
319      return k1->least_common_ancestor(k2);
320    }
321  }
322}
323
324
325// ------------------------------------------------------------------
326// ciTypeFlow::StateVector::StateVector
327//
328// Build a new state vector
329ciTypeFlow::StateVector::StateVector(ciTypeFlow* analyzer) {
330  _outer = analyzer;
331  _stack_size = -1;
332  _monitor_count = -1;
333  // Allocate the _types array
334  int max_cells = analyzer->max_cells();
335  _types = (ciType**)analyzer->arena()->Amalloc(sizeof(ciType*) * max_cells);
336  for (int i=0; i<max_cells; i++) {
337    _types[i] = top_type();
338  }
339  _trap_bci = -1;
340  _trap_index = 0;
341}
342
343// ------------------------------------------------------------------
344// ciTypeFlow::get_start_state
345//
346// Set this vector to the method entry state.
347const ciTypeFlow::StateVector* ciTypeFlow::get_start_state() {
348  StateVector* state = new StateVector(this);
349  if (is_osr_flow()) {
350    ciTypeFlow* non_osr_flow = method()->get_flow_analysis();
351    if (non_osr_flow->failing()) {
352      record_failure(non_osr_flow->failure_reason());
353      return NULL;
354    }
355    JsrSet* jsrs = new JsrSet(NULL, 16);
356    Block* non_osr_block = non_osr_flow->existing_block_at(start_bci(), jsrs);
357    if (non_osr_block == NULL) {
358      record_failure("cannot reach OSR point");
359      return NULL;
360    }
361    // load up the non-OSR state at this point
362    non_osr_block->copy_state_into(state);
363    int non_osr_start = non_osr_block->start();
364    if (non_osr_start != start_bci()) {
365      // must flow forward from it
366      if (CITraceTypeFlow) {
367        tty->print_cr(">> Interpreting pre-OSR block %d:", non_osr_start);
368      }
369      Block* block = block_at(non_osr_start, jsrs);
370      assert(block->limit() == start_bci(), "must flow forward to start");
371      flow_block(block, state, jsrs);
372    }
373    return state;
374    // Note:  The code below would be an incorrect for an OSR flow,
375    // even if it were possible for an OSR entry point to be at bci zero.
376  }
377  // "Push" the method signature into the first few locals.
378  state->set_stack_size(-max_locals());
379  if (!method()->is_static()) {
380    state->push(method()->holder());
381    assert(state->tos() == state->local(0), "");
382  }
383  for (ciSignatureStream str(method()->signature());
384       !str.at_return_type();
385       str.next()) {
386    state->push_translate(str.type());
387  }
388  // Set the rest of the locals to bottom.
389  Cell cell = state->next_cell(state->tos());
390  state->set_stack_size(0);
391  int limit = state->limit_cell();
392  for (; cell < limit; cell = state->next_cell(cell)) {
393    state->set_type_at(cell, state->bottom_type());
394  }
395  // Lock an object, if necessary.
396  state->set_monitor_count(method()->is_synchronized() ? 1 : 0);
397  return state;
398}
399
400// ------------------------------------------------------------------
401// ciTypeFlow::StateVector::copy_into
402//
403// Copy our value into some other StateVector
404void ciTypeFlow::StateVector::copy_into(ciTypeFlow::StateVector* copy)
405const {
406  copy->set_stack_size(stack_size());
407  copy->set_monitor_count(monitor_count());
408  Cell limit = limit_cell();
409  for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
410    copy->set_type_at(c, type_at(c));
411  }
412}
413
414// ------------------------------------------------------------------
415// ciTypeFlow::StateVector::meet
416//
417// Meets this StateVector with another, destructively modifying this
418// one.  Returns true if any modification takes place.
419bool ciTypeFlow::StateVector::meet(const ciTypeFlow::StateVector* incoming) {
420  if (monitor_count() == -1) {
421    set_monitor_count(incoming->monitor_count());
422  }
423  assert(monitor_count() == incoming->monitor_count(), "monitors must match");
424
425  if (stack_size() == -1) {
426    set_stack_size(incoming->stack_size());
427    Cell limit = limit_cell();
428    #ifdef ASSERT
429    { for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
430        assert(type_at(c) == top_type(), "");
431    } }
432    #endif
433    // Make a simple copy of the incoming state.
434    for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
435      set_type_at(c, incoming->type_at(c));
436    }
437    return true;  // it is always different the first time
438  }
439#ifdef ASSERT
440  if (stack_size() != incoming->stack_size()) {
441    _outer->method()->print_codes();
442    tty->print_cr("!!!! Stack size conflict");
443    tty->print_cr("Current state:");
444    print_on(tty);
445    tty->print_cr("Incoming state:");
446    ((StateVector*)incoming)->print_on(tty);
447  }
448#endif
449  assert(stack_size() == incoming->stack_size(), "sanity");
450
451  bool different = false;
452  Cell limit = limit_cell();
453  for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
454    ciType* t1 = type_at(c);
455    ciType* t2 = incoming->type_at(c);
456    if (!t1->equals(t2)) {
457      ciType* new_type = type_meet(t1, t2);
458      if (!t1->equals(new_type)) {
459        set_type_at(c, new_type);
460        different = true;
461      }
462    }
463  }
464  return different;
465}
466
467// ------------------------------------------------------------------
468// ciTypeFlow::StateVector::meet_exception
469//
470// Meets this StateVector with another, destructively modifying this
471// one.  The incoming state is coming via an exception.  Returns true
472// if any modification takes place.
473bool ciTypeFlow::StateVector::meet_exception(ciInstanceKlass* exc,
474                                     const ciTypeFlow::StateVector* incoming) {
475  if (monitor_count() == -1) {
476    set_monitor_count(incoming->monitor_count());
477  }
478  assert(monitor_count() == incoming->monitor_count(), "monitors must match");
479
480  if (stack_size() == -1) {
481    set_stack_size(1);
482  }
483
484  assert(stack_size() ==  1, "must have one-element stack");
485
486  bool different = false;
487
488  // Meet locals from incoming array.
489  Cell limit = local(_outer->max_locals()-1);
490  for (Cell c = start_cell(); c <= limit; c = next_cell(c)) {
491    ciType* t1 = type_at(c);
492    ciType* t2 = incoming->type_at(c);
493    if (!t1->equals(t2)) {
494      ciType* new_type = type_meet(t1, t2);
495      if (!t1->equals(new_type)) {
496        set_type_at(c, new_type);
497        different = true;
498      }
499    }
500  }
501
502  // Handle stack separately.  When an exception occurs, the
503  // only stack entry is the exception instance.
504  ciType* tos_type = type_at_tos();
505  if (!tos_type->equals(exc)) {
506    ciType* new_type = type_meet(tos_type, exc);
507    if (!tos_type->equals(new_type)) {
508      set_type_at_tos(new_type);
509      different = true;
510    }
511  }
512
513  return different;
514}
515
516// ------------------------------------------------------------------
517// ciTypeFlow::StateVector::push_translate
518void ciTypeFlow::StateVector::push_translate(ciType* type) {
519  BasicType basic_type = type->basic_type();
520  if (basic_type == T_BOOLEAN || basic_type == T_CHAR ||
521      basic_type == T_BYTE    || basic_type == T_SHORT) {
522    push_int();
523  } else {
524    push(type);
525    if (type->is_two_word()) {
526      push(half_type(type));
527    }
528  }
529}
530
531// ------------------------------------------------------------------
532// ciTypeFlow::StateVector::do_aaload
533void ciTypeFlow::StateVector::do_aaload(ciBytecodeStream* str) {
534  pop_int();
535  ciObjArrayKlass* array_klass = pop_objArray();
536  if (array_klass == NULL) {
537    // Did aaload on a null reference; push a null and ignore the exception.
538    // This instruction will never continue normally.  All we have to do
539    // is report a value that will meet correctly with any downstream
540    // reference types on paths that will truly be executed.  This null type
541    // meets with any reference type to yield that same reference type.
542    // (The compiler will generate an unconditonal exception here.)
543    push(null_type());
544    return;
545  }
546  if (!array_klass->is_loaded()) {
547    // Only fails for some -Xcomp runs
548    trap(str, array_klass,
549         Deoptimization::make_trap_request
550         (Deoptimization::Reason_unloaded,
551          Deoptimization::Action_reinterpret));
552    return;
553  }
554  ciKlass* element_klass = array_klass->element_klass();
555  if (!element_klass->is_loaded() && element_klass->is_instance_klass()) {
556    Untested("unloaded array element class in ciTypeFlow");
557    trap(str, element_klass,
558         Deoptimization::make_trap_request
559         (Deoptimization::Reason_unloaded,
560          Deoptimization::Action_reinterpret));
561  } else {
562    push_object(element_klass);
563  }
564}
565
566
567// ------------------------------------------------------------------
568// ciTypeFlow::StateVector::do_checkcast
569void ciTypeFlow::StateVector::do_checkcast(ciBytecodeStream* str) {
570  bool will_link;
571  ciKlass* klass = str->get_klass(will_link);
572  if (!will_link) {
573    // VM's interpreter will not load 'klass' if object is NULL.
574    // Type flow after this block may still be needed in two situations:
575    // 1) C2 uses do_null_assert() and continues compilation for later blocks
576    // 2) C2 does an OSR compile in a later block (see bug 4778368).
577    pop_object();
578    do_null_assert(klass);
579  } else {
580    pop_object();
581    push_object(klass);
582  }
583}
584
585// ------------------------------------------------------------------
586// ciTypeFlow::StateVector::do_getfield
587void ciTypeFlow::StateVector::do_getfield(ciBytecodeStream* str) {
588  // could add assert here for type of object.
589  pop_object();
590  do_getstatic(str);
591}
592
593// ------------------------------------------------------------------
594// ciTypeFlow::StateVector::do_getstatic
595void ciTypeFlow::StateVector::do_getstatic(ciBytecodeStream* str) {
596  bool will_link;
597  ciField* field = str->get_field(will_link);
598  if (!will_link) {
599    trap(str, field->holder(), str->get_field_holder_index());
600  } else {
601    ciType* field_type = field->type();
602    if (!field_type->is_loaded()) {
603      // Normally, we need the field's type to be loaded if we are to
604      // do anything interesting with its value.
605      // We used to do this:  trap(str, str->get_field_signature_index());
606      //
607      // There is one good reason not to trap here.  Execution can
608      // get past this "getfield" or "getstatic" if the value of
609      // the field is null.  As long as the value is null, the class
610      // does not need to be loaded!  The compiler must assume that
611      // the value of the unloaded class reference is null; if the code
612      // ever sees a non-null value, loading has occurred.
613      //
614      // This actually happens often enough to be annoying.  If the
615      // compiler throws an uncommon trap at this bytecode, you can
616      // get an endless loop of recompilations, when all the code
617      // needs to do is load a series of null values.  Also, a trap
618      // here can make an OSR entry point unreachable, triggering the
619      // assert on non_osr_block in ciTypeFlow::get_start_state.
620      // (See bug 4379915.)
621      do_null_assert(field_type->as_klass());
622    } else {
623      push_translate(field_type);
624    }
625  }
626}
627
628// ------------------------------------------------------------------
629// ciTypeFlow::StateVector::do_invoke
630void ciTypeFlow::StateVector::do_invoke(ciBytecodeStream* str,
631                                        bool has_receiver) {
632  bool will_link;
633  ciMethod* method = str->get_method(will_link);
634  if (!will_link) {
635    // We weren't able to find the method.
636    ciKlass* unloaded_holder = method->holder();
637    trap(str, unloaded_holder, str->get_method_holder_index());
638  } else {
639    ciSignature* signature = method->signature();
640    ciSignatureStream sigstr(signature);
641    int arg_size = signature->size();
642    int stack_base = stack_size() - arg_size;
643    int i = 0;
644    for( ; !sigstr.at_return_type(); sigstr.next()) {
645      ciType* type = sigstr.type();
646      ciType* stack_type = type_at(stack(stack_base + i++));
647      // Do I want to check this type?
648      // assert(stack_type->is_subtype_of(type), "bad type for field value");
649      if (type->is_two_word()) {
650        ciType* stack_type2 = type_at(stack(stack_base + i++));
651        assert(stack_type2->equals(half_type(type)), "must be 2nd half");
652      }
653    }
654    assert(arg_size == i, "must match");
655    for (int j = 0; j < arg_size; j++) {
656      pop();
657    }
658    if (has_receiver) {
659      // Check this?
660      pop_object();
661    }
662    assert(!sigstr.is_done(), "must have return type");
663    ciType* return_type = sigstr.type();
664    if (!return_type->is_void()) {
665      if (!return_type->is_loaded()) {
666        // As in do_getstatic(), generally speaking, we need the return type to
667        // be loaded if we are to do anything interesting with its value.
668        // We used to do this:  trap(str, str->get_method_signature_index());
669        //
670        // We do not trap here since execution can get past this invoke if
671        // the return value is null.  As long as the value is null, the class
672        // does not need to be loaded!  The compiler must assume that
673        // the value of the unloaded class reference is null; if the code
674        // ever sees a non-null value, loading has occurred.
675        //
676        // See do_getstatic() for similar explanation, as well as bug 4684993.
677        do_null_assert(return_type->as_klass());
678      } else {
679        push_translate(return_type);
680      }
681    }
682  }
683}
684
685// ------------------------------------------------------------------
686// ciTypeFlow::StateVector::do_jsr
687void ciTypeFlow::StateVector::do_jsr(ciBytecodeStream* str) {
688  push(ciReturnAddress::make(str->next_bci()));
689}
690
691// ------------------------------------------------------------------
692// ciTypeFlow::StateVector::do_ldc
693void ciTypeFlow::StateVector::do_ldc(ciBytecodeStream* str) {
694  ciConstant con = str->get_constant();
695  BasicType basic_type = con.basic_type();
696  if (basic_type == T_ILLEGAL) {
697    // OutOfMemoryError in the CI while loading constant
698    push_null();
699    outer()->record_failure("ldc did not link");
700    return;
701  }
702  if (basic_type == T_OBJECT || basic_type == T_ARRAY) {
703    ciObject* obj = con.as_object();
704    if (obj->is_null_object()) {
705      push_null();
706    } else if (obj->is_klass()) {
707      // The type of ldc <class> is java.lang.Class
708      push_object(outer()->env()->Class_klass());
709    } else {
710      push_object(obj->klass());
711    }
712  } else {
713    push_translate(ciType::make(basic_type));
714  }
715}
716
717// ------------------------------------------------------------------
718// ciTypeFlow::StateVector::do_multianewarray
719void ciTypeFlow::StateVector::do_multianewarray(ciBytecodeStream* str) {
720  int dimensions = str->get_dimensions();
721  bool will_link;
722  ciArrayKlass* array_klass = str->get_klass(will_link)->as_array_klass();
723  if (!will_link) {
724    trap(str, array_klass, str->get_klass_index());
725  } else {
726    for (int i = 0; i < dimensions; i++) {
727      pop_int();
728    }
729    push_object(array_klass);
730  }
731}
732
733// ------------------------------------------------------------------
734// ciTypeFlow::StateVector::do_new
735void ciTypeFlow::StateVector::do_new(ciBytecodeStream* str) {
736  bool will_link;
737  ciKlass* klass = str->get_klass(will_link);
738  if (!will_link) {
739    trap(str, klass, str->get_klass_index());
740  } else {
741    push_object(klass);
742  }
743}
744
745// ------------------------------------------------------------------
746// ciTypeFlow::StateVector::do_newarray
747void ciTypeFlow::StateVector::do_newarray(ciBytecodeStream* str) {
748  pop_int();
749  ciKlass* klass = ciTypeArrayKlass::make((BasicType)str->get_index());
750  push_object(klass);
751}
752
753// ------------------------------------------------------------------
754// ciTypeFlow::StateVector::do_putfield
755void ciTypeFlow::StateVector::do_putfield(ciBytecodeStream* str) {
756  do_putstatic(str);
757  if (_trap_bci != -1)  return;  // unloaded field holder, etc.
758  // could add assert here for type of object.
759  pop_object();
760}
761
762// ------------------------------------------------------------------
763// ciTypeFlow::StateVector::do_putstatic
764void ciTypeFlow::StateVector::do_putstatic(ciBytecodeStream* str) {
765  bool will_link;
766  ciField* field = str->get_field(will_link);
767  if (!will_link) {
768    trap(str, field->holder(), str->get_field_holder_index());
769  } else {
770    ciType* field_type = field->type();
771    ciType* type = pop_value();
772    // Do I want to check this type?
773    //      assert(type->is_subtype_of(field_type), "bad type for field value");
774    if (field_type->is_two_word()) {
775      ciType* type2 = pop_value();
776      assert(type2->is_two_word(), "must be 2nd half");
777      assert(type == half_type(type2), "must be 2nd half");
778    }
779  }
780}
781
782// ------------------------------------------------------------------
783// ciTypeFlow::StateVector::do_ret
784void ciTypeFlow::StateVector::do_ret(ciBytecodeStream* str) {
785  Cell index = local(str->get_index());
786
787  ciType* address = type_at(index);
788  assert(address->is_return_address(), "bad return address");
789  set_type_at(index, bottom_type());
790}
791
792// ------------------------------------------------------------------
793// ciTypeFlow::StateVector::trap
794//
795// Stop interpretation of this path with a trap.
796void ciTypeFlow::StateVector::trap(ciBytecodeStream* str, ciKlass* klass, int index) {
797  _trap_bci = str->cur_bci();
798  _trap_index = index;
799
800  // Log information about this trap:
801  CompileLog* log = outer()->env()->log();
802  if (log != NULL) {
803    int mid = log->identify(outer()->method());
804    int kid = (klass == NULL)? -1: log->identify(klass);
805    log->begin_elem("uncommon_trap method='%d' bci='%d'", mid, str->cur_bci());
806    char buf[100];
807    log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
808                                                          index));
809    if (kid >= 0)
810      log->print(" klass='%d'", kid);
811    log->end_elem();
812  }
813}
814
815// ------------------------------------------------------------------
816// ciTypeFlow::StateVector::do_null_assert
817// Corresponds to graphKit::do_null_assert.
818void ciTypeFlow::StateVector::do_null_assert(ciKlass* unloaded_klass) {
819  if (unloaded_klass->is_loaded()) {
820    // We failed to link, but we can still compute with this class,
821    // since it is loaded somewhere.  The compiler will uncommon_trap
822    // if the object is not null, but the typeflow pass can not assume
823    // that the object will be null, otherwise it may incorrectly tell
824    // the parser that an object is known to be null. 4761344, 4807707
825    push_object(unloaded_klass);
826  } else {
827    // The class is not loaded anywhere.  It is safe to model the
828    // null in the typestates, because we can compile in a null check
829    // which will deoptimize us if someone manages to load the
830    // class later.
831    push_null();
832  }
833}
834
835
836// ------------------------------------------------------------------
837// ciTypeFlow::StateVector::apply_one_bytecode
838//
839// Apply the effect of one bytecode to this StateVector
840bool ciTypeFlow::StateVector::apply_one_bytecode(ciBytecodeStream* str) {
841  _trap_bci = -1;
842  _trap_index = 0;
843
844  if (CITraceTypeFlow) {
845    tty->print_cr(">> Interpreting bytecode %d:%s", str->cur_bci(),
846                  Bytecodes::name(str->cur_bc()));
847  }
848
849  switch(str->cur_bc()) {
850  case Bytecodes::_aaload: do_aaload(str);                       break;
851
852  case Bytecodes::_aastore:
853    {
854      pop_object();
855      pop_int();
856      pop_objArray();
857      break;
858    }
859  case Bytecodes::_aconst_null:
860    {
861      push_null();
862      break;
863    }
864  case Bytecodes::_aload:   load_local_object(str->get_index());    break;
865  case Bytecodes::_aload_0: load_local_object(0);                   break;
866  case Bytecodes::_aload_1: load_local_object(1);                   break;
867  case Bytecodes::_aload_2: load_local_object(2);                   break;
868  case Bytecodes::_aload_3: load_local_object(3);                   break;
869
870  case Bytecodes::_anewarray:
871    {
872      pop_int();
873      bool will_link;
874      ciKlass* element_klass = str->get_klass(will_link);
875      if (!will_link) {
876        trap(str, element_klass, str->get_klass_index());
877      } else {
878        push_object(ciObjArrayKlass::make(element_klass));
879      }
880      break;
881    }
882  case Bytecodes::_areturn:
883  case Bytecodes::_ifnonnull:
884  case Bytecodes::_ifnull:
885    {
886      pop_object();
887      break;
888    }
889  case Bytecodes::_monitorenter:
890    {
891      pop_object();
892      set_monitor_count(monitor_count() + 1);
893      break;
894    }
895  case Bytecodes::_monitorexit:
896    {
897      pop_object();
898      assert(monitor_count() > 0, "must be a monitor to exit from");
899      set_monitor_count(monitor_count() - 1);
900      break;
901    }
902  case Bytecodes::_arraylength:
903    {
904      pop_array();
905      push_int();
906      break;
907    }
908  case Bytecodes::_astore:   store_local_object(str->get_index());  break;
909  case Bytecodes::_astore_0: store_local_object(0);                 break;
910  case Bytecodes::_astore_1: store_local_object(1);                 break;
911  case Bytecodes::_astore_2: store_local_object(2);                 break;
912  case Bytecodes::_astore_3: store_local_object(3);                 break;
913
914  case Bytecodes::_athrow:
915    {
916      NEEDS_CLEANUP;
917      pop_object();
918      break;
919    }
920  case Bytecodes::_baload:
921  case Bytecodes::_caload:
922  case Bytecodes::_iaload:
923  case Bytecodes::_saload:
924    {
925      pop_int();
926      ciTypeArrayKlass* array_klass = pop_typeArray();
927      // Put assert here for right type?
928      push_int();
929      break;
930    }
931  case Bytecodes::_bastore:
932  case Bytecodes::_castore:
933  case Bytecodes::_iastore:
934  case Bytecodes::_sastore:
935    {
936      pop_int();
937      pop_int();
938      pop_typeArray();
939      // assert here?
940      break;
941    }
942  case Bytecodes::_bipush:
943  case Bytecodes::_iconst_m1:
944  case Bytecodes::_iconst_0:
945  case Bytecodes::_iconst_1:
946  case Bytecodes::_iconst_2:
947  case Bytecodes::_iconst_3:
948  case Bytecodes::_iconst_4:
949  case Bytecodes::_iconst_5:
950  case Bytecodes::_sipush:
951    {
952      push_int();
953      break;
954    }
955  case Bytecodes::_checkcast: do_checkcast(str);                  break;
956
957  case Bytecodes::_d2f:
958    {
959      pop_double();
960      push_float();
961      break;
962    }
963  case Bytecodes::_d2i:
964    {
965      pop_double();
966      push_int();
967      break;
968    }
969  case Bytecodes::_d2l:
970    {
971      pop_double();
972      push_long();
973      break;
974    }
975  case Bytecodes::_dadd:
976  case Bytecodes::_ddiv:
977  case Bytecodes::_dmul:
978  case Bytecodes::_drem:
979  case Bytecodes::_dsub:
980    {
981      pop_double();
982      pop_double();
983      push_double();
984      break;
985    }
986  case Bytecodes::_daload:
987    {
988      pop_int();
989      ciTypeArrayKlass* array_klass = pop_typeArray();
990      // Put assert here for right type?
991      push_double();
992      break;
993    }
994  case Bytecodes::_dastore:
995    {
996      pop_double();
997      pop_int();
998      pop_typeArray();
999      // assert here?
1000      break;
1001    }
1002  case Bytecodes::_dcmpg:
1003  case Bytecodes::_dcmpl:
1004    {
1005      pop_double();
1006      pop_double();
1007      push_int();
1008      break;
1009    }
1010  case Bytecodes::_dconst_0:
1011  case Bytecodes::_dconst_1:
1012    {
1013      push_double();
1014      break;
1015    }
1016  case Bytecodes::_dload:   load_local_double(str->get_index());    break;
1017  case Bytecodes::_dload_0: load_local_double(0);                   break;
1018  case Bytecodes::_dload_1: load_local_double(1);                   break;
1019  case Bytecodes::_dload_2: load_local_double(2);                   break;
1020  case Bytecodes::_dload_3: load_local_double(3);                   break;
1021
1022  case Bytecodes::_dneg:
1023    {
1024      pop_double();
1025      push_double();
1026      break;
1027    }
1028  case Bytecodes::_dreturn:
1029    {
1030      pop_double();
1031      break;
1032    }
1033  case Bytecodes::_dstore:   store_local_double(str->get_index());  break;
1034  case Bytecodes::_dstore_0: store_local_double(0);                 break;
1035  case Bytecodes::_dstore_1: store_local_double(1);                 break;
1036  case Bytecodes::_dstore_2: store_local_double(2);                 break;
1037  case Bytecodes::_dstore_3: store_local_double(3);                 break;
1038
1039  case Bytecodes::_dup:
1040    {
1041      push(type_at_tos());
1042      break;
1043    }
1044  case Bytecodes::_dup_x1:
1045    {
1046      ciType* value1 = pop_value();
1047      ciType* value2 = pop_value();
1048      push(value1);
1049      push(value2);
1050      push(value1);
1051      break;
1052    }
1053  case Bytecodes::_dup_x2:
1054    {
1055      ciType* value1 = pop_value();
1056      ciType* value2 = pop_value();
1057      ciType* value3 = pop_value();
1058      push(value1);
1059      push(value3);
1060      push(value2);
1061      push(value1);
1062      break;
1063    }
1064  case Bytecodes::_dup2:
1065    {
1066      ciType* value1 = pop_value();
1067      ciType* value2 = pop_value();
1068      push(value2);
1069      push(value1);
1070      push(value2);
1071      push(value1);
1072      break;
1073    }
1074  case Bytecodes::_dup2_x1:
1075    {
1076      ciType* value1 = pop_value();
1077      ciType* value2 = pop_value();
1078      ciType* value3 = pop_value();
1079      push(value2);
1080      push(value1);
1081      push(value3);
1082      push(value2);
1083      push(value1);
1084      break;
1085    }
1086  case Bytecodes::_dup2_x2:
1087    {
1088      ciType* value1 = pop_value();
1089      ciType* value2 = pop_value();
1090      ciType* value3 = pop_value();
1091      ciType* value4 = pop_value();
1092      push(value2);
1093      push(value1);
1094      push(value4);
1095      push(value3);
1096      push(value2);
1097      push(value1);
1098      break;
1099    }
1100  case Bytecodes::_f2d:
1101    {
1102      pop_float();
1103      push_double();
1104      break;
1105    }
1106  case Bytecodes::_f2i:
1107    {
1108      pop_float();
1109      push_int();
1110      break;
1111    }
1112  case Bytecodes::_f2l:
1113    {
1114      pop_float();
1115      push_long();
1116      break;
1117    }
1118  case Bytecodes::_fadd:
1119  case Bytecodes::_fdiv:
1120  case Bytecodes::_fmul:
1121  case Bytecodes::_frem:
1122  case Bytecodes::_fsub:
1123    {
1124      pop_float();
1125      pop_float();
1126      push_float();
1127      break;
1128    }
1129  case Bytecodes::_faload:
1130    {
1131      pop_int();
1132      ciTypeArrayKlass* array_klass = pop_typeArray();
1133      // Put assert here.
1134      push_float();
1135      break;
1136    }
1137  case Bytecodes::_fastore:
1138    {
1139      pop_float();
1140      pop_int();
1141      ciTypeArrayKlass* array_klass = pop_typeArray();
1142      // Put assert here.
1143      break;
1144    }
1145  case Bytecodes::_fcmpg:
1146  case Bytecodes::_fcmpl:
1147    {
1148      pop_float();
1149      pop_float();
1150      push_int();
1151      break;
1152    }
1153  case Bytecodes::_fconst_0:
1154  case Bytecodes::_fconst_1:
1155  case Bytecodes::_fconst_2:
1156    {
1157      push_float();
1158      break;
1159    }
1160  case Bytecodes::_fload:   load_local_float(str->get_index());     break;
1161  case Bytecodes::_fload_0: load_local_float(0);                    break;
1162  case Bytecodes::_fload_1: load_local_float(1);                    break;
1163  case Bytecodes::_fload_2: load_local_float(2);                    break;
1164  case Bytecodes::_fload_3: load_local_float(3);                    break;
1165
1166  case Bytecodes::_fneg:
1167    {
1168      pop_float();
1169      push_float();
1170      break;
1171    }
1172  case Bytecodes::_freturn:
1173    {
1174      pop_float();
1175      break;
1176    }
1177  case Bytecodes::_fstore:    store_local_float(str->get_index());   break;
1178  case Bytecodes::_fstore_0:  store_local_float(0);                  break;
1179  case Bytecodes::_fstore_1:  store_local_float(1);                  break;
1180  case Bytecodes::_fstore_2:  store_local_float(2);                  break;
1181  case Bytecodes::_fstore_3:  store_local_float(3);                  break;
1182
1183  case Bytecodes::_getfield:  do_getfield(str);                      break;
1184  case Bytecodes::_getstatic: do_getstatic(str);                     break;
1185
1186  case Bytecodes::_goto:
1187  case Bytecodes::_goto_w:
1188  case Bytecodes::_nop:
1189  case Bytecodes::_return:
1190    {
1191      // do nothing.
1192      break;
1193    }
1194  case Bytecodes::_i2b:
1195  case Bytecodes::_i2c:
1196  case Bytecodes::_i2s:
1197  case Bytecodes::_ineg:
1198    {
1199      pop_int();
1200      push_int();
1201      break;
1202    }
1203  case Bytecodes::_i2d:
1204    {
1205      pop_int();
1206      push_double();
1207      break;
1208    }
1209  case Bytecodes::_i2f:
1210    {
1211      pop_int();
1212      push_float();
1213      break;
1214    }
1215  case Bytecodes::_i2l:
1216    {
1217      pop_int();
1218      push_long();
1219      break;
1220    }
1221  case Bytecodes::_iadd:
1222  case Bytecodes::_iand:
1223  case Bytecodes::_idiv:
1224  case Bytecodes::_imul:
1225  case Bytecodes::_ior:
1226  case Bytecodes::_irem:
1227  case Bytecodes::_ishl:
1228  case Bytecodes::_ishr:
1229  case Bytecodes::_isub:
1230  case Bytecodes::_iushr:
1231  case Bytecodes::_ixor:
1232    {
1233      pop_int();
1234      pop_int();
1235      push_int();
1236      break;
1237    }
1238  case Bytecodes::_if_acmpeq:
1239  case Bytecodes::_if_acmpne:
1240    {
1241      pop_object();
1242      pop_object();
1243      break;
1244    }
1245  case Bytecodes::_if_icmpeq:
1246  case Bytecodes::_if_icmpge:
1247  case Bytecodes::_if_icmpgt:
1248  case Bytecodes::_if_icmple:
1249  case Bytecodes::_if_icmplt:
1250  case Bytecodes::_if_icmpne:
1251    {
1252      pop_int();
1253      pop_int();
1254      break;
1255    }
1256  case Bytecodes::_ifeq:
1257  case Bytecodes::_ifle:
1258  case Bytecodes::_iflt:
1259  case Bytecodes::_ifge:
1260  case Bytecodes::_ifgt:
1261  case Bytecodes::_ifne:
1262  case Bytecodes::_ireturn:
1263  case Bytecodes::_lookupswitch:
1264  case Bytecodes::_tableswitch:
1265    {
1266      pop_int();
1267      break;
1268    }
1269  case Bytecodes::_iinc:
1270    {
1271      check_int(local(str->get_index()));
1272      break;
1273    }
1274  case Bytecodes::_iload:   load_local_int(str->get_index()); break;
1275  case Bytecodes::_iload_0: load_local_int(0);                      break;
1276  case Bytecodes::_iload_1: load_local_int(1);                      break;
1277  case Bytecodes::_iload_2: load_local_int(2);                      break;
1278  case Bytecodes::_iload_3: load_local_int(3);                      break;
1279
1280  case Bytecodes::_instanceof:
1281    {
1282      // Check for uncommon trap:
1283      do_checkcast(str);
1284      pop_object();
1285      push_int();
1286      break;
1287    }
1288  case Bytecodes::_invokeinterface: do_invoke(str, true);           break;
1289  case Bytecodes::_invokespecial:   do_invoke(str, true);           break;
1290  case Bytecodes::_invokestatic:    do_invoke(str, false);          break;
1291
1292  case Bytecodes::_invokevirtual:   do_invoke(str, true);           break;
1293
1294  case Bytecodes::_istore:   store_local_int(str->get_index());     break;
1295  case Bytecodes::_istore_0: store_local_int(0);                    break;
1296  case Bytecodes::_istore_1: store_local_int(1);                    break;
1297  case Bytecodes::_istore_2: store_local_int(2);                    break;
1298  case Bytecodes::_istore_3: store_local_int(3);                    break;
1299
1300  case Bytecodes::_jsr:
1301  case Bytecodes::_jsr_w: do_jsr(str);                              break;
1302
1303  case Bytecodes::_l2d:
1304    {
1305      pop_long();
1306      push_double();
1307      break;
1308    }
1309  case Bytecodes::_l2f:
1310    {
1311      pop_long();
1312      push_float();
1313      break;
1314    }
1315  case Bytecodes::_l2i:
1316    {
1317      pop_long();
1318      push_int();
1319      break;
1320    }
1321  case Bytecodes::_ladd:
1322  case Bytecodes::_land:
1323  case Bytecodes::_ldiv:
1324  case Bytecodes::_lmul:
1325  case Bytecodes::_lor:
1326  case Bytecodes::_lrem:
1327  case Bytecodes::_lsub:
1328  case Bytecodes::_lxor:
1329    {
1330      pop_long();
1331      pop_long();
1332      push_long();
1333      break;
1334    }
1335  case Bytecodes::_laload:
1336    {
1337      pop_int();
1338      ciTypeArrayKlass* array_klass = pop_typeArray();
1339      // Put assert here for right type?
1340      push_long();
1341      break;
1342    }
1343  case Bytecodes::_lastore:
1344    {
1345      pop_long();
1346      pop_int();
1347      pop_typeArray();
1348      // assert here?
1349      break;
1350    }
1351  case Bytecodes::_lcmp:
1352    {
1353      pop_long();
1354      pop_long();
1355      push_int();
1356      break;
1357    }
1358  case Bytecodes::_lconst_0:
1359  case Bytecodes::_lconst_1:
1360    {
1361      push_long();
1362      break;
1363    }
1364  case Bytecodes::_ldc:
1365  case Bytecodes::_ldc_w:
1366  case Bytecodes::_ldc2_w:
1367    {
1368      do_ldc(str);
1369      break;
1370    }
1371
1372  case Bytecodes::_lload:   load_local_long(str->get_index());      break;
1373  case Bytecodes::_lload_0: load_local_long(0);                     break;
1374  case Bytecodes::_lload_1: load_local_long(1);                     break;
1375  case Bytecodes::_lload_2: load_local_long(2);                     break;
1376  case Bytecodes::_lload_3: load_local_long(3);                     break;
1377
1378  case Bytecodes::_lneg:
1379    {
1380      pop_long();
1381      push_long();
1382      break;
1383    }
1384  case Bytecodes::_lreturn:
1385    {
1386      pop_long();
1387      break;
1388    }
1389  case Bytecodes::_lshl:
1390  case Bytecodes::_lshr:
1391  case Bytecodes::_lushr:
1392    {
1393      pop_int();
1394      pop_long();
1395      push_long();
1396      break;
1397    }
1398  case Bytecodes::_lstore:   store_local_long(str->get_index());    break;
1399  case Bytecodes::_lstore_0: store_local_long(0);                   break;
1400  case Bytecodes::_lstore_1: store_local_long(1);                   break;
1401  case Bytecodes::_lstore_2: store_local_long(2);                   break;
1402  case Bytecodes::_lstore_3: store_local_long(3);                   break;
1403
1404  case Bytecodes::_multianewarray: do_multianewarray(str);          break;
1405
1406  case Bytecodes::_new:      do_new(str);                           break;
1407
1408  case Bytecodes::_newarray: do_newarray(str);                      break;
1409
1410  case Bytecodes::_pop:
1411    {
1412      pop();
1413      break;
1414    }
1415  case Bytecodes::_pop2:
1416    {
1417      pop();
1418      pop();
1419      break;
1420    }
1421
1422  case Bytecodes::_putfield:       do_putfield(str);                 break;
1423  case Bytecodes::_putstatic:      do_putstatic(str);                break;
1424
1425  case Bytecodes::_ret: do_ret(str);                                 break;
1426
1427  case Bytecodes::_swap:
1428    {
1429      ciType* value1 = pop_value();
1430      ciType* value2 = pop_value();
1431      push(value1);
1432      push(value2);
1433      break;
1434    }
1435  case Bytecodes::_wide:
1436  default:
1437    {
1438      // The iterator should skip this.
1439      ShouldNotReachHere();
1440      break;
1441    }
1442  }
1443
1444  if (CITraceTypeFlow) {
1445    print_on(tty);
1446  }
1447
1448  return (_trap_bci != -1);
1449}
1450
1451#ifndef PRODUCT
1452// ------------------------------------------------------------------
1453// ciTypeFlow::StateVector::print_cell_on
1454void ciTypeFlow::StateVector::print_cell_on(outputStream* st, Cell c) const {
1455  ciType* type = type_at(c);
1456  if (type == top_type()) {
1457    st->print("top");
1458  } else if (type == bottom_type()) {
1459    st->print("bottom");
1460  } else if (type == null_type()) {
1461    st->print("null");
1462  } else if (type == long2_type()) {
1463    st->print("long2");
1464  } else if (type == double2_type()) {
1465    st->print("double2");
1466  } else if (is_int(type)) {
1467    st->print("int");
1468  } else if (is_long(type)) {
1469    st->print("long");
1470  } else if (is_float(type)) {
1471    st->print("float");
1472  } else if (is_double(type)) {
1473    st->print("double");
1474  } else if (type->is_return_address()) {
1475    st->print("address(%d)", type->as_return_address()->bci());
1476  } else {
1477    if (type->is_klass()) {
1478      type->as_klass()->name()->print_symbol_on(st);
1479    } else {
1480      st->print("UNEXPECTED TYPE");
1481      type->print();
1482    }
1483  }
1484}
1485
1486// ------------------------------------------------------------------
1487// ciTypeFlow::StateVector::print_on
1488void ciTypeFlow::StateVector::print_on(outputStream* st) const {
1489  int num_locals   = _outer->max_locals();
1490  int num_stack    = stack_size();
1491  int num_monitors = monitor_count();
1492  st->print_cr("  State : locals %d, stack %d, monitors %d", num_locals, num_stack, num_monitors);
1493  if (num_stack >= 0) {
1494    int i;
1495    for (i = 0; i < num_locals; i++) {
1496      st->print("    local %2d : ", i);
1497      print_cell_on(st, local(i));
1498      st->cr();
1499    }
1500    for (i = 0; i < num_stack; i++) {
1501      st->print("    stack %2d : ", i);
1502      print_cell_on(st, stack(i));
1503      st->cr();
1504    }
1505  }
1506}
1507#endif
1508
1509// ciTypeFlow::Block
1510//
1511// A basic block.
1512
1513// ------------------------------------------------------------------
1514// ciTypeFlow::Block::Block
1515ciTypeFlow::Block::Block(ciTypeFlow* outer,
1516                         ciBlock *ciblk,
1517                         ciTypeFlow::JsrSet* jsrs) {
1518  _ciblock = ciblk;
1519  _exceptions = NULL;
1520  _exc_klasses = NULL;
1521  _successors = NULL;
1522  _state = new (outer->arena()) StateVector(outer);
1523  JsrSet* new_jsrs =
1524    new (outer->arena()) JsrSet(outer->arena(), jsrs->size());
1525  jsrs->copy_into(new_jsrs);
1526  _jsrs = new_jsrs;
1527  _next = NULL;
1528  _on_work_list = false;
1529  _pre_order = -1; assert(!has_pre_order(), "");
1530  _private_copy = false;
1531  _trap_bci = -1;
1532  _trap_index = 0;
1533
1534  if (CITraceTypeFlow) {
1535    tty->print_cr(">> Created new block");
1536    print_on(tty);
1537  }
1538
1539  assert(this->outer() == outer, "outer link set up");
1540  assert(!outer->have_block_count(), "must not have mapped blocks yet");
1541}
1542
1543// ------------------------------------------------------------------
1544// ciTypeFlow::Block::clone_loop_head
1545//
1546ciTypeFlow::Block*
1547ciTypeFlow::Block::clone_loop_head(ciTypeFlow* analyzer,
1548                                   int branch_bci,
1549                                   ciTypeFlow::Block* target,
1550                                   ciTypeFlow::JsrSet* jsrs) {
1551  // Loop optimizations are not performed on Tier1 compiles. Do nothing.
1552  if (analyzer->env()->comp_level() < CompLevel_full_optimization) {
1553    return target;
1554  }
1555
1556  // The current block ends with a branch.
1557  //
1558  // If the target block appears to be the test-clause of a for loop, and
1559  // it is not too large, and it has not yet been cloned, clone it.
1560  // The pre-existing copy becomes the private clone used only by
1561  // the initial iteration of the loop.  (We know we are simulating
1562  // the initial iteration right now, since we have never calculated
1563  // successors before for this block.)
1564
1565  if (branch_bci <= start()
1566      && (target->limit() - target->start()) <= CICloneLoopTestLimit
1567      && target->private_copy_count() == 0) {
1568    // Setting the private_copy bit ensures that the target block cannot be
1569    // reached by any other paths, such as fall-in from the loop body.
1570    // The private copy will be accessible only on successor lists
1571    // created up to this point.
1572    target->set_private_copy(true);
1573    if (CITraceTypeFlow) {
1574      tty->print(">> Cloning a test-clause block ");
1575      print_value_on(tty);
1576      tty->cr();
1577    }
1578    // If the target is the current block, then later on a new copy of the
1579    // target block will be created when its bytecodes are reached by
1580    // an alternate path. (This is the case for loops with the loop
1581    // head at the bci-wise bottom of the loop, as with pre-1.4.2 javac.)
1582    //
1583    // Otherwise, duplicate the target block now and use it immediately.
1584    // (The case for loops with the loop head at the bci-wise top of the
1585    // loop, as with 1.4.2 javac.)
1586    //
1587    // In either case, the new copy of the block will remain public.
1588    if (target != this) {
1589      target = analyzer->block_at(branch_bci, jsrs);
1590    }
1591  }
1592  return target;
1593}
1594
1595// ------------------------------------------------------------------
1596// ciTypeFlow::Block::successors
1597//
1598// Get the successors for this Block.
1599GrowableArray<ciTypeFlow::Block*>*
1600ciTypeFlow::Block::successors(ciBytecodeStream* str,
1601                              ciTypeFlow::StateVector* state,
1602                              ciTypeFlow::JsrSet* jsrs) {
1603  if (_successors == NULL) {
1604    if (CITraceTypeFlow) {
1605      tty->print(">> Computing successors for block ");
1606      print_value_on(tty);
1607      tty->cr();
1608    }
1609
1610    ciTypeFlow* analyzer = outer();
1611    Arena* arena = analyzer->arena();
1612    Block* block = NULL;
1613    bool has_successor = !has_trap() &&
1614                         (control() != ciBlock::fall_through_bci || limit() < analyzer->code_size());
1615    if (!has_successor) {
1616      _successors =
1617        new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1618      // No successors
1619    } else if (control() == ciBlock::fall_through_bci) {
1620      assert(str->cur_bci() == limit(), "bad block end");
1621      // This block simply falls through to the next.
1622      _successors =
1623        new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1624
1625      Block* block = analyzer->block_at(limit(), _jsrs);
1626      assert(_successors->length() == FALL_THROUGH, "");
1627      _successors->append(block);
1628    } else {
1629      int current_bci = str->cur_bci();
1630      int next_bci = str->next_bci();
1631      int branch_bci = -1;
1632      Block* target = NULL;
1633      assert(str->next_bci() == limit(), "bad block end");
1634      // This block is not a simple fall-though.  Interpret
1635      // the current bytecode to find our successors.
1636      switch (str->cur_bc()) {
1637      case Bytecodes::_ifeq:         case Bytecodes::_ifne:
1638      case Bytecodes::_iflt:         case Bytecodes::_ifge:
1639      case Bytecodes::_ifgt:         case Bytecodes::_ifle:
1640      case Bytecodes::_if_icmpeq:    case Bytecodes::_if_icmpne:
1641      case Bytecodes::_if_icmplt:    case Bytecodes::_if_icmpge:
1642      case Bytecodes::_if_icmpgt:    case Bytecodes::_if_icmple:
1643      case Bytecodes::_if_acmpeq:    case Bytecodes::_if_acmpne:
1644      case Bytecodes::_ifnull:       case Bytecodes::_ifnonnull:
1645        // Our successors are the branch target and the next bci.
1646        branch_bci = str->get_dest();
1647        clone_loop_head(analyzer, branch_bci, this, jsrs);
1648        _successors =
1649          new (arena) GrowableArray<Block*>(arena, 2, 0, NULL);
1650        assert(_successors->length() == IF_NOT_TAKEN, "");
1651        _successors->append(analyzer->block_at(next_bci, jsrs));
1652        assert(_successors->length() == IF_TAKEN, "");
1653        _successors->append(analyzer->block_at(branch_bci, jsrs));
1654        break;
1655
1656      case Bytecodes::_goto:
1657        branch_bci = str->get_dest();
1658        _successors =
1659          new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1660        assert(_successors->length() == GOTO_TARGET, "");
1661        target = analyzer->block_at(branch_bci, jsrs);
1662        // If the target block has not been visited yet, and looks like
1663        // a two-way branch, attempt to clone it if it is a loop head.
1664        if (target->_successors != NULL
1665            && target->_successors->length() == (IF_TAKEN + 1)) {
1666          target = clone_loop_head(analyzer, branch_bci, target, jsrs);
1667        }
1668        _successors->append(target);
1669        break;
1670
1671      case Bytecodes::_jsr:
1672        branch_bci = str->get_dest();
1673        _successors =
1674          new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1675        assert(_successors->length() == GOTO_TARGET, "");
1676        _successors->append(analyzer->block_at(branch_bci, jsrs));
1677        break;
1678
1679      case Bytecodes::_goto_w:
1680      case Bytecodes::_jsr_w:
1681        _successors =
1682          new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1683        assert(_successors->length() == GOTO_TARGET, "");
1684        _successors->append(analyzer->block_at(str->get_far_dest(), jsrs));
1685        break;
1686
1687      case Bytecodes::_tableswitch:  {
1688        Bytecode_tableswitch *tableswitch =
1689          Bytecode_tableswitch_at(str->cur_bcp());
1690
1691        int len = tableswitch->length();
1692        _successors =
1693          new (arena) GrowableArray<Block*>(arena, len+1, 0, NULL);
1694        int bci = current_bci + tableswitch->default_offset();
1695        Block* block = analyzer->block_at(bci, jsrs);
1696        assert(_successors->length() == SWITCH_DEFAULT, "");
1697        _successors->append(block);
1698        while (--len >= 0) {
1699          int bci = current_bci + tableswitch->dest_offset_at(len);
1700          block = analyzer->block_at(bci, jsrs);
1701          assert(_successors->length() >= SWITCH_CASES, "");
1702          _successors->append_if_missing(block);
1703        }
1704        break;
1705      }
1706
1707      case Bytecodes::_lookupswitch: {
1708        Bytecode_lookupswitch *lookupswitch =
1709          Bytecode_lookupswitch_at(str->cur_bcp());
1710
1711        int npairs = lookupswitch->number_of_pairs();
1712        _successors =
1713          new (arena) GrowableArray<Block*>(arena, npairs+1, 0, NULL);
1714        int bci = current_bci + lookupswitch->default_offset();
1715        Block* block = analyzer->block_at(bci, jsrs);
1716        assert(_successors->length() == SWITCH_DEFAULT, "");
1717        _successors->append(block);
1718        while(--npairs >= 0) {
1719          LookupswitchPair *pair = lookupswitch->pair_at(npairs);
1720          int bci = current_bci + pair->offset();
1721          Block* block = analyzer->block_at(bci, jsrs);
1722          assert(_successors->length() >= SWITCH_CASES, "");
1723          _successors->append_if_missing(block);
1724        }
1725        break;
1726      }
1727
1728      case Bytecodes::_athrow:     case Bytecodes::_ireturn:
1729      case Bytecodes::_lreturn:    case Bytecodes::_freturn:
1730      case Bytecodes::_dreturn:    case Bytecodes::_areturn:
1731      case Bytecodes::_return:
1732        _successors =
1733          new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1734        // No successors
1735        break;
1736
1737      case Bytecodes::_ret: {
1738        _successors =
1739          new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1740
1741        Cell local = state->local(str->get_index());
1742        ciType* return_address = state->type_at(local);
1743        assert(return_address->is_return_address(), "verify: wrong type");
1744        int bci = return_address->as_return_address()->bci();
1745        assert(_successors->length() == GOTO_TARGET, "");
1746        _successors->append(analyzer->block_at(bci, jsrs));
1747        break;
1748      }
1749
1750      case Bytecodes::_wide:
1751      default:
1752        ShouldNotReachHere();
1753        break;
1754      }
1755    }
1756  }
1757  return _successors;
1758}
1759
1760// ------------------------------------------------------------------
1761// ciTypeFlow::Block:compute_exceptions
1762//
1763// Compute the exceptional successors and types for this Block.
1764void ciTypeFlow::Block::compute_exceptions() {
1765  assert(_exceptions == NULL && _exc_klasses == NULL, "repeat");
1766
1767  if (CITraceTypeFlow) {
1768    tty->print(">> Computing exceptions for block ");
1769    print_value_on(tty);
1770    tty->cr();
1771  }
1772
1773  ciTypeFlow* analyzer = outer();
1774  Arena* arena = analyzer->arena();
1775
1776  // Any bci in the block will do.
1777  ciExceptionHandlerStream str(analyzer->method(), start());
1778
1779  // Allocate our growable arrays.
1780  int exc_count = str.count();
1781  _exceptions = new (arena) GrowableArray<Block*>(arena, exc_count, 0, NULL);
1782  _exc_klasses = new (arena) GrowableArray<ciInstanceKlass*>(arena, exc_count,
1783                                                             0, NULL);
1784
1785  for ( ; !str.is_done(); str.next()) {
1786    ciExceptionHandler* handler = str.handler();
1787    int bci = handler->handler_bci();
1788    ciInstanceKlass* klass = NULL;
1789    if (bci == -1) {
1790      // There is no catch all.  It is possible to exit the method.
1791      break;
1792    }
1793    if (handler->is_catch_all()) {
1794      klass = analyzer->env()->Throwable_klass();
1795    } else {
1796      klass = handler->catch_klass();
1797    }
1798    _exceptions->append(analyzer->block_at(bci, _jsrs));
1799    _exc_klasses->append(klass);
1800  }
1801}
1802
1803// ------------------------------------------------------------------
1804// ciTypeFlow::Block::is_simpler_than
1805//
1806// A relation used to order our work list.  We work on a block earlier
1807// if it has a smaller jsr stack or it occurs earlier in the program
1808// text.
1809//
1810// Note: maybe we should redo this functionality to make blocks
1811// which correspond to exceptions lower priority.
1812bool ciTypeFlow::Block::is_simpler_than(ciTypeFlow::Block* other) {
1813  if (other == NULL) {
1814    return true;
1815  } else {
1816    int size1 = _jsrs->size();
1817    int size2 = other->_jsrs->size();
1818    if (size1 < size2) {
1819      return true;
1820    } else if (size2 < size1) {
1821      return false;
1822    } else {
1823#if 0
1824      if (size1 > 0) {
1825        int r1 = _jsrs->record_at(0)->return_address();
1826        int r2 = _jsrs->record_at(0)->return_address();
1827        if (r1 < r2) {
1828          return true;
1829        } else if (r2 < r1) {
1830          return false;
1831        } else {
1832          int e1 = _jsrs->record_at(0)->return_address();
1833          int e2 = _jsrs->record_at(0)->return_address();
1834          if (e1 < e2) {
1835            return true;
1836          } else if (e2 < e1) {
1837            return false;
1838          }
1839        }
1840      }
1841#endif
1842      return (start() <= other->start());
1843    }
1844  }
1845}
1846
1847// ------------------------------------------------------------------
1848// ciTypeFlow::Block::set_private_copy
1849// Use this only to make a pre-existing public block into a private copy.
1850void ciTypeFlow::Block::set_private_copy(bool z) {
1851  assert(z || (z == is_private_copy()), "cannot make a private copy public");
1852  _private_copy = z;
1853}
1854
1855#ifndef PRODUCT
1856// ------------------------------------------------------------------
1857// ciTypeFlow::Block::print_value_on
1858void ciTypeFlow::Block::print_value_on(outputStream* st) const {
1859  if (has_pre_order())  st->print("#%-2d ", pre_order());
1860  st->print("[%d - %d)", start(), limit());
1861  if (_jsrs->size() > 0) { st->print("/");  _jsrs->print_on(st); }
1862  if (is_private_copy())  st->print("/private_copy");
1863}
1864
1865// ------------------------------------------------------------------
1866// ciTypeFlow::Block::print_on
1867void ciTypeFlow::Block::print_on(outputStream* st) const {
1868  if ((Verbose || WizardMode)) {
1869    outer()->method()->print_codes_on(start(), limit(), st);
1870  }
1871  st->print_cr("  ====================================================  ");
1872  st->print ("  ");
1873  print_value_on(st);
1874  st->cr();
1875  _state->print_on(st);
1876  if (_successors == NULL) {
1877    st->print_cr("  No successor information");
1878  } else {
1879    int num_successors = _successors->length();
1880    st->print_cr("  Successors : %d", num_successors);
1881    for (int i = 0; i < num_successors; i++) {
1882      Block* successor = _successors->at(i);
1883      st->print("    ");
1884      successor->print_value_on(st);
1885      st->cr();
1886    }
1887  }
1888  if (_exceptions == NULL) {
1889    st->print_cr("  No exception information");
1890  } else {
1891    int num_exceptions = _exceptions->length();
1892    st->print_cr("  Exceptions : %d", num_exceptions);
1893    for (int i = 0; i < num_exceptions; i++) {
1894      Block* exc_succ = _exceptions->at(i);
1895      ciInstanceKlass* exc_klass = _exc_klasses->at(i);
1896      st->print("    ");
1897      exc_succ->print_value_on(st);
1898      st->print(" -- ");
1899      exc_klass->name()->print_symbol_on(st);
1900      st->cr();
1901    }
1902  }
1903  if (has_trap()) {
1904    st->print_cr("  Traps on %d with trap index %d", trap_bci(), trap_index());
1905  }
1906  st->print_cr("  ====================================================  ");
1907}
1908#endif
1909
1910// ciTypeFlow
1911//
1912// This is a pass over the bytecodes which computes the following:
1913//   basic block structure
1914//   interpreter type-states (a la the verifier)
1915
1916// ------------------------------------------------------------------
1917// ciTypeFlow::ciTypeFlow
1918ciTypeFlow::ciTypeFlow(ciEnv* env, ciMethod* method, int osr_bci) {
1919  _env = env;
1920  _method = method;
1921  _methodBlocks = method->get_method_blocks();
1922  _max_locals = method->max_locals();
1923  _max_stack = method->max_stack();
1924  _code_size = method->code_size();
1925  _osr_bci = osr_bci;
1926  _failure_reason = NULL;
1927  assert(start_bci() >= 0 && start_bci() < code_size() , "correct osr_bci argument");
1928
1929  _work_list = NULL;
1930  _next_pre_order = 0;
1931
1932  _ciblock_count = _methodBlocks->num_blocks();
1933  _idx_to_blocklist = NEW_ARENA_ARRAY(arena(), GrowableArray<Block*>*, _ciblock_count);
1934  for (int i = 0; i < _ciblock_count; i++) {
1935    _idx_to_blocklist[i] = NULL;
1936  }
1937  _block_map = NULL;  // until all blocks are seen
1938  _jsr_count = 0;
1939  _jsr_records = NULL;
1940}
1941
1942// ------------------------------------------------------------------
1943// ciTypeFlow::work_list_next
1944//
1945// Get the next basic block from our work list.
1946ciTypeFlow::Block* ciTypeFlow::work_list_next() {
1947  assert(!work_list_empty(), "work list must not be empty");
1948  Block* next_block = _work_list;
1949  _work_list = next_block->next();
1950  next_block->set_next(NULL);
1951  next_block->set_on_work_list(false);
1952  if (!next_block->has_pre_order()) {
1953    // Assign "pre_order" as each new block is taken from the work list.
1954    // This number may be used by following phases to order block visits.
1955    assert(!have_block_count(), "must not have mapped blocks yet")
1956    next_block->set_pre_order(_next_pre_order++);
1957  }
1958  return next_block;
1959}
1960
1961// ------------------------------------------------------------------
1962// ciTypeFlow::add_to_work_list
1963//
1964// Add a basic block to our work list.
1965void ciTypeFlow::add_to_work_list(ciTypeFlow::Block* block) {
1966  assert(!block->is_on_work_list(), "must not already be on work list");
1967
1968  if (CITraceTypeFlow) {
1969    tty->print(">> Adding block%s ", block->has_pre_order() ? " (again)" : "");
1970    block->print_value_on(tty);
1971    tty->print_cr(" to the work list : ");
1972  }
1973
1974  block->set_on_work_list(true);
1975  if (block->is_simpler_than(_work_list)) {
1976    block->set_next(_work_list);
1977    _work_list = block;
1978  } else {
1979    Block *temp = _work_list;
1980    while (!block->is_simpler_than(temp->next())) {
1981      if (CITraceTypeFlow) {
1982        tty->print(".");
1983      }
1984      temp = temp->next();
1985    }
1986    block->set_next(temp->next());
1987    temp->set_next(block);
1988  }
1989  if (CITraceTypeFlow) {
1990    tty->cr();
1991  }
1992}
1993
1994// ------------------------------------------------------------------
1995// ciTypeFlow::block_at
1996//
1997// Return the block beginning at bci which has a JsrSet compatible
1998// with jsrs.
1999ciTypeFlow::Block* ciTypeFlow::block_at(int bci, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
2000  // First find the right ciBlock.
2001  if (CITraceTypeFlow) {
2002    tty->print(">> Requesting block for %d/", bci);
2003    jsrs->print_on(tty);
2004    tty->cr();
2005  }
2006
2007  ciBlock* ciblk = _methodBlocks->block_containing(bci);
2008  assert(ciblk->start_bci() == bci, "bad ciBlock boundaries");
2009  Block* block = get_block_for(ciblk->index(), jsrs, option);
2010
2011  assert(block == NULL? (option == no_create): block->is_private_copy() == (option == create_private_copy), "create option consistent with result");
2012
2013  if (CITraceTypeFlow) {
2014    if (block != NULL) {
2015      tty->print(">> Found block ");
2016      block->print_value_on(tty);
2017      tty->cr();
2018    } else {
2019      tty->print_cr(">> No such block.");
2020    }
2021  }
2022
2023  return block;
2024}
2025
2026// ------------------------------------------------------------------
2027// ciTypeFlow::make_jsr_record
2028//
2029// Make a JsrRecord for a given (entry, return) pair, if such a record
2030// does not already exist.
2031ciTypeFlow::JsrRecord* ciTypeFlow::make_jsr_record(int entry_address,
2032                                                   int return_address) {
2033  if (_jsr_records == NULL) {
2034    _jsr_records = new (arena()) GrowableArray<JsrRecord*>(arena(),
2035                                                           _jsr_count,
2036                                                           0,
2037                                                           NULL);
2038  }
2039  JsrRecord* record = NULL;
2040  int len = _jsr_records->length();
2041  for (int i = 0; i < len; i++) {
2042    JsrRecord* record = _jsr_records->at(i);
2043    if (record->entry_address() == entry_address &&
2044        record->return_address() == return_address) {
2045      return record;
2046    }
2047  }
2048
2049  record = new (arena()) JsrRecord(entry_address, return_address);
2050  _jsr_records->append(record);
2051  return record;
2052}
2053
2054// ------------------------------------------------------------------
2055// ciTypeFlow::flow_exceptions
2056//
2057// Merge the current state into all exceptional successors at the
2058// current point in the code.
2059void ciTypeFlow::flow_exceptions(GrowableArray<ciTypeFlow::Block*>* exceptions,
2060                                 GrowableArray<ciInstanceKlass*>* exc_klasses,
2061                                 ciTypeFlow::StateVector* state) {
2062  int len = exceptions->length();
2063  assert(exc_klasses->length() == len, "must have same length");
2064  for (int i = 0; i < len; i++) {
2065    Block* block = exceptions->at(i);
2066    ciInstanceKlass* exception_klass = exc_klasses->at(i);
2067
2068    if (!exception_klass->is_loaded()) {
2069      // Do not compile any code for unloaded exception types.
2070      // Following compiler passes are responsible for doing this also.
2071      continue;
2072    }
2073
2074    if (block->meet_exception(exception_klass, state)) {
2075      // Block was modified.  Add it to the work list.
2076      if (!block->is_on_work_list()) {
2077        add_to_work_list(block);
2078      }
2079    }
2080  }
2081}
2082
2083// ------------------------------------------------------------------
2084// ciTypeFlow::flow_successors
2085//
2086// Merge the current state into all successors at the current point
2087// in the code.
2088void ciTypeFlow::flow_successors(GrowableArray<ciTypeFlow::Block*>* successors,
2089                                 ciTypeFlow::StateVector* state) {
2090  int len = successors->length();
2091  for (int i = 0; i < len; i++) {
2092    Block* block = successors->at(i);
2093    if (block->meet(state)) {
2094      // Block was modified.  Add it to the work list.
2095      if (!block->is_on_work_list()) {
2096        add_to_work_list(block);
2097      }
2098    }
2099  }
2100}
2101
2102// ------------------------------------------------------------------
2103// ciTypeFlow::can_trap
2104//
2105// Tells if a given instruction is able to generate an exception edge.
2106bool ciTypeFlow::can_trap(ciBytecodeStream& str) {
2107  // Cf. GenerateOopMap::do_exception_edge.
2108  if (!Bytecodes::can_trap(str.cur_bc()))  return false;
2109
2110  switch (str.cur_bc()) {
2111    case Bytecodes::_ldc:
2112    case Bytecodes::_ldc_w:
2113    case Bytecodes::_ldc2_w:
2114    case Bytecodes::_aload_0:
2115      // These bytecodes can trap for rewriting.  We need to assume that
2116      // they do not throw exceptions to make the monitor analysis work.
2117      return false;
2118
2119    case Bytecodes::_ireturn:
2120    case Bytecodes::_lreturn:
2121    case Bytecodes::_freturn:
2122    case Bytecodes::_dreturn:
2123    case Bytecodes::_areturn:
2124    case Bytecodes::_return:
2125      // We can assume the monitor stack is empty in this analysis.
2126      return false;
2127
2128    case Bytecodes::_monitorexit:
2129      // We can assume monitors are matched in this analysis.
2130      return false;
2131  }
2132
2133  return true;
2134}
2135
2136
2137// ------------------------------------------------------------------
2138// ciTypeFlow::flow_block
2139//
2140// Interpret the effects of the bytecodes on the incoming state
2141// vector of a basic block.  Push the changed state to succeeding
2142// basic blocks.
2143void ciTypeFlow::flow_block(ciTypeFlow::Block* block,
2144                            ciTypeFlow::StateVector* state,
2145                            ciTypeFlow::JsrSet* jsrs) {
2146  if (CITraceTypeFlow) {
2147    tty->print("\n>> ANALYZING BLOCK : ");
2148    tty->cr();
2149    block->print_on(tty);
2150  }
2151  assert(block->has_pre_order(), "pre-order is assigned before 1st flow");
2152
2153  int start = block->start();
2154  int limit = block->limit();
2155  int control = block->control();
2156  if (control != ciBlock::fall_through_bci) {
2157    limit = control;
2158  }
2159
2160  // Grab the state from the current block.
2161  block->copy_state_into(state);
2162
2163  GrowableArray<Block*>*           exceptions = block->exceptions();
2164  GrowableArray<ciInstanceKlass*>* exc_klasses = block->exc_klasses();
2165  bool has_exceptions = exceptions->length() > 0;
2166
2167  ciBytecodeStream str(method());
2168  str.reset_to_bci(start);
2169  Bytecodes::Code code;
2170  while ((code = str.next()) != ciBytecodeStream::EOBC() &&
2171         str.cur_bci() < limit) {
2172    // Check for exceptional control flow from this point.
2173    if (has_exceptions && can_trap(str)) {
2174      flow_exceptions(exceptions, exc_klasses, state);
2175    }
2176    // Apply the effects of the current bytecode to our state.
2177    bool res = state->apply_one_bytecode(&str);
2178
2179    // Watch for bailouts.
2180    if (failing())  return;
2181
2182    if (res) {
2183
2184      // We have encountered a trap.  Record it in this block.
2185      block->set_trap(state->trap_bci(), state->trap_index());
2186
2187      if (CITraceTypeFlow) {
2188        tty->print_cr(">> Found trap");
2189        block->print_on(tty);
2190      }
2191
2192      // Record (no) successors.
2193      block->successors(&str, state, jsrs);
2194
2195      // Discontinue interpretation of this Block.
2196      return;
2197    }
2198  }
2199
2200  GrowableArray<Block*>* successors = NULL;
2201  if (control != ciBlock::fall_through_bci) {
2202    // Check for exceptional control flow from this point.
2203    if (has_exceptions && can_trap(str)) {
2204      flow_exceptions(exceptions, exc_klasses, state);
2205    }
2206
2207    // Fix the JsrSet to reflect effect of the bytecode.
2208    block->copy_jsrs_into(jsrs);
2209    jsrs->apply_control(this, &str, state);
2210
2211    // Find successor edges based on old state and new JsrSet.
2212    successors = block->successors(&str, state, jsrs);
2213
2214    // Apply the control changes to the state.
2215    state->apply_one_bytecode(&str);
2216  } else {
2217    // Fall through control
2218    successors = block->successors(&str, NULL, NULL);
2219  }
2220
2221  // Pass our state to successors.
2222  flow_successors(successors, state);
2223}
2224
2225// ------------------------------------------------------------------
2226// ciTypeFlow::flow_types
2227//
2228// Perform the type flow analysis, creating and cloning Blocks as
2229// necessary.
2230void ciTypeFlow::flow_types() {
2231  ResourceMark rm;
2232  StateVector* temp_vector = new StateVector(this);
2233  JsrSet* temp_set = new JsrSet(NULL, 16);
2234
2235  // Create the method entry block.
2236  Block* block = block_at(start_bci(), temp_set);
2237  block->set_pre_order(_next_pre_order++);
2238  assert(block->is_start(), "start block must have order #0");
2239
2240  // Load the initial state into it.
2241  const StateVector* start_state = get_start_state();
2242  if (failing())  return;
2243  block->meet(start_state);
2244  add_to_work_list(block);
2245
2246  // Trickle away.
2247  while (!work_list_empty()) {
2248    Block* block = work_list_next();
2249    flow_block(block, temp_vector, temp_set);
2250
2251
2252    // NodeCountCutoff is the number of nodes at which the parser
2253    // will bail out.  Probably if we already have lots of BBs,
2254    // the parser will generate at least twice that many nodes and bail out.
2255    // Therefore, this is a conservatively large limit at which to
2256    // bail out in the pre-parse typeflow pass.
2257    int block_limit = MaxNodeLimit / 2;
2258
2259    if (_next_pre_order >= block_limit) {
2260      // Too many basic blocks.  Bail out.
2261      //
2262      // This can happen when try/finally constructs are nested to depth N,
2263      // and there is O(2**N) cloning of jsr bodies.  See bug 4697245!
2264      record_failure("too many basic blocks");
2265      return;
2266    }
2267
2268    // Watch for bailouts.
2269    if (failing())  return;
2270  }
2271}
2272
2273// ------------------------------------------------------------------
2274// ciTypeFlow::map_blocks
2275//
2276// Create the block map, which indexes blocks in pre_order.
2277void ciTypeFlow::map_blocks() {
2278  assert(_block_map == NULL, "single initialization");
2279  int pre_order_limit = _next_pre_order;
2280  _block_map = NEW_ARENA_ARRAY(arena(), Block*, pre_order_limit);
2281  assert(pre_order_limit == block_count(), "");
2282  int po;
2283  for (po = 0; po < pre_order_limit; po++) {
2284    debug_only(_block_map[po] = NULL);
2285  }
2286  ciMethodBlocks *mblks = _methodBlocks;
2287  ciBlock* current = NULL;
2288  int limit_bci = code_size();
2289  for (int bci = 0; bci < limit_bci; bci++) {
2290    ciBlock* ciblk = mblks->block_containing(bci);
2291    if (ciblk != NULL && ciblk != current) {
2292      current = ciblk;
2293      int curidx = ciblk->index();
2294      int block_count = (_idx_to_blocklist[curidx] == NULL) ? 0 : _idx_to_blocklist[curidx]->length();
2295      for (int i = 0; i < block_count; i++) {
2296        Block* block = _idx_to_blocklist[curidx]->at(i);
2297        if (!block->has_pre_order())  continue;
2298        int po = block->pre_order();
2299        assert(_block_map[po] == NULL, "unique ref to block");
2300        assert(0 <= po && po < pre_order_limit, "");
2301        _block_map[po] = block;
2302      }
2303    }
2304  }
2305  for (po = 0; po < pre_order_limit; po++) {
2306    assert(_block_map[po] != NULL, "must not drop any blocks");
2307    Block* block = _block_map[po];
2308    // Remove dead blocks from successor lists:
2309    for (int e = 0; e <= 1; e++) {
2310      GrowableArray<Block*>* l = e? block->exceptions(): block->successors();
2311      for (int i = 0; i < l->length(); i++) {
2312        Block* s = l->at(i);
2313        if (!s->has_pre_order()) {
2314          if (CITraceTypeFlow) {
2315            tty->print("Removing dead %s successor of #%d: ", (e? "exceptional":  "normal"), block->pre_order());
2316            s->print_value_on(tty);
2317            tty->cr();
2318          }
2319          l->remove(s);
2320          --i;
2321        }
2322      }
2323    }
2324  }
2325}
2326
2327// ------------------------------------------------------------------
2328// ciTypeFlow::get_block_for
2329//
2330// Find a block with this ciBlock which has a compatible JsrSet.
2331// If no such block exists, create it, unless the option is no_create.
2332// If the option is create_private_copy, always create a fresh private copy.
2333ciTypeFlow::Block* ciTypeFlow::get_block_for(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
2334  Arena* a = arena();
2335  GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
2336  if (blocks == NULL) {
2337    // Query only?
2338    if (option == no_create)  return NULL;
2339
2340    // Allocate the growable array.
2341    blocks = new (a) GrowableArray<Block*>(a, 4, 0, NULL);
2342    _idx_to_blocklist[ciBlockIndex] = blocks;
2343  }
2344
2345  if (option != create_private_copy) {
2346    int len = blocks->length();
2347    for (int i = 0; i < len; i++) {
2348      Block* block = blocks->at(i);
2349      if (!block->is_private_copy() && block->is_compatible_with(jsrs)) {
2350        return block;
2351      }
2352    }
2353  }
2354
2355  // Query only?
2356  if (option == no_create)  return NULL;
2357
2358  // We did not find a compatible block.  Create one.
2359  Block* new_block = new (a) Block(this, _methodBlocks->block(ciBlockIndex), jsrs);
2360  if (option == create_private_copy)  new_block->set_private_copy(true);
2361  blocks->append(new_block);
2362  return new_block;
2363}
2364
2365// ------------------------------------------------------------------
2366// ciTypeFlow::private_copy_count
2367//
2368int ciTypeFlow::private_copy_count(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs) const {
2369  GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
2370
2371  if (blocks == NULL) {
2372    return 0;
2373  }
2374
2375  int count = 0;
2376  int len = blocks->length();
2377  for (int i = 0; i < len; i++) {
2378    Block* block = blocks->at(i);
2379    if (block->is_private_copy() && block->is_compatible_with(jsrs)) {
2380      count++;
2381    }
2382  }
2383
2384  return count;
2385}
2386
2387// ------------------------------------------------------------------
2388// ciTypeFlow::do_flow
2389//
2390// Perform type inference flow analysis.
2391void ciTypeFlow::do_flow() {
2392  if (CITraceTypeFlow) {
2393    tty->print_cr("\nPerforming flow analysis on method");
2394    method()->print();
2395    if (is_osr_flow())  tty->print(" at OSR bci %d", start_bci());
2396    tty->cr();
2397    method()->print_codes();
2398  }
2399  if (CITraceTypeFlow) {
2400    tty->print_cr("Initial CI Blocks");
2401    print_on(tty);
2402  }
2403  flow_types();
2404  // Watch for bailouts.
2405  if (failing()) {
2406    return;
2407  }
2408  if (CIPrintTypeFlow || CITraceTypeFlow) {
2409    print_on(tty);
2410  }
2411  map_blocks();
2412}
2413
2414// ------------------------------------------------------------------
2415// ciTypeFlow::record_failure()
2416// The ciTypeFlow object keeps track of failure reasons separately from the ciEnv.
2417// This is required because there is not a 1-1 relation between the ciEnv and
2418// the TypeFlow passes within a compilation task.  For example, if the compiler
2419// is considering inlining a method, it will request a TypeFlow.  If that fails,
2420// the compilation as a whole may continue without the inlining.  Some TypeFlow
2421// requests are not optional; if they fail the requestor is responsible for
2422// copying the failure reason up to the ciEnv.  (See Parse::Parse.)
2423void ciTypeFlow::record_failure(const char* reason) {
2424  if (env()->log() != NULL) {
2425    env()->log()->elem("failure reason='%s' phase='typeflow'", reason);
2426  }
2427  if (_failure_reason == NULL) {
2428    // Record the first failure reason.
2429    _failure_reason = reason;
2430  }
2431}
2432
2433#ifndef PRODUCT
2434// ------------------------------------------------------------------
2435// ciTypeFlow::print_on
2436void ciTypeFlow::print_on(outputStream* st) const {
2437  // Walk through CI blocks
2438  st->print_cr("********************************************************");
2439  st->print   ("TypeFlow for ");
2440  method()->name()->print_symbol_on(st);
2441  int limit_bci = code_size();
2442  st->print_cr("  %d bytes", limit_bci);
2443  ciMethodBlocks  *mblks = _methodBlocks;
2444  ciBlock* current = NULL;
2445  for (int bci = 0; bci < limit_bci; bci++) {
2446    ciBlock* blk = mblks->block_containing(bci);
2447    if (blk != NULL && blk != current) {
2448      current = blk;
2449      current->print_on(st);
2450
2451      GrowableArray<Block*>* blocks = _idx_to_blocklist[blk->index()];
2452      int num_blocks = (blocks == NULL) ? 0 : blocks->length();
2453
2454      if (num_blocks == 0) {
2455        st->print_cr("  No Blocks");
2456      } else {
2457        for (int i = 0; i < num_blocks; i++) {
2458          Block* block = blocks->at(i);
2459          block->print_on(st);
2460        }
2461      }
2462      st->print_cr("--------------------------------------------------------");
2463      st->cr();
2464    }
2465  }
2466  st->print_cr("********************************************************");
2467  st->cr();
2468}
2469#endif
2470