deoptimization.cpp 81.1 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2016, 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
#include "precompiled.hpp"
#include "classfile/systemDictionary.hpp"
#include "code/debugInfoRec.hpp"
#include "code/nmethod.hpp"
#include "code/pcDesc.hpp"
#include "code/scopeDesc.hpp"
#include "interpreter/bytecode.hpp"
#include "interpreter/interpreter.hpp"
#include "interpreter/oopMapCache.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/oopFactory.hpp"
#include "memory/resourceArea.hpp"
37
#include "oops/method.hpp"
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include "oops/oop.inline.hpp"
#include "prims/jvmtiThreadState.hpp"
#include "runtime/biasedLocking.hpp"
#include "runtime/compilationPolicy.hpp"
#include "runtime/deoptimization.hpp"
#include "runtime/interfaceSupport.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/signature.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/thread.hpp"
#include "runtime/vframe.hpp"
#include "runtime/vframeArray.hpp"
#include "runtime/vframe_hp.hpp"
#include "utilities/events.hpp"
#include "utilities/xmlstream.hpp"
#ifdef TARGET_ARCH_x86
# include "vmreg_x86.inline.hpp"
#endif
#ifdef TARGET_ARCH_sparc
# include "vmreg_sparc.inline.hpp"
#endif
#ifdef TARGET_ARCH_zero
# include "vmreg_zero.inline.hpp"
#endif
62 63 64 65 66 67
#ifdef TARGET_ARCH_arm
# include "vmreg_arm.inline.hpp"
#endif
#ifdef TARGET_ARCH_ppc
# include "vmreg_ppc.inline.hpp"
#endif
68
#ifdef COMPILER2
69 70 71
#if defined AD_MD_HPP
# include AD_MD_HPP
#elif defined TARGET_ARCH_MODEL_x86_32
72
# include "adfiles/ad_x86_32.hpp"
73
#elif defined TARGET_ARCH_MODEL_x86_64
74
# include "adfiles/ad_x86_64.hpp"
75
#elif defined TARGET_ARCH_MODEL_sparc
76
# include "adfiles/ad_sparc.hpp"
77
#elif defined TARGET_ARCH_MODEL_zero
78
# include "adfiles/ad_zero.hpp"
79
#elif defined TARGET_ARCH_MODEL_ppc_64
80
# include "adfiles/ad_ppc_64.hpp"
81
#endif
82
#endif // COMPILER2
D
duke 已提交
83

84 85
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

D
duke 已提交
86 87 88 89
bool DeoptimizationMarker::_is_active = false;

Deoptimization::UnrollBlock::UnrollBlock(int  size_of_deoptimized_frame,
                                         int  caller_adjustment,
90
                                         int  caller_actual_parameters,
D
duke 已提交
91 92 93 94 95 96
                                         int  number_of_frames,
                                         intptr_t* frame_sizes,
                                         address* frame_pcs,
                                         BasicType return_type) {
  _size_of_deoptimized_frame = size_of_deoptimized_frame;
  _caller_adjustment         = caller_adjustment;
97
  _caller_actual_parameters  = caller_actual_parameters;
D
duke 已提交
98 99 100
  _number_of_frames          = number_of_frames;
  _frame_sizes               = frame_sizes;
  _frame_pcs                 = frame_pcs;
Z
zgu 已提交
101
  _register_block            = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
D
duke 已提交
102
  _return_type               = return_type;
103
  _initial_info              = 0;
D
duke 已提交
104 105 106 107 108 109 110 111 112 113
  // PD (x86 only)
  _counter_temp              = 0;
  _unpack_kind               = 0;
  _sender_sp_temp            = 0;

  _total_frame_sizes         = size_of_frames();
}


Deoptimization::UnrollBlock::~UnrollBlock() {
Z
zgu 已提交
114 115 116
  FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes, mtCompiler);
  FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs, mtCompiler);
  FREE_C_HEAP_ARRAY(intptr_t, _register_block, mtCompiler);
D
duke 已提交
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
}


intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {
  assert(register_number < RegisterMap::reg_count, "checking register number");
  return &_register_block[register_number * 2];
}



int Deoptimization::UnrollBlock::size_of_frames() const {
  // Acount first for the adjustment of the initial frame
  int result = _caller_adjustment;
  for (int index = 0; index < number_of_frames(); index++) {
    result += frame_sizes()[index];
  }
  return result;
}


void Deoptimization::UnrollBlock::print() {
  ttyLocker ttyl;
  tty->print_cr("UnrollBlock");
  tty->print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
  tty->print(   "  frame_sizes: ");
  for (int index = 0; index < number_of_frames(); index++) {
    tty->print("%d ", frame_sizes()[index]);
  }
  tty->cr();
}


// In order to make fetch_unroll_info work properly with escape
// analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and
// ResetNoHandleMark and HandleMark were removed from it. The actual reallocation
// of previously eliminated objects occurs in realloc_objects, which is
// called from the method fetch_unroll_info_helper below.
JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread))
  // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
  // but makes the entry a little slower. There is however a little dance we have to
  // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro

  // fetch_unroll_info() is called at the beginning of the deoptimization
  // handler. Note this fact before we start generating temporary frames
  // that can confuse an asynchronous stack walker. This counter is
  // decremented at the end of unpack_frames().
  thread->inc_in_deopt_handler();

  return fetch_unroll_info_helper(thread);
JRT_END


// This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread) {

  // Note: there is a safepoint safety issue here. No matter whether we enter
  // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
  // the vframeArray is created.
  //

  // Allocate our special deoptimization ResourceMark
  DeoptResourceMark* dmark = new DeoptResourceMark(thread);
  assert(thread->deopt_mark() == NULL, "Pending deopt!");
  thread->set_deopt_mark(dmark);

  frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect
  RegisterMap map(thread, true);
  RegisterMap dummy_map(thread, false);
  // Now get the deoptee with a valid map
  frame deoptee = stub_frame.sender(&map);
187 188 189
  // Set the deoptee nmethod
  assert(thread->deopt_nmethod() == NULL, "Pending deopt!");
  thread->set_deopt_nmethod(deoptee.cb()->as_nmethod_or_null());
D
duke 已提交
190

191 192 193 194
  if (VerifyStack) {
    thread->validate_frame_layout();
  }

D
duke 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207
  // Create a growable array of VFrames where each VFrame represents an inlined
  // Java frame.  This storage is allocated with the usual system arena.
  assert(deoptee.is_compiled_frame(), "Wrong frame type");
  GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
  vframe* vf = vframe::new_vframe(&deoptee, &map, thread);
  while (!vf->is_top()) {
    assert(vf->is_compiled_frame(), "Wrong frame type");
    chunk->push(compiledVFrame::cast(vf));
    vf = vf->sender();
  }
  assert(vf->is_compiled_frame(), "Wrong frame type");
  chunk->push(compiledVFrame::cast(vf));

208 209
  bool realloc_failures = false;

D
duke 已提交
210 211 212
#ifdef COMPILER2
  // Reallocate the non-escaping objects and restore their fields. Then
  // relock objects if synchronization on them was eliminated.
K
kvn 已提交
213
  if (DoEscapeAnalysis || EliminateNestedLocks) {
214
    if (EliminateAllocations) {
215
      assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");
216
      GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
217 218 219 220 221 222 223 224

      // The flag return_oop() indicates call sites which return oop
      // in compiled code. Such sites include java method calls,
      // runtime calls (for example, used to allocate new objects/arrays
      // on slow code path) and any other calls generated in compiled code.
      // It is not guaranteed that we can get such information here only
      // by analyzing bytecode in deoptimized frames. This is why this flag
      // is set during method compilation (see Compile::Process_OopMap_Node()).
225 226
      // If the previous frame was popped, we don't have a result.
      bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution();
227 228 229 230 231 232 233 234 235
      Handle return_value;
      if (save_oop_result) {
        // Reallocation may trigger GC. If deoptimization happened on return from
        // call which returns oop we need to save it since it is not in oopmap.
        oop result = deoptee.saved_oop_result(&map);
        assert(result == NULL || result->is_oop(), "must be oop");
        return_value = Handle(thread, result);
        assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
        if (TraceDeoptimization) {
V
vlivanov 已提交
236
          ttyLocker ttyl;
237
          tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, (void *)result, thread);
238 239
        }
      }
240 241
      if (objects != NULL) {
        JRT_BLOCK
242
          realloc_failures = realloc_objects(thread, &deoptee, objects, THREAD);
243
        JRT_END
244
        reassign_fields(&deoptee, &map, objects, realloc_failures);
D
duke 已提交
245
#ifndef PRODUCT
246 247 248 249 250
        if (TraceDeoptimization) {
          ttyLocker ttyl;
          tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, thread);
          print_objects(objects, realloc_failures);
        }
251
#endif
252
      }
253 254 255 256
      if (save_oop_result) {
        // Restore result.
        deoptee.set_saved_oop_result(&map, return_value());
      }
D
duke 已提交
257
    }
