ciTypeFlow.cpp 90.9 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include "precompiled.hpp"
#include "ci/ciConstant.hpp"
#include "ci/ciField.hpp"
#include "ci/ciMethod.hpp"
#include "ci/ciMethodData.hpp"
#include "ci/ciObjArrayKlass.hpp"
#include "ci/ciStreams.hpp"
#include "ci/ciTypeArrayKlass.hpp"
#include "ci/ciTypeFlow.hpp"
#include "compiler/compileLog.hpp"
#include "interpreter/bytecode.hpp"
#include "interpreter/bytecodes.hpp"
#include "memory/allocation.inline.hpp"
#include "runtime/deoptimization.hpp"
#include "utilities/growableArray.hpp"
D
duke 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

// ciTypeFlow::JsrSet
//
// A JsrSet represents some set of JsrRecords.  This class
// is used to record a set of all jsr routines which we permit
// execution to return (ret) from.
//
// During abstract interpretation, JsrSets are used to determine
// whether two paths which reach a given block are unique, and
// should be cloned apart, or are compatible, and should merge
// together.

// ------------------------------------------------------------------
// ciTypeFlow::JsrSet::JsrSet
ciTypeFlow::JsrSet::JsrSet(Arena* arena, int default_len) {
  if (arena != NULL) {
    // Allocate growable array in Arena.
    _set = new (arena) GrowableArray<JsrRecord*>(arena, default_len, 0, NULL);
  } else {
    // Allocate growable array in current ResourceArea.
    _set = new GrowableArray<JsrRecord*>(4, 0, NULL, false);
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::JsrSet::copy_into
void ciTypeFlow::JsrSet::copy_into(JsrSet* jsrs) {
  int len = size();
  jsrs->_set->clear();
  for (int i = 0; i < len; i++) {
    jsrs->_set->append(_set->at(i));
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::JsrSet::is_compatible_with
//
// !!!! MISGIVINGS ABOUT THIS... disregard
//
// Is this JsrSet compatible with some other JsrSet?
//
// In set-theoretic terms, a JsrSet can be viewed as a partial function
// from entry addresses to return addresses.  Two JsrSets A and B are
// compatible iff
//
//   For any x,
//   A(x) defined and B(x) defined implies A(x) == B(x)
//
// Less formally, two JsrSets are compatible when they have identical
// return addresses for any entry addresses they share in common.
bool ciTypeFlow::JsrSet::is_compatible_with(JsrSet* other) {
  // Walk through both sets in parallel.  If the same entry address
  // appears in both sets, then the return address must match for
  // the sets to be compatible.
  int size1 = size();
  int size2 = other->size();

  // Special case.  If nothing is on the jsr stack, then there can
  // be no ret.
  if (size2 == 0) {
    return true;
  } else if (size1 != size2) {
    return false;
  } else {
    for (int i = 0; i < size1; i++) {
      JsrRecord* record1 = record_at(i);
      JsrRecord* record2 = other->record_at(i);
      if (record1->entry_address() != record2->entry_address() ||
          record1->return_address() != record2->return_address()) {
        return false;
      }
    }
    return true;
  }

#if 0
  int pos1 = 0;
  int pos2 = 0;
  int size1 = size();
  int size2 = other->size();
  while (pos1 < size1 && pos2 < size2) {
    JsrRecord* record1 = record_at(pos1);
    JsrRecord* record2 = other->record_at(pos2);
    int entry1 = record1->entry_address();
    int entry2 = record2->entry_address();
    if (entry1 < entry2) {
      pos1++;
    } else if (entry1 > entry2) {
      pos2++;
    } else {
      if (record1->return_address() == record2->return_address()) {
        pos1++;
        pos2++;
      } else {
        // These two JsrSets are incompatible.
        return false;
      }
    }
  }
  // The two JsrSets agree.
  return true;
#endif
}

// ------------------------------------------------------------------
// ciTypeFlow::JsrSet::insert_jsr_record
//
// Insert the given JsrRecord into the JsrSet, maintaining the order
// of the set and replacing any element with the same entry address.
void ciTypeFlow::JsrSet::insert_jsr_record(JsrRecord* record) {
  int len = size();
  int entry = record->entry_address();
  int pos = 0;
  for ( ; pos < len; pos++) {
    JsrRecord* current = record_at(pos);
    if (entry == current->entry_address()) {
      // Stomp over this entry.
      _set->at_put(pos, record);
      assert(size() == len, "must be same size");
      return;
    } else if (entry < current->entry_address()) {
      break;
    }
  }

  // Insert the record into the list.
  JsrRecord* swap = record;
  JsrRecord* temp = NULL;
  for ( ; pos < len; pos++) {
    temp = _set->at(pos);
    _set->at_put(pos, swap);
    swap = temp;
  }
  _set->append(swap);
  assert(size() == len+1, "must be larger");
}

// ------------------------------------------------------------------
// ciTypeFlow::JsrSet::remove_jsr_record
//
// Remove the JsrRecord with the given return address from the JsrSet.
void ciTypeFlow::JsrSet::remove_jsr_record(int return_address) {
  int len = size();
  for (int i = 0; i < len; i++) {
    if (record_at(i)->return_address() == return_address) {
      // We have found the proper entry.  Remove it from the
      // JsrSet and exit.
      for (int j = i+1; j < len ; j++) {
        _set->at_put(j-1, _set->at(j));
      }
      _set->trunc_to(len-1);
      assert(size() == len-1, "must be smaller");
      return;
    }
  }
  assert(false, "verify: returning from invalid subroutine");
}

// ------------------------------------------------------------------
// ciTypeFlow::JsrSet::apply_control
//
// Apply the effect of a control-flow bytecode on the JsrSet.  The
// only bytecodes that modify the JsrSet are jsr and ret.
void ciTypeFlow::JsrSet::apply_control(ciTypeFlow* analyzer,
                                       ciBytecodeStream* str,
                                       ciTypeFlow::StateVector* state) {
  Bytecodes::Code code = str->cur_bc();
  if (code == Bytecodes::_jsr) {
    JsrRecord* record =
      analyzer->make_jsr_record(str->get_dest(), str->next_bci());
    insert_jsr_record(record);
  } else if (code == Bytecodes::_jsr_w) {
    JsrRecord* record =
      analyzer->make_jsr_record(str->get_far_dest(), str->next_bci());
    insert_jsr_record(record);
  } else if (code == Bytecodes::_ret) {
    Cell local = state->local(str->get_index());
    ciType* return_address = state->type_at(local);
    assert(return_address->is_return_address(), "verify: wrong type");
    if (size() == 0) {
      // Ret-state underflow:  Hit a ret w/o any previous jsrs.  Bail out.
      // This can happen when a loop is inside a finally clause (4614060).
      analyzer->record_failure("OSR in finally clause");
      return;
    }
    remove_jsr_record(return_address->as_return_address()->bci());
  }
}

#ifndef PRODUCT
// ------------------------------------------------------------------
// ciTypeFlow::JsrSet::print_on
void ciTypeFlow::JsrSet::print_on(outputStream* st) const {
  st->print("{ ");
  int num_elements = size();
  if (num_elements > 0) {
    int i = 0;
    for( ; i < num_elements - 1; i++) {
      _set->at(i)->print_on(st);
      st->print(", ");
    }
    _set->at(i)->print_on(st);
    st->print(" ");
  }
  st->print("}");
}
#endif

// ciTypeFlow::StateVector
//
// A StateVector summarizes the type information at some point in
// the program.

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::type_meet
//
// Meet two types.
//
// The semi-lattice of types use by this analysis are modeled on those
// of the verifier.  The lattice is as follows:
//
//        top_type() >= all non-extremal types >= bottom_type
//                             and
//   Every primitive type is comparable only with itself.  The meet of
//   reference types is determined by their kind: instance class,
//   interface, or array class.  The meet of two types of the same
//   kind is their least common ancestor.  The meet of two types of
//   different kinds is always java.lang.Object.
ciType* ciTypeFlow::StateVector::type_meet_internal(ciType* t1, ciType* t2, ciTypeFlow* analyzer) {
  assert(t1 != t2, "checked in caller");
  if (t1->equals(top_type())) {
    return t2;
  } else if (t2->equals(top_type())) {
    return t1;
  } else if (t1->is_primitive_type() || t2->is_primitive_type()) {
    // Special case null_type.  null_type meet any reference type T
    // is T.  null_type meet null_type is null_type.
    if (t1->equals(null_type())) {
      if (!t2->is_primitive_type() || t2->equals(null_type())) {
        return t2;
      }
    } else if (t2->equals(null_type())) {
      if (!t1->is_primitive_type()) {
        return t1;
      }
    }

    // At least one of the two types is a non-top primitive type.
    // The other type is not equal to it.  Fall to bottom.
    return bottom_type();
  } else {
    // Both types are non-top non-primitive types.  That is,
    // both types are either instanceKlasses or arrayKlasses.
    ciKlass* object_klass = analyzer->env()->Object_klass();
    ciKlass* k1 = t1->as_klass();
    ciKlass* k2 = t2->as_klass();
    if (k1->equals(object_klass) || k2->equals(object_klass)) {
      return object_klass;
    } else if (!k1->is_loaded() || !k2->is_loaded()) {
      // Unloaded classes fall to java.lang.Object at a merge.
      return object_klass;
    } else if (k1->is_interface() != k2->is_interface()) {
      // When an interface meets a non-interface, we get Object;
      // This is what the verifier does.
      return object_klass;
    } else if (k1->is_array_klass() || k2->is_array_klass()) {
      // When an array meets a non-array, we get Object.
      // When objArray meets typeArray, we also get Object.
      // And when typeArray meets different typeArray, we again get Object.
      // But when objArray meets objArray, we look carefully at element types.
      if (k1->is_obj_array_klass() && k2->is_obj_array_klass()) {
        // Meet the element types, then construct the corresponding array type.
        ciKlass* elem1 = k1->as_obj_array_klass()->element_klass();
        ciKlass* elem2 = k2->as_obj_array_klass()->element_klass();
        ciKlass* elem  = type_meet_internal(elem1, elem2, analyzer)->as_klass();
        // Do an easy shortcut if one type is a super of the other.
        if (elem == elem1) {
          assert(k1 == ciObjArrayKlass::make(elem), "shortcut is OK");
          return k1;
        } else if (elem == elem2) {
          assert(k2 == ciObjArrayKlass::make(elem), "shortcut is OK");
          return k2;
        } else {
          return ciObjArrayKlass::make(elem);
        }
      } else {
        return object_klass;
      }
    } else {
      // Must be two plain old instance klasses.
      assert(k1->is_instance_klass(), "previous cases handle non-instances");
      assert(k2->is_instance_klass(), "previous cases handle non-instances");
      return k1->least_common_ancestor(k2);
    }
  }
}


// ------------------------------------------------------------------
// ciTypeFlow::StateVector::StateVector
//
// Build a new state vector
ciTypeFlow::StateVector::StateVector(ciTypeFlow* analyzer) {
  _outer = analyzer;
  _stack_size = -1;
  _monitor_count = -1;
  // Allocate the _types array
  int max_cells = analyzer->max_cells();
  _types = (ciType**)analyzer->arena()->Amalloc(sizeof(ciType*) * max_cells);
  for (int i=0; i<max_cells; i++) {
    _types[i] = top_type();
  }
  _trap_bci = -1;
  _trap_index = 0;
354
  _def_locals.clear();
D
duke 已提交
355 356
}

357

D
duke 已提交
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
// ------------------------------------------------------------------
// ciTypeFlow::get_start_state
//
// Set this vector to the method entry state.
const ciTypeFlow::StateVector* ciTypeFlow::get_start_state() {
  StateVector* state = new StateVector(this);
  if (is_osr_flow()) {
    ciTypeFlow* non_osr_flow = method()->get_flow_analysis();
    if (non_osr_flow->failing()) {
      record_failure(non_osr_flow->failure_reason());
      return NULL;
    }
    JsrSet* jsrs = new JsrSet(NULL, 16);
    Block* non_osr_block = non_osr_flow->existing_block_at(start_bci(), jsrs);
    if (non_osr_block == NULL) {
      record_failure("cannot reach OSR point");
      return NULL;
    }
    // load up the non-OSR state at this point
    non_osr_block->copy_state_into(state);
    int non_osr_start = non_osr_block->start();
    if (non_osr_start != start_bci()) {
      // must flow forward from it
      if (CITraceTypeFlow) {
        tty->print_cr(">> Interpreting pre-OSR block %d:", non_osr_start);
      }
      Block* block = block_at(non_osr_start, jsrs);
      assert(block->limit() == start_bci(), "must flow forward to start");
      flow_block(block, state, jsrs);
    }
    return state;
    // Note:  The code below would be an incorrect for an OSR flow,
    // even if it were possible for an OSR entry point to be at bci zero.
  }
  // "Push" the method signature into the first few locals.
  state->set_stack_size(-max_locals());
  if (!method()->is_static()) {
    state->push(method()->holder());
    assert(state->tos() == state->local(0), "");
  }
  for (ciSignatureStream str(method()->signature());
       !str.at_return_type();
       str.next()) {
    state->push_translate(str.type());
  }
  // Set the rest of the locals to bottom.
  Cell cell = state->next_cell(state->tos());
  state->set_stack_size(0);
  int limit = state->limit_cell();
  for (; cell < limit; cell = state->next_cell(cell)) {
    state->set_type_at(cell, state->bottom_type());
  }
  // Lock an object, if necessary.
  state->set_monitor_count(method()->is_synchronized() ? 1 : 0);
  return state;
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::copy_into
//
// Copy our value into some other StateVector
void ciTypeFlow::StateVector::copy_into(ciTypeFlow::StateVector* copy)
const {
  copy->set_stack_size(stack_size());
  copy->set_monitor_count(monitor_count());
  Cell limit = limit_cell();
  for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
    copy->set_type_at(c, type_at(c));
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::meet
//
// Meets this StateVector with another, destructively modifying this
// one.  Returns true if any modification takes place.
bool ciTypeFlow::StateVector::meet(const ciTypeFlow::StateVector* incoming) {
  if (monitor_count() == -1) {
    set_monitor_count(incoming->monitor_count());
  }
  assert(monitor_count() == incoming->monitor_count(), "monitors must match");

  if (stack_size() == -1) {
    set_stack_size(incoming->stack_size());
    Cell limit = limit_cell();
    #ifdef ASSERT
    { for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
        assert(type_at(c) == top_type(), "");
    } }
    #endif
    // Make a simple copy of the incoming state.
    for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
      set_type_at(c, incoming->type_at(c));
    }
    return true;  // it is always different the first time
  }
#ifdef ASSERT
  if (stack_size() != incoming->stack_size()) {
    _outer->method()->print_codes();
    tty->print_cr("!!!! Stack size conflict");
    tty->print_cr("Current state:");
    print_on(tty);
    tty->print_cr("Incoming state:");
    ((StateVector*)incoming)->print_on(tty);
  }
#endif
  assert(stack_size() == incoming->stack_size(), "sanity");

  bool different = false;
  Cell limit = limit_cell();
  for (Cell c = start_cell(); c < limit; c = next_cell(c)) {
    ciType* t1 = type_at(c);
    ciType* t2 = incoming->type_at(c);
    if (!t1->equals(t2)) {
      ciType* new_type = type_meet(t1, t2);
      if (!t1->equals(new_type)) {
        set_type_at(c, new_type);
        different = true;
      }
    }
  }
  return different;
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::meet_exception
//
// Meets this StateVector with another, destructively modifying this
// one.  The incoming state is coming via an exception.  Returns true
// if any modification takes place.
bool ciTypeFlow::StateVector::meet_exception(ciInstanceKlass* exc,
                                     const ciTypeFlow::StateVector* incoming) {
  if (monitor_count() == -1) {
    set_monitor_count(incoming->monitor_count());
  }
  assert(monitor_count() == incoming->monitor_count(), "monitors must match");

  if (stack_size() == -1) {
    set_stack_size(1);
  }

  assert(stack_size() ==  1, "must have one-element stack");

  bool different = false;

  // Meet locals from incoming array.
  Cell limit = local(_outer->max_locals()-1);
  for (Cell c = start_cell(); c <= limit; c = next_cell(c)) {
    ciType* t1 = type_at(c);
    ciType* t2 = incoming->type_at(c);
    if (!t1->equals(t2)) {
      ciType* new_type = type_meet(t1, t2);
      if (!t1->equals(new_type)) {
        set_type_at(c, new_type);
        different = true;
      }
    }
  }

  // Handle stack separately.  When an exception occurs, the
  // only stack entry is the exception instance.
  ciType* tos_type = type_at_tos();
  if (!tos_type->equals(exc)) {
    ciType* new_type = type_meet(tos_type, exc);
    if (!tos_type->equals(new_type)) {
      set_type_at_tos(new_type);
      different = true;
    }
  }

  return different;
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::push_translate
void ciTypeFlow::StateVector::push_translate(ciType* type) {
  BasicType basic_type = type->basic_type();
  if (basic_type == T_BOOLEAN || basic_type == T_CHAR ||
      basic_type == T_BYTE    || basic_type == T_SHORT) {
    push_int();
  } else {
    push(type);
    if (type->is_two_word()) {
      push(half_type(type));
    }
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_aaload
void ciTypeFlow::StateVector::do_aaload(ciBytecodeStream* str) {
  pop_int();
  ciObjArrayKlass* array_klass = pop_objArray();
  if (array_klass == NULL) {
    // Did aaload on a null reference; push a null and ignore the exception.
    // This instruction will never continue normally.  All we have to do
    // is report a value that will meet correctly with any downstream
    // reference types on paths that will truly be executed.  This null type
    // meets with any reference type to yield that same reference type.
T
twisti 已提交
557
    // (The compiler will generate an unconditional exception here.)
D
duke 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    push(null_type());
    return;
  }
  if (!array_klass->is_loaded()) {
    // Only fails for some -Xcomp runs
    trap(str, array_klass,
         Deoptimization::make_trap_request
         (Deoptimization::Reason_unloaded,
          Deoptimization::Action_reinterpret));
    return;
  }
  ciKlass* element_klass = array_klass->element_klass();
  if (!element_klass->is_loaded() && element_klass->is_instance_klass()) {
    Untested("unloaded array element class in ciTypeFlow");
    trap(str, element_klass,
         Deoptimization::make_trap_request
         (Deoptimization::Reason_unloaded,
          Deoptimization::Action_reinterpret));
  } else {
    push_object(element_klass);
  }
}


// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_checkcast
void ciTypeFlow::StateVector::do_checkcast(ciBytecodeStream* str) {
  bool will_link;
  ciKlass* klass = str->get_klass(will_link);
  if (!will_link) {
    // VM's interpreter will not load 'klass' if object is NULL.
    // Type flow after this block may still be needed in two situations:
    // 1) C2 uses do_null_assert() and continues compilation for later blocks
    // 2) C2 does an OSR compile in a later block (see bug 4778368).
    pop_object();
    do_null_assert(klass);
  } else {
    pop_object();
    push_object(klass);
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_getfield
void ciTypeFlow::StateVector::do_getfield(ciBytecodeStream* str) {
  // could add assert here for type of object.
  pop_object();
  do_getstatic(str);
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_getstatic
void ciTypeFlow::StateVector::do_getstatic(ciBytecodeStream* str) {
  bool will_link;
  ciField* field = str->get_field(will_link);
  if (!will_link) {
    trap(str, field->holder(), str->get_field_holder_index());
  } else {
    ciType* field_type = field->type();
    if (!field_type->is_loaded()) {
      // Normally, we need the field's type to be loaded if we are to
      // do anything interesting with its value.
      // We used to do this:  trap(str, str->get_field_signature_index());
      //
      // There is one good reason not to trap here.  Execution can
      // get past this "getfield" or "getstatic" if the value of
      // the field is null.  As long as the value is null, the class
      // does not need to be loaded!  The compiler must assume that
      // the value of the unloaded class reference is null; if the code
      // ever sees a non-null value, loading has occurred.
      //
      // This actually happens often enough to be annoying.  If the
      // compiler throws an uncommon trap at this bytecode, you can
      // get an endless loop of recompilations, when all the code
      // needs to do is load a series of null values.  Also, a trap
      // here can make an OSR entry point unreachable, triggering the
      // assert on non_osr_block in ciTypeFlow::get_start_state.
      // (See bug 4379915.)
      do_null_assert(field_type->as_klass());
    } else {
      push_translate(field_type);
    }
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_invoke
void ciTypeFlow::StateVector::do_invoke(ciBytecodeStream* str,
646
                                        bool has_receiver) {
D
duke 已提交
647
  bool will_link;
648 649 650
  ciSignature* declared_signature = NULL;
  ciMethod* callee = str->get_method(will_link, &declared_signature);
  assert(declared_signature != NULL, "cannot be null");
D
duke 已提交
651 652
  if (!will_link) {
    // We weren't able to find the method.
653 654 655 656 657 658
    if (str->cur_bc() == Bytecodes::_invokedynamic) {
      trap(str, NULL,
           Deoptimization::make_trap_request
           (Deoptimization::Reason_uninitialized,
            Deoptimization::Action_reinterpret));
    } else {
659
      ciKlass* unloaded_holder = callee->holder();
660 661
      trap(str, unloaded_holder, str->get_method_holder_index());
    }
D
duke 已提交
662
  } else {
663 664 665 666 667 668
    // We are using the declared signature here because it might be
    // different from the callee signature (Cf. invokedynamic and
    // invokehandle).
    ciSignatureStream sigstr(declared_signature);
    const int arg_size = declared_signature->size();
    const int stack_base = stack_size() - arg_size;
D
duke 已提交
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
    int i = 0;
    for( ; !sigstr.at_return_type(); sigstr.next()) {
      ciType* type = sigstr.type();
      ciType* stack_type = type_at(stack(stack_base + i++));
      // Do I want to check this type?
      // assert(stack_type->is_subtype_of(type), "bad type for field value");
      if (type->is_two_word()) {
        ciType* stack_type2 = type_at(stack(stack_base + i++));
        assert(stack_type2->equals(half_type(type)), "must be 2nd half");
      }
    }
    assert(arg_size == i, "must match");
    for (int j = 0; j < arg_size; j++) {
      pop();
    }
    if (has_receiver) {
      // Check this?
      pop_object();
    }
    assert(!sigstr.is_done(), "must have return type");
    ciType* return_type = sigstr.type();
    if (!return_type->is_void()) {
      if (!return_type->is_loaded()) {
        // As in do_getstatic(), generally speaking, we need the return type to
        // be loaded if we are to do anything interesting with its value.
        // We used to do this:  trap(str, str->get_method_signature_index());
        //
        // We do not trap here since execution can get past this invoke if
        // the return value is null.  As long as the value is null, the class
        // does not need to be loaded!  The compiler must assume that
        // the value of the unloaded class reference is null; if the code
        // ever sees a non-null value, loading has occurred.
        //
        // See do_getstatic() for similar explanation, as well as bug 4684993.
        do_null_assert(return_type->as_klass());
      } else {
        push_translate(return_type);
      }
    }
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_jsr
void ciTypeFlow::StateVector::do_jsr(ciBytecodeStream* str) {
  push(ciReturnAddress::make(str->next_bci()));
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_ldc
void ciTypeFlow::StateVector::do_ldc(ciBytecodeStream* str) {
  ciConstant con = str->get_constant();
  BasicType basic_type = con.basic_type();
  if (basic_type == T_ILLEGAL) {
    // OutOfMemoryError in the CI while loading constant
    push_null();
    outer()->record_failure("ldc did not link");
    return;
  }
  if (basic_type == T_OBJECT || basic_type == T_ARRAY) {
    ciObject* obj = con.as_object();
    if (obj->is_null_object()) {
      push_null();
    } else {
733
      assert(obj->is_instance() || obj->is_array(), "must be java_mirror of klass");
D
duke 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
      push_object(obj->klass());
    }
  } else {
    push_translate(ciType::make(basic_type));
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_multianewarray
void ciTypeFlow::StateVector::do_multianewarray(ciBytecodeStream* str) {
  int dimensions = str->get_dimensions();
  bool will_link;
  ciArrayKlass* array_klass = str->get_klass(will_link)->as_array_klass();
  if (!will_link) {
    trap(str, array_klass, str->get_klass_index());
  } else {
    for (int i = 0; i < dimensions; i++) {
      pop_int();
    }
    push_object(array_klass);
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_new
void ciTypeFlow::StateVector::do_new(ciBytecodeStream* str) {
  bool will_link;
  ciKlass* klass = str->get_klass(will_link);
762
  if (!will_link || str->is_unresolved_klass()) {
D
duke 已提交
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
    trap(str, klass, str->get_klass_index());
  } else {
    push_object(klass);
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_newarray
void ciTypeFlow::StateVector::do_newarray(ciBytecodeStream* str) {
  pop_int();
  ciKlass* klass = ciTypeArrayKlass::make((BasicType)str->get_index());
  push_object(klass);
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_putfield
void ciTypeFlow::StateVector::do_putfield(ciBytecodeStream* str) {
  do_putstatic(str);
  if (_trap_bci != -1)  return;  // unloaded field holder, etc.
  // could add assert here for type of object.
  pop_object();
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_putstatic
void ciTypeFlow::StateVector::do_putstatic(ciBytecodeStream* str) {
  bool will_link;
  ciField* field = str->get_field(will_link);
  if (!will_link) {
    trap(str, field->holder(), str->get_field_holder_index());
  } else {
    ciType* field_type = field->type();
    ciType* type = pop_value();
    // Do I want to check this type?
    //      assert(type->is_subtype_of(field_type), "bad type for field value");
    if (field_type->is_two_word()) {
      ciType* type2 = pop_value();
      assert(type2->is_two_word(), "must be 2nd half");
      assert(type == half_type(type2), "must be 2nd half");
    }
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_ret
void ciTypeFlow::StateVector::do_ret(ciBytecodeStream* str) {
  Cell index = local(str->get_index());

  ciType* address = type_at(index);
  assert(address->is_return_address(), "bad return address");
  set_type_at(index, bottom_type());
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::trap
//
// Stop interpretation of this path with a trap.
void ciTypeFlow::StateVector::trap(ciBytecodeStream* str, ciKlass* klass, int index) {
  _trap_bci = str->cur_bci();
  _trap_index = index;

  // Log information about this trap:
  CompileLog* log = outer()->env()->log();
  if (log != NULL) {
    int mid = log->identify(outer()->method());
    int kid = (klass == NULL)? -1: log->identify(klass);
    log->begin_elem("uncommon_trap method='%d' bci='%d'", mid, str->cur_bci());
    char buf[100];
    log->print(" %s", Deoptimization::format_trap_request(buf, sizeof(buf),
                                                          index));
    if (kid >= 0)
      log->print(" klass='%d'", kid);
    log->end_elem();
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::do_null_assert
// Corresponds to graphKit::do_null_assert.
void ciTypeFlow::StateVector::do_null_assert(ciKlass* unloaded_klass) {
  if (unloaded_klass->is_loaded()) {
    // We failed to link, but we can still compute with this class,
    // since it is loaded somewhere.  The compiler will uncommon_trap
    // if the object is not null, but the typeflow pass can not assume
    // that the object will be null, otherwise it may incorrectly tell
    // the parser that an object is known to be null. 4761344, 4807707
    push_object(unloaded_klass);
  } else {
    // The class is not loaded anywhere.  It is safe to model the
    // null in the typestates, because we can compile in a null check
    // which will deoptimize us if someone manages to load the
    // class later.
    push_null();
  }
}


// ------------------------------------------------------------------
// ciTypeFlow::StateVector::apply_one_bytecode
//
// Apply the effect of one bytecode to this StateVector
bool ciTypeFlow::StateVector::apply_one_bytecode(ciBytecodeStream* str) {
  _trap_bci = -1;
  _trap_index = 0;

  if (CITraceTypeFlow) {
    tty->print_cr(">> Interpreting bytecode %d:%s", str->cur_bci(),
                  Bytecodes::name(str->cur_bc()));
  }

  switch(str->cur_bc()) {
  case Bytecodes::_aaload: do_aaload(str);                       break;

  case Bytecodes::_aastore:
    {
      pop_object();
      pop_int();
      pop_objArray();
      break;
    }
  case Bytecodes::_aconst_null:
    {
      push_null();
      break;
    }
  case Bytecodes::_aload:   load_local_object(str->get_index());    break;
  case Bytecodes::_aload_0: load_local_object(0);                   break;
  case Bytecodes::_aload_1: load_local_object(1);                   break;
  case Bytecodes::_aload_2: load_local_object(2);                   break;
  case Bytecodes::_aload_3: load_local_object(3);                   break;

  case Bytecodes::_anewarray:
    {
      pop_int();
      bool will_link;
      ciKlass* element_klass = str->get_klass(will_link);
      if (!will_link) {
        trap(str, element_klass, str->get_klass_index());
      } else {
        push_object(ciObjArrayKlass::make(element_klass));
      }
      break;
    }
  case Bytecodes::_areturn:
  case Bytecodes::_ifnonnull:
  case Bytecodes::_ifnull:
    {
      pop_object();
      break;
    }
  case Bytecodes::_monitorenter:
    {
      pop_object();
      set_monitor_count(monitor_count() + 1);
      break;
    }
  case Bytecodes::_monitorexit:
    {
      pop_object();
      assert(monitor_count() > 0, "must be a monitor to exit from");
      set_monitor_count(monitor_count() - 1);
      break;
    }
  case Bytecodes::_arraylength:
    {
      pop_array();
      push_int();
      break;
    }
  case Bytecodes::_astore:   store_local_object(str->get_index());  break;
  case Bytecodes::_astore_0: store_local_object(0);                 break;
  case Bytecodes::_astore_1: store_local_object(1);                 break;
  case Bytecodes::_astore_2: store_local_object(2);                 break;
  case Bytecodes::_astore_3: store_local_object(3);                 break;

  case Bytecodes::_athrow:
    {
      NEEDS_CLEANUP;
      pop_object();
      break;
    }
  case Bytecodes::_baload:
  case Bytecodes::_caload:
  case Bytecodes::_iaload:
  case Bytecodes::_saload:
    {
      pop_int();
      ciTypeArrayKlass* array_klass = pop_typeArray();
      // Put assert here for right type?
      push_int();
      break;
    }
  case Bytecodes::_bastore:
  case Bytecodes::_castore:
  case Bytecodes::_iastore:
  case Bytecodes::_sastore:
    {
      pop_int();
      pop_int();
      pop_typeArray();
      // assert here?
      break;
    }
  case Bytecodes::_bipush:
  case Bytecodes::_iconst_m1:
  case Bytecodes::_iconst_0:
  case Bytecodes::_iconst_1:
  case Bytecodes::_iconst_2:
  case Bytecodes::_iconst_3:
  case Bytecodes::_iconst_4:
  case Bytecodes::_iconst_5:
  case Bytecodes::_sipush:
    {
      push_int();
      break;
    }
  case Bytecodes::_checkcast: do_checkcast(str);                  break;

  case Bytecodes::_d2f:
    {
      pop_double();
      push_float();
      break;
    }
  case Bytecodes::_d2i:
    {
      pop_double();
      push_int();
      break;
    }
  case Bytecodes::_d2l:
    {
      pop_double();
      push_long();
      break;
    }
  case Bytecodes::_dadd:
  case Bytecodes::_ddiv:
  case Bytecodes::_dmul:
  case Bytecodes::_drem:
  case Bytecodes::_dsub:
    {
      pop_double();
      pop_double();
      push_double();
      break;
    }
  case Bytecodes::_daload:
    {
      pop_int();
      ciTypeArrayKlass* array_klass = pop_typeArray();
      // Put assert here for right type?
      push_double();
      break;
    }
  case Bytecodes::_dastore:
    {
      pop_double();
      pop_int();
      pop_typeArray();
      // assert here?
      break;
    }
  case Bytecodes::_dcmpg:
  case Bytecodes::_dcmpl:
    {
      pop_double();
      pop_double();
      push_int();
      break;
    }
  case Bytecodes::_dconst_0:
  case Bytecodes::_dconst_1:
    {
      push_double();
      break;
    }
  case Bytecodes::_dload:   load_local_double(str->get_index());    break;
  case Bytecodes::_dload_0: load_local_double(0);                   break;
  case Bytecodes::_dload_1: load_local_double(1);                   break;
  case Bytecodes::_dload_2: load_local_double(2);                   break;
  case Bytecodes::_dload_3: load_local_double(3);                   break;

  case Bytecodes::_dneg:
    {
      pop_double();
      push_double();
      break;
    }
  case Bytecodes::_dreturn:
    {
      pop_double();
      break;
    }
  case Bytecodes::_dstore:   store_local_double(str->get_index());  break;
  case Bytecodes::_dstore_0: store_local_double(0);                 break;
  case Bytecodes::_dstore_1: store_local_double(1);                 break;
  case Bytecodes::_dstore_2: store_local_double(2);                 break;
  case Bytecodes::_dstore_3: store_local_double(3);                 break;

  case Bytecodes::_dup:
    {
      push(type_at_tos());
      break;
    }
  case Bytecodes::_dup_x1:
    {
      ciType* value1 = pop_value();
      ciType* value2 = pop_value();
      push(value1);
      push(value2);
      push(value1);
      break;
    }
  case Bytecodes::_dup_x2:
    {
      ciType* value1 = pop_value();
      ciType* value2 = pop_value();
      ciType* value3 = pop_value();
      push(value1);
      push(value3);
      push(value2);
      push(value1);
      break;
    }
  case Bytecodes::_dup2:
    {
      ciType* value1 = pop_value();
      ciType* value2 = pop_value();
      push(value2);
      push(value1);
      push(value2);
      push(value1);
      break;
    }
  case Bytecodes::_dup2_x1:
    {
      ciType* value1 = pop_value();
      ciType* value2 = pop_value();
      ciType* value3 = pop_value();
      push(value2);
      push(value1);
      push(value3);
      push(value2);
      push(value1);
      break;
    }
  case Bytecodes::_dup2_x2:
    {
      ciType* value1 = pop_value();
      ciType* value2 = pop_value();
      ciType* value3 = pop_value();
      ciType* value4 = pop_value();
      push(value2);
      push(value1);
      push(value4);
      push(value3);
      push(value2);
      push(value1);
      break;
    }
  case Bytecodes::_f2d:
    {
      pop_float();
      push_double();
      break;
    }
  case Bytecodes::_f2i:
    {
      pop_float();
      push_int();
      break;
    }
  case Bytecodes::_f2l:
    {
      pop_float();
      push_long();
      break;
    }
  case Bytecodes::_fadd:
  case Bytecodes::_fdiv:
  case Bytecodes::_fmul:
  case Bytecodes::_frem:
  case Bytecodes::_fsub:
    {
      pop_float();
      pop_float();
      push_float();
      break;
    }
  case Bytecodes::_faload:
    {
      pop_int();
      ciTypeArrayKlass* array_klass = pop_typeArray();
      // Put assert here.
      push_float();
      break;
    }
  case Bytecodes::_fastore:
    {
      pop_float();
      pop_int();
      ciTypeArrayKlass* array_klass = pop_typeArray();
      // Put assert here.
      break;
    }
  case Bytecodes::_fcmpg:
  case Bytecodes::_fcmpl:
    {
      pop_float();
      pop_float();
      push_int();
      break;
    }
  case Bytecodes::_fconst_0:
  case Bytecodes::_fconst_1:
  case Bytecodes::_fconst_2:
    {
      push_float();
      break;
    }
  case Bytecodes::_fload:   load_local_float(str->get_index());     break;
  case Bytecodes::_fload_0: load_local_float(0);                    break;
  case Bytecodes::_fload_1: load_local_float(1);                    break;
  case Bytecodes::_fload_2: load_local_float(2);                    break;
  case Bytecodes::_fload_3: load_local_float(3);                    break;

  case Bytecodes::_fneg:
    {
      pop_float();
      push_float();
      break;
    }
  case Bytecodes::_freturn:
    {
      pop_float();
      break;
    }
  case Bytecodes::_fstore:    store_local_float(str->get_index());   break;
  case Bytecodes::_fstore_0:  store_local_float(0);                  break;
  case Bytecodes::_fstore_1:  store_local_float(1);                  break;
  case Bytecodes::_fstore_2:  store_local_float(2);                  break;
  case Bytecodes::_fstore_3:  store_local_float(3);                  break;

  case Bytecodes::_getfield:  do_getfield(str);                      break;
  case Bytecodes::_getstatic: do_getstatic(str);                     break;

  case Bytecodes::_goto:
  case Bytecodes::_goto_w:
  case Bytecodes::_nop:
  case Bytecodes::_return:
    {
      // do nothing.
      break;
    }
  case Bytecodes::_i2b:
  case Bytecodes::_i2c:
  case Bytecodes::_i2s:
  case Bytecodes::_ineg:
    {
      pop_int();
      push_int();
      break;
    }
  case Bytecodes::_i2d:
    {
      pop_int();
      push_double();
      break;
    }
  case Bytecodes::_i2f:
    {
      pop_int();
      push_float();
      break;
    }
  case Bytecodes::_i2l:
    {
      pop_int();
      push_long();
      break;
    }
  case Bytecodes::_iadd:
  case Bytecodes::_iand:
  case Bytecodes::_idiv:
  case Bytecodes::_imul:
  case Bytecodes::_ior:
  case Bytecodes::_irem:
  case Bytecodes::_ishl:
  case Bytecodes::_ishr:
  case Bytecodes::_isub:
  case Bytecodes::_iushr:
  case Bytecodes::_ixor:
    {
      pop_int();
      pop_int();
      push_int();
      break;
    }
  case Bytecodes::_if_acmpeq:
  case Bytecodes::_if_acmpne:
    {
      pop_object();
      pop_object();
      break;
    }
  case Bytecodes::_if_icmpeq:
  case Bytecodes::_if_icmpge:
  case Bytecodes::_if_icmpgt:
  case Bytecodes::_if_icmple:
  case Bytecodes::_if_icmplt:
  case Bytecodes::_if_icmpne:
    {
      pop_int();
      pop_int();
      break;
    }
  case Bytecodes::_ifeq:
  case Bytecodes::_ifle:
  case Bytecodes::_iflt:
  case Bytecodes::_ifge:
  case Bytecodes::_ifgt:
  case Bytecodes::_ifne:
  case Bytecodes::_ireturn:
  case Bytecodes::_lookupswitch:
  case Bytecodes::_tableswitch:
    {
      pop_int();
      break;
    }
  case Bytecodes::_iinc:
    {
1295 1296 1297
      int lnum = str->get_index();
      check_int(local(lnum));
      store_to_local(lnum);
D
duke 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
      break;
    }
  case Bytecodes::_iload:   load_local_int(str->get_index()); break;
  case Bytecodes::_iload_0: load_local_int(0);                      break;
  case Bytecodes::_iload_1: load_local_int(1);                      break;
  case Bytecodes::_iload_2: load_local_int(2);                      break;
  case Bytecodes::_iload_3: load_local_int(3);                      break;

  case Bytecodes::_instanceof:
    {
      // Check for uncommon trap:
      do_checkcast(str);
      pop_object();
      push_int();
      break;
    }
  case Bytecodes::_invokeinterface: do_invoke(str, true);           break;
  case Bytecodes::_invokespecial:   do_invoke(str, true);           break;
  case Bytecodes::_invokestatic:    do_invoke(str, false);          break;
  case Bytecodes::_invokevirtual:   do_invoke(str, true);           break;
1318
  case Bytecodes::_invokedynamic:   do_invoke(str, false);          break;
D
duke 已提交
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534

  case Bytecodes::_istore:   store_local_int(str->get_index());     break;
  case Bytecodes::_istore_0: store_local_int(0);                    break;
  case Bytecodes::_istore_1: store_local_int(1);                    break;
  case Bytecodes::_istore_2: store_local_int(2);                    break;
  case Bytecodes::_istore_3: store_local_int(3);                    break;

  case Bytecodes::_jsr:
  case Bytecodes::_jsr_w: do_jsr(str);                              break;

  case Bytecodes::_l2d:
    {
      pop_long();
      push_double();
      break;
    }
  case Bytecodes::_l2f:
    {
      pop_long();
      push_float();
      break;
    }
  case Bytecodes::_l2i:
    {
      pop_long();
      push_int();
      break;
    }
  case Bytecodes::_ladd:
  case Bytecodes::_land:
  case Bytecodes::_ldiv:
  case Bytecodes::_lmul:
  case Bytecodes::_lor:
  case Bytecodes::_lrem:
  case Bytecodes::_lsub:
  case Bytecodes::_lxor:
    {
      pop_long();
      pop_long();
      push_long();
      break;
    }
  case Bytecodes::_laload:
    {
      pop_int();
      ciTypeArrayKlass* array_klass = pop_typeArray();
      // Put assert here for right type?
      push_long();
      break;
    }
  case Bytecodes::_lastore:
    {
      pop_long();
      pop_int();
      pop_typeArray();
      // assert here?
      break;
    }
  case Bytecodes::_lcmp:
    {
      pop_long();
      pop_long();
      push_int();
      break;
    }
  case Bytecodes::_lconst_0:
  case Bytecodes::_lconst_1:
    {
      push_long();
      break;
    }
  case Bytecodes::_ldc:
  case Bytecodes::_ldc_w:
  case Bytecodes::_ldc2_w:
    {
      do_ldc(str);
      break;
    }

  case Bytecodes::_lload:   load_local_long(str->get_index());      break;
  case Bytecodes::_lload_0: load_local_long(0);                     break;
  case Bytecodes::_lload_1: load_local_long(1);                     break;
  case Bytecodes::_lload_2: load_local_long(2);                     break;
  case Bytecodes::_lload_3: load_local_long(3);                     break;

  case Bytecodes::_lneg:
    {
      pop_long();
      push_long();
      break;
    }
  case Bytecodes::_lreturn:
    {
      pop_long();
      break;
    }
  case Bytecodes::_lshl:
  case Bytecodes::_lshr:
  case Bytecodes::_lushr:
    {
      pop_int();
      pop_long();
      push_long();
      break;
    }
  case Bytecodes::_lstore:   store_local_long(str->get_index());    break;
  case Bytecodes::_lstore_0: store_local_long(0);                   break;
  case Bytecodes::_lstore_1: store_local_long(1);                   break;
  case Bytecodes::_lstore_2: store_local_long(2);                   break;
  case Bytecodes::_lstore_3: store_local_long(3);                   break;

  case Bytecodes::_multianewarray: do_multianewarray(str);          break;

  case Bytecodes::_new:      do_new(str);                           break;

  case Bytecodes::_newarray: do_newarray(str);                      break;

  case Bytecodes::_pop:
    {
      pop();
      break;
    }
  case Bytecodes::_pop2:
    {
      pop();
      pop();
      break;
    }

  case Bytecodes::_putfield:       do_putfield(str);                 break;
  case Bytecodes::_putstatic:      do_putstatic(str);                break;

  case Bytecodes::_ret: do_ret(str);                                 break;

  case Bytecodes::_swap:
    {
      ciType* value1 = pop_value();
      ciType* value2 = pop_value();
      push(value1);
      push(value2);
      break;
    }
  case Bytecodes::_wide:
  default:
    {
      // The iterator should skip this.
      ShouldNotReachHere();
      break;
    }
  }

  if (CITraceTypeFlow) {
    print_on(tty);
  }

  return (_trap_bci != -1);
}

#ifndef PRODUCT
// ------------------------------------------------------------------
// ciTypeFlow::StateVector::print_cell_on
void ciTypeFlow::StateVector::print_cell_on(outputStream* st, Cell c) const {
  ciType* type = type_at(c);
  if (type == top_type()) {
    st->print("top");
  } else if (type == bottom_type()) {
    st->print("bottom");
  } else if (type == null_type()) {
    st->print("null");
  } else if (type == long2_type()) {
    st->print("long2");
  } else if (type == double2_type()) {
    st->print("double2");
  } else if (is_int(type)) {
    st->print("int");
  } else if (is_long(type)) {
    st->print("long");
  } else if (is_float(type)) {
    st->print("float");
  } else if (is_double(type)) {
    st->print("double");
  } else if (type->is_return_address()) {
    st->print("address(%d)", type->as_return_address()->bci());
  } else {
    if (type->is_klass()) {
      type->as_klass()->name()->print_symbol_on(st);
    } else {
      st->print("UNEXPECTED TYPE");
      type->print();
    }
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::StateVector::print_on
void ciTypeFlow::StateVector::print_on(outputStream* st) const {
  int num_locals   = _outer->max_locals();
  int num_stack    = stack_size();
  int num_monitors = monitor_count();
  st->print_cr("  State : locals %d, stack %d, monitors %d", num_locals, num_stack, num_monitors);
  if (num_stack >= 0) {
    int i;
    for (i = 0; i < num_locals; i++) {
      st->print("    local %2d : ", i);
      print_cell_on(st, local(i));
      st->cr();
    }
    for (i = 0; i < num_stack; i++) {
      st->print("    stack %2d : ", i);
      print_cell_on(st, stack(i));
      st->cr();
    }
  }
}
#endif

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574

// ------------------------------------------------------------------
// ciTypeFlow::SuccIter::next
//
void ciTypeFlow::SuccIter::next() {
  int succ_ct = _pred->successors()->length();
  int next = _index + 1;
  if (next < succ_ct) {
    _index = next;
    _succ = _pred->successors()->at(next);
    return;
  }
  for (int i = next - succ_ct; i < _pred->exceptions()->length(); i++) {
    // Do not compile any code for unloaded exception types.
    // Following compiler passes are responsible for doing this also.
    ciInstanceKlass* exception_klass = _pred->exc_klasses()->at(i);
    if (exception_klass->is_loaded()) {
      _index = next;
      _succ = _pred->exceptions()->at(i);
      return;
    }
    next++;
  }
  _index = -1;
  _succ = NULL;
}

// ------------------------------------------------------------------
// ciTypeFlow::SuccIter::set_succ
//
void ciTypeFlow::SuccIter::set_succ(Block* succ) {
  int succ_ct = _pred->successors()->length();
  if (_index < succ_ct) {
    _pred->successors()->at_put(_index, succ);
  } else {
    int idx = _index - succ_ct;
    _pred->exceptions()->at_put(idx, succ);
  }
}

D
duke 已提交
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
// ciTypeFlow::Block
//
// A basic block.

// ------------------------------------------------------------------
// ciTypeFlow::Block::Block
ciTypeFlow::Block::Block(ciTypeFlow* outer,
                         ciBlock *ciblk,
                         ciTypeFlow::JsrSet* jsrs) {
  _ciblock = ciblk;
  _exceptions = NULL;
  _exc_klasses = NULL;
  _successors = NULL;
  _state = new (outer->arena()) StateVector(outer);
  JsrSet* new_jsrs =
    new (outer->arena()) JsrSet(outer->arena(), jsrs->size());
  jsrs->copy_into(new_jsrs);
  _jsrs = new_jsrs;
  _next = NULL;
  _on_work_list = false;
1595
  _backedge_copy = false;
K
kvn 已提交
1596
  _has_monitorenter = false;
D
duke 已提交
1597 1598
  _trap_bci = -1;
  _trap_index = 0;
1599
  df_init();
D
duke 已提交
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610

  if (CITraceTypeFlow) {
    tty->print_cr(">> Created new block");
    print_on(tty);
  }

  assert(this->outer() == outer, "outer link set up");
  assert(!outer->have_block_count(), "must not have mapped blocks yet");
}

// ------------------------------------------------------------------
1611 1612 1613 1614 1615 1616 1617
// ciTypeFlow::Block::df_init
void ciTypeFlow::Block::df_init() {
  _pre_order = -1; assert(!has_pre_order(), "");
  _post_order = -1; assert(!has_post_order(), "");
  _loop = NULL;
  _irreducible_entry = false;
  _rpo_next = NULL;
D
duke 已提交
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
}

// ------------------------------------------------------------------
// ciTypeFlow::Block::successors
//
// Get the successors for this Block.
GrowableArray<ciTypeFlow::Block*>*
ciTypeFlow::Block::successors(ciBytecodeStream* str,
                              ciTypeFlow::StateVector* state,
                              ciTypeFlow::JsrSet* jsrs) {
  if (_successors == NULL) {
    if (CITraceTypeFlow) {
      tty->print(">> Computing successors for block ");
      print_value_on(tty);
      tty->cr();
    }

    ciTypeFlow* analyzer = outer();
    Arena* arena = analyzer->arena();
    Block* block = NULL;
    bool has_successor = !has_trap() &&
                         (control() != ciBlock::fall_through_bci || limit() < analyzer->code_size());
    if (!has_successor) {
      _successors =
        new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
      // No successors
    } else if (control() == ciBlock::fall_through_bci) {
      assert(str->cur_bci() == limit(), "bad block end");
      // This block simply falls through to the next.
      _successors =
        new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);

      Block* block = analyzer->block_at(limit(), _jsrs);
      assert(_successors->length() == FALL_THROUGH, "");
      _successors->append(block);
    } else {
      int current_bci = str->cur_bci();
      int next_bci = str->next_bci();
      int branch_bci = -1;
      Block* target = NULL;
      assert(str->next_bci() == limit(), "bad block end");
      // This block is not a simple fall-though.  Interpret
      // the current bytecode to find our successors.
      switch (str->cur_bc()) {
      case Bytecodes::_ifeq:         case Bytecodes::_ifne:
      case Bytecodes::_iflt:         case Bytecodes::_ifge:
      case Bytecodes::_ifgt:         case Bytecodes::_ifle:
      case Bytecodes::_if_icmpeq:    case Bytecodes::_if_icmpne:
      case Bytecodes::_if_icmplt:    case Bytecodes::_if_icmpge:
      case Bytecodes::_if_icmpgt:    case Bytecodes::_if_icmple:
      case Bytecodes::_if_acmpeq:    case Bytecodes::_if_acmpne:
      case Bytecodes::_ifnull:       case Bytecodes::_ifnonnull:
        // Our successors are the branch target and the next bci.
        branch_bci = str->get_dest();
        _successors =
          new (arena) GrowableArray<Block*>(arena, 2, 0, NULL);
        assert(_successors->length() == IF_NOT_TAKEN, "");
        _successors->append(analyzer->block_at(next_bci, jsrs));
        assert(_successors->length() == IF_TAKEN, "");
        _successors->append(analyzer->block_at(branch_bci, jsrs));
        break;

      case Bytecodes::_goto:
        branch_bci = str->get_dest();
        _successors =
          new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
        assert(_successors->length() == GOTO_TARGET, "");
1685
        _successors->append(analyzer->block_at(branch_bci, jsrs));
D
duke 已提交
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
        break;

      case Bytecodes::_jsr:
        branch_bci = str->get_dest();
        _successors =
          new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
        assert(_successors->length() == GOTO_TARGET, "");
        _successors->append(analyzer->block_at(branch_bci, jsrs));
        break;

      case Bytecodes::_goto_w:
      case Bytecodes::_jsr_w:
        _successors =
          new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
        assert(_successors->length() == GOTO_TARGET, "");
        _successors->append(analyzer->block_at(str->get_far_dest(), jsrs));
        break;

      case Bytecodes::_tableswitch:  {
1705
        Bytecode_tableswitch tableswitch(str);
D
duke 已提交
1706

1707
        int len = tableswitch.length();
D
duke 已提交
1708 1709
        _successors =
          new (arena) GrowableArray<Block*>(arena, len+1, 0, NULL);
1710
        int bci = current_bci + tableswitch.default_offset();
D
duke 已提交
1711 1712 1713 1714
        Block* block = analyzer->block_at(bci, jsrs);
        assert(_successors->length() == SWITCH_DEFAULT, "");
        _successors->append(block);
        while (--len >= 0) {
1715
          int bci = current_bci + tableswitch.dest_offset_at(len);
D
duke 已提交
1716 1717 1718 1719 1720 1721 1722 1723
          block = analyzer->block_at(bci, jsrs);
          assert(_successors->length() >= SWITCH_CASES, "");
          _successors->append_if_missing(block);
        }
        break;
      }

      case Bytecodes::_lookupswitch: {
1724
        Bytecode_lookupswitch lookupswitch(str);
D
duke 已提交
1725

1726
        int npairs = lookupswitch.number_of_pairs();
D
duke 已提交
1727 1728
        _successors =
          new (arena) GrowableArray<Block*>(arena, npairs+1, 0, NULL);
1729
        int bci = current_bci + lookupswitch.default_offset();
D
duke 已提交
1730 1731 1732 1733
        Block* block = analyzer->block_at(bci, jsrs);
        assert(_successors->length() == SWITCH_DEFAULT, "");
        _successors->append(block);
        while(--npairs >= 0) {
1734 1735
          LookupswitchPair pair = lookupswitch.pair_at(npairs);
          int bci = current_bci + pair.offset();
D
duke 已提交
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
          Block* block = analyzer->block_at(bci, jsrs);
          assert(_successors->length() >= SWITCH_CASES, "");
          _successors->append_if_missing(block);
        }
        break;
      }

      case Bytecodes::_athrow:     case Bytecodes::_ireturn:
      case Bytecodes::_lreturn:    case Bytecodes::_freturn:
      case Bytecodes::_dreturn:    case Bytecodes::_areturn:
      case Bytecodes::_return:
        _successors =
          new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);
        // No successors
        break;

      case Bytecodes::_ret: {
        _successors =
          new (arena) GrowableArray<Block*>(arena, 1, 0, NULL);

        Cell local = state->local(str->get_index());
        ciType* return_address = state->type_at(local);
        assert(return_address->is_return_address(), "verify: wrong type");
        int bci = return_address->as_return_address()->bci();
        assert(_successors->length() == GOTO_TARGET, "");
        _successors->append(analyzer->block_at(bci, jsrs));
        break;
      }

      case Bytecodes::_wide:
      default:
        ShouldNotReachHere();
        break;
      }
    }
  }
  return _successors;
}

// ------------------------------------------------------------------
// ciTypeFlow::Block:compute_exceptions
//
// Compute the exceptional successors and types for this Block.
void ciTypeFlow::Block::compute_exceptions() {
  assert(_exceptions == NULL && _exc_klasses == NULL, "repeat");

  if (CITraceTypeFlow) {
    tty->print(">> Computing exceptions for block ");
    print_value_on(tty);
    tty->cr();
  }

  ciTypeFlow* analyzer = outer();
  Arena* arena = analyzer->arena();

  // Any bci in the block will do.
  ciExceptionHandlerStream str(analyzer->method(), start());

  // Allocate our growable arrays.
  int exc_count = str.count();
  _exceptions = new (arena) GrowableArray<Block*>(arena, exc_count, 0, NULL);
  _exc_klasses = new (arena) GrowableArray<ciInstanceKlass*>(arena, exc_count,
                                                             0, NULL);

  for ( ; !str.is_done(); str.next()) {
    ciExceptionHandler* handler = str.handler();
    int bci = handler->handler_bci();
    ciInstanceKlass* klass = NULL;
    if (bci == -1) {
      // There is no catch all.  It is possible to exit the method.
      break;
    }
    if (handler->is_catch_all()) {
      klass = analyzer->env()->Throwable_klass();
    } else {
      klass = handler->catch_klass();
    }
    _exceptions->append(analyzer->block_at(bci, _jsrs));
    _exc_klasses->append(klass);
  }
}

// ------------------------------------------------------------------
1819 1820 1821 1822 1823 1824 1825 1826 1827
// ciTypeFlow::Block::set_backedge_copy
// Use this only to make a pre-existing public block into a backedge copy.
void ciTypeFlow::Block::set_backedge_copy(bool z) {
  assert(z || (z == is_backedge_copy()), "cannot make a backedge copy public");
  _backedge_copy = z;
}

// ------------------------------------------------------------------
// ciTypeFlow::Block::is_clonable_exit
D
duke 已提交
1828
//
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
// At most 2 normal successors, one of which continues looping,
// and all exceptional successors must exit.
bool ciTypeFlow::Block::is_clonable_exit(ciTypeFlow::Loop* lp) {
  int normal_cnt  = 0;
  int in_loop_cnt = 0;
  for (SuccIter iter(this); !iter.done(); iter.next()) {
    Block* succ = iter.succ();
    if (iter.is_normal_ctrl()) {
      if (++normal_cnt > 2) return false;
      if (lp->contains(succ->loop())) {
        if (++in_loop_cnt > 1) return false;
D
duke 已提交
1840
      }
1841 1842
    } else {
      if (lp->contains(succ->loop())) return false;
D
duke 已提交
1843 1844
    }
  }
1845
  return in_loop_cnt == 1;
D
duke 已提交
1846 1847 1848
}

// ------------------------------------------------------------------
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
// ciTypeFlow::Block::looping_succ
//
ciTypeFlow::Block* ciTypeFlow::Block::looping_succ(ciTypeFlow::Loop* lp) {
  assert(successors()->length() <= 2, "at most 2 normal successors");
  for (SuccIter iter(this); !iter.done(); iter.next()) {
    Block* succ = iter.succ();
    if (lp->contains(succ->loop())) {
      return succ;
    }
  }
  return NULL;
D
duke 已提交
1860 1861 1862 1863 1864 1865
}

#ifndef PRODUCT
// ------------------------------------------------------------------
// ciTypeFlow::Block::print_value_on
void ciTypeFlow::Block::print_value_on(outputStream* st) const {
1866 1867
  if (has_pre_order()) st->print("#%-2d ", pre_order());
  if (has_rpo())       st->print("rpo#%-2d ", rpo());
D
duke 已提交
1868
  st->print("[%d - %d)", start(), limit());
1869 1870
  if (is_loop_head()) st->print(" lphd");
  if (is_irreducible_entry()) st->print(" irred");
D
duke 已提交
1871
  if (_jsrs->size() > 0) { st->print("/");  _jsrs->print_on(st); }
1872
  if (is_backedge_copy())  st->print("/backedge_copy");
D
duke 已提交
1873 1874 1875 1876 1877
}

// ------------------------------------------------------------------
// ciTypeFlow::Block::print_on
void ciTypeFlow::Block::print_on(outputStream* st) const {
1878 1879
  if ((Verbose || WizardMode) && (limit() >= 0)) {
    // Don't print 'dummy' blocks (i.e. blocks with limit() '-1')
D
duke 已提交
1880 1881 1882 1883 1884
    outer()->method()->print_codes_on(start(), limit(), st);
  }
  st->print_cr("  ====================================================  ");
  st->print ("  ");
  print_value_on(st);
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
  st->print(" Stored locals: "); def_locals()->print_on(st, outer()->method()->max_locals()); tty->cr();
  if (loop() && loop()->parent() != NULL) {
    st->print(" loops:");
    Loop* lp = loop();
    do {
      st->print(" %d<-%d", lp->head()->pre_order(),lp->tail()->pre_order());
      if (lp->is_irreducible()) st->print("(ir)");
      lp = lp->parent();
    } while (lp->parent() != NULL);
  }
D
duke 已提交
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
  st->cr();
  _state->print_on(st);
  if (_successors == NULL) {
    st->print_cr("  No successor information");
  } else {
    int num_successors = _successors->length();
    st->print_cr("  Successors : %d", num_successors);
    for (int i = 0; i < num_successors; i++) {
      Block* successor = _successors->at(i);
      st->print("    ");
      successor->print_value_on(st);
      st->cr();
    }
  }
  if (_exceptions == NULL) {
    st->print_cr("  No exception information");
  } else {
    int num_exceptions = _exceptions->length();
    st->print_cr("  Exceptions : %d", num_exceptions);
    for (int i = 0; i < num_exceptions; i++) {
      Block* exc_succ = _exceptions->at(i);
      ciInstanceKlass* exc_klass = _exc_klasses->at(i);
      st->print("    ");
      exc_succ->print_value_on(st);
      st->print(" -- ");
      exc_klass->name()->print_symbol_on(st);
      st->cr();
    }
  }
  if (has_trap()) {
    st->print_cr("  Traps on %d with trap index %d", trap_bci(), trap_index());
  }
  st->print_cr("  ====================================================  ");
}
#endif

1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
#ifndef PRODUCT
// ------------------------------------------------------------------
// ciTypeFlow::LocalSet::print_on
void ciTypeFlow::LocalSet::print_on(outputStream* st, int limit) const {
  st->print("{");
  for (int i = 0; i < max; i++) {
    if (test(i)) st->print(" %d", i);
  }
  if (limit > max) {
    st->print(" %d..%d ", max, limit);
  }
  st->print(" }");
}
#endif

D
duke 已提交
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960
// ciTypeFlow
//
// This is a pass over the bytecodes which computes the following:
//   basic block structure
//   interpreter type-states (a la the verifier)

// ------------------------------------------------------------------
// ciTypeFlow::ciTypeFlow
ciTypeFlow::ciTypeFlow(ciEnv* env, ciMethod* method, int osr_bci) {
  _env = env;
  _method = method;
  _methodBlocks = method->get_method_blocks();
  _max_locals = method->max_locals();
  _max_stack = method->max_stack();
  _code_size = method->code_size();
1961
  _has_irreducible_entry = false;
D
duke 已提交
1962 1963
  _osr_bci = osr_bci;
  _failure_reason = NULL;
1964
  assert(0 <= start_bci() && start_bci() < code_size() , err_msg("correct osr_bci argument: 0 <= %d < %d", start_bci(), code_size()));
D
duke 已提交
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
  _work_list = NULL;

  _ciblock_count = _methodBlocks->num_blocks();
  _idx_to_blocklist = NEW_ARENA_ARRAY(arena(), GrowableArray<Block*>*, _ciblock_count);
  for (int i = 0; i < _ciblock_count; i++) {
    _idx_to_blocklist[i] = NULL;
  }
  _block_map = NULL;  // until all blocks are seen
  _jsr_count = 0;
  _jsr_records = NULL;
}

// ------------------------------------------------------------------
// ciTypeFlow::work_list_next
//
// Get the next basic block from our work list.
ciTypeFlow::Block* ciTypeFlow::work_list_next() {
  assert(!work_list_empty(), "work list must not be empty");
  Block* next_block = _work_list;
  _work_list = next_block->next();
  next_block->set_next(NULL);
  next_block->set_on_work_list(false);
  return next_block;
}

// ------------------------------------------------------------------
// ciTypeFlow::add_to_work_list
//
// Add a basic block to our work list.
1994
// List is sorted by decreasing postorder sort (same as increasing RPO)
D
duke 已提交
1995 1996 1997 1998
void ciTypeFlow::add_to_work_list(ciTypeFlow::Block* block) {
  assert(!block->is_on_work_list(), "must not already be on work list");

  if (CITraceTypeFlow) {
1999
    tty->print(">> Adding block ");
D
duke 已提交
2000 2001 2002 2003 2004
    block->print_value_on(tty);
    tty->print_cr(" to the work list : ");
  }

  block->set_on_work_list(true);
2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017

  // decreasing post order sort

  Block* prev = NULL;
  Block* current = _work_list;
  int po = block->post_order();
  while (current != NULL) {
    if (!current->has_post_order() || po > current->post_order())
      break;
    prev = current;
    current = current->next();
  }
  if (prev == NULL) {
D
duke 已提交
2018 2019 2020
    block->set_next(_work_list);
    _work_list = block;
  } else {
2021 2022
    block->set_next(current);
    prev->set_next(block);
D
duke 已提交
2023
  }
2024

D
duke 已提交
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046
  if (CITraceTypeFlow) {
    tty->cr();
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::block_at
//
// Return the block beginning at bci which has a JsrSet compatible
// with jsrs.
ciTypeFlow::Block* ciTypeFlow::block_at(int bci, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
  // First find the right ciBlock.
  if (CITraceTypeFlow) {
    tty->print(">> Requesting block for %d/", bci);
    jsrs->print_on(tty);
    tty->cr();
  }

  ciBlock* ciblk = _methodBlocks->block_containing(bci);
  assert(ciblk->start_bci() == bci, "bad ciBlock boundaries");
  Block* block = get_block_for(ciblk->index(), jsrs, option);

2047
  assert(block == NULL? (option == no_create): block->is_backedge_copy() == (option == create_backedge_copy), "create option consistent with result");
D
duke 已提交
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110

  if (CITraceTypeFlow) {
    if (block != NULL) {
      tty->print(">> Found block ");
      block->print_value_on(tty);
      tty->cr();
    } else {
      tty->print_cr(">> No such block.");
    }
  }

  return block;
}

// ------------------------------------------------------------------
// ciTypeFlow::make_jsr_record
//
// Make a JsrRecord for a given (entry, return) pair, if such a record
// does not already exist.
ciTypeFlow::JsrRecord* ciTypeFlow::make_jsr_record(int entry_address,
                                                   int return_address) {
  if (_jsr_records == NULL) {
    _jsr_records = new (arena()) GrowableArray<JsrRecord*>(arena(),
                                                           _jsr_count,
                                                           0,
                                                           NULL);
  }
  JsrRecord* record = NULL;
  int len = _jsr_records->length();
  for (int i = 0; i < len; i++) {
    JsrRecord* record = _jsr_records->at(i);
    if (record->entry_address() == entry_address &&
        record->return_address() == return_address) {
      return record;
    }
  }

  record = new (arena()) JsrRecord(entry_address, return_address);
  _jsr_records->append(record);
  return record;
}

// ------------------------------------------------------------------
// ciTypeFlow::flow_exceptions
//
// Merge the current state into all exceptional successors at the
// current point in the code.
void ciTypeFlow::flow_exceptions(GrowableArray<ciTypeFlow::Block*>* exceptions,
                                 GrowableArray<ciInstanceKlass*>* exc_klasses,
                                 ciTypeFlow::StateVector* state) {
  int len = exceptions->length();
  assert(exc_klasses->length() == len, "must have same length");
  for (int i = 0; i < len; i++) {
    Block* block = exceptions->at(i);
    ciInstanceKlass* exception_klass = exc_klasses->at(i);

    if (!exception_klass->is_loaded()) {
      // Do not compile any code for unloaded exception types.
      // Following compiler passes are responsible for doing this also.
      continue;
    }

    if (block->meet_exception(exception_klass, state)) {
2111 2112 2113
      // Block was modified and has PO.  Add it to the work list.
      if (block->has_post_order() &&
          !block->is_on_work_list()) {
D
duke 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
        add_to_work_list(block);
      }
    }
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::flow_successors
//
// Merge the current state into all successors at the current point
// in the code.
void ciTypeFlow::flow_successors(GrowableArray<ciTypeFlow::Block*>* successors,
                                 ciTypeFlow::StateVector* state) {
  int len = successors->length();
  for (int i = 0; i < len; i++) {
    Block* block = successors->at(i);
    if (block->meet(state)) {
2131 2132 2133
      // Block was modified and has PO.  Add it to the work list.
      if (block->has_post_order() &&
          !block->is_on_work_list()) {
D
duke 已提交
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
        add_to_work_list(block);
      }
    }
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::can_trap
//
// Tells if a given instruction is able to generate an exception edge.
bool ciTypeFlow::can_trap(ciBytecodeStream& str) {
  // Cf. GenerateOopMap::do_exception_edge.
  if (!Bytecodes::can_trap(str.cur_bc()))  return false;

  switch (str.cur_bc()) {
2149
    // %%% FIXME: ldc of Class can generate an exception
D
duke 已提交
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
    case Bytecodes::_ldc:
    case Bytecodes::_ldc_w:
    case Bytecodes::_ldc2_w:
    case Bytecodes::_aload_0:
      // These bytecodes can trap for rewriting.  We need to assume that
      // they do not throw exceptions to make the monitor analysis work.
      return false;

    case Bytecodes::_ireturn:
    case Bytecodes::_lreturn:
    case Bytecodes::_freturn:
    case Bytecodes::_dreturn:
    case Bytecodes::_areturn:
    case Bytecodes::_return:
      // We can assume the monitor stack is empty in this analysis.
      return false;

    case Bytecodes::_monitorexit:
      // We can assume monitors are matched in this analysis.
      return false;
  }

  return true;
}

2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188
// ------------------------------------------------------------------
// ciTypeFlow::clone_loop_heads
//
// Clone the loop heads
bool ciTypeFlow::clone_loop_heads(Loop* lp, StateVector* temp_vector, JsrSet* temp_set) {
  bool rslt = false;
  for (PreorderLoops iter(loop_tree_root()); !iter.done(); iter.next()) {
    lp = iter.current();
    Block* head = lp->head();
    if (lp == loop_tree_root() ||
        lp->is_irreducible() ||
        !head->is_clonable_exit(lp))
      continue;

K
kvn 已提交
2189 2190 2191 2192
    // Avoid BoxLock merge.
    if (EliminateNestedLocks && head->has_monitorenter())
      continue;

2193 2194 2195
    // check not already cloned
    if (head->backedge_copy_count() != 0)
      continue;
2196 2197 2198 2199

    // Don't clone head of OSR loop to get correct types in start block.
    if (is_osr_flow() && head->start() == start_bci())
      continue;
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286

    // check _no_ shared head below us
    Loop* ch;
    for (ch = lp->child(); ch != NULL && ch->head() != head; ch = ch->sibling());
    if (ch != NULL)
      continue;

    // Clone head
    Block* new_head = head->looping_succ(lp);
    Block* clone = clone_loop_head(lp, temp_vector, temp_set);
    // Update lp's info
    clone->set_loop(lp);
    lp->set_head(new_head);
    lp->set_tail(clone);
    // And move original head into outer loop
    head->set_loop(lp->parent());

    rslt = true;
  }
  return rslt;
}

// ------------------------------------------------------------------
// ciTypeFlow::clone_loop_head
//
// Clone lp's head and replace tail's successors with clone.
//
//  |
//  v
// head <-> body
//  |
//  v
// exit
//
// new_head
//
//  |
//  v
// head ----------\
//  |             |
//  |             v
//  |  clone <-> body
//  |    |
//  | /--/
//  | |
//  v v
// exit
//
ciTypeFlow::Block* ciTypeFlow::clone_loop_head(Loop* lp, StateVector* temp_vector, JsrSet* temp_set) {
  Block* head = lp->head();
  Block* tail = lp->tail();
  if (CITraceTypeFlow) {
    tty->print(">> Requesting clone of loop head "); head->print_value_on(tty);
    tty->print("  for predecessor ");                tail->print_value_on(tty);
    tty->cr();
  }
  Block* clone = block_at(head->start(), head->jsrs(), create_backedge_copy);
  assert(clone->backedge_copy_count() == 1, "one backedge copy for all back edges");

  assert(!clone->has_pre_order(), "just created");
  clone->set_next_pre_order();

  // Insert clone after (orig) tail in reverse post order
  clone->set_rpo_next(tail->rpo_next());
  tail->set_rpo_next(clone);

  // tail->head becomes tail->clone
  for (SuccIter iter(tail); !iter.done(); iter.next()) {
    if (iter.succ() == head) {
      iter.set_succ(clone);
    }
  }
  flow_block(tail, temp_vector, temp_set);
  if (head == tail) {
    // For self-loops, clone->head becomes clone->clone
    flow_block(clone, temp_vector, temp_set);
    for (SuccIter iter(clone); !iter.done(); iter.next()) {
      if (iter.succ() == head) {
        iter.set_succ(clone);
        break;
      }
    }
  }
  flow_block(clone, temp_vector, temp_set);

  return clone;
}
D
duke 已提交
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312

// ------------------------------------------------------------------
// ciTypeFlow::flow_block
//
// Interpret the effects of the bytecodes on the incoming state
// vector of a basic block.  Push the changed state to succeeding
// basic blocks.
void ciTypeFlow::flow_block(ciTypeFlow::Block* block,
                            ciTypeFlow::StateVector* state,
                            ciTypeFlow::JsrSet* jsrs) {
  if (CITraceTypeFlow) {
    tty->print("\n>> ANALYZING BLOCK : ");
    tty->cr();
    block->print_on(tty);
  }
  assert(block->has_pre_order(), "pre-order is assigned before 1st flow");

  int start = block->start();
  int limit = block->limit();
  int control = block->control();
  if (control != ciBlock::fall_through_bci) {
    limit = control;
  }

  // Grab the state from the current block.
  block->copy_state_into(state);
2313
  state->def_locals()->clear();
D
duke 已提交
2314 2315 2316 2317 2318

  GrowableArray<Block*>*           exceptions = block->exceptions();
  GrowableArray<ciInstanceKlass*>* exc_klasses = block->exc_klasses();
  bool has_exceptions = exceptions->length() > 0;

2319 2320
  bool exceptions_used = false;

D
duke 已提交
2321 2322 2323 2324 2325 2326 2327 2328
  ciBytecodeStream str(method());
  str.reset_to_bci(start);
  Bytecodes::Code code;
  while ((code = str.next()) != ciBytecodeStream::EOBC() &&
         str.cur_bci() < limit) {
    // Check for exceptional control flow from this point.
    if (has_exceptions && can_trap(str)) {
      flow_exceptions(exceptions, exc_klasses, state);
2329
      exceptions_used = true;
D
duke 已提交
2330 2331 2332 2333 2334 2335 2336
    }
    // Apply the effects of the current bytecode to our state.
    bool res = state->apply_one_bytecode(&str);

    // Watch for bailouts.
    if (failing())  return;

K
kvn 已提交
2337 2338 2339 2340
    if (str.cur_bc() == Bytecodes::_monitorenter) {
      block->set_has_monitorenter();
    }

D
duke 已提交
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
    if (res) {

      // We have encountered a trap.  Record it in this block.
      block->set_trap(state->trap_bci(), state->trap_index());

      if (CITraceTypeFlow) {
        tty->print_cr(">> Found trap");
        block->print_on(tty);
      }

2351 2352 2353
      // Save set of locals defined in this block
      block->def_locals()->add(state->def_locals());

D
duke 已提交
2354 2355 2356
      // Record (no) successors.
      block->successors(&str, state, jsrs);

2357 2358
      assert(!has_exceptions || exceptions_used, "Not removing exceptions");

D
duke 已提交
2359 2360 2361 2362 2363 2364 2365 2366 2367 2368
      // Discontinue interpretation of this Block.
      return;
    }
  }

  GrowableArray<Block*>* successors = NULL;
  if (control != ciBlock::fall_through_bci) {
    // Check for exceptional control flow from this point.
    if (has_exceptions && can_trap(str)) {
      flow_exceptions(exceptions, exc_klasses, state);
2369
      exceptions_used = true;
D
duke 已提交
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385
    }

    // Fix the JsrSet to reflect effect of the bytecode.
    block->copy_jsrs_into(jsrs);
    jsrs->apply_control(this, &str, state);

    // Find successor edges based on old state and new JsrSet.
    successors = block->successors(&str, state, jsrs);

    // Apply the control changes to the state.
    state->apply_one_bytecode(&str);
  } else {
    // Fall through control
    successors = block->successors(&str, NULL, NULL);
  }

2386 2387 2388 2389 2390 2391 2392
  // Save set of locals defined in this block
  block->def_locals()->add(state->def_locals());

  // Remove untaken exception paths
  if (!exceptions_used)
    exceptions->clear();

D
duke 已提交
2393 2394 2395 2396
  // Pass our state to successors.
  flow_successors(successors, state);
}

2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
// ------------------------------------------------------------------
// ciTypeFlow::PostOrderLoops::next
//
// Advance to next loop tree using a postorder, left-to-right traversal.
void ciTypeFlow::PostorderLoops::next() {
  assert(!done(), "must not be done.");
  if (_current->sibling() != NULL) {
    _current = _current->sibling();
    while (_current->child() != NULL) {
      _current = _current->child();
    }
  } else {
    _current = _current->parent();
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::PreOrderLoops::next
//
// Advance to next loop tree using a preorder, left-to-right traversal.
void ciTypeFlow::PreorderLoops::next() {
  assert(!done(), "must not be done.");
  if (_current->child() != NULL) {
    _current = _current->child();
  } else if (_current->sibling() != NULL) {
    _current = _current->sibling();
  } else {
    while (_current != _root && _current->sibling() == NULL) {
      _current = _current->parent();
    }
    if (_current == _root) {
      _current = NULL;
      assert(done(), "must be done.");
    } else {
      assert(_current->sibling() != NULL, "must be more to do");
      _current = _current->sibling();
    }
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::Loop::sorted_merge
//
// Merge the branch lp into this branch, sorting on the loop head
// pre_orders. Returns the leaf of the merged branch.
// Child and sibling pointers will be setup later.
// Sort is (looking from leaf towards the root)
//  descending on primary key: loop head's pre_order, and
//  ascending  on secondary key: loop tail's pre_order.
ciTypeFlow::Loop* ciTypeFlow::Loop::sorted_merge(Loop* lp) {
  Loop* leaf = this;
  Loop* prev = NULL;
  Loop* current = leaf;
  while (lp != NULL) {
    int lp_pre_order = lp->head()->pre_order();
    // Find insertion point for "lp"
    while (current != NULL) {
      if (current == lp)
        return leaf; // Already in list
      if (current->head()->pre_order() < lp_pre_order)
        break;
      if (current->head()->pre_order() == lp_pre_order &&
          current->tail()->pre_order() > lp->tail()->pre_order()) {
        break;
      }
      prev = current;
      current = current->parent();
    }
    Loop* next_lp = lp->parent(); // Save future list of items to insert
    // Insert lp before current
    lp->set_parent(current);
    if (prev != NULL) {
      prev->set_parent(lp);
    } else {
      leaf = lp;
    }
    prev = lp;     // Inserted item is new prev[ious]
    lp = next_lp;  // Next item to insert
  }
  return leaf;
}

// ------------------------------------------------------------------
// ciTypeFlow::build_loop_tree
//
// Incrementally build loop tree.
void ciTypeFlow::build_loop_tree(Block* blk) {
  assert(!blk->is_post_visited(), "precondition");
  Loop* innermost = NULL; // merge of loop tree branches over all successors

  for (SuccIter iter(blk); !iter.done(); iter.next()) {
    Loop*  lp   = NULL;
    Block* succ = iter.succ();
    if (!succ->is_post_visited()) {
      // Found backedge since predecessor post visited, but successor is not
      assert(succ->pre_order() <= blk->pre_order(), "should be backedge");

      // Create a LoopNode to mark this loop.
      lp = new (arena()) Loop(succ, blk);
      if (succ->loop() == NULL)
        succ->set_loop(lp);
      // succ->loop will be updated to innermost loop on a later call, when blk==succ

    } else {  // Nested loop
      lp = succ->loop();

      // If succ is loop head, find outer loop.
      while (lp != NULL && lp->head() == succ) {
        lp = lp->parent();
      }
      if (lp == NULL) {
        // Infinite loop, it's parent is the root
        lp = loop_tree_root();
      }
    }

    // Check for irreducible loop.
    // Successor has already been visited. If the successor's loop head
    // has already been post-visited, then this is another entry into the loop.
    while (lp->head()->is_post_visited() && lp != loop_tree_root()) {
      _has_irreducible_entry = true;
      lp->set_irreducible(succ);
      if (!succ->is_on_work_list()) {
        // Assume irreducible entries need more data flow
        add_to_work_list(succ);
      }
2523 2524 2525 2526 2527 2528 2529
      Loop* plp = lp->parent();
      if (plp == NULL) {
        // This only happens for some irreducible cases.  The parent
        // will be updated during a later pass.
        break;
      }
      lp = plp;
2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542
    }

    // Merge loop tree branch for all successors.
    innermost = innermost == NULL ? lp : innermost->sorted_merge(lp);

  } // end loop

  if (innermost == NULL) {
    assert(blk->successors()->length() == 0, "CFG exit");
    blk->set_loop(loop_tree_root());
  } else if (innermost->head() == blk) {
    // If loop header, complete the tree pointers
    if (blk->loop() != innermost) {
2543
#ifdef ASSERT
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
      assert(blk->loop()->head() == innermost->head(), "same head");
      Loop* dl;
      for (dl = innermost; dl != NULL && dl != blk->loop(); dl = dl->parent());
      assert(dl == blk->loop(), "blk->loop() already in innermost list");
#endif
      blk->set_loop(innermost);
    }
    innermost->def_locals()->add(blk->def_locals());
    Loop* l = innermost;
    Loop* p = l->parent();
    while (p && l->head() == blk) {
      l->set_sibling(p->child());  // Put self on parents 'next child'
      p->set_child(l);             // Make self the first child of parent
      p->def_locals()->add(l->def_locals());
      l = p;                       // Walk up the parent chain
      p = l->parent();
    }
  } else {
    blk->set_loop(innermost);
    innermost->def_locals()->add(blk->def_locals());
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::Loop::contains
//
// Returns true if lp is nested loop.
bool ciTypeFlow::Loop::contains(ciTypeFlow::Loop* lp) const {
  assert(lp != NULL, "");
  if (this == lp || head() == lp->head()) return true;
  int depth1 = depth();
  int depth2 = lp->depth();
  if (depth1 > depth2)
    return false;
  while (depth1 < depth2) {
    depth2--;
    lp = lp->parent();
  }
  return this == lp;
}

// ------------------------------------------------------------------
// ciTypeFlow::Loop::depth
//
// Loop depth
int ciTypeFlow::Loop::depth() const {
  int dp = 0;
  for (Loop* lp = this->parent(); lp != NULL; lp = lp->parent())
    dp++;
  return dp;
}

#ifndef PRODUCT
// ------------------------------------------------------------------
// ciTypeFlow::Loop::print
void ciTypeFlow::Loop::print(outputStream* st, int indent) const {
  for (int i = 0; i < indent; i++) st->print(" ");
  st->print("%d<-%d %s",
            is_root() ? 0 : this->head()->pre_order(),
            is_root() ? 0 : this->tail()->pre_order(),
            is_irreducible()?" irr":"");
  st->print(" defs: ");
  def_locals()->print_on(st, _head->outer()->method()->max_locals());
  st->cr();
  for (Loop* ch = child(); ch != NULL; ch = ch->sibling())
    ch->print(st, indent+2);
}
#endif

// ------------------------------------------------------------------
// ciTypeFlow::df_flow_types
//
// Perform the depth first type flow analysis. Helper for flow_types.
void ciTypeFlow::df_flow_types(Block* start,
                               bool do_flow,
                               StateVector* temp_vector,
                               JsrSet* temp_set) {
  int dft_len = 100;
2622
  GrowableArray<Block*> stk(dft_len);
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689

  ciBlock* dummy = _methodBlocks->make_dummy_block();
  JsrSet* root_set = new JsrSet(NULL, 0);
  Block* root_head = new (arena()) Block(this, dummy, root_set);
  Block* root_tail = new (arena()) Block(this, dummy, root_set);
  root_head->set_pre_order(0);
  root_head->set_post_order(0);
  root_tail->set_pre_order(max_jint);
  root_tail->set_post_order(max_jint);
  set_loop_tree_root(new (arena()) Loop(root_head, root_tail));

  stk.push(start);

  _next_pre_order = 0;  // initialize pre_order counter
  _rpo_list = NULL;
  int next_po = 0;      // initialize post_order counter

  // Compute RPO and the control flow graph
  int size;
  while ((size = stk.length()) > 0) {
    Block* blk = stk.top(); // Leave node on stack
    if (!blk->is_visited()) {
      // forward arc in graph
      assert (!blk->has_pre_order(), "");
      blk->set_next_pre_order();

      if (_next_pre_order >= MaxNodeLimit / 2) {
        // Too many basic blocks.  Bail out.
        // This can happen when try/finally constructs are nested to depth N,
        // and there is O(2**N) cloning of jsr bodies.  See bug 4697245!
        // "MaxNodeLimit / 2" is used because probably the parser will
        // generate at least twice that many nodes and bail out.
        record_failure("too many basic blocks");
        return;
      }
      if (do_flow) {
        flow_block(blk, temp_vector, temp_set);
        if (failing()) return; // Watch for bailouts.
      }
    } else if (!blk->is_post_visited()) {
      // cross or back arc
      for (SuccIter iter(blk); !iter.done(); iter.next()) {
        Block* succ = iter.succ();
        if (!succ->is_visited()) {
          stk.push(succ);
        }
      }
      if (stk.length() == size) {
        // There were no additional children, post visit node now
        stk.pop(); // Remove node from stack

        build_loop_tree(blk);
        blk->set_post_order(next_po++);   // Assign post order
        prepend_to_rpo_list(blk);
        assert(blk->is_post_visited(), "");

        if (blk->is_loop_head() && !blk->is_on_work_list()) {
          // Assume loop heads need more data flow
          add_to_work_list(blk);
        }
      }
    } else {
      stk.pop(); // Remove post-visited node from stack
    }
  }
}

D
duke 已提交
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
// ------------------------------------------------------------------
// ciTypeFlow::flow_types
//
// Perform the type flow analysis, creating and cloning Blocks as
// necessary.
void ciTypeFlow::flow_types() {
  ResourceMark rm;
  StateVector* temp_vector = new StateVector(this);
  JsrSet* temp_set = new JsrSet(NULL, 16);

  // Create the method entry block.
2701
  Block* start = block_at(start_bci(), temp_set);
D
duke 已提交
2702 2703 2704 2705

  // Load the initial state into it.
  const StateVector* start_state = get_start_state();
  if (failing())  return;
2706
  start->meet(start_state);
D
duke 已提交
2707

2708 2709
  // Depth first visit
  df_flow_types(start, true /*do flow*/, temp_vector, temp_set);
D
duke 已提交
2710

2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
  if (failing())  return;
  assert(_rpo_list == start, "must be start");

  // Any loops found?
  if (loop_tree_root()->child() != NULL &&
      env()->comp_level() >= CompLevel_full_optimization) {
      // Loop optimizations are not performed on Tier1 compiles.

    bool changed = clone_loop_heads(loop_tree_root(), temp_vector, temp_set);

    // If some loop heads were cloned, recompute postorder and loop tree
    if (changed) {
      loop_tree_root()->set_child(NULL);
      for (Block* blk = _rpo_list; blk != NULL;) {
        Block* next = blk->rpo_next();
        blk->df_init();
        blk = next;
      }
      df_flow_types(start, false /*no flow*/, temp_vector, temp_set);
    }
  }
D
duke 已提交
2732

2733 2734 2735 2736
  if (CITraceTypeFlow) {
    tty->print_cr("\nLoop tree");
    loop_tree_root()->print();
  }
D
duke 已提交
2737

2738
  // Continue flow analysis until fixed point reached
D
duke 已提交
2739

2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
  debug_only(int max_block = _next_pre_order;)

  while (!work_list_empty()) {
    Block* blk = work_list_next();
    assert (blk->has_post_order(), "post order assigned above");

    flow_block(blk, temp_vector, temp_set);

    assert (max_block == _next_pre_order, "no new blocks");
    assert (!failing(), "no more bailouts");
D
duke 已提交
2750 2751 2752 2753 2754 2755
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::map_blocks
//
2756
// Create the block map, which indexes blocks in reverse post-order.
D
duke 已提交
2757 2758
void ciTypeFlow::map_blocks() {
  assert(_block_map == NULL, "single initialization");
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
  int block_ct = _next_pre_order;
  _block_map = NEW_ARENA_ARRAY(arena(), Block*, block_ct);
  assert(block_ct == block_count(), "");

  Block* blk = _rpo_list;
  for (int m = 0; m < block_ct; m++) {
    int rpo = blk->rpo();
    assert(rpo == m, "should be sequential");
    _block_map[rpo] = blk;
    blk = blk->rpo_next();
  }
  assert(blk == NULL, "should be done");

  for (int j = 0; j < block_ct; j++) {
    assert(_block_map[j] != NULL, "must not drop any blocks");
    Block* block = _block_map[j];
D
duke 已提交
2775 2776 2777
    // Remove dead blocks from successor lists:
    for (int e = 0; e <= 1; e++) {
      GrowableArray<Block*>* l = e? block->exceptions(): block->successors();
2778 2779 2780
      for (int k = 0; k < l->length(); k++) {
        Block* s = l->at(k);
        if (!s->has_post_order()) {
D
duke 已提交
2781 2782 2783 2784 2785 2786
          if (CITraceTypeFlow) {
            tty->print("Removing dead %s successor of #%d: ", (e? "exceptional":  "normal"), block->pre_order());
            s->print_value_on(tty);
            tty->cr();
          }
          l->remove(s);
2787
          --k;
D
duke 已提交
2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
        }
      }
    }
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::get_block_for
//
// Find a block with this ciBlock which has a compatible JsrSet.
// If no such block exists, create it, unless the option is no_create.
2799
// If the option is create_backedge_copy, always create a fresh backedge copy.
D
duke 已提交
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
ciTypeFlow::Block* ciTypeFlow::get_block_for(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs, CreateOption option) {
  Arena* a = arena();
  GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];
  if (blocks == NULL) {
    // Query only?
    if (option == no_create)  return NULL;

    // Allocate the growable array.
    blocks = new (a) GrowableArray<Block*>(a, 4, 0, NULL);
    _idx_to_blocklist[ciBlockIndex] = blocks;
  }

2812
  if (option != create_backedge_copy) {
D
duke 已提交
2813 2814 2815
    int len = blocks->length();
    for (int i = 0; i < len; i++) {
      Block* block = blocks->at(i);
2816
      if (!block->is_backedge_copy() && block->is_compatible_with(jsrs)) {
D
duke 已提交
2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
        return block;
      }
    }
  }

  // Query only?
  if (option == no_create)  return NULL;

  // We did not find a compatible block.  Create one.
  Block* new_block = new (a) Block(this, _methodBlocks->block(ciBlockIndex), jsrs);
2827
  if (option == create_backedge_copy)  new_block->set_backedge_copy(true);
D
duke 已提交
2828 2829 2830 2831 2832
  blocks->append(new_block);
  return new_block;
}

// ------------------------------------------------------------------
2833
// ciTypeFlow::backedge_copy_count
D
duke 已提交
2834
//
2835
int ciTypeFlow::backedge_copy_count(int ciBlockIndex, ciTypeFlow::JsrSet* jsrs) const {
D
duke 已提交
2836 2837 2838 2839 2840 2841 2842 2843 2844 2845
  GrowableArray<Block*>* blocks = _idx_to_blocklist[ciBlockIndex];

  if (blocks == NULL) {
    return 0;
  }

  int count = 0;
  int len = blocks->length();
  for (int i = 0; i < len; i++) {
    Block* block = blocks->at(i);
2846
    if (block->is_backedge_copy() && block->is_compatible_with(jsrs)) {
D
duke 已提交
2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
      count++;
    }
  }

  return count;
}

// ------------------------------------------------------------------
// ciTypeFlow::do_flow
//
// Perform type inference flow analysis.
void ciTypeFlow::do_flow() {
  if (CITraceTypeFlow) {
    tty->print_cr("\nPerforming flow analysis on method");
    method()->print();
    if (is_osr_flow())  tty->print(" at OSR bci %d", start_bci());
    tty->cr();
    method()->print_codes();
  }
  if (CITraceTypeFlow) {
    tty->print_cr("Initial CI Blocks");
    print_on(tty);
  }
  flow_types();
  // Watch for bailouts.
  if (failing()) {
    return;
  }
2875 2876 2877

  map_blocks();

D
duke 已提交
2878
  if (CIPrintTypeFlow || CITraceTypeFlow) {
2879
    rpo_print_on(tty);
D
duke 已提交
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
  }
}

// ------------------------------------------------------------------
// ciTypeFlow::record_failure()
// The ciTypeFlow object keeps track of failure reasons separately from the ciEnv.
// This is required because there is not a 1-1 relation between the ciEnv and
// the TypeFlow passes within a compilation task.  For example, if the compiler
// is considering inlining a method, it will request a TypeFlow.  If that fails,
// the compilation as a whole may continue without the inlining.  Some TypeFlow
// requests are not optional; if they fail the requestor is responsible for
// copying the failure reason up to the ciEnv.  (See Parse::Parse.)
void ciTypeFlow::record_failure(const char* reason) {
  if (env()->log() != NULL) {
    env()->log()->elem("failure reason='%s' phase='typeflow'", reason);
  }
  if (_failure_reason == NULL) {
    // Record the first failure reason.
    _failure_reason = reason;
  }
}

#ifndef PRODUCT
// ------------------------------------------------------------------
// ciTypeFlow::print_on
void ciTypeFlow::print_on(outputStream* st) const {
  // Walk through CI blocks
  st->print_cr("********************************************************");
  st->print   ("TypeFlow for ");
  method()->name()->print_symbol_on(st);
  int limit_bci = code_size();
  st->print_cr("  %d bytes", limit_bci);
  ciMethodBlocks  *mblks = _methodBlocks;
  ciBlock* current = NULL;
  for (int bci = 0; bci < limit_bci; bci++) {
    ciBlock* blk = mblks->block_containing(bci);
    if (blk != NULL && blk != current) {
      current = blk;
      current->print_on(st);

      GrowableArray<Block*>* blocks = _idx_to_blocklist[blk->index()];
      int num_blocks = (blocks == NULL) ? 0 : blocks->length();

      if (num_blocks == 0) {
        st->print_cr("  No Blocks");
      } else {
        for (int i = 0; i < num_blocks; i++) {
          Block* block = blocks->at(i);
          block->print_on(st);
        }
      }
      st->print_cr("--------------------------------------------------------");
      st->cr();
    }
  }
  st->print_cr("********************************************************");
  st->cr();
}
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952

void ciTypeFlow::rpo_print_on(outputStream* st) const {
  st->print_cr("********************************************************");
  st->print   ("TypeFlow for ");
  method()->name()->print_symbol_on(st);
  int limit_bci = code_size();
  st->print_cr("  %d bytes", limit_bci);
  for (Block* blk = _rpo_list; blk != NULL; blk = blk->rpo_next()) {
    blk->print_on(st);
    st->print_cr("--------------------------------------------------------");
    st->cr();
  }
  st->print_cr("********************************************************");
  st->cr();
}
D
duke 已提交
2953
#endif