1 /*
   2  * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "ci/ciConstant.hpp"
  27 #include "ci/ciField.hpp"
  28 #include "ci/ciMethod.hpp"
  29 #include "ci/ciMethodData.hpp"
  30 #include "ci/ciObjArrayKlass.hpp"
  31 #include "ci/ciStreams.hpp"
  32 #include "ci/ciTypeArrayKlass.hpp"
  33 #include "ci/ciTypeFlow.hpp"
  34 #include "compiler/compileLog.hpp"
  35 #include "interpreter/bytecode.hpp"
  36 #include "interpreter/bytecodes.hpp"
  37 #include "memory/allocation.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "opto/compile.hpp"
  40 #include "opto/node.hpp"
  41 #include "runtime/deoptimization.hpp"
  42 #include "utilities/growableArray.hpp"
  43 
  44 // ciTypeFlow::JsrSet
  45 //
  46 // A JsrSet represents some set of JsrRecords.  This class
  47 // is used to record a set of all jsr routines which we permit
  48 // execution to return (ret) from.
  49 //
  50 // During abstract interpretation, JsrSets are used to determine
  51 // whether two paths which reach a given block are unique, and
  52 // should be cloned apart, or are compatible, and should merge
  53 // together.
  54 
  55 // ------------------------------------------------------------------
  56 // ciTypeFlow::JsrSet::JsrSet
  57 ciTypeFlow::JsrSet::JsrSet(Arena* arena, int default_len) {
  58   if (arena != NULL) {
  59     // Allocate growable array in Arena.
  60     _set = new (arena) GrowableArray<JsrRecord*>(arena, default_len, 0, NULL);
  61   } else {
  62     // Allocate growable array in current ResourceArea.
  63     _set = new GrowableArray<JsrRecord*>(4, 0, NULL, false);
  64   }
  65 }
  66 
  67 // ------------------------------------------------------------------
  68 // ciTypeFlow::JsrSet::copy_into
  69 void ciTypeFlow::JsrSet::copy_into(JsrSet* jsrs) {
  70   int len = size();
  71   jsrs->_set->clear();
  72   for (int i = 0; i < len; i++) {
  73     jsrs->_set->append(_set->at(i));
  74   }
  75 }
  76 
  77 // ------------------------------------------------------------------
  78 // ciTypeFlow::JsrSet::is_compatible_with
  79 //
  80 // !!!! MISGIVINGS ABOUT THIS... disregard
  81 //
  82 // Is this JsrSet compatible with some other JsrSet?
  83 //
  84 // In set-theoretic terms, a JsrSet can be viewed as a partial function
  85 // from entry addresses to return addresses.  Two JsrSets A and B are
  86 // compatible iff
  87 //
  88 //   For any x,
  89 //   A(x) defined and B(x) defined implies A(x) == B(x)
  90 //
  91 // Less formally, two JsrSets are compatible when they have identical
  92 // return addresses for any entry addresses they share in common.
  93 bool ciTypeFlow::JsrSet::is_compatible_with(JsrSet* other) {
  94   // Walk through both sets in parallel.  If the same entry address
  95   // appears in both sets, then the return address must match for
  96   // the sets to be compatible.
  97   int size1 = size();
  98   int size2 = other->size();
  99 
 100   // Special case.  If nothing is on the jsr stack, then there can
 101   // be no ret.
 102   if (size2 == 0) {
 103     return true;
 104   } else if (size1 != size2) {
 105     return false;
 106   } else {
 107     for (int i = 0; i < size1; i++) {
 108       JsrRecord* record1 = record_at(i);
 109       JsrRecord* record2 = other->record_at(i);
 110       if (record1->entry_address() != record2->entry_address() ||
 111           record1->return_address() != record2->return_address()) {
 112         return false;
 113       }
 114     }
 115     return true;
 116   }
 117 
 118 #if 0
 119   int pos1 = 0;
 120   int pos2 = 0;
 121   int size1 = size();
 122   int size2 = other->size();
 123   while (pos1 < size1 && pos2 < size2) {
 124     JsrRecord* record1 = record_at(pos1);
 125     JsrRecord* record2 = other->record_at(pos2);
 126     int entry1 = record1->entry_address();
 127     int entry2 = record2->entry_address();
 128     if (entry1 < entry2) {
 129       pos1++;
 130     } else if (entry1 > entry2) {
 131       pos2++;
 132     } else {
 133       if (record1->return_address() == record2->return_address()) {
 134         pos1++;
 135         pos2++;
 136       } else {
 137         // These two JsrSets are incompatible.
 138         return false;
 139       }
 140     }
 141   }
 142   // The two JsrSets agree.
 143   return true;
 144 #endif
 145 }
 146 
 147 // ------------------------------------------------------------------
 148 // ciTypeFlow::JsrSet::insert_jsr_record
 149 //
 150 // Insert the given JsrRecord into the JsrSet, maintaining the order
 151 // of the set and replacing any element with the same entry address.
 152 void ciTypeFlow::JsrSet::insert_jsr_record(JsrRecord* record) {
 153   int len = size();
 154   int entry = record->entry_address();
 155   int pos = 0;
 156   for ( ; pos < len; pos++) {
 157     JsrRecord* current = record_at(pos);
 158     if (entry == current->entry_address()) {
 159       // Stomp over this entry.
 160       _set->at_put(pos, record);
 161       assert(size() == len, "must be same size");
 162       return;
 163     } else if (entry < current->entry_address()) {
 164       break;
 165     }
 166   }
 167 
 168   // Insert the record into the list.
 169   JsrRecord* swap = record;
 170   JsrRecord* temp = NULL;
 171   for ( ; pos < len; pos++) {
 172     temp = _set->at(pos);
 173     _set->at_put(pos, swap);
 174     swap = temp;
 175   }
 176   _set->append(swap);
 177   assert(size() == len+1, "must be larger");
 178 }
 179 
 180 // ------------------------------------------------------------------
 181 // ciTypeFlow::JsrSet::remove_jsr_record
 182 //
 183 // Remove the JsrRecord with the given return address from the JsrSet.
 184 void ciTypeFlow::JsrSet::remove_jsr_record(int return_address) {
 185   int len = size();
 186   for (int i = 0; i < len; i++) {
 187     if (record_at(i)->return_address() == return_address) {
 188       // We have found the proper entry.  Remove it from the
 189       // JsrSet and exit.
 190       for (int j = i+1; j < len ; j++) {
 191         _set->at_put(j-1, _set->at(j));
 192       }
 193       _set->trunc_to(len-1);
 194       assert(size() == len-1, "must be smaller");
 195       return;
 196     }
 197   }
 198   assert(false, "verify: returning from invalid subroutine");
 199 }
 200 
 201 // ------------------------------------------------------------------
 202 // ciTypeFlow::JsrSet::apply_control
 203 //
 204 // Apply the effect of a control-flow bytecode on the JsrSet.  The
 205 // only bytecodes that modify the JsrSet are jsr and ret.
 206 void ciTypeFlow::JsrSet::apply_control(ciTypeFlow* analyzer,
 207                                        ciBytecodeStream* str,
 208                                        ciTypeFlow::StateVector* state) {
 209   Bytecodes::Code code = str->cur_bc();
 210   if (code == Bytecodes::_jsr) {
 211     JsrRecord* record =
 212       analyzer->make_jsr_record(str->get_dest(), str->next_bci());
 213     insert_jsr_record(record);
 214   } else if (code == Bytecodes::_jsr_w) {
 215     JsrRecord* record =
 216       analyzer->make_jsr_record(str->get_far_dest(), str->next_bci());
 217     insert_jsr_record(record);
 218   } else if (code == Bytecodes::_ret) {
 219     Cell local = state->local(str->get_index());
 220     ciType* return_address = state->type_at(local);
 221     assert(return_address->is_return_address(), "verify: wrong type");
 222     if (size() == 0) {
 223       // Ret-state underflow:  Hit a ret w/o any previous jsrs.  Bail out.
 224       // This can happen when a loop is inside a finally clause (4614060).
 225       analyzer->record_failure("OSR in finally clause");
 226       return;
 227     }
 228     remove_jsr_record(return_address->as_return_address()->bci());
 229   }
 230 }
 231 
 232 #ifndef PRODUCT
 233 // ------------------------------------------------------------------
 234 // ciTypeFlow::JsrSet::print_on
 235 void ciTypeFlow::JsrSet::print_on(outputStream* st) const {
 236   st->print("{ ");
 237   int num_elements = size();
 238   if (num_elements > 0) {
 239     int i = 0;
 240     for( ; i < num_elements - 1; i++) {
 241       _set->at(i)->print_on(st);
 242       st->print(", ");
 243     }
 244     _set->at(i)->print_on(st);
 245     st->print(" ");
 246   }
 247   st->print("}");
 248 }
 249 #endif
 250 
 251 // ciTypeFlow::StateVector
 252 //
 253 // A StateVector summarizes the type information at some point in
 254 // the program.
 255 
 256 // ------------------------------------------------------------------
 257 // ciTypeFlow::StateVector::type_meet
 258 //
 259 // Meet two types.
 260 //
 261 // The semi-lattice of types use by this analysis are modeled on those
 262 // of the verifier.  The lattice is as follows:
 263 //
 264 //        top_type() >= all non-extremal types >= bottom_type
 265 //                             and
 266 //   Every primitive type is comparable only with itself.  The meet of
 267 //   reference types is determined by their kind: instance class,
 268 //   interface, or array class.  The meet of two types of the same
 269 //   kind is their least common ancestor.  The meet of two types of
 270 //   different kinds is always java.lang.Object.
 271 ciType* ciTypeFlow::StateVector::type_meet_internal(ciType* t1, ciType* t2, ciTypeFlow* analyzer) {
 272   assert(t1 != t2, "checked in caller");
 273   if (t1->equals(top_type())) {
 274     return t2;
 275   } else if (t2->equals(top_type())) {
 276     return t1;
 277   } else if (t1->is_primitive_type() || t2->is_primitive_type()) {
 278     // Special case null_type.  null_type meet any reference type T
 279     // is T.  null_type meet null_type is null_type.
 280     if (t1->equals(null_type())) {
 281       if (!t2->is_primitive_type() || t2->equals(null_type())) {
 282         return t2;
 283       }
 284     } else if (t2->equals(null_type())) {
 285       if (!t1->is_primitive_type()) {
 286         return t1;
 287       }
 288     }
 289 
 290     // At least one of the two types is a non-top primitive type.
 291     // The other type is not equal to it.  Fall to bottom.
 292     return bottom_type();
 293   } else {
 294     // Both types are non-top non-primitive types.  That is,
 295     // both types are either instanceKlasses or arrayKlasses.
 296     ciKlass* object_klass = analyzer->env()->Object_klass();
 297     ciKlass* k1 = t1->as_klass();
 298     ciKlass* k2 = t2->as_klass();
 299     if (k1->equals(object_klass) || k2->equals(object_klass)) {
 300       return object_klass;
 301     } else if (!k1->is_loaded() || !k2->is_loaded()) {
 302       // Unloaded classes fall to java.lang.Object at a merge.
 303       return object_klass;
 304     } else if (k1->is_interface() != k2->is_interface()) {
 305       // When an interface meets a non-interface, we get Object;
 306       // This is what the verifier does.
 307       return object_klass;
 308     } else if (k1->is_array_klass() || k2->is_array_klass()) {
 309       // When an array meets a non-array, we get Object.
 310       // When objArray meets typeArray, we also get Object.
 311       // And when typeArray meets different typeArray, we again get Object.
 312       // But when objArray meets objArray, we look carefully at element types.
 313       if (k1->is_obj_array_klass() && k2->is_obj_array_klass()) {
 314         // Meet the element types, then construct the corresponding array type.
 315         ciKlass* elem1 = k1->as_obj_array_klass()->element_klass();
 316         ciKlass* elem2 = k2->as_obj_array_klass()->element_klass();
 317         ciKlass* elem  = type_meet_internal(elem1, elem2, analyzer)->as_klass();
 318         // Do an easy shortcut if one type is a super of the other.
 319         if (elem == elem1) {
 320           assert(k1 == ciObjArrayKlass::make(elem), "shortcut is OK");
 321           return k1;
 322         } else if (elem == elem2) {
 323           assert(k2 == ciObjArrayKlass::make(elem), "shortcut is OK");
 324           return k2;
 325         } else {
 326           return ciObjArrayKlass::make(elem);
 327         }
 328       } else {
 329         return object_klass;
 330       }
 331     } else {
 332       // Must be two plain old instance klasses.
 333       assert(k1->is_instance_klass(), "previous cases handle non-instances");
 334       assert(k2->is_instance_klass(), "previous cases handle non-instances");
 335       return k1->least_common_ancestor(k2);
 336     }
 337   }
 338 }
 339 
 340 
 341 // ------------------------------------------------------------------
 342 // ciTypeFlow::StateVector::StateVector
 343 //
 344 // Build a new state vector
 345 ciTypeFlow::StateVector::StateVector(ciTypeFlow* analyzer) {
 346   _outer = analyzer;
 347   _stack_size = -1;
 348   _monitor_count = -1;
 349   // Allocate the _types array
 350   int max_cells = analyzer->max_cells();
 351   _types = (ciType**)analyzer->arena()->Amalloc(sizeof(ciType*) * max_cells);
 352   for (int i=0; i<max_cells; i++) {
 353     _types[i] = top_type();
 354   }
 355   _trap_bci = -1;
 356   _trap_index = 0;
 357   _def_locals.clear();
 358 }
 359 
 360 
 361 // ------------------------------------------------------------------
 362 // ciTypeFlow::get_start_state
 363 //
 364 // Set this vector to the method entry state.
 365 const ciTypeFlow::StateVector* ciTypeFlow::get_start_state() {
 366   StateVector* state = new StateVector(this);
 367   if (is_osr_flow()) {
 368     ciTypeFlow* non_osr_flow = method()->get_flow_analysis();
 369     if (non_osr_flow->failing()) {
 370       record_failure(non_osr_flow->failure_reason());
 371       return NULL;
 372     }
 373     JsrSet* jsrs = new JsrSet(NULL, 16);
 374     Block* non_osr_block = non_osr_flow->existing_block_at(start_bci(), jsrs);
 375     if (non_osr_block == NULL) {
 376       record_failure("cannot reach OSR point");
 377       return NULL;
 378     }
 379     // load up the non-OSR state at this point
 380     non_osr_block->copy_state_into(state);
 381     int non_osr_start = non_osr_block->start();
 382     if (non_osr_start != start_bci()) {
 383       // must flow forward from it
 384       if (CITraceTypeFlow) {
 385         tty->print_cr(">> Interpreting pre-OSR block %d:", non_osr_start);
 386       }
 387       Block* block = block_at(non_osr_start, jsrs);
 388       assert(block->limit() == start_bci(), "must flow forward to start");
 389       flow_block(block, state, jsrs);
 390     }
 391     return state;
 392     // Note:  The code below would be an incorrect for an OSR flow,
 393     // even if it were possible for an OSR entry point to be at bci zero.
 394   }
 395   // "Push" the method signature into the first few locals.
 396   state->set_stack_size(-max_locals());
 397   if (!method()->is_static()) {
 398     state->push(method()->holder());
 399     assert(state->tos() == state->local(0), "");
 400   }
 401   for (ciSignatureStream str(method()->signature());
 402        !str.at_return_type();
 403        str.next()) {
 404     state->push_translate(str.type());
 405   }
 406   // Set the rest of the locals to bottom.
 407   Cell cell = state->next_cell(state->tos());
 408   state->set_stack_size(0);
 409   int limit = state->limit_cell();
 410   for (; cell < limit; cell = state->next_cell(cell)) {
 411     state->set_type_at(cell, state->bottom_type());
 412   }
 413   // Lock an object, if necessary.
 414   state->set_monitor_count(method()->is_synchronized() ? 1 : 0);
 415   return state;
 416 }
 417 
 418 // ------------------------------------------------------------------
 419 // ciTypeFlow::StateVector::copy_into
 420 //
 421 // Copy our value into some other StateVector
 422 void ciTypeFlow::StateVector::copy_into(ciTypeFlow::StateVector* copy)
 423 const {
 424   copy->set_stack_size(stack_size());
 425   copy->set_monitor_count(monitor_count());
 426   Cell limit = limit_cell();
 427   for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
 428     copy->set_type_at(c, type_at(c));
 429   }
 430 }
 431 
 432 // ------------------------------------------------------------------
 433 // ciTypeFlow::StateVector::meet
 434 //
 435 // Meets this StateVector with another, destructively modifying this
 436 // one.  Returns true if any modification takes place.
 437 bool ciTypeFlow::StateVector::meet(const ciTypeFlow::StateVector* incoming) {
 438   if (monitor_count() == -1) {
 439     set_monitor_count(incoming->monitor_count());
 440   }
 441   assert(monitor_count() == incoming->monitor_count(), "monitors must match");
 442 
 443   if (stack_size() == -1) {
 444     set_stack_size(incoming->stack_size());
 445     Cell limit = limit_cell();
 446     #ifdef ASSERT
 447     { for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
 448         assert(type_at(c) == top_type(), "");
 449     } }
 450     #endif
 451     // Make a simple copy of the incoming state.
 452     for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
 453       set_type_at(c, incoming->type_at(c));
 454     }
 455     return true;  // it is always different the first time
 456   }
 457 #ifdef ASSERT
 458   if (stack_size() != incoming->stack_size()) {
 459     _outer->method()->print_codes();
 460     tty->print_cr("!!!! Stack size conflict");
 461     tty->print_cr("Current state:");
 462     print_on(tty);
 463     tty->print_cr("Incoming state:");
 464     ((StateVector*)incoming)->print_on(tty);
 465   }
 466 #endif
 467   assert(stack_size() == incoming->stack_size(), "sanity");
 468 
 469   bool different = false;
 470   Cell limit = limit_cell();
 471   for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
 472     ciType* t1 = type_at(c);
 473     ciType* t2 = incoming->type_at(c);
 474     if (!t1->equals(t2)) {
 475       ciType* new_type = type_meet(t1, t2);
 476       if (!t1->equals(new_type)) {
 477         set_type_at(c, new_type);
 478         different = true;
 479       }
 480     }
 481   }
 482   return different;
 483 }
 484 
 485 // ------------------------------------------------------------------
 486 // ciTypeFlow::StateVector::meet_exception
 487 //
 488 // Meets this StateVector with another, destructively modifying this
 489 // one.  The incoming state is coming via an exception.  Returns true
 490 // if any modification takes place.
 491 bool ciTypeFlow::StateVector::meet_exception(ciInstanceKlass* exc,
 492                                      const ciTypeFlow::StateVector* incoming) {
 493   if (monitor_count() == -1) {
 494     set_monitor_count(incoming->monitor_count());
 495   }
 496   assert(monitor_count() == incoming->monitor_count(), "monitors must match");
 497 
 498   if (stack_size() == -1) {
 499     set_stack_size(1);
 500   }
 501 
 502   assert(stack_size() ==  1, "must have one-element stack");
 503 
 504   bool different = false;
 505 
 506   // Meet locals from incoming array.
 507   Cell limit = local(_outer->max_locals()-1);
 508   for (Cell c = start_cell(); c <= limit; c = next_cell(c)) {
 509     ciType* t1 = type_at(c);
 510     ciType* t2 = incoming->type_at(c);
 511     if (!t1->equals(t2)) {
 512       ciType* new_type = type_meet(t1, t2);
 513       if (!t1->equals(new_type)) {
 514         set_type_at(c, new_type);
 515         different = true;
 516       }
 517     }
 518   }
 519 
 520   // Handle stack separately.  When an exception occurs, the
 521   // only stack entry is the exception instance.
 522   ciType* tos_type = type_at_tos();
 523   if (!tos_type->equals(exc)) {
 524     ciType* new_type = type_meet(tos_type, exc);
 525     if (!tos_type->equals(new_type)) {
 526       set_type_at_tos(new_type);
 527       different = true;
 528     }
 529   }
 530 
 531   return different;
 532 }
 533 
 534 // ------------------------------------------------------------------
 535 // ciTypeFlow::StateVector::push_translate
 536 void ciTypeFlow::StateVector::push_translate(ciType* type) {
 537   BasicType basic_type = type->basic_type();
 538   if (basic_type == T_BOOLEAN || basic_type == T_CHAR ||
 539       basic_type == T_BYTE    || basic_type == T_SHORT) {
 540     push_int();
 541   } else {
 542     push(type);
 543     if (type->is_two_word()) {
 544       push(half_type(type));
 545     }
 546   }
 547 }
 548 
 549 // ------------------------------------------------------------------
 550 // ciTypeFlow::StateVector::do_aaload
 551 void ciTypeFlow::StateVector::do_aaload(ciBytecodeStream* str) {
 552   pop_int();
 553   ciObjArrayKlass* array_klass = pop_objArray();
 554   if (array_klass == NULL) {
 555     // Did aaload on a null reference; push a null and ignore the exception.
 556     // This instruction will never continue normally.  All we have to do
 557     // is report a value that will meet correctly with any downstream
 558     // reference types on paths that will truly be executed.  This null type
 559     // meets with any reference type to yield that same reference type.
 560     // (The compiler will generate an unconditional exception here.)
 561     push(null_type());
 562     return;
 563   }
 564   if (!array_klass->is_loaded()) {
 565     // Only fails for some -Xcomp runs
 566     trap(str, array_klass,
 567          Deoptimization::make_trap_request
 568          (Deoptimization::Reason_unloaded,
 569           Deoptimization::Action_reinterpret));
 570     return;
 571   }
 572   ciKlass* element_klass = array_klass->element_klass();
 573   if (!element_klass->is_loaded() && element_klass->is_instance_klass()) {
 574     Untested("unloaded array element class in ciTypeFlow");
 575     trap(str, element_klass,
 576          Deoptimization::make_trap_request
 577          (Deoptimization::Reason_unloaded,
 578           Deoptimization::Action_reinterpret));
 579   } else {
 580     push_object(element_klass);
 581   }
 582 }
 583 
 584 
 585 // ------------------------------------------------------------------
 586 // ciTypeFlow::StateVector::do_checkcast
 587 void ciTypeFlow::StateVector::do_checkcast(ciBytecodeStream* str) {
 588   bool will_link;
 589   ciKlass* klass = str->get_klass(will_link);
 590   if (!will_link) {
 591     // VM's interpreter will not load 'klass' if object is NULL.
 592     // Type flow after this block may still be needed in two situations:
 593     // 1) C2 uses do_null_assert() and continues compilation for later blocks
 594     // 2) C2 does an OSR compile in a later block (see bug 4778368).
 595     pop_object();
 596     do_null_assert(klass);
 597   } else {
 598     pop_object();
 599     push_object(klass);
 600   }
 601 }
 602 
 603 // ------------------------------------------------------------------
 604 // ciTypeFlow::StateVector::do_getfield
 605 void ciTypeFlow::StateVector::do_getfield(ciBytecodeStream* str) {
 606   // could add assert here for type of object.
 607   pop_object();
 608   do_getstatic(str);
 609 }
 610 
 611 // ------------------------------------------------------------------
 612 // ciTypeFlow::StateVector::do_getstatic
 613 void ciTypeFlow::StateVector::do_getstatic(ciBytecodeStream* str) {
 614   bool will_link;
 615   ciField* field = str->get_field(will_link);
 616   if (!will_link) {
 617     trap(str, field->holder(), str->get_field_holder_index());
 618   } else {
 619     ciType* field_type = field->type();
 620     if (!field_type->is_loaded()) {
 621       // Normally, we need the field's type to be loaded if we are to
 622       // do anything interesting with its value.
 623       // We used to do this:  trap(str, str->get_field_signature_index());
 624       //
 625       // There is one good reason not to trap here.  Execution can
 626       // get past this "getfield" or "getstatic" if the value of
 627       // the field is null.  As long as the value is null, the class
 628       // does not need to be loaded!  The compiler must assume that
 629       // the value of the unloaded class reference is null; if the code
 630       // ever sees a non-null value, loading has occurred.
 631       //
 632       // This actually happens often enough to be annoying.  If the
 633       // compiler throws an uncommon trap at this bytecode, you can
 634       // get an endless loop of recompilations, when all the code
 635       // needs to do is load a series of null values.  Also, a trap
 636       // here can make an OSR entry point unreachable, triggering the
 637       // assert on non_osr_block in ciTypeFlow::get_start_state.
 638       // (See bug 4379915.)
 639       do_null_assert(field_type->as_klass());
 640     } else {
 641       push_translate(field_type);
 642     }
 643   }
 644 }
 645 
 646 // ------------------------------------------------------------------
 647 // ciTypeFlow::StateVector::do_invoke
 648 void ciTypeFlow::StateVector::do_invoke(ciBytecodeStream* str,
 649                                         bool has_receiver) {
 650   bool will_link;
 651   ciSignature* declared_signature = NULL;
 652   ciMethod* callee = str->get_method(will_link, &declared_signature);
 653   assert(declared_signature != NULL, "cannot be null");
 654   if (!will_link) {
 655     // We weren't able to find the method.
 656     if (str->cur_bc() == Bytecodes::_invokedynamic) {
 657       trap(str, NULL,
 658            Deoptimization::make_trap_request
 659            (Deoptimization::Reason_uninitialized,
 660             Deoptimization::Action_reinterpret));
 661     } else {
 662       ciKlass* unloaded_holder = callee->holder();
 663       trap(str, unloaded_holder, str->get_method_holder_index());
 664     }
 665   } else {
 666     // We are using the declared signature here because it might be
 667     // different from the callee signature (Cf. invokedynamic and
 668     // invokehandle).
 669     ciSignatureStream sigstr(declared_signature);
 670     const int arg_size = declared_signature->size();
 671     const int stack_base = stack_size() - arg_size;
 672     int i = 0;
 673     for( ; !sigstr.at_return_type(); sigstr.next()) {
 674       ciType* type = sigstr.type();
 675       ciType* stack_type = type_at(stack(stack_base + i++));
 676       // Do I want to check this type?
 677       // assert(stack_type->is_subtype_of(type), "bad type for field value");
 678       if (type->is_two_word()) {
 679         ciType* stack_type2 = type_at(stack(stack_base + i++));
 680         assert(stack_type2->equals(half_type(type)), "must be 2nd half");
 681       }
 682     }
 683     assert(arg_size == i, "must match");
 684     for (int j = 0; j < arg_size; j++) {
 685       pop();
 686     }
 687     if (has_receiver) {
 688       // Check this?
 689       pop_object();
 690     }
 691     assert(!sigstr.is_done(), "must have return type");
 692     ciType* return_type = sigstr.type();
 693     if (!return_type->is_void()) {
 694       if (!return_type->is_loaded()) {
 695         // As in do_getstatic(), generally speaking, we need the return type to
 696         // be loaded if we are to do anything interesting with its value.
 697         // We used to do this:  trap(str, str->get_method_signature_index());
 698         //
 699         // We do not trap here since execution can get past this invoke if
 700         // the return value is null.  As long as the value is null, the class
 701         // does not need to be loaded!  The compiler must assume that
 702         // the value of the unloaded class reference is null; if the code
 703         // ever sees a non-null value, loading has occurred.
 704         //
 705         // See do_getstatic() for similar explanation, as well as bug 4684993.
 706         do_null_assert(return_type->as_klass());
 707       } else {
 708         push_translate(return_type);
 709       }
 710     }
 711   }
 712 }
 713 
 714 // ------------------------------------------------------------------
 715 // ciTypeFlow::StateVector::do_jsr
 716 void ciTypeFlow::StateVector::do_jsr(ciBytecodeStream* str) {
 717   push(ciReturnAddress::make(str->next_bci()));
 718 }
 719 
 720 // ------------------------------------------------------------------
 721 // ciTypeFlow::StateVector::do_ldc
 722 void ciTypeFlow::StateVector::do_ldc(ciBytecodeStream* str) {
 723   ciConstant con = str->get_constant();
 724   BasicType basic_type = con.basic_type();
 725   if (basic_type == T_ILLEGAL) {
 726     // OutOfMemoryError in the CI while loading constant
 727     push_null();
 728     outer()->record_failure("ldc did not link");
 729     return;
 730   }
 731   if (basic_type == T_OBJECT || basic_type == T_ARRAY) {
 732     ciObject* obj = con.as_object();
 733     if (obj->is_null_object()) {
 734       push_null();
 735     } else {
 736       assert(obj->is_instance() || obj->is_array(), "must be java_mirror of klass");
 737       push_object(obj->klass());
 738     }
 739   } else {
 740     push_translate(ciType::make(basic_type));
 741   }
 742 }
 743 
 744 // ------------------------------------------------------------------
 745 // ciTypeFlow::StateVector::do_multianewarray
 746 void ciTypeFlow::StateVector::do_multianewarray(ciBytecodeStream* str) {
 747   int dimensions = str->get_dimensions();
 748   bool will_link;
 749   ciArrayKlass* array_klass = str->get_klass(will_link)->as_array_klass();
 750   if (!will_link) {
 751     trap(str, array_klass, str->get_klass_index());
 752   } else {
 753     for (int i = 0; i < dimensions; i++) {
 754       pop_int();
 755     }
 756     push_object(array_klass);
 757   }
 758 }
 759 
 760 // ------------------------------------------------------------------
 761 // ciTypeFlow::StateVector::do_new
 762 void ciTypeFlow::StateVector::do_new(ciBytecodeStream* str) {
 763   bool will_link;
 764   ciKlass* klass = str->get_klass(will_link);
 765   if (!will_link || str->is_unresolved_klass()) {
 766     trap(str, klass, str->get_klass_index());
 767   } else {
 768     push_object(klass);
 769   }
 770 }
 771 
 772 // ------------------------------------------------------------------
 773 // ciTypeFlow::StateVector::do_newarray
 774 void ciTypeFlow::StateVector::do_newarray(ciBytecodeStream* str) {
 775   pop_int();
 776   ciKlass* klass = ciTypeArrayKlass::make((BasicType)str->get_index());
 777   push_object(klass);
 778 }
 779 
 780 // ------------------------------------------------------------------
 781 // ciTypeFlow::StateVector::do_putfield
 782 void ciTypeFlow::StateVector::do_putfield(ciBytecodeStream* str) {
 783   do_putstatic(str);
 784   if (_trap_bci != -1)  return;  // unloaded field holder, etc.
 785   // could add assert here for type of object.
 786   pop_object();
 787 }
 788 
 789 // ------------------------------------------------------------------
 790 // ciTypeFlow::StateVector::do_putstatic
 791 void ciTypeFlow::StateVector::do_putstatic(ciBytecodeStream* str) {
 792   bool will_link;
 793   ciField* field = str->get_field(will_link);
 794   if (!will_link) {
 795     trap(str, field->holder(), str->get_field_holder_index());
 796   } else {
 797     ciType* field_type = field->type();
 798     ciType* type = pop_value();
 799     // Do I want to check this type?
 800     //      assert(type->is_subtype_of(field_type), "bad type for field value");
 801     if (field_type->is_two_word()) {
 802       ciType* type2 = pop_value();
 803       assert(type2->is_two_word(), "must be 2nd half");
 804       assert(type == half_type(type2), "must be 2nd half");
 805     }
 806   }
 807 }
 808 
 809 // ------------------------------------------------------------------
 810 // ciTypeFlow::StateVector::do_ret
 811 void ciTypeFlow::StateVector::do_ret(ciBytecodeStream* str) {
 812   Cell index = local(str->get_index());
 813 
 814   ciType* address = type_at(index);
 815   assert(address->is_return_address(), "bad return address");
 816   set_type_at(index, bottom_type());
 817 }
 818 
 819 // ------------------------------------------------------------------
 820 // ciTypeFlow::StateVector::trap
 821 //
 822 // Stop interpretation of this path with a trap.
 823 void ciTypeFlow::StateVector::trap(ciBytecodeStream* str, ciKlass* klass, int index) {
 824   _trap_bci = str->cur_bci();
 825   _trap_index = index;
 826 
 827   // Log information about this trap:
 828   CompileLog* log = outer()->env()->log();
 829   if (log != NULL) {
 830     int mid = log->identify(outer()->method());
 831     int kid = (klass == NULL)? -1: log->identify(klass);
 832     log->begin_elem("uncommon_trap method='%d' bci='%d'", mid, str->cur_bci());
 833     char buf[100];
 834     log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
 835                                                           index));
 836     if (kid >= 0)
 837       log->print(" klass='%d'", kid);
 838     log->end_elem();
 839   }
 840 }
 841 
 842 // ------------------------------------------------------------------
 843 // ciTypeFlow::StateVector::do_null_assert
 844 // Corresponds to graphKit::do_null_assert.
 845 void ciTypeFlow::StateVector::do_null_assert(ciKlass* unloaded_klass) {
 846   if (unloaded_klass->is_loaded()) {
 847     // We failed to link, but we can still compute with this class,
 848     // since it is loaded somewhere.  The compiler will uncommon_trap
 849     // if the object is not null, but the typeflow pass can not assume
 850     // that the object will be null, otherwise it may incorrectly tell
 851     // the parser that an object is known to be null. 4761344, 4807707
 852     push_object(unloaded_klass);
 853   } else {
 854     // The class is not loaded anywhere.  It is safe to model the
 855     // null in the typestates, because we can compile in a null check
 856     // which will deoptimize us if someone manages to load the
 857     // class later.
 858     push_null();
 859   }
 860 }
 861 
 862 
 863 // ------------------------------------------------------------------
 864 // ciTypeFlow::StateVector::apply_one_bytecode
 865 //
 866 // Apply the effect of one bytecode to this StateVector
 867 bool ciTypeFlow::StateVector::apply_one_bytecode(ciBytecodeStream* str) {
 868   _trap_bci = -1;
 869   _trap_index = 0;
 870 
 871   if (CITraceTypeFlow) {
 872     tty->print_cr(">> Interpreting bytecode %d:%s", str->cur_bci(),
 873                   Bytecodes::name(str->cur_bc()));
 874   }
 875 
 876   switch(str->cur_bc()) {
 877   case Bytecodes::_aaload: do_aaload(str);                       break;
 878 
 879   case Bytecodes::_aastore:
 880     {
 881       pop_object();
 882       pop_int();
 883       pop_objArray();
 884       break;
 885     }
 886   case Bytecodes::_aconst_null:
 887     {
 888       push_null();
 889       break;
 890     }
 891   case Bytecodes::_aload:   load_local_object(str->get_index());    break;
 892   case Bytecodes::_aload_0: load_local_object(0);                   break;
 893   case Bytecodes::_aload_1: load_local_object(1);                   break;
 894   case Bytecodes::_aload_2: load_local_object(2);                   break;
 895   case Bytecodes::_aload_3: load_local_object(3);                   break;
 896 
 897   case Bytecodes::_anewarray:
 898     {
 899       pop_int();
 900       bool will_link;
 901       ciKlass* element_klass = str->get_klass(will_link);
 902       if (!will_link) {
 903         trap(str, element_klass, str->get_klass_index());
 904       } else {
 905         push_object(ciObjArrayKlass::make(element_klass));
 906       }
 907       break;
 908     }
 909   case Bytecodes::_areturn:
 910   case Bytecodes::_ifnonnull:
 911   case Bytecodes::_ifnull:
 912     {
 913       pop_object();
 914       break;
 915     }
 916   case Bytecodes::_monitorenter:
 917     {
 918       pop_object();
 919       set_monitor_count(monitor_count() + 1);
 920       break;
 921     }
 922   case Bytecodes::_monitorexit:
 923     {
 924       pop_object();
 925       assert(monitor_count() > 0, "must be a monitor to exit from");
 926       set_monitor_count(monitor_count() - 1);
 927       break;
 928     }
 929   case Bytecodes::_arraylength:
 930     {
 931       pop_array();
 932       push_int();
 933       break;
 934     }
 935   case Bytecodes::_astore:   store_local_object(str->get_index());  break;
 936   case Bytecodes::_astore_0: store_local_object(0);                 break;
 937   case Bytecodes::_astore_1: store_local_object(1);                 break;
 938   case Bytecodes::_astore_2: store_local_object(2);                 break;
 939   case Bytecodes::_astore_3: store_local_object(3);                 break;
 940 
 941   case Bytecodes::_athrow:
 942     {
 943       NEEDS_CLEANUP;
 944       pop_object();
 945       break;
 946     }
 947   case Bytecodes::_baload:
 948   case Bytecodes::_caload:
 949   case Bytecodes::_iaload:
 950   case Bytecodes::_saload:
 951     {
 952       pop_int();
 953       ciTypeArrayKlass* array_klass = pop_typeArray();
 954       // Put assert here for right type?
 955       push_int();
 956       break;
 957     }
 958   case Bytecodes::_bastore:
 959   case Bytecodes::_castore:
 960   case Bytecodes::_iastore:
 961   case Bytecodes::_sastore:
 962     {
 963       pop_int();
 964       pop_int();
 965       pop_typeArray();
 966       // assert here?
 967       break;
 968     }
 969   case Bytecodes::_bipush:
 970   case Bytecodes::_iconst_m1:
 971   case Bytecodes::_iconst_0:
 972   case Bytecodes::_iconst_1:
 973   case Bytecodes::_iconst_2:
 974   case Bytecodes::_iconst_3:
 975   case Bytecodes::_iconst_4:
 976   case Bytecodes::_iconst_5:
 977   case Bytecodes::_sipush:
 978     {
 979       push_int();
 980       break;
 981     }
 982   case Bytecodes::_checkcast: do_checkcast(str);                  break;
 983 
 984   case Bytecodes::_d2f:
 985     {
 986       pop_double();
 987       push_float();
 988       break;
 989     }
 990   case Bytecodes::_d2i:
 991     {
 992       pop_double();
 993       push_int();
 994       break;
 995     }
 996   case Bytecodes::_d2l:
 997     {
 998       pop_double();
 999       push_long();
1000       break;
1001     }
1002   case Bytecodes::_dadd:
1003   case Bytecodes::_ddiv:
1004   case Bytecodes::_dmul:
1005   case Bytecodes::_drem:
1006   case Bytecodes::_dsub:
1007     {
1008       pop_double();
1009       pop_double();
1010       push_double();
1011       break;
1012     }
1013   case Bytecodes::_daload:
1014     {
1015       pop_int();
1016       ciTypeArrayKlass* array_klass = pop_typeArray();
1017       // Put assert here for right type?
1018       push_double();
1019       break;
1020     }
1021   case Bytecodes::_dastore:
1022     {
1023       pop_double();
1024       pop_int();
1025       pop_typeArray();
1026       // assert here?
1027       break;
1028     }
1029   case Bytecodes::_dcmpg:
1030   case Bytecodes::_dcmpl:
1031     {
1032       pop_double();
1033       pop_double();
1034       push_int();
1035       break;
1036     }
1037   case Bytecodes::_dconst_0:
1038   case Bytecodes::_dconst_1:
1039     {
1040       push_double();
1041       break;
1042     }
1043   case Bytecodes::_dload:   load_local_double(str->get_index());    break;
1044   case Bytecodes::_dload_0: load_local_double(0);                   break;
1045   case Bytecodes::_dload_1: load_local_double(1);                   break;
1046   case Bytecodes::_dload_2: load_local_double(2);                   break;
1047   case Bytecodes::_dload_3: load_local_double(3);                   break;
1048 
1049   case Bytecodes::_dneg:
1050     {
1051       pop_double();
1052       push_double();
1053       break;
1054     }
1055   case Bytecodes::_dreturn:
1056     {
1057       pop_double();
1058       break;
1059     }
1060   case Bytecodes::_dstore:   store_local_double(str->get_index());  break;
1061   case Bytecodes::_dstore_0: store_local_double(0);                 break;
1062   case Bytecodes::_dstore_1: store_local_double(1);                 break;
1063   case Bytecodes::_dstore_2: store_local_double(2);                 break;
1064   case Bytecodes::_dstore_3: store_local_double(3);                 break;
1065 
1066   case Bytecodes::_dup:
1067     {
1068       push(type_at_tos());
1069       break;
1070     }
1071   case Bytecodes::_dup_x1:
1072     {
1073       ciType* value1 = pop_value();
1074       ciType* value2 = pop_value();
1075       push(value1);
1076       push(value2);
1077       push(value1);
1078       break;
1079     }
1080   case Bytecodes::_dup_x2:
1081     {
1082       ciType* value1 = pop_value();
1083       ciType* value2 = pop_value();
1084       ciType* value3 = pop_value();
1085       push(value1);
1086       push(value3);
1087       push(value2);
1088       push(value1);
1089       break;
1090     }
1091   case Bytecodes::_dup2:
1092     {
1093       ciType* value1 = pop_value();
1094       ciType* value2 = pop_value();
1095       push(value2);
1096       push(value1);
1097       push(value2);
1098       push(value1);
1099       break;
1100     }
1101   case Bytecodes::_dup2_x1:
1102     {
1103       ciType* value1 = pop_value();
1104       ciType* value2 = pop_value();
1105       ciType* value3 = pop_value();
1106       push(value2);
1107       push(value1);
1108       push(value3);
1109       push(value2);
1110       push(value1);
1111       break;
1112     }
1113   case Bytecodes::_dup2_x2:
1114     {
1115       ciType* value1 = pop_value();
1116       ciType* value2 = pop_value();
1117       ciType* value3 = pop_value();
1118       ciType* value4 = pop_value();
1119       push(value2);
1120       push(value1);
1121       push(value4);
1122       push(value3);
1123       push(value2);
1124       push(value1);
1125       break;
1126     }
1127   case Bytecodes::_f2d:
1128     {
1129       pop_float();
1130       push_double();
1131       break;
1132     }
1133   case Bytecodes::_f2i:
1134     {
1135       pop_float();
1136       push_int();
1137       break;
1138     }
1139   case Bytecodes::_f2l:
1140     {
1141       pop_float();
1142       push_long();
1143       break;
1144     }
1145   case Bytecodes::_fadd:
1146   case Bytecodes::_fdiv:
1147   case Bytecodes::_fmul:
1148   case Bytecodes::_frem:
1149   case Bytecodes::_fsub:
1150     {
1151       pop_float();
1152       pop_float();
1153       push_float();
1154       break;
1155     }
1156   case Bytecodes::_faload:
1157     {
1158       pop_int();
1159       ciTypeArrayKlass* array_klass = pop_typeArray();
1160       // Put assert here.
1161       push_float();
1162       break;
1163     }
1164   case Bytecodes::_fastore:
1165     {
1166       pop_float();
1167       pop_int();
1168       ciTypeArrayKlass* array_klass = pop_typeArray();
1169       // Put assert here.
1170       break;
1171     }
1172   case Bytecodes::_fcmpg:
1173   case Bytecodes::_fcmpl:
1174     {
1175       pop_float();
1176       pop_float();
1177       push_int();
1178       break;
1179     }
1180   case Bytecodes::_fconst_0:
1181   case Bytecodes::_fconst_1:
1182   case Bytecodes::_fconst_2:
1183     {
1184       push_float();
1185       break;
1186     }
1187   case Bytecodes::_fload:   load_local_float(str->get_index());     break;
1188   case Bytecodes::_fload_0: load_local_float(0);                    break;
1189   case Bytecodes::_fload_1: load_local_float(1);                    break;
1190   case Bytecodes::_fload_2: load_local_float(2);                    break;
1191   case Bytecodes::_fload_3: load_local_float(3);                    break;
1192 
1193   case Bytecodes::_fneg:
1194     {
1195       pop_float();
1196       push_float();
1197       break;
1198     }
1199   case Bytecodes::_freturn:
1200     {
1201       pop_float();
1202       break;
1203     }
1204   case Bytecodes::_fstore:    store_local_float(str->get_index());   break;
1205   case Bytecodes::_fstore_0:  store_local_float(0);                  break;
1206   case Bytecodes::_fstore_1:  store_local_float(1);                  break;
1207   case Bytecodes::_fstore_2:  store_local_float(2);                  break;
1208   case Bytecodes::_fstore_3:  store_local_float(3);                  break;
1209 
1210   case Bytecodes::_getfield:  do_getfield(str);                      break;
1211   case Bytecodes::_getstatic: do_getstatic(str);                     break;
1212 
1213   case Bytecodes::_goto:
1214   case Bytecodes::_goto_w:
1215   case Bytecodes::_nop:
1216   case Bytecodes::_return:
1217     {
1218       // do nothing.
1219       break;
1220     }
1221   case Bytecodes::_i2b:
1222   case Bytecodes::_i2c:
1223   case Bytecodes::_i2s:
1224   case Bytecodes::_ineg:
1225     {
1226       pop_int();
1227       push_int();
1228       break;
1229     }
1230   case Bytecodes::_i2d:
1231     {
1232       pop_int();
1233       push_double();
1234       break;
1235     }
1236   case Bytecodes::_i2f:
1237     {
1238       pop_int();
1239       push_float();
1240       break;
1241     }
1242   case Bytecodes::_i2l:
1243     {
1244       pop_int();
1245       push_long();
1246       break;
1247     }
1248   case Bytecodes::_iadd:
1249   case Bytecodes::_iand:
1250   case Bytecodes::_idiv:
1251   case Bytecodes::_imul:
1252   case Bytecodes::_ior:
1253   case Bytecodes::_irem:
1254   case Bytecodes::_ishl:
1255   case Bytecodes::_ishr:
1256   case Bytecodes::_isub:
1257   case Bytecodes::_iushr:
1258   case Bytecodes::_ixor:
1259     {
1260       pop_int();
1261       pop_int();
1262       push_int();
1263       break;
1264     }
1265   case Bytecodes::_if_acmpeq:
1266   case Bytecodes::_if_acmpne:
1267     {
1268       pop_object();
1269       pop_object();
1270       break;
1271     }
1272   case Bytecodes::_if_icmpeq:
1273   case Bytecodes::_if_icmpge:
1274   case Bytecodes::_if_icmpgt:
1275   case Bytecodes::_if_icmple:
1276   case Bytecodes::_if_icmplt:
1277   case Bytecodes::_if_icmpne:
1278     {
1279       pop_int();
1280       pop_int();
1281       break;
1282     }
1283   case Bytecodes::_ifeq:
1284   case Bytecodes::_ifle:
1285   case Bytecodes::_iflt:
1286   case Bytecodes::_ifge:
1287   case Bytecodes::_ifgt:
1288   case Bytecodes::_ifne:
1289   case Bytecodes::_ireturn:
1290   case Bytecodes::_lookupswitch:
1291   case Bytecodes::_tableswitch:
1292     {
1293       pop_int();
1294       break;
1295     }
1296   case Bytecodes::_iinc:
1297     {
1298       int lnum = str->get_index();
1299       check_int(local(lnum));
1300       store_to_local(lnum);
1301       break;
1302     }
1303   case Bytecodes::_iload:   load_local_int(str->get_index()); break;
1304   case Bytecodes::_iload_0: load_local_int(0);                      break;
1305   case Bytecodes::_iload_1: load_local_int(1);                      break;
1306   case Bytecodes::_iload_2: load_local_int(2);                      break;
1307   case Bytecodes::_iload_3: load_local_int(3);                      break;
1308 
1309   case Bytecodes::_instanceof:
1310     {
1311       // Check for uncommon trap:
1312       do_checkcast(str);
1313       pop_object();
1314       push_int();
1315       break;
1316     }
1317   case Bytecodes::_invokeinterface: do_invoke(str, true);           break;
1318   case Bytecodes::_invokespecial:   do_invoke(str, true);           break;
1319   case Bytecodes::_invokestatic:    do_invoke(str, false);          break;
1320   case Bytecodes::_invokevirtual:   do_invoke(str, true);           break;
1321   case Bytecodes::_invokedynamic:   do_invoke(str, false);          break;
1322 
1323   case Bytecodes::_istore:   store_local_int(str->get_index());     break;
1324   case Bytecodes::_istore_0: store_local_int(0);                    break;
1325   case Bytecodes::_istore_1: store_local_int(1);                    break;
1326   case Bytecodes::_istore_2: store_local_int(2);                    break;
1327   case Bytecodes::_istore_3: store_local_int(3);                    break;
1328 
1329   case Bytecodes::_jsr:
1330   case Bytecodes::_jsr_w: do_jsr(str);                              break;
1331 
1332   case Bytecodes::_l2d:
1333     {
1334       pop_long();
1335       push_double();
1336       break;
1337     }
1338   case Bytecodes::_l2f:
1339     {
1340       pop_long();
1341       push_float();
1342       break;
1343     }
1344   case Bytecodes::_l2i:
1345     {
1346       pop_long();
1347       push_int();
1348       break;
1349     }
1350   case Bytecodes::_ladd:
1351   case Bytecodes::_land:
1352   case Bytecodes::_ldiv:
1353   case Bytecodes::_lmul:
1354   case Bytecodes::_lor:
1355   case Bytecodes::_lrem:
1356   case Bytecodes::_lsub:
1357   case Bytecodes::_lxor:
1358     {
1359       pop_long();
1360       pop_long();
1361       push_long();
1362       break;
1363     }
1364   case Bytecodes::_laload:
1365     {
1366       pop_int();
1367       ciTypeArrayKlass* array_klass = pop_typeArray();
1368       // Put assert here for right type?
1369       push_long();
1370       break;
1371     }
1372   case Bytecodes::_lastore:
1373     {
1374       pop_long();
1375       pop_int();
1376       pop_typeArray();
1377       // assert here?
1378       break;
1379     }
1380   case Bytecodes::_lcmp:
1381     {
1382       pop_long();
1383       pop_long();
1384       push_int();
1385       break;
1386     }
1387   case Bytecodes::_lconst_0:
1388   case Bytecodes::_lconst_1:
1389     {
1390       push_long();
1391       break;
1392     }
1393   case Bytecodes::_ldc:
1394   case Bytecodes::_ldc_w:
1395   case Bytecodes::_ldc2_w:
1396     {
1397       do_ldc(str);
1398       break;
1399     }
1400 
1401   case Bytecodes::_lload:   load_local_long(str->get_index());      break;
1402   case Bytecodes::_lload_0: load_local_long(0);                     break;
1403   case Bytecodes::_lload_1: load_local_long(1);                     break;
1404   case Bytecodes::_lload_2: load_local_long(2);                     break;
1405   case Bytecodes::_lload_3: load_local_long(3);                     break;
1406 
1407   case Bytecodes::_lneg:
1408     {
1409       pop_long();
1410       push_long();
1411       break;
1412     }
1413   case Bytecodes::_lreturn:
1414     {
1415       pop_long();
1416       break;
1417     }
1418   case Bytecodes::_lshl:
1419   case Bytecodes::_lshr:
1420   case Bytecodes::_lushr:
1421     {
1422       pop_int();
1423       pop_long();
1424       push_long();
1425       break;
1426     }
1427   case Bytecodes::_lstore:   store_local_long(str->get_index());    break;
1428   case Bytecodes::_lstore_0: store_local_long(0);                   break;
1429   case Bytecodes::_lstore_1: store_local_long(1);                   break;
1430   case Bytecodes::_lstore_2: store_local_long(2);                   break;
1431   case Bytecodes::_lstore_3: store_local_long(3);                   break;
1432 
1433   case Bytecodes::_multianewarray: do_multianewarray(str);          break;
1434 
1435   case Bytecodes::_new:      do_new(str);                           break;
1436 
1437   case Bytecodes::_newarray: do_newarray(str);                      break;
1438 
1439   case Bytecodes::_pop:
1440     {
1441       pop();
1442       break;
1443     }
1444   case Bytecodes::_pop2:
1445     {
1446       pop();
1447       pop();
1448       break;
1449     }
1450 
1451   case Bytecodes::_putfield:       do_putfield(str);                 break;
1452   case Bytecodes::_putstatic:      do_putstatic(str);                break;
1453 
1454   case Bytecodes::_ret: do_ret(str);                                 break;
1455 
1456   case Bytecodes::_swap:
1457     {
1458       ciType* value1 = pop_value();
1459       ciType* value2 = pop_value();
1460       push(value1);
1461       push(value2);
1462       break;
1463     }
1464   case Bytecodes::_wide:
1465   default:
1466     {
1467       // The iterator should skip this.
1468       ShouldNotReachHere();
1469       break;
1470     }
1471   }
1472 
1473   if (CITraceTypeFlow) {
1474     print_on(tty);
1475   }
1476 
1477   return (_trap_bci != -1);
1478 }
1479 
1480 #ifndef PRODUCT
1481 // ------------------------------------------------------------------
1482 // ciTypeFlow::StateVector::print_cell_on
1483 void ciTypeFlow::StateVector::print_cell_on(outputStream* st, Cell c) const {
1484   ciType* type = type_at(c);
1485   if (type == top_type()) {
1486     st->print("top");
1487   } else if (type == bottom_type()) {
1488     st->print("bottom");
1489   } else if (type == null_type()) {
1490     st->print("null");
1491   } else if (type == long2_type()) {
1492     st->print("long2");
1493   } else if (type == double2_type()) {
1494     st->print("double2");
1495   } else if (is_int(type)) {
1496     st->print("int");
1497   } else if (is_long(type)) {
1498     st->print("long");
1499   } else if (is_float(type)) {
1500     st->print("float");
1501   } else if (is_double(type)) {
1502     st->print("double");
1503   } else if (type->is_return_address()) {
1504     st->print("address(%d)", type->as_return_address()->bci());
1505   } else {
1506     if (type->is_klass()) {
1507       type->as_klass()->name()->print_symbol_on(st);
1508     } else {
1509       st->print("UNEXPECTED TYPE");
1510       type->print();
1511     }
1512   }
1513 }
1514 
1515 // ------------------------------------------------------------------
1516 // ciTypeFlow::StateVector::print_on
1517 void ciTypeFlow::StateVector::print_on(outputStream* st) const {
1518   int num_locals   = _outer->max_locals();
1519   int num_stack    = stack_size();
1520   int num_monitors = monitor_count();
1521   st->print_cr("  State : locals %d, stack %d, monitors %d", num_locals, num_stack, num_monitors);
1522   if (num_stack >= 0) {
1523     int i;
1524     for (i = 0; i < num_locals; i++) {
1525       st->print("    local %2d : ", i);
1526       print_cell_on(st, local(i));
1527       st->cr();
1528     }
1529     for (i = 0; i < num_stack; i++) {
1530       st->print("    stack %2d : ", i);
1531       print_cell_on(st, stack(i));
1532       st->cr();
1533     }
1534   }
1535 }
1536 #endif
1537 
1538 
1539 // ------------------------------------------------------------------
1540 // ciTypeFlow::SuccIter::next
1541 //
1542 void ciTypeFlow::SuccIter::next() {
1543   int succ_ct = _pred->successors()->length();
1544   int next = _index + 1;
1545   if (next < succ_ct) {
1546     _index = next;
1547     _succ = _pred->successors()->at(next);
1548     return;
1549   }
1550   for (int i = next - succ_ct; i < _pred->exceptions()->length(); i++) {
1551     // Do not compile any code for unloaded exception types.
1552     // Following compiler passes are responsible for doing this also.
1553     ciInstanceKlass* exception_klass = _pred->exc_klasses()->at(i);
1554     if (exception_klass->is_loaded()) {
1555       _index = next;
1556       _succ = _pred->exceptions()->at(i);
1557       return;
1558     }
1559     next++;
1560   }
1561   _index = -1;
1562   _succ = NULL;
1563 }
1564 
1565 // ------------------------------------------------------------------
1566 // ciTypeFlow::SuccIter::set_succ
1567 //
1568 void ciTypeFlow::SuccIter::set_succ(Block* succ) {
1569   int succ_ct = _pred->successors()->length();
1570   if (_index < succ_ct) {
1571     _pred->successors()->at_put(_index, succ);
1572   } else {
1573     int idx = _index - succ_ct;
1574     _pred->exceptions()->at_put(idx, succ);
1575   }
1576 }
1577 
1578 // ciTypeFlow::Block
1579 //
1580 // A basic block.
1581 
1582 // ------------------------------------------------------------------
1583 // ciTypeFlow::Block::Block
1584 ciTypeFlow::Block::Block(ciTypeFlow* outer,
1585                          ciBlock *ciblk,
1586                          ciTypeFlow::JsrSet* jsrs) {
1587   _ciblock = ciblk;
1588   _exceptions = NULL;
1589   _exc_klasses = NULL;
1590   _successors = NULL;
1591   _predecessors = new (outer->arena()) GrowableArray<Block*>(outer->arena(), 1, 0, NULL);
1592   _state = new (outer->arena()) StateVector(outer);
1593   JsrSet* new_jsrs =
1594     new (outer->arena()) JsrSet(outer->arena(), jsrs->size());
1595   jsrs->copy_into(new_jsrs);
1596   _jsrs = new_jsrs;
1597   _next = NULL;
1598   _on_work_list = false;
1599   _backedge_copy = false;
1600   _has_monitorenter = false;
1601   _trap_bci = -1;
1602   _trap_index = 0;
1603   df_init();
1604 
1605   if (CITraceTypeFlow) {
1606     tty->print_cr(">> Created new block");
1607     print_on(tty);
1608   }
1609 
1610   assert(this->outer() == outer, "outer link set up");
1611   assert(!outer->have_block_count(), "must not have mapped blocks yet");
1612 }
1613 
1614 // ------------------------------------------------------------------
1615 // ciTypeFlow::Block::df_init
1616 void ciTypeFlow::Block::df_init() {
1617   _pre_order = -1; assert(!has_pre_order(), "");
1618   _post_order = -1; assert(!has_post_order(), "");
1619   _loop = NULL;
1620   _irreducible_entry = false;
1621   _rpo_next = NULL;
1622 }
1623 
1624 // ------------------------------------------------------------------
1625 // ciTypeFlow::Block::successors
1626 //
1627 // Get the successors for this Block.
1628 GrowableArray<ciTypeFlow::Block*>*
1629 ciTypeFlow::Block::successors(ciBytecodeStream* str,
1630                               ciTypeFlow::StateVector* state,
1631                               ciTypeFlow::JsrSet* jsrs) {
1632   if (_successors == NULL) {
1633     if (CITraceTypeFlow) {
1634       tty->print(">> Computing successors for block ");
1635       print_value_on(tty);
1636       tty->cr();
1637     }
1638 
1639     ciTypeFlow* analyzer = outer();
1640     Arena* arena = analyzer->arena();
1641     Block* block = NULL;
1642     bool has_successor = !has_trap() &&
1643                          (control() != ciBlock::fall_through_bci || limit() < analyzer->code_size());
1644     if (!has_successor) {
1645       _successors =
1646         new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1647       // No successors
1648     } else if (control() == ciBlock::fall_through_bci) {
1649       assert(str->cur_bci() == limit(), "bad block end");
1650       // This block simply falls through to the next.
1651       _successors =
1652         new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1653 
1654       Block* block = analyzer->block_at(limit(), _jsrs);
1655       assert(_successors->length() == FALL_THROUGH, "");
1656       _successors->append(block);
1657     } else {
1658       int current_bci = str->cur_bci();
1659       int next_bci = str->next_bci();
1660       int branch_bci = -1;
1661       Block* target = NULL;
1662       assert(str->next_bci() == limit(), "bad block end");
1663       // This block is not a simple fall-though.  Interpret
1664       // the current bytecode to find our successors.
1665       switch (str->cur_bc()) {
1666       case Bytecodes::_ifeq:         case Bytecodes::_ifne:
1667       case Bytecodes::_iflt:         case Bytecodes::_ifge:
1668       case Bytecodes::_ifgt:         case Bytecodes::_ifle:
1669       case Bytecodes::_if_icmpeq:    case Bytecodes::_if_icmpne:
1670       case Bytecodes::_if_icmplt:    case Bytecodes::_if_icmpge:
1671       case Bytecodes::_if_icmpgt:    case Bytecodes::_if_icmple:
1672       case Bytecodes::_if_acmpeq:    case Bytecodes::_if_acmpne:
1673       case Bytecodes::_ifnull:       case Bytecodes::_ifnonnull:
1674         // Our successors are the branch target and the next bci.
1675         branch_bci = str->get_dest();
1676         _successors =
1677           new (arena) GrowableArray<Block*>(arena, 2, 0, NULL);
1678         assert(_successors->length() == IF_NOT_TAKEN, "");
1679         _successors->append(analyzer->block_at(next_bci, jsrs));
1680         assert(_successors->length() == IF_TAKEN, "");
1681         _successors->append(analyzer->block_at(branch_bci, jsrs));
1682         break;
1683 
1684       case Bytecodes::_goto:
1685         branch_bci = str->get_dest();
1686         _successors =
1687           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1688         assert(_successors->length() == GOTO_TARGET, "");
1689         _successors->append(analyzer->block_at(branch_bci, jsrs));
1690         break;
1691 
1692       case Bytecodes::_jsr:
1693         branch_bci = str->get_dest();
1694         _successors =
1695           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1696         assert(_successors->length() == GOTO_TARGET, "");
1697         _successors->append(analyzer->block_at(branch_bci, jsrs));
1698         break;
1699 
1700       case Bytecodes::_goto_w:
1701       case Bytecodes::_jsr_w:
1702         _successors =
1703           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1704         assert(_successors->length() == GOTO_TARGET, "");
1705         _successors->append(analyzer->block_at(str->get_far_dest(), jsrs));
1706         break;
1707 
1708       case Bytecodes::_tableswitch:  {
1709         Bytecode_tableswitch tableswitch(str);
1710 
1711         int len = tableswitch.length();
1712         _successors =
1713           new (arena) GrowableArray<Block*>(arena, len+1, 0, NULL);
1714         int bci = current_bci + tableswitch.default_offset();
1715         Block* block = analyzer->block_at(bci, jsrs);
1716         assert(_successors->length() == SWITCH_DEFAULT, "");
1717         _successors->append(block);
1718         while (--len >= 0) {
1719           int bci = current_bci + tableswitch.dest_offset_at(len);
1720           block = analyzer->block_at(bci, jsrs);
1721           assert(_successors->length() >= SWITCH_CASES, "");
1722           _successors->append_if_missing(block);
1723         }
1724         break;
1725       }
1726 
1727       case Bytecodes::_lookupswitch: {
1728         Bytecode_lookupswitch lookupswitch(str);
1729 
1730         int npairs = lookupswitch.number_of_pairs();
1731         _successors =
1732           new (arena) GrowableArray<Block*>(arena, npairs+1, 0, NULL);
1733         int bci = current_bci + lookupswitch.default_offset();
1734         Block* block = analyzer->block_at(bci, jsrs);
1735         assert(_successors->length() == SWITCH_DEFAULT, "");
1736         _successors->append(block);
1737         while(--npairs >= 0) {
1738           LookupswitchPair pair = lookupswitch.pair_at(npairs);
1739           int bci = current_bci + pair.offset();
1740           Block* block = analyzer->block_at(bci, jsrs);
1741           assert(_successors->length() >= SWITCH_CASES, "");
1742           _successors->append_if_missing(block);
1743         }
1744         break;
1745       }
1746 
1747       case Bytecodes::_athrow:     case Bytecodes::_ireturn:
1748       case Bytecodes::_lreturn:    case Bytecodes::_freturn:
1749       case Bytecodes::_dreturn:    case Bytecodes::_areturn:
1750       case Bytecodes::_return:
1751         _successors =
1752           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1753         // No successors
1754         break;
1755 
1756       case Bytecodes::_ret: {
1757         _successors =
1758           new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
1759 
1760         Cell local = state->local(str->get_index());
1761         ciType* return_address = state->type_at(local);
1762         assert(return_address->is_return_address(), "verify: wrong type");
1763         int bci = return_address->as_return_address()->bci();
1764         assert(_successors->length() == GOTO_TARGET, "");
1765         _successors->append(analyzer->block_at(bci, jsrs));
1766         break;
1767       }
1768 
1769       case Bytecodes::_wide:
1770       default:
1771         ShouldNotReachHere();
1772         break;
1773       }
1774     }
1775 
1776     // Set predecessor information
1777     for (int i = 0; i < _successors->length(); i++) {
1778       Block* block = _successors->at(i);
1779       block->predecessors()->append(this);
1780     }
1781   }
1782   return _successors;
1783 }
1784 
1785 // ------------------------------------------------------------------
1786 // ciTypeFlow::Block:compute_exceptions
1787 //
1788 // Compute the exceptional successors and types for this Block.
1789 void ciTypeFlow::Block::compute_exceptions() {
1790   assert(_exceptions == NULL && _exc_klasses == NULL, "repeat");
1791 
1792   if (CITraceTypeFlow) {
1793     tty->print(">> Computing exceptions for block ");
1794     print_value_on(tty);
1795     tty->cr();
1796   }
1797 
1798   ciTypeFlow* analyzer = outer();
1799   Arena* arena = analyzer->arena();
1800 
1801   // Any bci in the block will do.
1802   ciExceptionHandlerStream str(analyzer->method(), start());
1803 
1804   // Allocate our growable arrays.
1805   int exc_count = str.count();
1806   _exceptions = new (arena) GrowableArray<Block*>(arena, exc_count, 0, NULL);
1807   _exc_klasses = new (arena) GrowableArray<ciInstanceKlass*>(arena, exc_count,
1808                                                              0, NULL);
1809 
1810   for ( ; !str.is_done(); str.next()) {
1811     ciExceptionHandler* handler = str.handler();
1812     int bci = handler->handler_bci();
1813     ciInstanceKlass* klass = NULL;
1814     if (bci == -1) {
1815       // There is no catch all.  It is possible to exit the method.
1816       break;
1817     }
1818     if (handler->is_catch_all()) {
1819       klass = analyzer->env()->Throwable_klass();
1820     } else {
1821       klass = handler->catch_klass();
1822     }
1823     _exceptions->append(analyzer->block_at(bci, _jsrs));
1824     _exc_klasses->append(klass);
1825   }
1826 }
1827 
1828 // ------------------------------------------------------------------
1829 // ciTypeFlow::Block::set_backedge_copy
1830 // Use this only to make a pre-existing public block into a backedge copy.
1831 void ciTypeFlow::Block::set_backedge_copy(bool z) {
1832   assert(z || (z == is_backedge_copy()), "cannot make a backedge copy public");
1833   _backedge_copy = z;
1834 }
1835 
1836 // ------------------------------------------------------------------
1837 // ciTypeFlow::Block::is_clonable_exit
1838 //
1839 // At most 2 normal successors, one of which continues looping,
1840 // and all exceptional successors must exit.
1841 bool ciTypeFlow::Block::is_clonable_exit(ciTypeFlow::Loop* lp) {
1842   int normal_cnt  = 0;
1843   int in_loop_cnt = 0;
1844   for (SuccIter iter(this); !iter.done(); iter.next()) {
1845     Block* succ = iter.succ();
1846     if (iter.is_normal_ctrl()) {
1847       if (++normal_cnt > 2) return false;
1848       if (lp->contains(succ->loop())) {
1849         if (++in_loop_cnt > 1) return false;
1850       }
1851     } else {
1852       if (lp->contains(succ->loop())) return false;
1853     }
1854   }
1855   return in_loop_cnt == 1;
1856 }
1857 
1858 // ------------------------------------------------------------------
1859 // ciTypeFlow::Block::looping_succ
1860 //
1861 ciTypeFlow::Block* ciTypeFlow::Block::looping_succ(ciTypeFlow::Loop* lp) {
1862   assert(successors()->length() <= 2, "at most 2 normal successors");
1863   for (SuccIter iter(this); !iter.done(); iter.next()) {
1864     Block* succ = iter.succ();
1865     if (lp->contains(succ->loop())) {
1866       return succ;
1867     }
1868   }
1869   return NULL;
1870 }
1871 
1872 #ifndef PRODUCT
1873 // ------------------------------------------------------------------
1874 // ciTypeFlow::Block::print_value_on
1875 void ciTypeFlow::Block::print_value_on(outputStream* st) const {
1876   if (has_pre_order()) st->print("#%-2d ", pre_order());
1877   if (has_rpo())       st->print("rpo#%-2d ", rpo());
1878   st->print("[%d - %d)", start(), limit());
1879   if (is_loop_head()) st->print(" lphd");
1880   if (is_irreducible_entry()) st->print(" irred");
1881   if (_jsrs->size() > 0) { st->print("/");  _jsrs->print_on(st); }
1882   if (is_backedge_copy())  st->print("/backedge_copy");
1883 }
1884 
1885 // ------------------------------------------------------------------
1886 // ciTypeFlow::Block::print_on
1887 void ciTypeFlow::Block::print_on(outputStream* st) const {
1888   if ((Verbose || WizardMode) && (limit() >= 0)) {
1889     // Don't print 'dummy' blocks (i.e. blocks with limit() '-1')
1890     outer()->method()->print_codes_on(start(), limit(), st);
1891   }
1892   st->print_cr("  ====================================================  ");
1893   st->print ("  ");
1894   print_value_on(st);
1895   st->print(" Stored locals: "); def_locals()->print_on(st, outer()->method()->max_locals()); tty->cr();
1896   if (loop() && loop()->parent() != NULL) {
1897     st->print(" loops:");
1898     Loop* lp = loop();
1899     do {
1900       st->print(" %d<-%d", lp->head()->pre_order(),lp->tail()->pre_order());
1901       if (lp->is_irreducible()) st->print("(ir)");
1902       lp = lp->parent();
1903     } while (lp->parent() != NULL);
1904   }
1905   st->cr();
1906   _state->print_on(st);
1907   if (_successors == NULL) {
1908     st->print_cr("  No successor information");
1909   } else {
1910     int num_successors = _successors->length();
1911     st->print_cr("  Successors : %d", num_successors);
1912     for (int i = 0; i < num_successors; i++) {
1913       Block* successor = _successors->at(i);
1914       st->print("    ");
1915       successor->print_value_on(st);
1916       st->cr();
1917     }
1918   }
1919   if (_predecessors == NULL) {
1920     st->print_cr("  No predecessor information");
1921   } else {
1922     int num_predecessors = _predecessors->length();
1923     st->print_cr("  Predecessors : %d", num_predecessors);
1924     for (int i = 0; i < num_predecessors; i++) {
1925       Block* predecessor = _predecessors->at(i);
1926       st->print("    ");
1927       predecessor->print_value_on(st);
1928       st->cr();
1929     }
1930   }
1931   if (_exceptions == NULL) {
1932     st->print_cr("  No exception information");
1933   } else {
1934     int num_exceptions = _exceptions->length();
1935     st->print_cr("  Exceptions : %d", num_exceptions);
1936     for (int i = 0; i < num_exceptions; i++) {
1937       Block* exc_succ = _exceptions->at(i);
1938       ciInstanceKlass* exc_klass = _exc_klasses->at(i);
1939       st->print("    ");
1940       exc_succ->print_value_on(st);
1941       st->print(" -- ");
1942       exc_klass->name()->print_symbol_on(st);
1943       st->cr();
1944     }
1945   }
1946   if (has_trap()) {
1947     st->print_cr("  Traps on %d with trap index %d", trap_bci(), trap_index());
1948   }
1949   st->print_cr("  ====================================================  ");
1950 }
1951 #endif
1952 
1953 #ifndef PRODUCT
1954 // ------------------------------------------------------------------
1955 // ciTypeFlow::LocalSet::print_on
1956 void ciTypeFlow::LocalSet::print_on(outputStream* st, int limit) const {
1957   st->print("{");
1958   for (int i = 0; i < max; i++) {
1959     if (test(i)) st->print(" %d", i);
1960   }
1961   if (limit > max) {
1962     st->print(" %d..%d ", max, limit);
1963   }
1964   st->print(" }");
1965 }
1966 #endif
1967 
1968 // ciTypeFlow
1969 //
1970 // This is a pass over the bytecodes which computes the following:
1971 //   basic block structure
1972 //   interpreter type-states (a la the verifier)
1973 
1974 // ------------------------------------------------------------------
1975 // ciTypeFlow::ciTypeFlow
1976 ciTypeFlow::ciTypeFlow(ciEnv* env, ciMethod* method, int osr_bci) {
1977   _env = env;
1978   _method = method;
1979   _methodBlocks = method->get_method_blocks();
1980   _max_locals = method->max_locals();
1981   _max_stack = method->max_stack();
1982   _code_size = method->code_size();
1983   _has_irreducible_entry = false;
1984   _osr_bci = osr_bci;
1985   _failure_reason = NULL;
1986   assert(0 <= start_bci() && start_bci() < code_size() , "correct osr_bci argument: 0 <= %d < %d", start_bci(), code_size());
1987   _work_list = NULL;
1988 
1989   _ciblock_count = _methodBlocks->num_blocks();
1990   _idx_to_blocklist = NEW_ARENA_ARRAY(arena(), GrowableArray<Block*>*, _ciblock_count);
1991   for (int i = 0; i < _ciblock_count; i++) {
1992     _idx_to_blocklist[i] = NULL;
1993   }
1994   _block_map = NULL;  // until all blocks are seen
1995   _jsr_count = 0;
1996   _jsr_records = NULL;
1997 }
1998 
1999 // ------------------------------------------------------------------
2000 // ciTypeFlow::work_list_next
2001 //
2002 // Get the next basic block from our work list.
2003 ciTypeFlow::Block* ciTypeFlow::work_list_next() {
2004   assert(!work_list_empty(), "work list must not be empty");
2005   Block* next_block = _work_list;
2006   _work_list = next_block->next();
2007   next_block->set_next(NULL);
2008   next_block->set_on_work_list(false);
2009   return next_block;
2010 }
2011 
2012 // ------------------------------------------------------------------
2013 // ciTypeFlow::add_to_work_list
2014 //
2015 // Add a basic block to our work list.
2016 // List is sorted by decreasing postorder sort (same as increasing RPO)
2017 void ciTypeFlow::add_to_work_list(ciTypeFlow::Block* block) {
2018   assert(!block->is_on_work_list(), "must not already be on work list");
2019 
2020   if (CITraceTypeFlow) {
2021     tty->print(">> Adding block ");
2022     block->print_value_on(tty);
2023     tty->print_cr(" to the work list : ");
2024   }
2025 
2026   block->set_on_work_list(true);
2027 
2028   // decreasing post order sort
2029 
2030   Block* prev = NULL;
2031   Block* current = _work_list;
2032   int po = block->post_order();
2033   while (current != NULL) {
2034     if (!current->has_post_order() || po > current->post_order())
2035       break;
2036     prev = current;
2037     current = current->next();
2038   }
2039   if (prev == NULL) {
2040     block->set_next(_work_list);
2041     _work_list = block;
2042   } else {
2043     block->set_next(current);
2044     prev->set_next(block);
2045   }
2046 
2047   if (CITraceTypeFlow) {
2048     tty->cr();
2049   }
2050 }
2051 
2052 // ------------------------------------------------------------------
2053 // ciTypeFlow::block_at
2054 //
2055 // Return the block beginning at bci which has a JsrSet compatible
2056 // with jsrs.
2057 ciTypeFlow::Block* ciTypeFlow::block_at(int bci, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
2058   // First find the right ciBlock.
2059   if (CITraceTypeFlow) {
2060     tty->print(">> Requesting block for %d/", bci);
2061     jsrs->print_on(tty);
2062     tty->cr();
2063   }
2064 
2065   ciBlock* ciblk = _methodBlocks->block_containing(bci);
2066   assert(ciblk->start_bci() == bci, "bad ciBlock boundaries");
2067   Block* block = get_block_for(ciblk->index(), jsrs, option);
2068 
2069   assert(block == NULL? (option == no_create): block->is_backedge_copy() == (option == create_backedge_copy), "create option consistent with result");
2070 
2071   if (CITraceTypeFlow) {
2072     if (block != NULL) {
2073       tty->print(">> Found block ");
2074       block->print_value_on(tty);
2075       tty->cr();
2076     } else {
2077       tty->print_cr(">> No such block.");
2078     }
2079   }
2080 
2081   return block;
2082 }
2083 
2084 // ------------------------------------------------------------------
2085 // ciTypeFlow::make_jsr_record
2086 //
2087 // Make a JsrRecord for a given (entry, return) pair, if such a record
2088 // does not already exist.
2089 ciTypeFlow::JsrRecord* ciTypeFlow::make_jsr_record(int entry_address,
2090                                                    int return_address) {
2091   if (_jsr_records == NULL) {
2092     _jsr_records = new (arena()) GrowableArray<JsrRecord*>(arena(),
2093                                                            _jsr_count,
2094                                                            0,
2095                                                            NULL);
2096   }
2097   JsrRecord* record = NULL;
2098   int len = _jsr_records->length();
2099   for (int i = 0; i < len; i++) {
2100     JsrRecord* record = _jsr_records->at(i);
2101     if (record->entry_address() == entry_address &&
2102         record->return_address() == return_address) {
2103       return record;
2104     }
2105   }
2106 
2107   record = new (arena()) JsrRecord(entry_address, return_address);
2108   _jsr_records->append(record);
2109   return record;
2110 }
2111 
2112 // ------------------------------------------------------------------
2113 // ciTypeFlow::flow_exceptions
2114 //
2115 // Merge the current state into all exceptional successors at the
2116 // current point in the code.
2117 void ciTypeFlow::flow_exceptions(GrowableArray<ciTypeFlow::Block*>* exceptions,
2118                                  GrowableArray<ciInstanceKlass*>* exc_klasses,
2119                                  ciTypeFlow::StateVector* state) {
2120   int len = exceptions->length();
2121   assert(exc_klasses->length() == len, "must have same length");
2122   for (int i = 0; i < len; i++) {
2123     Block* block = exceptions->at(i);
2124     ciInstanceKlass* exception_klass = exc_klasses->at(i);
2125 
2126     if (!exception_klass->is_loaded()) {
2127       // Do not compile any code for unloaded exception types.
2128       // Following compiler passes are responsible for doing this also.
2129       continue;
2130     }
2131 
2132     if (block->meet_exception(exception_klass, state)) {
2133       // Block was modified and has PO.  Add it to the work list.
2134       if (block->has_post_order() &&
2135           !block->is_on_work_list()) {
2136         add_to_work_list(block);
2137       }
2138     }
2139   }
2140 }
2141 
2142 // ------------------------------------------------------------------
2143 // ciTypeFlow::flow_successors
2144 //
2145 // Merge the current state into all successors at the current point
2146 // in the code.
2147 void ciTypeFlow::flow_successors(GrowableArray<ciTypeFlow::Block*>* successors,
2148                                  ciTypeFlow::StateVector* state) {
2149   int len = successors->length();
2150   for (int i = 0; i < len; i++) {
2151     Block* block = successors->at(i);
2152     if (block->meet(state)) {
2153       // Block was modified and has PO.  Add it to the work list.
2154       if (block->has_post_order() &&
2155           !block->is_on_work_list()) {
2156         add_to_work_list(block);
2157       }
2158     }
2159   }
2160 }
2161 
2162 // ------------------------------------------------------------------
2163 // ciTypeFlow::can_trap
2164 //
2165 // Tells if a given instruction is able to generate an exception edge.
2166 bool ciTypeFlow::can_trap(ciBytecodeStream& str) {
2167   // Cf. GenerateOopMap::do_exception_edge.
2168   if (!Bytecodes::can_trap(str.cur_bc()))  return false;
2169 
2170   switch (str.cur_bc()) {
2171     // %%% FIXME: ldc of Class can generate an exception
2172     case Bytecodes::_ldc:
2173     case Bytecodes::_ldc_w:
2174     case Bytecodes::_ldc2_w:
2175     case Bytecodes::_aload_0:
2176       // These bytecodes can trap for rewriting.  We need to assume that
2177       // they do not throw exceptions to make the monitor analysis work.
2178       return false;
2179 
2180     case Bytecodes::_ireturn:
2181     case Bytecodes::_lreturn:
2182     case Bytecodes::_freturn:
2183     case Bytecodes::_dreturn:
2184     case Bytecodes::_areturn:
2185     case Bytecodes::_return:
2186       // We can assume the monitor stack is empty in this analysis.
2187       return false;
2188 
2189     case Bytecodes::_monitorexit:
2190       // We can assume monitors are matched in this analysis.
2191       return false;
2192   }
2193 
2194   return true;
2195 }
2196 
2197 // ------------------------------------------------------------------
2198 // ciTypeFlow::clone_loop_heads
2199 //
2200 // Clone the loop heads
2201 bool ciTypeFlow::clone_loop_heads(Loop* lp, StateVector* temp_vector, JsrSet* temp_set) {
2202   bool rslt = false;
2203   for (PreorderLoops iter(loop_tree_root()); !iter.done(); iter.next()) {
2204     lp = iter.current();
2205     Block* head = lp->head();
2206     if (lp == loop_tree_root() ||
2207         lp->is_irreducible() ||
2208         !head->is_clonable_exit(lp))
2209       continue;
2210 
2211     // Avoid BoxLock merge.
2212     if (EliminateNestedLocks && head->has_monitorenter())
2213       continue;
2214 
2215     // check not already cloned
2216     if (head->backedge_copy_count() != 0)
2217       continue;
2218 
2219     // Don't clone head of OSR loop to get correct types in start block.
2220     if (is_osr_flow() && head->start() == start_bci())
2221       continue;
2222 
2223     // check _no_ shared head below us
2224     Loop* ch;
2225     for (ch = lp->child(); ch != NULL && ch->head() != head; ch = ch->sibling());
2226     if (ch != NULL)
2227       continue;
2228 
2229     // Clone head
2230     Block* new_head = head->looping_succ(lp);
2231     Block* clone = clone_loop_head(lp, temp_vector, temp_set);
2232     // Update lp's info
2233     clone->set_loop(lp);
2234     lp->set_head(new_head);
2235     lp->set_tail(clone);
2236     // And move original head into outer loop
2237     head->set_loop(lp->parent());
2238 
2239     rslt = true;
2240   }
2241   return rslt;
2242 }
2243 
2244 // ------------------------------------------------------------------
2245 // ciTypeFlow::clone_loop_head
2246 //
2247 // Clone lp's head and replace tail's successors with clone.
2248 //
2249 //  |
2250 //  v
2251 // head <-> body
2252 //  |
2253 //  v
2254 // exit
2255 //
2256 // new_head
2257 //
2258 //  |
2259 //  v
2260 // head ----------\
2261 //  |             |
2262 //  |             v
2263 //  |  clone <-> body
2264 //  |    |
2265 //  | /--/
2266 //  | |
2267 //  v v
2268 // exit
2269 //
2270 ciTypeFlow::Block* ciTypeFlow::clone_loop_head(Loop* lp, StateVector* temp_vector, JsrSet* temp_set) {
2271   Block* head = lp->head();
2272   Block* tail = lp->tail();
2273   if (CITraceTypeFlow) {
2274     tty->print(">> Requesting clone of loop head "); head->print_value_on(tty);
2275     tty->print("  for predecessor ");                tail->print_value_on(tty);
2276     tty->cr();
2277   }
2278   Block* clone = block_at(head->start(), head->jsrs(), create_backedge_copy);
2279   assert(clone->backedge_copy_count() == 1, "one backedge copy for all back edges");
2280 
2281   assert(!clone->has_pre_order(), "just created");
2282   clone->set_next_pre_order();
2283 
2284   // Insert clone after (orig) tail in reverse post order
2285   clone->set_rpo_next(tail->rpo_next());
2286   tail->set_rpo_next(clone);
2287 
2288   // tail->head becomes tail->clone
2289   for (SuccIter iter(tail); !iter.done(); iter.next()) {
2290     if (iter.succ() == head) {
2291       iter.set_succ(clone);
2292     }
2293   }
2294   flow_block(tail, temp_vector, temp_set);
2295   if (head == tail) {
2296     // For self-loops, clone->head becomes clone->clone
2297     flow_block(clone, temp_vector, temp_set);
2298     for (SuccIter iter(clone); !iter.done(); iter.next()) {
2299       if (iter.succ() == head) {
2300         iter.set_succ(clone);
2301         break;
2302       }
2303     }
2304   }
2305   flow_block(clone, temp_vector, temp_set);
2306 
2307   return clone;
2308 }
2309 
2310 // ------------------------------------------------------------------
2311 // ciTypeFlow::flow_block
2312 //
2313 // Interpret the effects of the bytecodes on the incoming state
2314 // vector of a basic block.  Push the changed state to succeeding
2315 // basic blocks.
2316 void ciTypeFlow::flow_block(ciTypeFlow::Block* block,
2317                             ciTypeFlow::StateVector* state,
2318                             ciTypeFlow::JsrSet* jsrs) {
2319   if (CITraceTypeFlow) {
2320     tty->print("\n>> ANALYZING BLOCK : ");
2321     tty->cr();
2322     block->print_on(tty);
2323   }
2324   assert(block->has_pre_order(), "pre-order is assigned before 1st flow");
2325 
2326   int start = block->start();
2327   int limit = block->limit();
2328   int control = block->control();
2329   if (control != ciBlock::fall_through_bci) {
2330     limit = control;
2331   }
2332 
2333   // Grab the state from the current block.
2334   block->copy_state_into(state);
2335   state->def_locals()->clear();
2336 
2337   GrowableArray<Block*>*           exceptions = block->exceptions();
2338   GrowableArray<ciInstanceKlass*>* exc_klasses = block->exc_klasses();
2339   bool has_exceptions = exceptions->length() > 0;
2340 
2341   bool exceptions_used = false;
2342 
2343   ciBytecodeStream str(method());
2344   str.reset_to_bci(start);
2345   Bytecodes::Code code;
2346   while ((code = str.next()) != ciBytecodeStream::EOBC() &&
2347          str.cur_bci() < limit) {
2348     // Check for exceptional control flow from this point.
2349     if (has_exceptions && can_trap(str)) {
2350       flow_exceptions(exceptions, exc_klasses, state);
2351       exceptions_used = true;
2352     }
2353     // Apply the effects of the current bytecode to our state.
2354     bool res = state->apply_one_bytecode(&str);
2355 
2356     // Watch for bailouts.
2357     if (failing())  return;
2358 
2359     if (str.cur_bc() == Bytecodes::_monitorenter) {
2360       block->set_has_monitorenter();
2361     }
2362 
2363     if (res) {
2364 
2365       // We have encountered a trap.  Record it in this block.
2366       block->set_trap(state->trap_bci(), state->trap_index());
2367 
2368       if (CITraceTypeFlow) {
2369         tty->print_cr(">> Found trap");
2370         block->print_on(tty);
2371       }
2372 
2373       // Save set of locals defined in this block
2374       block->def_locals()->add(state->def_locals());
2375 
2376       // Record (no) successors.
2377       block->successors(&str, state, jsrs);
2378 
2379       assert(!has_exceptions || exceptions_used, "Not removing exceptions");
2380 
2381       // Discontinue interpretation of this Block.
2382       return;
2383     }
2384   }
2385 
2386   GrowableArray<Block*>* successors = NULL;
2387   if (control != ciBlock::fall_through_bci) {
2388     // Check for exceptional control flow from this point.
2389     if (has_exceptions && can_trap(str)) {
2390       flow_exceptions(exceptions, exc_klasses, state);
2391       exceptions_used = true;
2392     }
2393 
2394     // Fix the JsrSet to reflect effect of the bytecode.
2395     block->copy_jsrs_into(jsrs);
2396     jsrs->apply_control(this, &str, state);
2397 
2398     // Find successor edges based on old state and new JsrSet.
2399     successors = block->successors(&str, state, jsrs);
2400 
2401     // Apply the control changes to the state.
2402     state->apply_one_bytecode(&str);
2403   } else {
2404     // Fall through control
2405     successors = block->successors(&str, NULL, NULL);
2406   }
2407 
2408   // Save set of locals defined in this block
2409   block->def_locals()->add(state->def_locals());
2410 
2411   // Remove untaken exception paths
2412   if (!exceptions_used)
2413     exceptions->clear();
2414 
2415   // Pass our state to successors.
2416   flow_successors(successors, state);
2417 }
2418 
2419 // ------------------------------------------------------------------
2420 // ciTypeFlow::PostOrderLoops::next
2421 //
2422 // Advance to next loop tree using a postorder, left-to-right traversal.
2423 void ciTypeFlow::PostorderLoops::next() {
2424   assert(!done(), "must not be done.");
2425   if (_current->sibling() != NULL) {
2426     _current = _current->sibling();
2427     while (_current->child() != NULL) {
2428       _current = _current->child();
2429     }
2430   } else {
2431     _current = _current->parent();
2432   }
2433 }
2434 
2435 // ------------------------------------------------------------------
2436 // ciTypeFlow::PreOrderLoops::next
2437 //
2438 // Advance to next loop tree using a preorder, left-to-right traversal.
2439 void ciTypeFlow::PreorderLoops::next() {
2440   assert(!done(), "must not be done.");
2441   if (_current->child() != NULL) {
2442     _current = _current->child();
2443   } else if (_current->sibling() != NULL) {
2444     _current = _current->sibling();
2445   } else {
2446     while (_current != _root && _current->sibling() == NULL) {
2447       _current = _current->parent();
2448     }
2449     if (_current == _root) {
2450       _current = NULL;
2451       assert(done(), "must be done.");
2452     } else {
2453       assert(_current->sibling() != NULL, "must be more to do");
2454       _current = _current->sibling();
2455     }
2456   }
2457 }
2458 
2459 // ------------------------------------------------------------------
2460 // ciTypeFlow::Loop::sorted_merge
2461 //
2462 // Merge the branch lp into this branch, sorting on the loop head
2463 // pre_orders. Returns the leaf of the merged branch.
2464 // Child and sibling pointers will be setup later.
2465 // Sort is (looking from leaf towards the root)
2466 //  descending on primary key: loop head's pre_order, and
2467 //  ascending  on secondary key: loop tail's pre_order.
2468 ciTypeFlow::Loop* ciTypeFlow::Loop::sorted_merge(Loop* lp) {
2469   Loop* leaf = this;
2470   Loop* prev = NULL;
2471   Loop* current = leaf;
2472   while (lp != NULL) {
2473     int lp_pre_order = lp->head()->pre_order();
2474     // Find insertion point for "lp"
2475     while (current != NULL) {
2476       if (current == lp)
2477         return leaf; // Already in list
2478       if (current->head()->pre_order() < lp_pre_order)
2479         break;
2480       if (current->head()->pre_order() == lp_pre_order &&
2481           current->tail()->pre_order() > lp->tail()->pre_order()) {
2482         break;
2483       }
2484       prev = current;
2485       current = current->parent();
2486     }
2487     Loop* next_lp = lp->parent(); // Save future list of items to insert
2488     // Insert lp before current
2489     lp->set_parent(current);
2490     if (prev != NULL) {
2491       prev->set_parent(lp);
2492     } else {
2493       leaf = lp;
2494     }
2495     prev = lp;     // Inserted item is new prev[ious]
2496     lp = next_lp;  // Next item to insert
2497   }
2498   return leaf;
2499 }
2500 
2501 // ------------------------------------------------------------------
2502 // ciTypeFlow::build_loop_tree
2503 //
2504 // Incrementally build loop tree.
2505 void ciTypeFlow::build_loop_tree(Block* blk) {
2506   assert(!blk->is_post_visited(), "precondition");
2507   Loop* innermost = NULL; // merge of loop tree branches over all successors
2508 
2509   for (SuccIter iter(blk); !iter.done(); iter.next()) {
2510     Loop*  lp   = NULL;
2511     Block* succ = iter.succ();
2512     if (!succ->is_post_visited()) {
2513       // Found backedge since predecessor post visited, but successor is not
2514       assert(succ->pre_order() <= blk->pre_order(), "should be backedge");
2515 
2516       // Create a LoopNode to mark this loop.
2517       lp = new (arena()) Loop(succ, blk);
2518       if (succ->loop() == NULL)
2519         succ->set_loop(lp);
2520       // succ->loop will be updated to innermost loop on a later call, when blk==succ
2521 
2522     } else {  // Nested loop
2523       lp = succ->loop();
2524 
2525       // If succ is loop head, find outer loop.
2526       while (lp != NULL && lp->head() == succ) {
2527         lp = lp->parent();
2528       }
2529       if (lp == NULL) {
2530         // Infinite loop, it's parent is the root
2531         lp = loop_tree_root();
2532       }
2533     }
2534 
2535     // Check for irreducible loop.
2536     // Successor has already been visited. If the successor's loop head
2537     // has already been post-visited, then this is another entry into the loop.
2538     while (lp->head()->is_post_visited() && lp != loop_tree_root()) {
2539       _has_irreducible_entry = true;
2540       lp->set_irreducible(succ);
2541       if (!succ->is_on_work_list()) {
2542         // Assume irreducible entries need more data flow
2543         add_to_work_list(succ);
2544       }
2545       Loop* plp = lp->parent();
2546       if (plp == NULL) {
2547         // This only happens for some irreducible cases.  The parent
2548         // will be updated during a later pass.
2549         break;
2550       }
2551       lp = plp;
2552     }
2553 
2554     // Merge loop tree branch for all successors.
2555     innermost = innermost == NULL ? lp : innermost->sorted_merge(lp);
2556 
2557   } // end loop
2558 
2559   if (innermost == NULL) {
2560     assert(blk->successors()->length() == 0, "CFG exit");
2561     blk->set_loop(loop_tree_root());
2562   } else if (innermost->head() == blk) {
2563     // If loop header, complete the tree pointers
2564     if (blk->loop() != innermost) {
2565 #ifdef ASSERT
2566       assert(blk->loop()->head() == innermost->head(), "same head");
2567       Loop* dl;
2568       for (dl = innermost; dl != NULL && dl != blk->loop(); dl = dl->parent());
2569       assert(dl == blk->loop(), "blk->loop() already in innermost list");
2570 #endif
2571       blk->set_loop(innermost);
2572     }
2573     innermost->def_locals()->add(blk->def_locals());
2574     Loop* l = innermost;
2575     Loop* p = l->parent();
2576     while (p && l->head() == blk) {
2577       l->set_sibling(p->child());  // Put self on parents 'next child'
2578       p->set_child(l);             // Make self the first child of parent
2579       p->def_locals()->add(l->def_locals());
2580       l = p;                       // Walk up the parent chain
2581       p = l->parent();
2582     }
2583   } else {
2584     blk->set_loop(innermost);
2585     innermost->def_locals()->add(blk->def_locals());
2586   }
2587 }
2588 
2589 // ------------------------------------------------------------------
2590 // ciTypeFlow::Loop::contains
2591 //
2592 // Returns true if lp is nested loop.
2593 bool ciTypeFlow::Loop::contains(ciTypeFlow::Loop* lp) const {
2594   assert(lp != NULL, "");
2595   if (this == lp || head() == lp->head()) return true;
2596   int depth1 = depth();
2597   int depth2 = lp->depth();
2598   if (depth1 > depth2)
2599     return false;
2600   while (depth1 < depth2) {
2601     depth2--;
2602     lp = lp->parent();
2603   }
2604   return this == lp;
2605 }
2606 
2607 // ------------------------------------------------------------------
2608 // ciTypeFlow::Loop::depth
2609 //
2610 // Loop depth
2611 int ciTypeFlow::Loop::depth() const {
2612   int dp = 0;
2613   for (Loop* lp = this->parent(); lp != NULL; lp = lp->parent())
2614     dp++;
2615   return dp;
2616 }
2617 
2618 #ifndef PRODUCT
2619 // ------------------------------------------------------------------
2620 // ciTypeFlow::Loop::print
2621 void ciTypeFlow::Loop::print(outputStream* st, int indent) const {
2622   for (int i = 0; i < indent; i++) st->print(" ");
2623   st->print("%d<-%d %s",
2624             is_root() ? 0 : this->head()->pre_order(),
2625             is_root() ? 0 : this->tail()->pre_order(),
2626             is_irreducible()?" irr":"");
2627   st->print(" defs: ");
2628   def_locals()->print_on(st, _head->outer()->method()->max_locals());
2629   st->cr();
2630   for (Loop* ch = child(); ch != NULL; ch = ch->sibling())
2631     ch->print(st, indent+2);
2632 }
2633 #endif
2634 
2635 // ------------------------------------------------------------------
2636 // ciTypeFlow::df_flow_types
2637 //
2638 // Perform the depth first type flow analysis. Helper for flow_types.
2639 void ciTypeFlow::df_flow_types(Block* start,
2640                                bool do_flow,
2641                                StateVector* temp_vector,
2642                                JsrSet* temp_set) {
2643   int dft_len = 100;
2644   GrowableArray<Block*> stk(dft_len);
2645 
2646   ciBlock* dummy = _methodBlocks->make_dummy_block();
2647   JsrSet* root_set = new JsrSet(NULL, 0);
2648   Block* root_head = new (arena()) Block(this, dummy, root_set);
2649   Block* root_tail = new (arena()) Block(this, dummy, root_set);
2650   root_head->set_pre_order(0);
2651   root_head->set_post_order(0);
2652   root_tail->set_pre_order(max_jint);
2653   root_tail->set_post_order(max_jint);
2654   set_loop_tree_root(new (arena()) Loop(root_head, root_tail));
2655 
2656   stk.push(start);
2657 
2658   _next_pre_order = 0;  // initialize pre_order counter
2659   _rpo_list = NULL;
2660   int next_po = 0;      // initialize post_order counter
2661 
2662   // Compute RPO and the control flow graph
2663   int size;
2664   while ((size = stk.length()) > 0) {
2665     Block* blk = stk.top(); // Leave node on stack
2666     if (!blk->is_visited()) {
2667       // forward arc in graph
2668       assert (!blk->has_pre_order(), "");
2669       blk->set_next_pre_order();
2670 
2671       if (_next_pre_order >= (int)Compile::current()->max_node_limit() / 2) {
2672         // Too many basic blocks.  Bail out.
2673         // This can happen when try/finally constructs are nested to depth N,
2674         // and there is O(2**N) cloning of jsr bodies.  See bug 4697245!
2675         // "MaxNodeLimit / 2" is used because probably the parser will
2676         // generate at least twice that many nodes and bail out.
2677         record_failure("too many basic blocks");
2678         return;
2679       }
2680       if (do_flow) {
2681         flow_block(blk, temp_vector, temp_set);
2682         if (failing()) return; // Watch for bailouts.
2683       }
2684     } else if (!blk->is_post_visited()) {
2685       // cross or back arc
2686       for (SuccIter iter(blk); !iter.done(); iter.next()) {
2687         Block* succ = iter.succ();
2688         if (!succ->is_visited()) {
2689           stk.push(succ);
2690         }
2691       }
2692       if (stk.length() == size) {
2693         // There were no additional children, post visit node now
2694         stk.pop(); // Remove node from stack
2695 
2696         build_loop_tree(blk);
2697         blk->set_post_order(next_po++);   // Assign post order
2698         prepend_to_rpo_list(blk);
2699         assert(blk->is_post_visited(), "");
2700 
2701         if (blk->is_loop_head() && !blk->is_on_work_list()) {
2702           // Assume loop heads need more data flow
2703           add_to_work_list(blk);
2704         }
2705       }
2706     } else {
2707       stk.pop(); // Remove post-visited node from stack
2708     }
2709   }
2710 }
2711 
2712 // ------------------------------------------------------------------
2713 // ciTypeFlow::flow_types
2714 //
2715 // Perform the type flow analysis, creating and cloning Blocks as
2716 // necessary.
2717 void ciTypeFlow::flow_types() {
2718   ResourceMark rm;
2719   StateVector* temp_vector = new StateVector(this);
2720   JsrSet* temp_set = new JsrSet(NULL, 16);
2721 
2722   // Create the method entry block.
2723   Block* start = block_at(start_bci(), temp_set);
2724 
2725   // Load the initial state into it.
2726   const StateVector* start_state = get_start_state();
2727   if (failing())  return;
2728   start->meet(start_state);
2729 
2730   // Depth first visit
2731   df_flow_types(start, true /*do flow*/, temp_vector, temp_set);
2732 
2733   if (failing())  return;
2734   assert(_rpo_list == start, "must be start");
2735 
2736   // Any loops found?
2737   if (loop_tree_root()->child() != NULL &&
2738       env()->comp_level() >= CompLevel_full_optimization) {
2739       // Loop optimizations are not performed on Tier1 compiles.
2740 
2741     bool changed = clone_loop_heads(loop_tree_root(), temp_vector, temp_set);
2742 
2743     // If some loop heads were cloned, recompute postorder and loop tree
2744     if (changed) {
2745       loop_tree_root()->set_child(NULL);
2746       for (Block* blk = _rpo_list; blk != NULL;) {
2747         Block* next = blk->rpo_next();
2748         blk->df_init();
2749         blk = next;
2750       }
2751       df_flow_types(start, false /*no flow*/, temp_vector, temp_set);
2752     }
2753   }
2754 
2755   if (CITraceTypeFlow) {
2756     tty->print_cr("\nLoop tree");
2757     loop_tree_root()->print();
2758   }
2759 
2760   // Continue flow analysis until fixed point reached
2761 
2762   debug_only(int max_block = _next_pre_order;)
2763 
2764   while (!work_list_empty()) {
2765     Block* blk = work_list_next();
2766     assert (blk->has_post_order(), "post order assigned above");
2767 
2768     flow_block(blk, temp_vector, temp_set);
2769 
2770     assert (max_block == _next_pre_order, "no new blocks");
2771     assert (!failing(), "no more bailouts");
2772   }
2773 }
2774 
2775 // ------------------------------------------------------------------
2776 // ciTypeFlow::map_blocks
2777 //
2778 // Create the block map, which indexes blocks in reverse post-order.
2779 void ciTypeFlow::map_blocks() {
2780   assert(_block_map == NULL, "single initialization");
2781   int block_ct = _next_pre_order;
2782   _block_map = NEW_ARENA_ARRAY(arena(), Block*, block_ct);
2783   assert(block_ct == block_count(), "");
2784 
2785   Block* blk = _rpo_list;
2786   for (int m = 0; m < block_ct; m++) {
2787     int rpo = blk->rpo();
2788     assert(rpo == m, "should be sequential");
2789     _block_map[rpo] = blk;
2790     blk = blk->rpo_next();
2791   }
2792   assert(blk == NULL, "should be done");
2793 
2794   for (int j = 0; j < block_ct; j++) {
2795     assert(_block_map[j] != NULL, "must not drop any blocks");
2796     Block* block = _block_map[j];
2797     // Remove dead blocks from successor lists:
2798     for (int e = 0; e <= 1; e++) {
2799       GrowableArray<Block*>* l = e? block->exceptions(): block->successors();
2800       for (int k = 0; k < l->length(); k++) {
2801         Block* s = l->at(k);
2802         if (!s->has_post_order()) {
2803           if (CITraceTypeFlow) {
2804             tty->print("Removing dead %s successor of #%d: ", (e? "exceptional":  "normal"), block->pre_order());
2805             s->print_value_on(tty);
2806             tty->cr();
2807           }
2808           l->remove(s);
2809           --k;
2810         }
2811       }
2812     }
2813   }
2814 }
2815 
2816 // ------------------------------------------------------------------
2817 // ciTypeFlow::get_block_for
2818 //
2819 // Find a block with this ciBlock which has a compatible JsrSet.
2820 // If no such block exists, create it, unless the option is no_create.
2821 // If the option is create_backedge_copy, always create a fresh backedge copy.
2822 ciTypeFlow::Block* ciTypeFlow::get_block_for(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
2823   Arena* a = arena();
2824   GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
2825   if (blocks == NULL) {
2826     // Query only?
2827     if (option == no_create)  return NULL;
2828 
2829     // Allocate the growable array.
2830     blocks = new (a) GrowableArray<Block*>(a, 4, 0, NULL);
2831     _idx_to_blocklist[ciBlockIndex] = blocks;
2832   }
2833 
2834   if (option != create_backedge_copy) {
2835     int len = blocks->length();
2836     for (int i = 0; i < len; i++) {
2837       Block* block = blocks->at(i);
2838       if (!block->is_backedge_copy() && block->is_compatible_with(jsrs)) {
2839         return block;
2840       }
2841     }
2842   }
2843 
2844   // Query only?
2845   if (option == no_create)  return NULL;
2846 
2847   // We did not find a compatible block.  Create one.
2848   Block* new_block = new (a) Block(this, _methodBlocks->block(ciBlockIndex), jsrs);
2849   if (option == create_backedge_copy)  new_block->set_backedge_copy(true);
2850   blocks->append(new_block);
2851   return new_block;
2852 }
2853 
2854 // ------------------------------------------------------------------
2855 // ciTypeFlow::backedge_copy_count
2856 //
2857 int ciTypeFlow::backedge_copy_count(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs) const {
2858   GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
2859 
2860   if (blocks == NULL) {
2861     return 0;
2862   }
2863 
2864   int count = 0;
2865   int len = blocks->length();
2866   for (int i = 0; i < len; i++) {
2867     Block* block = blocks->at(i);
2868     if (block->is_backedge_copy() && block->is_compatible_with(jsrs)) {
2869       count++;
2870     }
2871   }
2872 
2873   return count;
2874 }
2875 
2876 // ------------------------------------------------------------------
2877 // ciTypeFlow::do_flow
2878 //
2879 // Perform type inference flow analysis.
2880 void ciTypeFlow::do_flow() {
2881   if (CITraceTypeFlow) {
2882     tty->print_cr("\nPerforming flow analysis on method");
2883     method()->print();
2884     if (is_osr_flow())  tty->print(" at OSR bci %d", start_bci());
2885     tty->cr();
2886     method()->print_codes();
2887   }
2888   if (CITraceTypeFlow) {
2889     tty->print_cr("Initial CI Blocks");
2890     print_on(tty);
2891   }
2892   flow_types();
2893   // Watch for bailouts.
2894   if (failing()) {
2895     return;
2896   }
2897 
2898   map_blocks();
2899 
2900   if (CIPrintTypeFlow || CITraceTypeFlow) {
2901     rpo_print_on(tty);
2902   }
2903 }
2904 
2905 // ------------------------------------------------------------------
2906 // ciTypeFlow::is_dominated_by
2907 //
2908 // Determine if the instruction at bci is dominated by the instruction at dom_bci.
2909 bool ciTypeFlow::is_dominated_by(int bci, int dom_bci) {
2910   ResourceMark rm;
2911   JsrSet* jsrs = new ciTypeFlow::JsrSet(NULL);
2912   int        index = _methodBlocks->block_containing(bci)->index();
2913   int    dom_index = _methodBlocks->block_containing(dom_bci)->index();
2914   Block*     block = get_block_for(index, jsrs, ciTypeFlow::no_create);
2915   Block* dom_block = get_block_for(dom_index, jsrs, ciTypeFlow::no_create);
2916 
2917   // Start block dominates all other blocks
2918   if (start_block()->rpo() == dom_block->rpo()) {
2919     return true;
2920   }
2921 
2922   // Dominated[i] is true if block i is dominated by dom_block
2923   int num_blocks = _methodBlocks->num_blocks();
2924   bool* dominated = NEW_RESOURCE_ARRAY(bool, num_blocks);
2925   for (int i = 0; i < num_blocks; ++i) {
2926     dominated[i] = true;
2927   }
2928   dominated[start_block()->rpo()] = false;
2929 
2930   // Iterative dominator algorithm
2931   bool changed = true;
2932   while (changed) {
2933     changed = false;
2934     // Use reverse postorder iteration
2935     for (Block* blk = _rpo_list; blk != NULL; blk = blk->rpo_next()) {
2936       if (blk->is_start()) {
2937         // Ignore start block
2938         continue;
2939       }
2940       // The block is dominated if it is the dominating block
2941       // itself or if all predecessors are dominated.
2942       int index = blk->rpo();
2943       bool dom = (index == dom_block->rpo());
2944       if (!dom) {
2945         // Check if all predecessors are dominated
2946         dom = true;
2947         for (int i = 0; i < blk->predecessors()->length(); ++i) {
2948           Block* pred = blk->predecessors()->at(i);
2949           if (!dominated[pred->rpo()]) {
2950             dom = false;
2951             break;
2952           }
2953         }
2954       }
2955       // Update dominator information
2956       if (dominated[index] != dom) {
2957         changed = true;
2958         dominated[index] = dom;
2959       }
2960     }
2961   }
2962   // block dominated by dom_block?
2963   return dominated[block->rpo()];
2964 }
2965 
2966 // ------------------------------------------------------------------
2967 // ciTypeFlow::record_failure()
2968 // The ciTypeFlow object keeps track of failure reasons separately from the ciEnv.
2969 // This is required because there is not a 1-1 relation between the ciEnv and
2970 // the TypeFlow passes within a compilation task.  For example, if the compiler
2971 // is considering inlining a method, it will request a TypeFlow.  If that fails,
2972 // the compilation as a whole may continue without the inlining.  Some TypeFlow
2973 // requests are not optional; if they fail the requestor is responsible for
2974 // copying the failure reason up to the ciEnv.  (See Parse::Parse.)
2975 void ciTypeFlow::record_failure(const char* reason) {
2976   if (env()->log() != NULL) {
2977     env()->log()->elem("failure reason='%s' phase='typeflow'", reason);
2978   }
2979   if (_failure_reason == NULL) {
2980     // Record the first failure reason.
2981     _failure_reason = reason;
2982   }
2983 }
2984 
2985 #ifndef PRODUCT
2986 // ------------------------------------------------------------------
2987 // ciTypeFlow::print_on
2988 void ciTypeFlow::print_on(outputStream* st) const {
2989   // Walk through CI blocks
2990   st->print_cr("********************************************************");
2991   st->print   ("TypeFlow for ");
2992   method()->name()->print_symbol_on(st);
2993   int limit_bci = code_size();
2994   st->print_cr("  %d bytes", limit_bci);
2995   ciMethodBlocks  *mblks = _methodBlocks;
2996   ciBlock* current = NULL;
2997   for (int bci = 0; bci < limit_bci; bci++) {
2998     ciBlock* blk = mblks->block_containing(bci);
2999     if (blk != NULL && blk != current) {
3000       current = blk;
3001       current->print_on(st);
3002 
3003       GrowableArray<Block*>* blocks = _idx_to_blocklist[blk->index()];
3004       int num_blocks = (blocks == NULL) ? 0 : blocks->length();
3005 
3006       if (num_blocks == 0) {
3007         st->print_cr("  No Blocks");
3008       } else {
3009         for (int i = 0; i < num_blocks; i++) {
3010           Block* block = blocks->at(i);
3011           block->print_on(st);
3012         }
3013       }
3014       st->print_cr("--------------------------------------------------------");
3015       st->cr();
3016     }
3017   }
3018   st->print_cr("********************************************************");
3019   st->cr();
3020 }
3021 
3022 void ciTypeFlow::rpo_print_on(outputStream* st) const {
3023   st->print_cr("********************************************************");
3024   st->print   ("TypeFlow for ");
3025   method()->name()->print_symbol_on(st);
3026   int limit_bci = code_size();
3027   st->print_cr("  %d bytes", limit_bci);
3028   for (Block* blk = _rpo_list; blk != NULL; blk = blk->rpo_next()) {
3029     blk->print_on(st);
3030     st->print_cr("--------------------------------------------------------");
3031     st->cr();
3032   }
3033   st->print_cr("********************************************************");
3034   st->cr();
3035 }
3036 #endif