258
    if (EliminateLocks) {
259 260 261
#ifndef PRODUCT
      bool first = true;
#endif
262
      for (int i = 0; i < chunk->length(); i++) {
263 264 265 266
        compiledVFrame* cvf = chunk->at(i);
        assert (cvf->scope() != NULL,"expect only compiled java frames");
        GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
        if (monitors->is_nonempty()) {
267
          relock_objects(monitors, thread, realloc_failures);
D
duke 已提交
268
#ifndef PRODUCT
269 270 271
          if (TraceDeoptimization) {
            ttyLocker ttyl;
            for (int j = 0; j < monitors->length(); j++) {
272 273 274 275 276 277
              MonitorInfo* mi = monitors->at(j);
              if (mi->eliminated()) {
                if (first) {
                  first = false;
                  tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread);
                }
278 279 280 281 282 283
                if (mi->owner_is_scalar_replaced()) {
                  Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
                  tty->print_cr("     failed reallocation for klass %s", k->external_name());
                } else {
                  tty->print_cr("     object <" INTPTR_FORMAT "> locked", (void *)mi->owner());
                }
284
              }
D
duke 已提交
285 286 287
            }
          }
#endif
288
        }
D
duke 已提交
289 290 291 292 293 294 295 296 297
      }
    }
  }
#endif // COMPILER2
  // Ensure that no safepoint is taken after pointers have been stored
  // in fields of rematerialized objects.  If a safepoint occurs from here on
  // out the java state residing in the vframeArray will be missed.
  No_Safepoint_Verifier no_safepoint;

298 299 300 301 302 303
  vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures);
#ifdef COMPILER2
  if (realloc_failures) {
    pop_frames_failed_reallocs(thread, array);
  }
#endif
D
duke 已提交
304

305
  assert(thread->vframe_array_head() == NULL, "Pending deopt!");
D
duke 已提交
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
  thread->set_vframe_array_head(array);

  // Now that the vframeArray has been created if we have any deferred local writes
  // added by jvmti then we can free up that structure as the data is now in the
  // vframeArray

  if (thread->deferred_locals() != NULL) {
    GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals();
    int i = 0;
    do {
      // Because of inlining we could have multiple vframes for a single frame
      // and several of the vframes could have deferred writes. Find them all.
      if (list->at(i)->id() == array->original().id()) {
        jvmtiDeferredLocalVariableSet* dlv = list->at(i);
        list->remove_at(i);
        // individual jvmtiDeferredLocalVariableSet are CHeapObj's
        delete dlv;
      } else {
        i++;
      }
    } while ( i < list->length() );
    if (list->length() == 0) {
      thread->set_deferred_locals(NULL);
      // free the list and elements back to C heap.
      delete list;
    }

  }

335
#ifndef SHARK
D
duke 已提交
336 337 338 339 340 341
  // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
  CodeBlob* cb = stub_frame.cb();
  // Verify we have the right vframeArray
  assert(cb->frame_size() >= 0, "Unexpected frame size");
  intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();

342 343 344 345 346 347
  // If the deopt call site is a MethodHandle invoke call site we have
  // to adjust the unpack_sp.
  nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
  if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))
    unpack_sp = deoptee.unextended_sp();

D
duke 已提交
348 349 350
#ifdef ASSERT
  assert(cb->is_deoptimization_stub() || cb->is_uncommon_trap_stub(), "just checking");
#endif
351 352 353 354
#else
  intptr_t* unpack_sp = stub_frame.sender(&dummy_map).unextended_sp();
#endif // !SHARK

D
duke 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368
  // This is a guarantee instead of an assert because if vframe doesn't match
  // we will unpack the wrong deoptimized frame and wind up in strange places
  // where it will be very difficult to figure out what went wrong. Better
  // to die an early death here than some very obscure death later when the
  // trail is cold.
  // Note: on ia64 this guarantee can be fooled by frames with no memory stack
  // in that it will fail to detect a problem when there is one. This needs
  // more work in tiger timeframe.
  guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");

  int number_of_frames = array->frames();

  // Compute the vframes' sizes.  Note that frame_sizes[] entries are ordered from outermost to innermost
  // virtual activation, which is the reverse of the elements in the vframes array.
Z
zgu 已提交
369
  intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
D
duke 已提交
370
  // +1 because we always have an interpreter return address for the final slot.
Z
zgu 已提交
371
  address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
D
duke 已提交
372 373 374 375 376 377 378 379 380 381 382
  int popframe_extra_args = 0;
  // Create an interpreter return address for the stub to use as its return
  // address so the skeletal frames are perfectly walkable
  frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);

  // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
  // activation be put back on the expression stack of the caller for reexecution
  if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {
    popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words());
  }

383 384 385 386 387 388 389 390 391 392 393 394
  // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
  // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
  // than simply use array->sender.pc(). This requires us to walk the current set of frames
  //
  frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
  deopt_sender = deopt_sender.sender(&dummy_map);     // Now deoptee caller

  // It's possible that the number of paramters at the call site is
  // different than number of arguments in the callee when method
  // handles are used.  If the caller is interpreted get the real
  // value so that the proper amount of space can be added to it's
  // frame.
395
  bool caller_was_method_handle = false;
396 397
  if (deopt_sender.is_interpreted_frame()) {
    methodHandle method = deopt_sender.interpreter_frame_method();
398
    Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
399
    if (cur.is_invokedynamic() || cur.is_invokehandle()) {
400 401 402 403 404
      // Method handle invokes may involve fairly arbitrary chains of
      // calls so it's impossible to know how much actual space the
      // caller has for locals.
      caller_was_method_handle = true;
    }
405 406
  }

D
duke 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420
  //
  // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
  // frame_sizes/frame_pcs[1] next oldest frame (int)
  // frame_sizes/frame_pcs[n] youngest frame (int)
  //
  // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
  // owns the space for the return address to it's caller).  Confusing ain't it.
  //
  // The vframe array can address vframes with indices running from
  // 0.._frames-1. Index  0 is the youngest frame and _frame - 1 is the oldest (root) frame.
  // When we create the skeletal frames we need the oldest frame to be in the zero slot
  // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
  // so things look a little strange in this loop.
  //
421 422
  int callee_parameters = 0;
  int callee_locals = 0;
D
duke 已提交
423 424 425 426
  for (int index = 0; index < array->frames(); index++ ) {
    // frame[number_of_frames - 1 ] = on_stack_size(youngest)
    // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
    // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
427
    frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
D
duke 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
                                                                                                    callee_locals,
                                                                                                    index == 0,
                                                                                                    popframe_extra_args);
    // This pc doesn't have to be perfect just good enough to identify the frame
    // as interpreted so the skeleton frame will be walkable
    // The correct pc will be set when the skeleton frame is completely filled out
    // The final pc we store in the loop is wrong and will be overwritten below
    frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;

    callee_parameters = array->element(index)->method()->size_of_parameters();
    callee_locals = array->element(index)->method()->max_locals();
    popframe_extra_args = 0;
  }

  // Compute whether the root vframe returns a float or double value.
  BasicType return_type;
  {
    HandleMark hm;
    methodHandle method(thread, array->element(0)->method());
447
    Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
448
    return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
D
duke 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
  }

  // Compute information for handling adapters and adjusting the frame size of the caller.
  int caller_adjustment = 0;

  // Compute the amount the oldest interpreter frame will have to adjust
  // its caller's stack by. If the caller is a compiled frame then
  // we pretend that the callee has no parameters so that the
  // extension counts for the full amount of locals and not just
  // locals-parms. This is because without a c2i adapter the parm
  // area as created by the compiled frame will not be usable by
  // the interpreter. (Depending on the calling convention there
  // may not even be enough space).

  // QQQ I'd rather see this pushed down into last_frame_adjust
  // and have it take the sender (aka caller).

466
  if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {
D
duke 已提交
467
    caller_adjustment = last_frame_adjust(0, callee_locals);
468
  } else if (callee_locals > callee_parameters) {
D
duke 已提交
469 470 471
    // The caller frame may need extending to accommodate
    // non-parameter locals of the first unpacked interpreted frame.
    // Compute that adjustment.
472
    caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
D
duke 已提交
473 474 475 476 477 478 479 480
  }

  // If the sender is deoptimized the we must retrieve the address of the handler
  // since the frame will "magically" show the original pc before the deopt
  // and we'd undo the deopt.

  frame_pcs[0] = deopt_sender.raw_pc();

481
#ifndef SHARK
D
duke 已提交
482
  assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");
483
#endif // SHARK
D
duke 已提交
484 485 486

  UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
                                      caller_adjustment * BytesPerWord,
487
                                      caller_was_method_handle ? 0 : callee_parameters,
D
duke 已提交
488 489 490 491
                                      number_of_frames,
                                      frame_sizes,
                                      frame_pcs,
                                      return_type);
492 493 494 495
  // On some platforms, we need a way to pass some platform dependent
  // information to the unpacking code so the skeletal frames come out
  // correct (initial fp value, unextended sp, ...)
  info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
D
duke 已提交
496 497 498

  if (array->frames() > 1) {
    if (VerifyStack && TraceDeoptimization) {
V
vlivanov 已提交
499
      ttyLocker ttyl;
D
duke 已提交
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
      tty->print_cr("Deoptimizing method containing inlining");
    }
  }

  array->set_unroll_block(info);
  return info;
}

