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