// Called to cleanup deoptimization data structures in normal case
// after unpacking to stack and when stack overflow error occurs
void Deoptimization::cleanup_deopt_info(JavaThread *thread,
                                        vframeArray *array) {

  // Get array if coming from exception
  if (array == NULL) {
    array = thread->vframe_array_head();
  }
  thread->set_vframe_array_head(NULL);

  // Free the previous UnrollBlock
  vframeArray* old_array = thread->vframe_array_last();
  thread->set_vframe_array_last(array);

  if (old_array != NULL) {
    UnrollBlock* old_info = old_array->unroll_block();
    old_array->set_unroll_block(NULL);
    delete old_info;
    delete old_array;
  }

  // Deallocate any resource creating in this routine and any ResourceObjs allocated
  // inside the vframeArray (StackValueCollections)

  delete thread->deopt_mark();
  thread->set_deopt_mark(NULL);
535
  thread->set_deopt_nmethod(NULL);
D
duke 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579


  if (JvmtiExport::can_pop_frame()) {
#ifndef CC_INTERP
    // Regardless of whether we entered this routine with the pending
    // popframe condition bit set, we should always clear it now
    thread->clear_popframe_condition();
#else
    // C++ interpeter will clear has_pending_popframe when it enters
    // with method_resume. For deopt_resume2 we clear it now.
    if (thread->popframe_forcing_deopt_reexecution())
        thread->clear_popframe_condition();
#endif /* CC_INTERP */
  }

  // unpack_frames() is called at the end of the deoptimization handler
  // and (in C2) at the end of the uncommon trap handler. Note this fact
  // so that an asynchronous stack walker can work again. This counter is
  // incremented at the beginning of fetch_unroll_info() and (in C2) at
  // the beginning of uncommon_trap().
  thread->dec_in_deopt_handler();
}


// Return BasicType of value being returned
JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))

  // We are already active int he special DeoptResourceMark any ResourceObj's we
  // allocate will be freed at the end of the routine.

  // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
  // but makes the entry a little slower. There is however a little dance we have to
  // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
  ResetNoHandleMark rnhm; // No-op in release/product versions
  HandleMark hm;

  frame stub_frame = thread->last_frame();

  // Since the frame to unpack is the top frame of this thread, the vframe_array_head
  // must point to the vframeArray for the unpack frame.
  vframeArray* array = thread->vframe_array_head();

#ifndef PRODUCT
  if (TraceDeoptimization) {
V
vlivanov 已提交
580
    ttyLocker ttyl;
D
duke 已提交
581 582 583
    tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", thread, array, exec_mode);
  }
#endif
584 585
  Events::log(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
              stub_frame.pc(), stub_frame.sp(), exec_mode);
D
duke 已提交
586 587 588 589

  UnrollBlock* info = array->unroll_block();

  // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
590
  array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
D
duke 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606

  BasicType bt = info->return_type();

  // If we have an exception pending, claim that the return type is an oop
  // so the deopt_blob does not overwrite the exception_oop.

  if (exec_mode == Unpack_exception)
    bt = T_OBJECT;

  // Cleanup thread deopt data
  cleanup_deopt_info(thread, array);

#ifndef PRODUCT
  if (VerifyStack) {
    ResourceMark res_mark;

607 608
    thread->validate_frame_layout();

D
duke 已提交
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
    // Verify that the just-unpacked frames match the interpreter's
    // notions of expression stack and locals
    vframeArray* cur_array = thread->vframe_array_last();
    RegisterMap rm(thread, false);
    rm.set_include_argument_oops(false);
    bool is_top_frame = true;
    int callee_size_of_parameters = 0;
    int callee_max_locals = 0;
    for (int i = 0; i < cur_array->frames(); i++) {
      vframeArrayElement* el = cur_array->element(i);
      frame* iframe = el->iframe();
      guarantee(iframe->is_interpreted_frame(), "Wrong frame type");

      // Get the oop map for this bci
      InterpreterOopMap mask;
      int cur_invoke_parameter_size = 0;
      bool try_next_mask = false;
      int next_mask_expression_stack_size = -1;
      int top_frame_expression_stack_adjustment = 0;
      methodHandle mh(thread, iframe->interpreter_frame_method());
      OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
      BytecodeStream str(mh);
      str.set_start(iframe->interpreter_frame_bci());
      int max_bci = mh->code_size();
      // Get to the next bytecode if possible
      assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
      // Check to see if we can grab the number of outgoing arguments
      // at an uncommon trap for an invoke (where the compiler
      // generates debug info before the invoke has executed)
      Bytecodes::Code cur_code = str.next();
639 640 641 642 643
      if (cur_code == Bytecodes::_invokevirtual   ||
          cur_code == Bytecodes::_invokespecial   ||
          cur_code == Bytecodes::_invokestatic    ||
          cur_code == Bytecodes::_invokeinterface ||
          cur_code == Bytecodes::_invokedynamic) {
644
        Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
645
        Symbol* signature = invoke.signature();
D
duke 已提交
646 647
        ArgumentSizeComputer asc(signature);
        cur_invoke_parameter_size = asc.size();
648
        if (invoke.has_receiver()) {
D
duke 已提交
649 650 651
          // Add in receiver
          ++cur_invoke_parameter_size;
        }
652 653 654
        if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
          callee_size_of_parameters++;
        }
D
duke 已提交
655 656 657 658 659 660 661 662 663 664 665 666 667 668
      }
      if (str.bci() < max_bci) {
        Bytecodes::Code bc = str.next();
        if (bc >= 0) {
          // The interpreter oop map generator reports results before
          // the current bytecode has executed except in the case of
          // calls. It seems to be hard to tell whether the compiler
          // has emitted debug information matching the "state before"
          // a given bytecode or the state after, so we try both
          switch (cur_code) {
            case Bytecodes::_invokevirtual:
            case Bytecodes::_invokespecial:
            case Bytecodes::_invokestatic:
            case Bytecodes::_invokeinterface:
669
            case Bytecodes::_invokedynamic:
D
duke 已提交
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
            case Bytecodes::_athrow:
              break;
            default: {
              InterpreterOopMap next_mask;
              OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
              next_mask_expression_stack_size = next_mask.expression_stack_size();
              // Need to subtract off the size of the result type of
              // the bytecode because this is not described in the
              // debug info but returned to the interpreter in the TOS
              // caching register
              BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
              if (bytecode_result_type != T_ILLEGAL) {
                top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
              }
              assert(top_frame_expression_stack_adjustment >= 0, "");
              try_next_mask = true;
              break;
            }
          }
        }
      }

      // Verify stack depth and oops in frame
      // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
      if (!(
            /* SPARC */
            (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
            /* x86 */
            (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
            (try_next_mask &&
             (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
                                                                    top_frame_expression_stack_adjustment))) ||
            (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
703
            (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&
D
duke 已提交
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
             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
            )) {
        ttyLocker ttyl;

        // Print out some information that will help us debug the problem
        tty->print_cr("Wrong number of expression stack elements during deoptimization");
        tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
        tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
                      iframe->interpreter_frame_expression_stack_size());
        tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
        tty->print_cr("  try_next_mask = %d", try_next_mask);
        tty->print_cr("  next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
        tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
        tty->print_cr("  callee_max_locals = %d", callee_max_locals);
        tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
        tty->print_cr("  exec_mode = %d", exec_mode);
        tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
        tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = " UINTX_FORMAT, thread, thread->osthread()->thread_id());
        tty->print_cr("  Interpreted frames:");
        for (int k = 0; k < cur_array->frames(); k++) {
          vframeArrayElement* el = cur_array->element(k);
          tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
        }
        cur_array->print_on_2(tty);
        guarantee(false, "wrong number of expression stack elements during deopt");
      }
      VerifyOopClosure verify;
731
      iframe->oops_interpreted_do(&verify, NULL, &rm, false);
D
duke 已提交
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
      callee_size_of_parameters = mh->size_of_parameters();
      callee_max_locals = mh->max_locals();
      is_top_frame = false;
    }
  }
#endif /* !PRODUCT */


  return bt;
JRT_END


int Deoptimization::deoptimize_dependents() {
  Threads::deoptimized_wrt_marked_nmethods();
  return 0;
}


#ifdef COMPILER2
bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, GrowableArray<ScopeValue*>* objects, TRAPS) {
  Handle pending_exception(thread->pending_exception());
  const char* exception_file = thread->exception_file();
  int exception_line = thread->exception_line();
  thread->clear_pending_exception();

757 758
  bool failures = false;

D
duke 已提交
759 760 761 762
  for (int i = 0; i < objects->length(); i++) {
    assert(objects->at(i)->is_object(), "invalid debug information");
    ObjectValue* sv = (ObjectValue*) objects->at(i);

763
    KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
D
duke 已提交
764 765 766
    oop obj = NULL;

    if (k->oop_is_instance()) {
767
      InstanceKlass* ik = InstanceKlass::cast(k());
768
      obj = ik->allocate_instance(THREAD);
D
duke 已提交
769
    } else if (k->oop_is_typeArray()) {
770
      TypeArrayKlass* ak = TypeArrayKlass::cast(k());
D
duke 已提交
771 772
      assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
      int len = sv->field_size() / type2size[ak->element_type()];
773
      obj = ak->allocate(len, THREAD);
D
duke 已提交
774
    } else if (k->oop_is_objArray()) {
775
      ObjArrayKlass* ak = ObjArrayKlass::cast(k());
776 777 778 779 780
      obj = ak->allocate(sv->field_size(), THREAD);
    }

    if (obj == NULL) {
      failures = true;
D
duke 已提交
781 782 783
    }

    assert(sv->value().is_null(), "redundant reallocation");
784 785
    assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");
    CLEAR_PENDING_EXCEPTION;
D
duke 已提交
786 787 788
    sv->set_value(obj);
  }

789 790 791
  if (failures) {
    THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
  } else if (pending_exception.not_null()) {
D
duke 已提交
792 793 794
    thread->set_pending_exception(pending_exception(), exception_file, exception_line);
  }

795
  return failures;
D
duke 已提交
796 797 798 799 800 801 802 803
}

// This assumes that the fields are stored in ObjectValue in the same order
// they are yielded by do_nonstatic_fields.
class FieldReassigner: public FieldClosure {
  frame* _fr;
  RegisterMap* _reg_map;
  ObjectValue* _sv;
804
  InstanceKlass* _ik;
D
duke 已提交
805 806 807 808 809 810 811 812 813 814 815
  oop _obj;

  int _i;
public:
  FieldReassigner(frame* fr, RegisterMap* reg_map, ObjectValue* sv, oop obj) :
    _fr(fr), _reg_map(reg_map), _sv(sv), _obj(obj), _i(0) {}

  int i() const { return _i; }


  void do_field(fieldDescriptor* fd) {
816
    intptr_t val;
D
duke 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829
    StackValue* value =
      StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(i()));
    int offset = fd->offset();
    switch (fd->field_type()) {
    case T_OBJECT: case T_ARRAY:
      assert(value->type() == T_OBJECT, "Agreement.");
      _obj->obj_field_put(offset, value->get_obj()());
      break;

    case T_LONG: case T_DOUBLE: {
      assert(value->type() == T_INT, "Agreement.");
      StackValue* low =
        StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(++_i));
830 831 832 833 834 835 836
#ifdef _LP64
      jlong res = (jlong)low->get_int();
#else
#ifdef SPARC
      // For SPARC we have to swap high and low words.
      jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
#else
D
duke 已提交
837
      jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
838 839
#endif //SPARC
#endif
D
duke 已提交
840 841 842
      _obj->long_field_put(offset, res);
      break;
    }
843
    // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
D
duke 已提交
844 845
    case T_INT: case T_FLOAT: // 4 bytes.
      assert(value->type() == T_INT, "Agreement.");
846 847
      val = value->get_int();
      _obj->int_field_put(offset, (jint)*((jint*)&val));
D
duke 已提交
848 849
      break;

850
    case T_SHORT:
D
duke 已提交
851
      assert(value->type() == T_INT, "Agreement.");
852 853
      val = value->get_int();
      _obj->short_field_put(offset, (jshort)*((jint*)&val));
D
duke 已提交
854 855
      break;

856 857 858 859 860 861 862 863 864 865 866 867 868
    case T_CHAR:
      assert(value->type() == T_INT, "Agreement.");
      val = value->get_int();
      _obj->char_field_put(offset, (jchar)*((jint*)&val));
      break;

    case T_BYTE:
      assert(value->type() == T_INT, "Agreement.");
      val = value->get_int();
      _obj->byte_field_put(offset, (jbyte)*((jint*)&val));
      break;

    case T_BOOLEAN:
D
duke 已提交
869
      assert(value->type() == T_INT, "Agreement.");
870 871
      val = value->get_int();
      _obj->bool_field_put(offset, (jboolean)*((jint*)&val));
D
duke 已提交
872 873 874 875 876 877 878 879 880 881 882 883
      break;

    default:
      ShouldNotReachHere();
    }
    _i++;
  }
};

// restore elements of an eliminated type array
void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
  int index = 0;
884
  intptr_t val;
D
duke 已提交
885 886 887 888

  for (int i = 0; i < sv->field_size(); i++) {
    StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
    switch(type) {
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
    case T_LONG: case T_DOUBLE: {
      assert(value->type() == T_INT, "Agreement.");
      StackValue* low =
        StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
#ifdef _LP64
      jlong res = (jlong)low->get_int();
#else
#ifdef SPARC
      // For SPARC we have to swap high and low words.
      jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
#else
      jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
#endif //SPARC
#endif
      obj->long_at_put(index, res);
      break;
    }

    // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
    case T_INT: case T_FLOAT: // 4 bytes.
      assert(value->type() == T_INT, "Agreement.");
      val = value->get_int();
      obj->int_at_put(index, (jint)*((jint*)&val));
      break;

914
    case T_SHORT:
915 916 917 918 919
      assert(value->type() == T_INT, "Agreement.");
      val = value->get_int();
      obj->short_at_put(index, (jshort)*((jint*)&val));
      break;

920 921 922 923 924 925 926 927 928 929 930 931 932
    case T_CHAR:
      assert(value->type() == T_INT, "Agreement.");
      val = value->get_int();
      obj->char_at_put(index, (jchar)*((jint*)&val));
      break;

    case T_BYTE:
      assert(value->type() == T_INT, "Agreement.");
      val = value->get_int();
      obj->byte_at_put(index, (jbyte)*((jint*)&val));
      break;

    case T_BOOLEAN:
933 934 935 936 937
      assert(value->type() == T_INT, "Agreement.");
      val = value->get_int();
      obj->bool_at_put(index, (jboolean)*((jint*)&val));
      break;

D
duke 已提交
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
      default:
        ShouldNotReachHere();
    }
    index++;
  }
}


// restore fields of an eliminated object array
void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
  for (int i = 0; i < sv->field_size(); i++) {
    StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
    assert(value->type() == T_OBJECT, "object element expected");
    obj->obj_at_put(i, value->get_obj()());
  }
}


// restore fields of all eliminated objects and arrays
957
void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
D
duke 已提交
958 959
  for (int i = 0; i < objects->length(); i++) {
    ObjectValue* sv = (ObjectValue*) objects->at(i);
960
    KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
D
duke 已提交
961
    Handle obj = sv->value();
962 963 964 965
    assert(obj.not_null() || realloc_failures, "reallocation was missed");
    if (obj.is_null()) {
      continue;
    }
D
duke 已提交
966 967

    if (k->oop_is_instance()) {
968
      InstanceKlass* ik = InstanceKlass::cast(k());
D
duke 已提交
969 970 971
      FieldReassigner reassign(fr, reg_map, sv, obj());
      ik->do_nonstatic_fields(&reassign);
    } else if (k->oop_is_typeArray()) {
972
      TypeArrayKlass* ak = TypeArrayKlass::cast(k());
D
duke 已提交
973 974 975 976 977 978 979 980 981
      reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
    } else if (k->oop_is_objArray()) {
      reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
    }
  }
}


// relock objects for which synchronization was eliminated
982
void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread, bool realloc_failures) {
D
duke 已提交
983
  for (int i = 0; i < monitors->length(); i++) {
984 985
    MonitorInfo* mon_info = monitors->at(i);
    if (mon_info->eliminated()) {
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
      assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
      if (!mon_info->owner_is_scalar_replaced()) {
        Handle obj = Handle(mon_info->owner());
        markOop mark = obj->mark();
        if (UseBiasedLocking && mark->has_bias_pattern()) {
          // New allocated objects may have the mark set to anonymously biased.
          // Also the deoptimized method may called methods with synchronization
          // where the thread-local object is bias locked to the current thread.
          assert(mark->is_biased_anonymously() ||
                 mark->biased_locker() == thread, "should be locked to current thread");
          // Reset mark word to unbiased prototype.
          markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
          obj->set_mark(unbiased_prototype);
        }
        BasicLock* lock = mon_info->lock();
        ObjectSynchronizer::slow_enter(obj, lock, thread);
        assert(mon_info->owner()->is_locked(), "object must be locked now");
1003
      }
D
duke 已提交
1004 1005 1006 1007 1008 1009 1010
    }
  }
}


#ifndef PRODUCT
// print information about reallocated objects
1011
void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
D
duke 已提交
1012 1013 1014 1015
  fieldDescriptor fd;

  for (int i = 0; i < objects->length(); i++) {
    ObjectValue* sv = (ObjectValue*) objects->at(i);
1016
    KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
D
duke 已提交
1017 1018
    Handle obj = sv->value();

1019
    tty->print("     object <" INTPTR_FORMAT "> of type ", (void *)sv->value()());
1020
    k->print_value();
1021 1022 1023 1024 1025 1026
    assert(obj.not_null() || realloc_failures, "reallocation was missed");
    if (obj.is_null()) {
      tty->print(" allocation failed");
    } else {
      tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);
    }
D
duke 已提交
1027 1028
    tty->cr();

1029
    if (Verbose && !obj.is_null()) {
D
duke 已提交
1030 1031 1032 1033 1034 1035 1036
      k->oop_print_on(obj(), tty);
    }
  }
}
#endif
#endif // COMPILER2

1037
vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
1038
  Events::log(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, fr.pc(), fr.sp());
D
duke 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054

#ifndef PRODUCT
  if (TraceDeoptimization) {
    ttyLocker ttyl;
    tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", thread);
    fr.print_on(tty);
    tty->print_cr("     Virtual frames (innermost first):");
    for (int index = 0; index < chunk->length(); index++) {
      compiledVFrame* vf = chunk->at(index);
      tty->print("       %2d - ", index);
      vf->print_value();
      int bci = chunk->at(index)->raw_bci();
      const char* code_name;
      if (bci == SynchronizationEntryBCI) {
        code_name = "sync entry";
      } else {
1055
        Bytecodes::Code code = vf->method()->code_at(bci);
D
duke 已提交
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
        code_name = Bytecodes::name(code);
      }
      tty->print(" - %s", code_name);
      tty->print_cr(" @ bci %d ", bci);
      if (Verbose) {
        vf->print();
        tty->cr();
      }
    }
  }
#endif

  // Register map for next frame (used for stack crawl).  We capture
  // the state of the deopt'ing frame's caller.  Thus if we need to
  // stuff a C2I adapter we can properly fill in the callee-save
  // register locations.
  frame caller = fr.sender(reg_map);
  int frame_size = caller.sp() - fr.sp();

  frame sender = caller;

  // Since the Java thread being deoptimized will eventually adjust it's own stack,
  // the vframeArray containing the unpacking information is allocated in the C heap.
  // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1080
  vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
D
duke 已提交
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094

  // Compare the vframeArray to the collected vframes
  assert(array->structural_compare(thread, chunk), "just checking");

#ifndef PRODUCT
  if (TraceDeoptimization) {
    ttyLocker ttyl;
    tty->print_cr("     Created vframeArray " INTPTR_FORMAT, array);
  }
#endif // PRODUCT

  return array;
}

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
#ifdef COMPILER2
void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
  // Reallocation of some scalar replaced objects failed. Record
  // that we need to pop all the interpreter frames for the
  // deoptimized compiled frame.
  assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
  thread->set_frames_to_pop_failed_realloc(array->frames());
  // Unlock all monitors here otherwise the interpreter will see a
  // mix of locked and unlocked monitors (because of failed
  // reallocations of synchronized objects) and be confused.
  for (int i = 0; i < array->frames(); i++) {
    MonitorChunk* monitors = array->element(i)->monitors();
    if (monitors != NULL) {
      for (int j = 0; j < monitors->number_of_monitors(); j++) {
        BasicObjectLock* src = monitors->at(j);
        if (src->obj() != NULL) {
          ObjectSynchronizer::fast_exit(src->obj(), src->lock(), thread);
        }
      }
      array->element(i)->free_monitors(thread);
#ifdef ASSERT
      array->element(i)->set_removed_monitors();
#endif
    }
  }
}
#endif
D
duke 已提交
1122 1123 1124 1125 1126

static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke) {
  GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
  for (int i = 0; i < monitors->length(); i++) {
    MonitorInfo* mon_info = monitors->at(i);
1127
    if (!mon_info->eliminated() && mon_info->owner() != NULL) {
D
duke 已提交
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
      objects_to_revoke->append(Handle(mon_info->owner()));
    }
  }
}


void Deoptimization::revoke_biases_of_monitors(JavaThread* thread, frame fr, RegisterMap* map) {
  if (!UseBiasedLocking) {
    return;
  }

  GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();

  // Unfortunately we don't have a RegisterMap available in most of
  // the places we want to call this routine so we need to walk the
  // stack again to update the register map.
  if (map == NULL || !map->update_map()) {
    StackFrameStream sfs(thread, true);
    bool found = false;
    while (!found && !sfs.is_done()) {
      frame* cur = sfs.current();
      sfs.next();
      found = cur->id() == fr.id();
    }
    assert(found, "frame to be deoptimized not found on target thread's stack");
    map = sfs.register_map();
  }

  vframe* vf = vframe::new_vframe(&fr, map, thread);
  compiledVFrame* cvf = compiledVFrame::cast(vf);
  // Revoke monitors' biases in all scopes
  while (!cvf->is_top()) {
    collect_monitors(cvf, objects_to_revoke);
    cvf = compiledVFrame::cast(cvf->sender());
  }
  collect_monitors(cvf, objects_to_revoke);

  if (SafepointSynchronize::is_at_safepoint()) {
    BiasedLocking::revoke_at_safepoint(objects_to_revoke);
  } else {
    BiasedLocking::revoke(objects_to_revoke);
  }
}


void Deoptimization::revoke_biases_of_monitors(CodeBlob* cb) {
  if (!UseBiasedLocking) {
    return;
  }

  assert(SafepointSynchronize::is_at_safepoint(), "must only be called from safepoint");
  GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
  for (JavaThread* jt = Threads::first(); jt != NULL ; jt = jt->next()) {
    if (jt->has_last_Java_frame()) {
      StackFrameStream sfs(jt, true);
      while (!sfs.is_done()) {
        frame* cur = sfs.current();
        if (cb->contains(cur->pc())) {
          vframe* vf = vframe::new_vframe(cur, sfs.register_map(), jt);
          compiledVFrame* cvf = compiledVFrame::cast(vf);
          // Revoke monitors' biases in all scopes
          while (!cvf->is_top()) {
            collect_monitors(cvf, objects_to_revoke);
            cvf = compiledVFrame::cast(cvf->sender());
          }
          collect_monitors(cvf, objects_to_revoke);
        }
        sfs.next();
      }
    }
  }
  BiasedLocking::revoke_at_safepoint(objects_to_revoke);
}


void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr) {
  assert(fr.can_be_deoptimized(), "checking frame type");

  gather_statistics(Reason_constraint, Action_none, Bytecodes::_illegal);

  // Patch the nmethod so that when execution returns to it we will
  // deopt the execution state and return to the interpreter.
  fr.deoptimize(thread);
}

void Deoptimization::deoptimize(JavaThread* thread, frame fr, RegisterMap *map) {
  // Deoptimize only if the frame comes from compile code.
  // Do not deoptimize the frame which is already patched
  // during the execution of the loops below.
  if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
    return;
  }
  ResourceMark rm;
  DeoptimizationMarker dm;
  if (UseBiasedLocking) {
    revoke_biases_of_monitors(thread, fr, map);
  }
  deoptimize_single_frame(thread, fr);

}


1230 1231 1232
void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id) {
  assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
         "can only deoptimize other thread at a safepoint");
D
duke 已提交
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
  // Compute frame and register map based on thread and sp.
  RegisterMap reg_map(thread, UseBiasedLocking);
  frame fr = thread->last_frame();
  while (fr.id() != id) {
    fr = fr.sender(&reg_map);
  }
  deoptimize(thread, fr, &reg_map);
}


1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
  if (thread == Thread::current()) {
    Deoptimization::deoptimize_frame_internal(thread, id);
  } else {
    VM_DeoptimizeFrame deopt(thread, id);
    VMThread::execute(&deopt);
  }
}


D
duke 已提交
1253 1254 1255 1256 1257 1258 1259 1260
// JVMTI PopFrame support
JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
{
  thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
}
JRT_END


1261
#if defined(COMPILER2) || defined(SHARK)
D
duke 已提交
1262 1263 1264
void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index, TRAPS) {
  // in case of an unresolved klass entry, load the class.
  if (constant_pool->tag_at(index).is_unresolved_klass()) {
1265
    Klass* tk = constant_pool->klass_at(index, CHECK);
D
duke 已提交
1266 1267 1268 1269 1270
    return;
  }

  if (!constant_pool->tag_at(index).is_symbol()) return;

1271
  Handle class_loader (THREAD, constant_pool->pool_holder()->class_loader());
1272
  Symbol*  symbol  = constant_pool->symbol_at(index);
D
duke 已提交
1273 1274 1275

  // class name?
  if (symbol->byte_at(0) != '(') {
1276
    Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());
D
duke 已提交
1277 1278 1279 1280 1281
    SystemDictionary::resolve_or_null(symbol, class_loader, protection_domain, CHECK);
    return;
  }

  // then it must be a signature!
1282
  ResourceMark rm(THREAD);
D
duke 已提交
1283 1284
  for (SignatureStream ss(symbol); !ss.is_done(); ss.next()) {
    if (ss.is_object()) {
1285
      Symbol* class_name = ss.as_symbol(CHECK);
1286
      Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());
D
duke 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
      SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK);
    }
  }
}


void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index) {
  EXCEPTION_MARK;
  load_class_by_index(constant_pool, index, THREAD);
  if (HAS_PENDING_EXCEPTION) {
    // Exception happened during classloading. We ignore the exception here, since it
1298
    // is going to be rethrown since the current activation is going to be deoptimized and
D
duke 已提交
1299 1300
    // the interpreter will re-execute the bytecode.
    CLEAR_PENDING_EXCEPTION;
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
    // Class loading called java code which may have caused a stack
    // overflow. If the exception was thrown right before the return
    // to the runtime the stack is no longer guarded. Reguard the
    // stack otherwise if we return to the uncommon trap blob and the
    // stack bang causes a stack overflow we crash.
    assert(THREAD->is_Java_thread(), "only a java thread can be here");
    JavaThread* thread = (JavaThread*)THREAD;
    bool guard_pages_enabled = thread->stack_yellow_zone_enabled();
    if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
    assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
D
duke 已提交
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
  }
}

JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) {
  HandleMark hm;

  // uncommon_trap() is called at the beginning of the uncommon trap
  // handler. Note this fact before we start generating temporary frames
  // that can confuse an asynchronous stack walker. This counter is
  // decremented at the end of unpack_frames().
  thread->inc_in_deopt_handler();

  // We need to update the map if we have biased locking.
  RegisterMap reg_map(thread, UseBiasedLocking);
  frame stub_frame = thread->last_frame();
  frame fr = stub_frame.sender(&reg_map);
  // Make sure the calling nmethod is not getting deoptimized and removed
  // before we are done with it.
  nmethodLocker nl(fr.pc());

1331
  // Log a message
1332 1333
  Events::log(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT,
              trap_request, fr.pc());
1334

D
duke 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
  {
    ResourceMark rm;

    // Revoke biases of any monitors in the frame to ensure we can migrate them
    revoke_biases_of_monitors(thread, fr, &reg_map);

    DeoptReason reason = trap_request_reason(trap_request);
    DeoptAction action = trap_request_action(trap_request);
    jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1

    vframe*  vf  = vframe::new_vframe(&fr, &reg_map, thread);
    compiledVFrame* cvf = compiledVFrame::cast(vf);

    nmethod* nm = cvf->code();

    ScopeDesc*      trap_scope  = cvf->scope();
    methodHandle    trap_method = trap_scope->method();
    int             trap_bci    = trap_scope->bci();
1353
    Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
D
duke 已提交
1354 1355 1356 1357 1358

    // Record this event in the histogram.
    gather_statistics(reason, action, trap_bc);

    // Ensure that we can record deopt. history:
1359 1360
    // Need MDO to record RTM code generation state.
    bool create_if_missing = ProfileTraps RTM_OPT_ONLY( || UseRTMLocking );
D
duke 已提交
1361

1362 1363
    MethodData* trap_mdo =
      get_method_data(thread, trap_method, create_if_missing);
D
duke 已提交
1364

1365 1366 1367 1368 1369
    // Log a message
    Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d",
                              trap_reason_name(reason), trap_action_name(action), fr.pc(),
                              trap_method->name_and_sig_as_C_string(), trap_bci);

D
duke 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    // Print a bunch of diagnostics, if requested.
    if (TraceDeoptimization || LogCompilation) {
      ResourceMark rm;
      ttyLocker ttyl;
      char buf[100];
      if (xtty != NULL) {
        xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT"' %s",
                         os::current_thread_id(),
                         format_trap_request(buf, sizeof(buf), trap_request));
        nm->log_identity(xtty);
      }
1381
      Symbol* class_name = NULL;
D
duke 已提交
1382 1383 1384 1385
      bool unresolved = false;
      if (unloaded_class_index >= 0) {
        constantPoolHandle constants (THREAD, trap_method->constants());
        if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
1386
          class_name = constants->klass_name_at(unloaded_class_index);
D
duke 已提交
1387 1388 1389 1390
          unresolved = true;
          if (xtty != NULL)
            xtty->print(" unresolved='1'");
        } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
1391
          class_name = constants->symbol_at(unloaded_class_index);
D
duke 已提交
1392 1393 1394 1395
        }
        if (xtty != NULL)
          xtty->name(class_name);
      }
1396
      if (xtty != NULL && trap_mdo != NULL) {
D
duke 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
        // Dump the relevant MDO state.
        // This is the deopt count for the current reason, any previous
        // reasons or recompiles seen at this point.
        int dcnt = trap_mdo->trap_count(reason);
        if (dcnt != 0)
          xtty->print(" count='%d'", dcnt);
        ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
        int dos = (pdata == NULL)? 0: pdata->trap_state();
        if (dos != 0) {
          xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
          if (trap_state_is_recompiled(dos)) {
            int recnt2 = trap_mdo->overflow_recompile_count();
            if (recnt2 != 0)
              xtty->print(" recompiles2='%d'", recnt2);
          }
        }
      }
      if (xtty != NULL) {
        xtty->stamp();
        xtty->end_head();
      }
      if (TraceDeoptimization) {  // make noise on the tty
        tty->print("Uncommon trap occurred in");
        nm->method()->print_short_name(tty);
V
vlivanov 已提交
1421
        tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d",
D
duke 已提交
1422
                   fr.pc(),
V
vlivanov 已提交
1423
                   os::current_thread_id(),
D
duke 已提交
1424 1425 1426
                   trap_reason_name(reason),
                   trap_action_name(action),
                   unloaded_class_index);
1427
        if (class_name != NULL) {
D
duke 已提交
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
          tty->print(unresolved ? " unresolved class: " : " symbol: ");
          class_name->print_symbol_on(tty);
        }
        tty->cr();
      }
      if (xtty != NULL) {
        // Log the precise location of the trap.
        for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
          xtty->begin_elem("jvms bci='%d'", sd->bci());
          xtty->method(sd->method());
          xtty->end_elem();
          if (sd->is_top())  break;
        }
        xtty->tail("uncommon_trap");
      }
    }
    // (End diagnostic printout.)

    // Load class if necessary
    if (unloaded_class_index >= 0) {
      constantPoolHandle constants(THREAD, trap_method->constants());
      load_class_by_index(constants, unloaded_class_index);
    }

    // Flush the nmethod if necessary and desirable.
    //
    // We need to avoid situations where we are re-flushing the nmethod
    // because of a hot deoptimization site.  Repeated flushes at the same
    // point need to be detected by the compiler and avoided.  If the compiler
    // cannot avoid them (or has a bug and "refuses" to avoid them), this
    // module must take measures to avoid an infinite cycle of recompilation
    // and deoptimization.  There are several such measures:
    //
    //   1. If a recompilation is ordered a second time at some site X
    //   and for the same reason R, the action is adjusted to 'reinterpret',
    //   to give the interpreter time to exercise the method more thoroughly.
    //   If this happens, the method's overflow_recompile_count is incremented.
    //
    //   2. If the compiler fails to reduce the deoptimization rate, then
    //   the method's overflow_recompile_count will begin to exceed the set
    //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
    //   is adjusted to 'make_not_compilable', and the method is abandoned
    //   to the interpreter.  This is a performance hit for hot methods,
    //   but is better than a disastrous infinite cycle of recompilations.
    //   (Actually, only the method containing the site X is abandoned.)
    //
    //   3. In parallel with the previous measures, if the total number of
    //   recompilations of a method exceeds the much larger set limit
    //   PerMethodRecompilationCutoff, the method is abandoned.
    //   This should only happen if the method is very large and has
    //   many "lukewarm" deoptimizations.  The code which enforces this
1479
    //   limit is elsewhere (class nmethod, class Method).
D
duke 已提交
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
    //
    // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
    // to recompile at each bytecode independently of the per-BCI cutoff.
    //
    // The decision to update code is up to the compiler, and is encoded
    // in the Action_xxx code.  If the compiler requests Action_none
    // no trap state is changed, no compiled code is changed, and the
    // computation suffers along in the interpreter.
    //
    // The other action codes specify various tactics for decompilation
    // and recompilation.  Action_maybe_recompile is the loosest, and
    // allows the compiled code to stay around until enough traps are seen,
    // and until the compiler gets around to recompiling the trapping method.
    //
    // The other actions cause immediate removal of the present code.

1496 1497 1498 1499
    // Traps caused by injected profile shouldn't pollute trap counts.
    bool injected_profile_trap = trap_method->has_injected_profile() &&
                                 (reason == Reason_intrinsic || reason == Reason_unreached);
    bool update_trap_state = !injected_profile_trap;
D
duke 已提交
1500 1501
    bool make_not_entrant = false;
    bool make_not_compilable = false;
I
iveresov 已提交
1502
    bool reprofile = false;
D
duke 已提交
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
    switch (action) {
    case Action_none:
      // Keep the old code.
      update_trap_state = false;
      break;
    case Action_maybe_recompile:
      // Do not need to invalidate the present code, but we can
      // initiate another
      // Start compiler without (necessarily) invalidating the nmethod.
      // The system will tolerate the old code, but new code should be
      // generated when possible.
      break;
    case Action_reinterpret:
      // Go back into the interpreter for a while, and then consider
      // recompiling form scratch.
      make_not_entrant = true;
      // Reset invocation counter for outer most method.
      // This will allow the interpreter to exercise the bytecodes
      // for a while before recompiling.
      // By contrast, Action_make_not_entrant is immediate.
      //
      // Note that the compiler will track null_check, null_assert,
      // range_check, and class_check events and log them as if they
      // had been traps taken from compiled code.  This will update
      // the MDO trap history so that the next compilation will
      // properly detect hot trap sites.
I
iveresov 已提交
1529
      reprofile = true;
D
duke 已提交
1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
      break;
    case Action_make_not_entrant:
      // Request immediate recompilation, and get rid of the old code.
      // Make them not entrant, so next time they are called they get
      // recompiled.  Unloaded classes are loaded now so recompile before next
      // time they are called.  Same for uninitialized.  The interpreter will
      // link the missing class, if any.
      make_not_entrant = true;
      break;
    case Action_make_not_compilable:
      // Give up on compiling this method at all.
      make_not_entrant = true;
      make_not_compilable = true;
      break;
    default:
      ShouldNotReachHere();
    }

    // Setting +ProfileTraps fixes the following, on all platforms:
    // 4852688: ProfileInterpreter is off by default for ia64.  The result is
    // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
1551
    // recompile relies on a MethodData* to record heroic opt failures.
D
duke 已提交
1552 1553 1554 1555

    // Whether the interpreter is producing MDO data or not, we also need
    // to use the MDO to detect hot deoptimization points and control
    // aggressive optimization.
1556 1557
    bool inc_recompile_count = false;
    ProfileData* pdata = NULL;
1558 1559
    if (ProfileTraps && update_trap_state && trap_mdo != NULL) {
      assert(trap_mdo == get_method_data(thread, trap_method, false), "sanity");
D
duke 已提交
1560 1561 1562
      uint this_trap_count = 0;
      bool maybe_prior_trap = false;
      bool maybe_prior_recompile = false;
1563
      pdata = query_update_method_data(trap_mdo, trap_bci, reason,
1564
                                   nm->method(),
D
duke 已提交
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
                                   //outputs:
                                   this_trap_count,
                                   maybe_prior_trap,
                                   maybe_prior_recompile);
      // Because the interpreter also counts null, div0, range, and class
      // checks, these traps from compiled code are double-counted.
      // This is harmless; it just means that the PerXTrapLimit values
      // are in effect a little smaller than they look.

      DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
      if (per_bc_reason != Reason_none) {
        // Now take action based on the partially known per-BCI history.
        if (maybe_prior_trap
            && this_trap_count >= (uint)PerBytecodeTrapLimit) {
          // If there are too many traps at this BCI, force a recompile.
          // This will allow the compiler to see the limit overflow, and
          // take corrective action, if possible.  The compiler generally
          // does not use the exact PerBytecodeTrapLimit value, but instead
          // changes its tactics if it sees any traps at all.  This provides
          // a little hysteresis, delaying a recompile until a trap happens
          // several times.
          //
          // Actually, since there is only one bit of counter per BCI,
          // the possible per-BCI counts are {0,1,(per-method count)}.
          // This produces accurate results if in fact there is only
          // one hot trap site, but begins to get fuzzy if there are
          // many sites.  For example, if there are ten sites each
          // trapping two or more times, they each get the blame for
          // all of their traps.
          make_not_entrant = true;
        }

        // Detect repeated recompilation at the same BCI, and enforce a limit.
        if (make_not_entrant && maybe_prior_recompile) {
          // More than one recompile at this point.
1600
          inc_recompile_count = maybe_prior_trap;
D
duke 已提交
1601 1602 1603 1604 1605 1606 1607 1608 1609
        }
      } else {
        // For reasons which are not recorded per-bytecode, we simply
        // force recompiles unconditionally.
        // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
        make_not_entrant = true;
      }

      // Go back to the compiler if there are too many traps in this method.
1610
      if (this_trap_count >= per_method_trap_limit(reason)) {
D
duke 已提交
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
        // If there are too many traps in this method, force a recompile.
        // This will allow the compiler to see the limit overflow, and
        // take corrective action, if possible.
        // (This condition is an unlikely backstop only, because the
        // PerBytecodeTrapLimit is more likely to take effect first,
        // if it is applicable.)
        make_not_entrant = true;
      }

      // Here's more hysteresis:  If there has been a recompile at
      // this trap point already, run the method in the interpreter
      // for a while to exercise it more thoroughly.
      if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
I
iveresov 已提交
1624
        reprofile = true;
D
duke 已提交
1625 1626
      }

1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    }

    // Take requested actions on the method:

    // Recompile
    if (make_not_entrant) {
      if (!nm->make_not_entrant()) {
        return; // the call did not change nmethod's state
      }

      if (pdata != NULL) {
D
duke 已提交
1638 1639 1640 1641 1642 1643
        // Record the recompilation event, if any.
        int tstate0 = pdata->trap_state();
        int tstate1 = trap_state_set_recompiled(tstate0, true);
        if (tstate1 != tstate0)
          pdata->set_trap_state(tstate1);
      }
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654

#if INCLUDE_RTM_OPT
      // Restart collecting RTM locking abort statistic if the method
      // is recompiled for a reason other than RTM state change.
      // Assume that in new recompiled code the statistic could be different,
      // for example, due to different inlining.
      if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&
          UseRTMDeopt && (nm->rtm_state() != ProfileRTM)) {
        trap_mdo->atomic_set_rtm_state(ProfileRTM);
      }
#endif
D
duke 已提交
1655 1656
    }

1657 1658 1659 1660 1661 1662 1663 1664
    if (inc_recompile_count) {
      trap_mdo->inc_overflow_recompile_count();
      if ((uint)trap_mdo->overflow_recompile_count() >
          (uint)PerBytecodeRecompilationCutoff) {
        // Give up on the method containing the bad BCI.
        if (trap_method() == nm->method()) {
          make_not_compilable = true;
        } else {
1665
          trap_method->set_not_compilable(CompLevel_full_optimization, true, "overflow_recompile_count > PerBytecodeRecompilationCutoff");
1666 1667 1668 1669
          // But give grace to the enclosing nm->method().
        }
      }
    }
D
duke 已提交
1670

I
iveresov 已提交
1671 1672 1673
    // Reprofile
    if (reprofile) {
      CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method());
D
duke 已提交
1674 1675 1676
    }

    // Give up compiling
I
iveresov 已提交
1677
    if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
D
duke 已提交
1678
      assert(make_not_entrant, "consistent");
I
iveresov 已提交
1679
      nm->method()->set_not_compilable(CompLevel_full_optimization);
D
duke 已提交
1680 1681 1682 1683 1684 1685 1686
    }

  } // Free marked resources

}
JRT_END

1687
MethodData*
D
duke 已提交
1688 1689 1690
Deoptimization::get_method_data(JavaThread* thread, methodHandle m,
                                bool create_if_missing) {
  Thread* THREAD = thread;
1691
  MethodData* mdo = m()->method_data();
D
duke 已提交
1692 1693 1694
  if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {
    // Build an MDO.  Ignore errors like OutOfMemory;
    // that simply means we won't have an MDO to update.
1695
    Method::build_interpreter_method_data(m, THREAD);
D
duke 已提交
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
    if (HAS_PENDING_EXCEPTION) {
      assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
      CLEAR_PENDING_EXCEPTION;
    }
    mdo = m()->method_data();
  }
  return mdo;
}

ProfileData*
1706
Deoptimization::query_update_method_data(MethodData* trap_mdo,
D
duke 已提交
1707 1708
                                         int trap_bci,
                                         Deoptimization::DeoptReason reason,
1709
                                         Method* compiled_method,
D
duke 已提交
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
                                         //outputs:
                                         uint& ret_this_trap_count,
                                         bool& ret_maybe_prior_trap,
                                         bool& ret_maybe_prior_recompile) {
  uint prior_trap_count = trap_mdo->trap_count(reason);
  uint this_trap_count  = trap_mdo->inc_trap_count(reason);

  // If the runtime cannot find a place to store trap history,
  // it is estimated based on the general condition of the method.
  // If the method has ever been recompiled, or has ever incurred
  // a trap with the present reason , then this BCI is assumed
  // (pessimistically) to be the culprit.
  bool maybe_prior_trap      = (prior_trap_count != 0);
  bool maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
  ProfileData* pdata = NULL;


  // For reasons which are recorded per bytecode, we check per-BCI data.
  DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
  if (per_bc_reason != Reason_none) {
    // Find the profile data for this BCI.  If there isn't one,
    // try to allocate one from the MDO's set of spares.
    // This will let us detect a repeated trap at this point.
1733
    pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);
D
duke 已提交
1734 1735

    if (pdata != NULL) {
1736 1737 1738 1739 1740 1741 1742
      if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
        if (LogCompilation && xtty != NULL) {
          ttyLocker ttyl;
          // no more room for speculative traps in this MDO
          xtty->elem("speculative_traps_oom");
        }
      }
D
duke 已提交
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
      // Query the trap state of this profile datum.
      int tstate0 = pdata->trap_state();
      if (!trap_state_has_reason(tstate0, per_bc_reason))
        maybe_prior_trap = false;
      if (!trap_state_is_recompiled(tstate0))
        maybe_prior_recompile = false;

      // Update the trap state of this profile datum.
      int tstate1 = tstate0;
      // Record the reason.
      tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
      // Store the updated state on the MDO, for next time.
      if (tstate1 != tstate0)
        pdata->set_trap_state(tstate1);
    } else {
1758 1759
      if (LogCompilation && xtty != NULL) {
        ttyLocker ttyl;
D
duke 已提交
1760 1761
        // Missing MDP?  Leave a small complaint in the log.
        xtty->elem("missing_mdp bci='%d'", trap_bci);
1762
      }
D
duke 已提交
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
    }
  }

  // Return results:
  ret_this_trap_count = this_trap_count;
  ret_maybe_prior_trap = maybe_prior_trap;
  ret_maybe_prior_recompile = maybe_prior_recompile;
  return pdata;
}

void
1774
Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
D
duke 已提交
1775 1776 1777 1778 1779
  ResourceMark rm;
  // Ignored outputs:
  uint ignore_this_trap_count;
  bool ignore_maybe_prior_trap;
  bool ignore_maybe_prior_recompile;
1780
  assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
D
duke 已提交
1781 1782
  query_update_method_data(trap_mdo, trap_bci,
                           (DeoptReason)reason,
1783
                           NULL,
D
duke 已提交
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 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
                           ignore_this_trap_count,
                           ignore_maybe_prior_trap,
                           ignore_maybe_prior_recompile);
}

Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request) {

  // Still in Java no safepoints
  {
    // This enters VM and may safepoint
    uncommon_trap_inner(thread, trap_request);
  }
  return fetch_unroll_info_helper(thread);
}

// Local derived constants.
// Further breakdown of DataLayout::trap_state, as promised by DataLayout.
const int DS_REASON_MASK   = DataLayout::trap_mask >> 1;
const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;

//---------------------------trap_state_reason---------------------------------
Deoptimization::DeoptReason
Deoptimization::trap_state_reason(int trap_state) {
  // This assert provides the link between the width of DataLayout::trap_bits
  // and the encoding of "recorded" reasons.  It ensures there are enough
  // bits to store all needed reasons in the per-BCI MDO profile.
  assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
  int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
  trap_state -= recompile_bit;
  if (trap_state == DS_REASON_MASK) {
    return Reason_many;
  } else {
    assert((int)Reason_none == 0, "state=0 => Reason_none");
    return (DeoptReason)trap_state;
  }
}
//-------------------------trap_state_has_reason-------------------------------
int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
  assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
  assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
  int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
  trap_state -= recompile_bit;
  if (trap_state == DS_REASON_MASK) {
    return -1;  // true, unspecifically (bottom of state lattice)
  } else if (trap_state == reason) {
    return 1;   // true, definitely
  } else if (trap_state == 0) {
    return 0;   // false, definitely (top of state lattice)
  } else {
    return 0;   // false, definitely
  }
}
//-------------------------trap_state_add_reason-------------------------------
int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
  assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
  int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
  trap_state -= recompile_bit;
  if (trap_state == DS_REASON_MASK) {
    return trap_state + recompile_bit;     // already at state lattice bottom
  } else if (trap_state == reason) {
    return trap_state + recompile_bit;     // the condition is already true
  } else if (trap_state == 0) {
    return reason + recompile_bit;          // no condition has yet been true
  } else {
    return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
  }
}
//-----------------------trap_state_is_recompiled------------------------------
bool Deoptimization::trap_state_is_recompiled(int trap_state) {
  return (trap_state & DS_RECOMPILE_BIT) != 0;
}
//-----------------------trap_state_set_recompiled-----------------------------
int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
  if (z)  return trap_state |  DS_RECOMPILE_BIT;
  else    return trap_state & ~DS_RECOMPILE_BIT;
}
//---------------------------format_trap_state---------------------------------
1861
// This is used for debugging and diagnostics, including LogFile output.
D
duke 已提交
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
                                              int trap_state) {
  DeoptReason reason      = trap_state_reason(trap_state);
  bool        recomp_flag = trap_state_is_recompiled(trap_state);
  // Re-encode the state from its decoded components.
  int decoded_state = 0;
  if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
    decoded_state = trap_state_add_reason(decoded_state, reason);
  if (recomp_flag)
    decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
  // If the state re-encodes properly, format it symbolically.
  // Because this routine is used for debugging and diagnostics,
  // be robust even if the state is a strange value.
  size_t len;
  if (decoded_state != trap_state) {
    // Random buggy state that doesn't decode??
    len = jio_snprintf(buf, buflen, "#%d", trap_state);
  } else {
    len = jio_snprintf(buf, buflen, "%s%s",
                       trap_reason_name(reason),
                       recomp_flag ? " recompiled" : "");
  }
  return buf;
}


//--------------------------------statics--------------------------------------
Deoptimization::DeoptAction Deoptimization::_unloaded_action
  = Deoptimization::Action_reinterpret;
const char* Deoptimization::_trap_reason_name[Reason_LIMIT] = {
  // Note:  Keep this in sync. with enum DeoptReason.
  "none",
  "null_check",
  "null_assert",
  "range_check",
  "class_check",
  "array_check",
  "intrinsic",
1900
  "bimorphic",
D
duke 已提交
1901 1902 1903 1904 1905 1906
  "unloaded",
  "uninitialized",
  "unreached",
  "unhandled",
  "constraint",
  "div0_check",
1907
  "age",
1908
  "predicate",
1909
  "loop_limit_check",
1910
  "speculate_class_check",
1911 1912
  "rtm_state_change",
  "unstable_if"
D
duke 已提交
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
};
const char* Deoptimization::_trap_action_name[Action_LIMIT] = {
  // Note:  Keep this in sync. with enum DeoptAction.
  "none",
  "maybe_recompile",
  "reinterpret",
  "make_not_entrant",
  "make_not_compilable"
};

const char* Deoptimization::trap_reason_name(int reason) {
  if (reason == Reason_many)  return "many";
  if ((uint)reason < Reason_LIMIT)
    return _trap_reason_name[reason];
  static char buf[20];
  sprintf(buf, "reason%d", reason);
  return buf;
}
const char* Deoptimization::trap_action_name(int action) {
  if ((uint)action < Action_LIMIT)
    return _trap_action_name[action];
  static char buf[20];
  sprintf(buf, "action%d", action);
  return buf;
}

1939
// This is used for debugging and diagnostics, including LogFile output.
D
duke 已提交
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 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 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
                                                int trap_request) {
  jint unloaded_class_index = trap_request_index(trap_request);
  const char* reason = trap_reason_name(trap_request_reason(trap_request));
  const char* action = trap_action_name(trap_request_action(trap_request));
  size_t len;
  if (unloaded_class_index < 0) {
    len = jio_snprintf(buf, buflen, "reason='%s' action='%s'",
                       reason, action);
  } else {
    len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'",
                       reason, action, unloaded_class_index);
  }
  return buf;
}

juint Deoptimization::_deoptimization_hist
        [Deoptimization::Reason_LIMIT]
    [1 + Deoptimization::Action_LIMIT]
        [Deoptimization::BC_CASE_LIMIT]
  = {0};

enum {
  LSB_BITS = 8,
  LSB_MASK = right_n_bits(LSB_BITS)
};

void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
                                       Bytecodes::Code bc) {
  assert(reason >= 0 && reason < Reason_LIMIT, "oob");
  assert(action >= 0 && action < Action_LIMIT, "oob");
  _deoptimization_hist[Reason_none][0][0] += 1;  // total
  _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
  juint* cases = _deoptimization_hist[reason][1+action];
  juint* bc_counter_addr = NULL;
  juint  bc_counter      = 0;
  // Look for an unused counter, or an exact match to this BC.
  if (bc != Bytecodes::_illegal) {
    for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
      juint* counter_addr = &cases[bc_case];
      juint  counter = *counter_addr;
      if ((counter == 0 && bc_counter_addr == NULL)
          || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
        // this counter is either free or is already devoted to this BC
        bc_counter_addr = counter_addr;
        bc_counter = counter | bc;
      }
    }
  }
  if (bc_counter_addr == NULL) {
    // Overflow, or no given bytecode.
    bc_counter_addr = &cases[BC_CASE_LIMIT-1];
    bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
  }
  *bc_counter_addr = bc_counter + (1 << LSB_BITS);
}

jint Deoptimization::total_deoptimization_count() {
  return _deoptimization_hist[Reason_none][0][0];
}

jint Deoptimization::deoptimization_count(DeoptReason reason) {
  assert(reason >= 0 && reason < Reason_LIMIT, "oob");
  return _deoptimization_hist[reason][0][0];
}

void Deoptimization::print_statistics() {
  juint total = total_deoptimization_count();
  juint account = total;
  if (total != 0) {
    ttyLocker ttyl;
    if (xtty != NULL)  xtty->head("statistics type='deoptimization'");
    tty->print_cr("Deoptimization traps recorded:");
    #define PRINT_STAT_LINE(name, r) \
      tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
    PRINT_STAT_LINE("total", total);
    // For each non-zero entry in the histogram, print the reason,
    // the action, and (if specifically known) the type of bytecode.
    for (int reason = 0; reason < Reason_LIMIT; reason++) {
      for (int action = 0; action < Action_LIMIT; action++) {
        juint* cases = _deoptimization_hist[reason][1+action];
        for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
          juint counter = cases[bc_case];
          if (counter != 0) {
            char name[1*K];
            Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
            if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
              bc = Bytecodes::_illegal;
            sprintf(name, "%s/%s/%s",
                    trap_reason_name(reason),
                    trap_action_name(action),
                    Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
            juint r = counter >> LSB_BITS;
            tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
            account -= r;
          }
        }
      }
    }
    if (account != 0) {
      PRINT_STAT_LINE("unaccounted", account);
    }
    #undef PRINT_STAT_LINE
    if (xtty != NULL)  xtty->tail("statistics");
  }
}
2046
#else // COMPILER2 || SHARK
D
duke 已提交
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062


// Stubs for C1 only system.
bool Deoptimization::trap_state_is_recompiled(int trap_state) {
  return false;
}

const char* Deoptimization::trap_reason_name(int reason) {
  return "unknown";
}

void Deoptimization::print_statistics() {
  // no output
}

void
2063
Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
D
duke 已提交
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
  // no udpate
}

int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
  return 0;
}

void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
                                       Bytecodes::Code bc) {
  // no update
}

const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
                                              int trap_state) {
  jio_snprintf(buf, buflen, "#%d", trap_state);
  return buf;
}

2082
#endif // COMPILER2 || SHARK