1 
   2 
   3 /*
   4  * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 #include "precompiled.hpp"
  28 #include "jvm.h"
  29 #include "classfile/symbolTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "code/debugInfoRec.hpp"
  33 #include "code/nmethod.hpp"
  34 #include "code/pcDesc.hpp"
  35 #include "code/scopeDesc.hpp"
  36 #include "compiler/compilationPolicy.hpp"
  37 #include "interpreter/bytecode.hpp"
  38 #include "interpreter/interpreter.hpp"
  39 #include "interpreter/oopMapCache.hpp"
  40 #include "memory/allocation.inline.hpp"
  41 #include "memory/oopFactory.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "memory/universe.hpp"
  44 #include "oops/constantPool.hpp"
  45 #include "oops/method.hpp"
  46 #include "oops/objArrayKlass.hpp"
  47 #include "oops/objArrayOop.inline.hpp"
  48 #include "oops/oop.inline.hpp"
  49 #include "oops/fieldStreams.inline.hpp"
  50 #include "oops/typeArrayOop.inline.hpp"
  51 #include "oops/verifyOopClosure.hpp"
  52 #include "prims/jvmtiThreadState.hpp"
  53 #include "runtime/atomic.hpp"
  54 #include "runtime/biasedLocking.hpp"
  55 #include "runtime/deoptimization.hpp"
  56 #include "runtime/fieldDescriptor.hpp"
  57 #include "runtime/fieldDescriptor.inline.hpp"
  58 #include "runtime/frame.inline.hpp"
  59 #include "runtime/handles.inline.hpp"
  60 #include "runtime/interfaceSupport.inline.hpp"
  61 #include "runtime/jniHandles.inline.hpp"
  62 #include "runtime/safepointVerifiers.hpp"
  63 #include "runtime/sharedRuntime.hpp"
  64 #include "runtime/signature.hpp"
  65 #include "runtime/stubRoutines.hpp"
  66 #include "runtime/thread.hpp"
  67 #include "runtime/threadSMR.hpp"
  68 #include "runtime/vframe.hpp"
  69 #include "runtime/vframeArray.hpp"
  70 #include "runtime/vframe_hp.hpp"
  71 #include "utilities/events.hpp"
  72 #include "utilities/macros.hpp"
  73 #include "utilities/preserveException.hpp"
  74 #include "utilities/xmlstream.hpp"
  75 #if INCLUDE_JFR
  76 #include "jfr/jfrEvents.hpp"
  77 #include "jfr/metadata/jfrSerializer.hpp"
  78 #endif
  79 
  80 bool DeoptimizationMarker::_is_active = false;
  81 
  82 Deoptimization::UnrollBlock::UnrollBlock(int  size_of_deoptimized_frame,
  83                                          int  caller_adjustment,
  84                                          int  caller_actual_parameters,
  85                                          int  number_of_frames,
  86                                          intptr_t* frame_sizes,
  87                                          address* frame_pcs,
  88                                          BasicType return_type,
  89                                          int exec_mode) {
  90   _size_of_deoptimized_frame = size_of_deoptimized_frame;
  91   _caller_adjustment         = caller_adjustment;
  92   _caller_actual_parameters  = caller_actual_parameters;
  93   _number_of_frames          = number_of_frames;
  94   _frame_sizes               = frame_sizes;
  95   _frame_pcs                 = frame_pcs;
  96   _register_block            = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
  97   _return_type               = return_type;
  98   _initial_info              = 0;
  99   // PD (x86 only)
 100   _counter_temp              = 0;
 101   _unpack_kind               = exec_mode;
 102   _sender_sp_temp            = 0;
 103 
 104   _total_frame_sizes         = size_of_frames();
 105   assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");
 106 }
 107 
 108 
 109 Deoptimization::UnrollBlock::~UnrollBlock() {
 110   FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes);
 111   FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs);
 112   FREE_C_HEAP_ARRAY(intptr_t, _register_block);
 113 }
 114 
 115 
 116 intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {
 117   assert(register_number < RegisterMap::reg_count, "checking register number");
 118   return &_register_block[register_number * 2];
 119 }
 120 
 121 
 122 
 123 int Deoptimization::UnrollBlock::size_of_frames() const {
 124   // Acount first for the adjustment of the initial frame
 125   int result = _caller_adjustment;
 126   for (int index = 0; index < number_of_frames(); index++) {
 127     result += frame_sizes()[index];
 128   }
 129   return result;
 130 }
 131 
 132 
 133 void Deoptimization::UnrollBlock::print() {
 134   ttyLocker ttyl;
 135   tty->print_cr("UnrollBlock");
 136   tty->print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
 137   tty->print(   "  frame_sizes: ");
 138   for (int index = 0; index < number_of_frames(); index++) {
 139     tty->print(INTX_FORMAT " ", frame_sizes()[index]);
 140   }
 141   tty->cr();
 142 }
 143 
 144 
 145 // In order to make fetch_unroll_info work properly with escape
 146 // analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and
 147 // ResetNoHandleMark and HandleMark were removed from it. The actual reallocation
 148 // of previously eliminated objects occurs in realloc_objects, which is
 149 // called from the method fetch_unroll_info_helper below.
 150 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread, int exec_mode))
 151   // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
 152   // but makes the entry a little slower. There is however a little dance we have to
 153   // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
 154 
 155   // fetch_unroll_info() is called at the beginning of the deoptimization
 156   // handler. Note this fact before we start generating temporary frames
 157   // that can confuse an asynchronous stack walker. This counter is
 158   // decremented at the end of unpack_frames().
 159   if (TraceDeoptimization) {
 160     tty->print_cr("Deoptimizing thread " INTPTR_FORMAT, p2i(thread));
 161   }
 162   thread->inc_in_deopt_handler();
 163 
 164   return fetch_unroll_info_helper(thread, exec_mode);
 165 JRT_END
 166 
 167 #if COMPILER2_OR_JVMCI
 168 static bool eliminate_allocations(JavaThread* thread, int exec_mode, CompiledMethod* compiled_method,
 169                                   frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk) {
 170   bool realloc_failures = false;
 171   assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");
 172 
 173   GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
 174 
 175   // The flag return_oop() indicates call sites which return oop
 176   // in compiled code. Such sites include java method calls,
 177   // runtime calls (for example, used to allocate new objects/arrays
 178   // on slow code path) and any other calls generated in compiled code.
 179   // It is not guaranteed that we can get such information here only
 180   // by analyzing bytecode in deoptimized frames. This is why this flag
 181   // is set during method compilation (see Compile::Process_OopMap_Node()).
 182   // If the previous frame was popped or if we are dispatching an exception,
 183   // we don't have an oop result.
 184   bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);
 185   Handle return_value;
 186   if (save_oop_result) {
 187     // Reallocation may trigger GC. If deoptimization happened on return from
 188     // call which returns oop we need to save it since it is not in oopmap.
 189     oop result = deoptee.saved_oop_result(&map);
 190     assert(oopDesc::is_oop_or_null(result), "must be oop");
 191     return_value = Handle(thread, result);
 192     assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
 193     if (TraceDeoptimization) {
 194       ttyLocker ttyl;
 195       tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
 196     }
 197   }
 198   if (objects != NULL) {
 199     JRT_BLOCK
 200       realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);
 201     JRT_END
 202     bool skip_internal = (compiled_method != NULL) && !compiled_method->is_compiled_by_jvmci();
 203     Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal);
 204 #ifndef PRODUCT
 205     if (TraceDeoptimization) {
 206       ttyLocker ttyl;
 207       tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(thread));
 208       Deoptimization::print_objects(objects, realloc_failures);
 209     }
 210 #endif
 211   }
 212   if (save_oop_result) {
 213     // Restore result.
 214     deoptee.set_saved_oop_result(&map, return_value());
 215   }
 216   return realloc_failures;
 217 }
 218 
 219 static void eliminate_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
 220 #ifndef PRODUCT
 221   bool first = true;
 222 #endif
 223   for (int i = 0; i < chunk->length(); i++) {
 224     compiledVFrame* cvf = chunk->at(i);
 225     assert (cvf->scope() != NULL,"expect only compiled java frames");
 226     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
 227     if (monitors->is_nonempty()) {
 228       Deoptimization::relock_objects(monitors, thread, realloc_failures);
 229 #ifndef PRODUCT
 230       if (PrintDeoptimizationDetails) {
 231         ttyLocker ttyl;
 232         for (int j = 0; j < monitors->length(); j++) {
 233           MonitorInfo* mi = monitors->at(j);
 234           if (mi->eliminated()) {
 235             if (first) {
 236               first = false;
 237               tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread));
 238             }
 239             if (mi->owner_is_scalar_replaced()) {
 240               Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
 241               tty->print_cr("     failed reallocation for klass %s", k->external_name());
 242             } else {
 243               tty->print_cr("     object <" INTPTR_FORMAT "> locked", p2i(mi->owner()));
 244             }
 245           }
 246         }
 247       }
 248 #endif // !PRODUCT
 249     }
 250   }
 251 }
 252 #endif // COMPILER2_OR_JVMCI
 253 
 254 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
 255 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread, int exec_mode) {
 256 
 257   // Note: there is a safepoint safety issue here. No matter whether we enter
 258   // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
 259   // the vframeArray is created.
 260   //
 261 
 262   // Allocate our special deoptimization ResourceMark
 263   DeoptResourceMark* dmark = new DeoptResourceMark(thread);
 264   assert(thread->deopt_mark() == NULL, "Pending deopt!");
 265   thread->set_deopt_mark(dmark);
 266 
 267   frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect
 268   RegisterMap map(thread, true);
 269   RegisterMap dummy_map(thread, false);
 270   // Now get the deoptee with a valid map
 271   frame deoptee = stub_frame.sender(&map);
 272   // Set the deoptee nmethod
 273   assert(thread->deopt_compiled_method() == NULL, "Pending deopt!");
 274   CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();
 275   thread->set_deopt_compiled_method(cm);
 276 
 277   if (VerifyStack) {
 278     thread->validate_frame_layout();
 279   }
 280 
 281   // Create a growable array of VFrames where each VFrame represents an inlined
 282   // Java frame.  This storage is allocated with the usual system arena.
 283   assert(deoptee.is_compiled_frame(), "Wrong frame type");
 284   GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
 285   vframe* vf = vframe::new_vframe(&deoptee, &map, thread);
 286   while (!vf->is_top()) {
 287     assert(vf->is_compiled_frame(), "Wrong frame type");
 288     chunk->push(compiledVFrame::cast(vf));
 289     vf = vf->sender();
 290   }
 291   assert(vf->is_compiled_frame(), "Wrong frame type");
 292   chunk->push(compiledVFrame::cast(vf));
 293 
 294   bool realloc_failures = false;
 295 
 296 #if COMPILER2_OR_JVMCI
 297 #if INCLUDE_JVMCI
 298   bool jvmci_enabled = true;
 299 #else
 300   bool jvmci_enabled = false;
 301 #endif
 302 
 303   // Reallocate the non-escaping objects and restore their fields. Then
 304   // relock objects if synchronization on them was eliminated.
 305   if (jvmci_enabled COMPILER2_PRESENT( || (DoEscapeAnalysis && EliminateAllocations) )) {
 306     realloc_failures = eliminate_allocations(thread, exec_mode, cm, deoptee, map, chunk);
 307   }
 308 #endif // COMPILER2_OR_JVMCI
 309 
 310   // Revoke biases, done with in java state.
 311   // No safepoints allowed after this
 312   revoke_from_deopt_handler(thread, deoptee, &map);
 313 
 314   // Ensure that no safepoint is taken after pointers have been stored
 315   // in fields of rematerialized objects.  If a safepoint occurs from here on
 316   // out the java state residing in the vframeArray will be missed.
 317   // Locks may be rebaised in a safepoint.
 318   NoSafepointVerifier no_safepoint;
 319 
 320 #if COMPILER2_OR_JVMCI
 321   if (jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) )) {
 322     eliminate_locks(thread, chunk, realloc_failures);
 323   }
 324 #endif // COMPILER2_OR_JVMCI
 325 
 326   ScopeDesc* trap_scope = chunk->at(0)->scope();
 327   Handle exceptionObject;
 328   if (trap_scope->rethrow_exception()) {
 329     if (PrintDeoptimizationDetails) {
 330       tty->print_cr("Exception to be rethrown in the interpreter for method %s::%s at bci %d", trap_scope->method()->method_holder()->name()->as_C_string(), trap_scope->method()->name()->as_C_string(), trap_scope->bci());
 331     }
 332     GrowableArray<ScopeValue*>* expressions = trap_scope->expressions();
 333     guarantee(expressions != NULL && expressions->length() > 0, "must have exception to throw");
 334     ScopeValue* topOfStack = expressions->top();
 335     exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();
 336     guarantee(exceptionObject() != NULL, "exception oop can not be null");
 337   }
 338 
 339   vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures);
 340 #if COMPILER2_OR_JVMCI
 341   if (realloc_failures) {
 342     pop_frames_failed_reallocs(thread, array);
 343   }
 344 #endif
 345 
 346   assert(thread->vframe_array_head() == NULL, "Pending deopt!");
 347   thread->set_vframe_array_head(array);
 348 
 349   // Now that the vframeArray has been created if we have any deferred local writes
 350   // added by jvmti then we can free up that structure as the data is now in the
 351   // vframeArray
 352 
 353   if (thread->deferred_locals() != NULL) {
 354     GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals();
 355     int i = 0;
 356     do {
 357       // Because of inlining we could have multiple vframes for a single frame
 358       // and several of the vframes could have deferred writes. Find them all.
 359       if (list->at(i)->id() == array->original().id()) {
 360         jvmtiDeferredLocalVariableSet* dlv = list->at(i);
 361         list->remove_at(i);
 362         // individual jvmtiDeferredLocalVariableSet are CHeapObj's
 363         delete dlv;
 364       } else {
 365         i++;
 366       }
 367     } while ( i < list->length() );
 368     if (list->length() == 0) {
 369       thread->set_deferred_locals(NULL);
 370       // free the list and elements back to C heap.
 371       delete list;
 372     }
 373 
 374   }
 375 
 376   // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
 377   CodeBlob* cb = stub_frame.cb();
 378   // Verify we have the right vframeArray
 379   assert(cb->frame_size() >= 0, "Unexpected frame size");
 380   intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
 381 
 382   // If the deopt call site is a MethodHandle invoke call site we have
 383   // to adjust the unpack_sp.
 384   nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
 385   if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))
 386     unpack_sp = deoptee.unextended_sp();
 387 
 388 #ifdef ASSERT
 389   assert(cb->is_deoptimization_stub() ||
 390          cb->is_uncommon_trap_stub() ||
 391          strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||
 392          strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,
 393          "unexpected code blob: %s", cb->name());
 394 #endif
 395 
 396   // This is a guarantee instead of an assert because if vframe doesn't match
 397   // we will unpack the wrong deoptimized frame and wind up in strange places
 398   // where it will be very difficult to figure out what went wrong. Better
 399   // to die an early death here than some very obscure death later when the
 400   // trail is cold.
 401   // Note: on ia64 this guarantee can be fooled by frames with no memory stack
 402   // in that it will fail to detect a problem when there is one. This needs
 403   // more work in tiger timeframe.
 404   guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
 405 
 406   int number_of_frames = array->frames();
 407 
 408   // Compute the vframes' sizes.  Note that frame_sizes[] entries are ordered from outermost to innermost
 409   // virtual activation, which is the reverse of the elements in the vframes array.
 410   intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
 411   // +1 because we always have an interpreter return address for the final slot.
 412   address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
 413   int popframe_extra_args = 0;
 414   // Create an interpreter return address for the stub to use as its return
 415   // address so the skeletal frames are perfectly walkable
 416   frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
 417 
 418   // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
 419   // activation be put back on the expression stack of the caller for reexecution
 420   if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {
 421     popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words());
 422   }
 423 
 424   // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
 425   // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
 426   // than simply use array->sender.pc(). This requires us to walk the current set of frames
 427   //
 428   frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
 429   deopt_sender = deopt_sender.sender(&dummy_map);     // Now deoptee caller
 430 
 431   // It's possible that the number of parameters at the call site is
 432   // different than number of arguments in the callee when method
 433   // handles are used.  If the caller is interpreted get the real
 434   // value so that the proper amount of space can be added to it's
 435   // frame.
 436   bool caller_was_method_handle = false;
 437   if (deopt_sender.is_interpreted_frame()) {
 438     methodHandle method(thread, deopt_sender.interpreter_frame_method());
 439     Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
 440     if (cur.is_invokedynamic() || cur.is_invokehandle()) {
 441       // Method handle invokes may involve fairly arbitrary chains of
 442       // calls so it's impossible to know how much actual space the
 443       // caller has for locals.
 444       caller_was_method_handle = true;
 445     }
 446   }
 447 
 448   //
 449   // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
 450   // frame_sizes/frame_pcs[1] next oldest frame (int)
 451   // frame_sizes/frame_pcs[n] youngest frame (int)
 452   //
 453   // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
 454   // owns the space for the return address to it's caller).  Confusing ain't it.
 455   //
 456   // The vframe array can address vframes with indices running from
 457   // 0.._frames-1. Index  0 is the youngest frame and _frame - 1 is the oldest (root) frame.
 458   // When we create the skeletal frames we need the oldest frame to be in the zero slot
 459   // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
 460   // so things look a little strange in this loop.
 461   //
 462   int callee_parameters = 0;
 463   int callee_locals = 0;
 464   for (int index = 0; index < array->frames(); index++ ) {
 465     // frame[number_of_frames - 1 ] = on_stack_size(youngest)
 466     // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
 467     // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
 468     frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
 469                                                                                                     callee_locals,
 470                                                                                                     index == 0,
 471                                                                                                     popframe_extra_args);
 472     // This pc doesn't have to be perfect just good enough to identify the frame
 473     // as interpreted so the skeleton frame will be walkable
 474     // The correct pc will be set when the skeleton frame is completely filled out
 475     // The final pc we store in the loop is wrong and will be overwritten below
 476     frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
 477 
 478     callee_parameters = array->element(index)->method()->size_of_parameters();
 479     callee_locals = array->element(index)->method()->max_locals();
 480     popframe_extra_args = 0;
 481   }
 482 
 483   // Compute whether the root vframe returns a float or double value.
 484   BasicType return_type;
 485   {
 486     methodHandle method(thread, array->element(0)->method());
 487     Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
 488     return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
 489   }
 490 
 491   // Compute information for handling adapters and adjusting the frame size of the caller.
 492   int caller_adjustment = 0;
 493 
 494   // Compute the amount the oldest interpreter frame will have to adjust
 495   // its caller's stack by. If the caller is a compiled frame then
 496   // we pretend that the callee has no parameters so that the
 497   // extension counts for the full amount of locals and not just
 498   // locals-parms. This is because without a c2i adapter the parm
 499   // area as created by the compiled frame will not be usable by
 500   // the interpreter. (Depending on the calling convention there
 501   // may not even be enough space).
 502 
 503   // QQQ I'd rather see this pushed down into last_frame_adjust
 504   // and have it take the sender (aka caller).
 505 
 506   if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {
 507     caller_adjustment = last_frame_adjust(0, callee_locals);
 508   } else if (callee_locals > callee_parameters) {
 509     // The caller frame may need extending to accommodate
 510     // non-parameter locals of the first unpacked interpreted frame.
 511     // Compute that adjustment.
 512     caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
 513   }
 514 
 515   // If the sender is deoptimized the we must retrieve the address of the handler
 516   // since the frame will "magically" show the original pc before the deopt
 517   // and we'd undo the deopt.
 518 
 519   frame_pcs[0] = deopt_sender.raw_pc();
 520 
 521   assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");
 522 
 523 #if INCLUDE_JVMCI
 524   if (exceptionObject() != NULL) {
 525     thread->set_exception_oop(exceptionObject());
 526     exec_mode = Unpack_exception;
 527   }
 528 #endif
 529 
 530   if (thread->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {
 531     assert(thread->has_pending_exception(), "should have thrown OOME");
 532     thread->set_exception_oop(thread->pending_exception());
 533     thread->clear_pending_exception();
 534     exec_mode = Unpack_exception;
 535   }
 536 
 537 #if INCLUDE_JVMCI
 538   if (thread->frames_to_pop_failed_realloc() > 0) {
 539     thread->set_pending_monitorenter(false);
 540   }
 541 #endif
 542 
 543   UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
 544                                       caller_adjustment * BytesPerWord,
 545                                       caller_was_method_handle ? 0 : callee_parameters,
 546                                       number_of_frames,
 547                                       frame_sizes,
 548                                       frame_pcs,
 549                                       return_type,
 550                                       exec_mode);
 551   // On some platforms, we need a way to pass some platform dependent
 552   // information to the unpacking code so the skeletal frames come out
 553   // correct (initial fp value, unextended sp, ...)
 554   info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
 555 
 556   if (array->frames() > 1) {
 557     if (VerifyStack && TraceDeoptimization) {
 558       ttyLocker ttyl;
 559       tty->print_cr("Deoptimizing method containing inlining");
 560     }
 561   }
 562 
 563   array->set_unroll_block(info);
 564   return info;
 565 }
 566 
 567 // Called to cleanup deoptimization data structures in normal case
 568 // after unpacking to stack and when stack overflow error occurs
 569 void Deoptimization::cleanup_deopt_info(JavaThread *thread,
 570                                         vframeArray *array) {
 571 
 572   // Get array if coming from exception
 573   if (array == NULL) {
 574     array = thread->vframe_array_head();
 575   }
 576   thread->set_vframe_array_head(NULL);
 577 
 578   // Free the previous UnrollBlock
 579   vframeArray* old_array = thread->vframe_array_last();
 580   thread->set_vframe_array_last(array);
 581 
 582   if (old_array != NULL) {
 583     UnrollBlock* old_info = old_array->unroll_block();
 584     old_array->set_unroll_block(NULL);
 585     delete old_info;
 586     delete old_array;
 587   }
 588 
 589   // Deallocate any resource creating in this routine and any ResourceObjs allocated
 590   // inside the vframeArray (StackValueCollections)
 591 
 592   delete thread->deopt_mark();
 593   thread->set_deopt_mark(NULL);
 594   thread->set_deopt_compiled_method(NULL);
 595 
 596 
 597   if (JvmtiExport::can_pop_frame()) {
 598 #ifndef CC_INTERP
 599     // Regardless of whether we entered this routine with the pending
 600     // popframe condition bit set, we should always clear it now
 601     thread->clear_popframe_condition();
 602 #else
 603     // C++ interpreter will clear has_pending_popframe when it enters
 604     // with method_resume. For deopt_resume2 we clear it now.
 605     if (thread->popframe_forcing_deopt_reexecution())
 606         thread->clear_popframe_condition();
 607 #endif /* CC_INTERP */
 608   }
 609 
 610   // unpack_frames() is called at the end of the deoptimization handler
 611   // and (in C2) at the end of the uncommon trap handler. Note this fact
 612   // so that an asynchronous stack walker can work again. This counter is
 613   // incremented at the beginning of fetch_unroll_info() and (in C2) at
 614   // the beginning of uncommon_trap().
 615   thread->dec_in_deopt_handler();
 616 }
 617 
 618 // Moved from cpu directories because none of the cpus has callee save values.
 619 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.
 620 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {
 621 
 622   // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in
 623   // the days we had adapter frames. When we deoptimize a situation where a
 624   // compiled caller calls a compiled caller will have registers it expects
 625   // to survive the call to the callee. If we deoptimize the callee the only
 626   // way we can restore these registers is to have the oldest interpreter
 627   // frame that we create restore these values. That is what this routine
 628   // will accomplish.
 629 
 630   // At the moment we have modified c2 to not have any callee save registers
 631   // so this problem does not exist and this routine is just a place holder.
 632 
 633   assert(f->is_interpreted_frame(), "must be interpreted");
 634 }
 635 
 636 // Return BasicType of value being returned
 637 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
 638 
 639   // We are already active in the special DeoptResourceMark any ResourceObj's we
 640   // allocate will be freed at the end of the routine.
 641 
 642   // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
 643   // but makes the entry a little slower. There is however a little dance we have to
 644   // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
 645   ResetNoHandleMark rnhm; // No-op in release/product versions
 646   HandleMark hm;
 647 
 648   frame stub_frame = thread->last_frame();
 649 
 650   // Since the frame to unpack is the top frame of this thread, the vframe_array_head
 651   // must point to the vframeArray for the unpack frame.
 652   vframeArray* array = thread->vframe_array_head();
 653 
 654 #ifndef PRODUCT
 655   if (TraceDeoptimization) {
 656     ttyLocker ttyl;
 657     tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d",
 658                   p2i(thread), p2i(array), exec_mode);
 659   }
 660 #endif
 661   Events::log_deopt_message(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
 662               p2i(stub_frame.pc()), p2i(stub_frame.sp()), exec_mode);
 663 
 664   UnrollBlock* info = array->unroll_block();
 665 
 666   // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
 667   array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
 668 
 669   BasicType bt = info->return_type();
 670 
 671   // If we have an exception pending, claim that the return type is an oop
 672   // so the deopt_blob does not overwrite the exception_oop.
 673 
 674   if (exec_mode == Unpack_exception)
 675     bt = T_OBJECT;
 676 
 677   // Cleanup thread deopt data
 678   cleanup_deopt_info(thread, array);
 679 
 680 #ifndef PRODUCT
 681   if (VerifyStack) {
 682     ResourceMark res_mark;
 683     // Clear pending exception to not break verification code (restored afterwards)
 684     PRESERVE_EXCEPTION_MARK;
 685 
 686     thread->validate_frame_layout();
 687 
 688     // Verify that the just-unpacked frames match the interpreter's
 689     // notions of expression stack and locals
 690     vframeArray* cur_array = thread->vframe_array_last();
 691     RegisterMap rm(thread, false);
 692     rm.set_include_argument_oops(false);
 693     bool is_top_frame = true;
 694     int callee_size_of_parameters = 0;
 695     int callee_max_locals = 0;
 696     for (int i = 0; i < cur_array->frames(); i++) {
 697       vframeArrayElement* el = cur_array->element(i);
 698       frame* iframe = el->iframe();
 699       guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
 700 
 701       // Get the oop map for this bci
 702       InterpreterOopMap mask;
 703       int cur_invoke_parameter_size = 0;
 704       bool try_next_mask = false;
 705       int next_mask_expression_stack_size = -1;
 706       int top_frame_expression_stack_adjustment = 0;
 707       methodHandle mh(thread, iframe->interpreter_frame_method());
 708       OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
 709       BytecodeStream str(mh, iframe->interpreter_frame_bci());
 710       int max_bci = mh->code_size();
 711       // Get to the next bytecode if possible
 712       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
 713       // Check to see if we can grab the number of outgoing arguments
 714       // at an uncommon trap for an invoke (where the compiler
 715       // generates debug info before the invoke has executed)
 716       Bytecodes::Code cur_code = str.next();
 717       if (Bytecodes::is_invoke(cur_code)) {
 718         Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
 719         cur_invoke_parameter_size = invoke.size_of_parameters();
 720         if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
 721           callee_size_of_parameters++;
 722         }
 723       }
 724       if (str.bci() < max_bci) {
 725         Bytecodes::Code next_code = str.next();
 726         if (next_code >= 0) {
 727           // The interpreter oop map generator reports results before
 728           // the current bytecode has executed except in the case of
 729           // calls. It seems to be hard to tell whether the compiler
 730           // has emitted debug information matching the "state before"
 731           // a given bytecode or the state after, so we try both
 732           if (!Bytecodes::is_invoke(cur_code) && cur_code != Bytecodes::_athrow) {
 733             // Get expression stack size for the next bytecode
 734             InterpreterOopMap next_mask;
 735             OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
 736             next_mask_expression_stack_size = next_mask.expression_stack_size();
 737             if (Bytecodes::is_invoke(next_code)) {
 738               Bytecode_invoke invoke(mh, str.bci());
 739               next_mask_expression_stack_size += invoke.size_of_parameters();
 740             }
 741             // Need to subtract off the size of the result type of
 742             // the bytecode because this is not described in the
 743             // debug info but returned to the interpreter in the TOS
 744             // caching register
 745             BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
 746             if (bytecode_result_type != T_ILLEGAL) {
 747               top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
 748             }
 749             assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive");
 750             try_next_mask = true;
 751           }
 752         }
 753       }
 754 
 755       // Verify stack depth and oops in frame
 756       // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
 757       if (!(
 758             /* SPARC */
 759             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
 760             /* x86 */
 761             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
 762             (try_next_mask &&
 763              (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
 764                                                                     top_frame_expression_stack_adjustment))) ||
 765             (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
 766             (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&
 767              (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
 768             )) {
 769         {
 770           ttyLocker ttyl;
 771 
 772           // Print out some information that will help us debug the problem
 773           tty->print_cr("Wrong number of expression stack elements during deoptimization");
 774           tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
 775           tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
 776                         iframe->interpreter_frame_expression_stack_size());
 777           tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
 778           tty->print_cr("  try_next_mask = %d", try_next_mask);
 779           tty->print_cr("  next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
 780           tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
 781           tty->print_cr("  callee_max_locals = %d", callee_max_locals);
 782           tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
 783           tty->print_cr("  exec_mode = %d", exec_mode);
 784           tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
 785           tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());
 786           tty->print_cr("  Interpreted frames:");
 787           for (int k = 0; k < cur_array->frames(); k++) {
 788             vframeArrayElement* el = cur_array->element(k);
 789             tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
 790           }
 791           cur_array->print_on_2(tty);
 792         } // release tty lock before calling guarantee
 793         guarantee(false, "wrong number of expression stack elements during deopt");
 794       }
 795       VerifyOopClosure verify;
 796       iframe->oops_interpreted_do(&verify, &rm, false);
 797       callee_size_of_parameters = mh->size_of_parameters();
 798       callee_max_locals = mh->max_locals();
 799       is_top_frame = false;
 800     }
 801   }
 802 #endif /* !PRODUCT */
 803 
 804 
 805   return bt;
 806 JRT_END
 807 
 808 class DeoptimizeMarkedClosure : public HandshakeClosure {
 809  public:
 810   DeoptimizeMarkedClosure() : HandshakeClosure("Deoptimize") {}
 811   void do_thread(Thread* thread) {
 812     JavaThread* jt = (JavaThread*)thread;
 813     jt->deoptimize_marked_methods();
 814   }
 815 };
 816 
 817 void Deoptimization::deoptimize_all_marked(nmethod* nmethod_only) {
 818   ResourceMark rm;
 819   DeoptimizationMarker dm;
 820 
 821   // Make the dependent methods not entrant
 822   if (nmethod_only != NULL) {
 823     nmethod_only->mark_for_deoptimization();
 824     nmethod_only->make_not_entrant();
 825   } else {
 826     MutexLocker mu(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, Mutex::_no_safepoint_check_flag);
 827     CodeCache::make_marked_nmethods_not_entrant();
 828   }
 829 
 830   DeoptimizeMarkedClosure deopt;
 831   if (SafepointSynchronize::is_at_safepoint()) {
 832     Threads::java_threads_do(&deopt);
 833   } else {
 834     Handshake::execute(&deopt);
 835   }
 836 }
 837 
 838 Deoptimization::DeoptAction Deoptimization::_unloaded_action
 839   = Deoptimization::Action_reinterpret;
 840 
 841 
 842 
 843 #if INCLUDE_JVMCI || INCLUDE_AOT
 844 template<typename CacheType>
 845 class BoxCacheBase : public CHeapObj<mtCompiler> {
 846 protected:
 847   static InstanceKlass* find_cache_klass(Symbol* klass_name, TRAPS) {
 848     ResourceMark rm;
 849     char* klass_name_str = klass_name->as_C_string();
 850     Klass* k = SystemDictionary::find(klass_name, Handle(), Handle(), THREAD);
 851     guarantee(k != NULL, "%s must be loaded", klass_name_str);
 852     InstanceKlass* ik = InstanceKlass::cast(k);
 853     guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str);
 854     CacheType::compute_offsets(ik);
 855     return ik;
 856   }
 857 };
 858 
 859 template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache  : public BoxCacheBase<CacheType> {
 860   PrimitiveType _low;
 861   PrimitiveType _high;
 862   jobject _cache;
 863 protected:
 864   static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton;
 865   BoxCache(Thread* thread) {
 866     InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(CacheType::symbol(), thread);
 867     objArrayOop cache = CacheType::cache(ik);
 868     assert(cache->length() > 0, "Empty cache");
 869     _low = BoxType::value(cache->obj_at(0));
 870     _high = _low + cache->length() - 1;
 871     _cache = JNIHandles::make_global(Handle(thread, cache));
 872   }
 873   ~BoxCache() {
 874     JNIHandles::destroy_global(_cache);
 875   }
 876 public:
 877   static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) {
 878     if (_singleton == NULL) {
 879       BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread);
 880       if (!Atomic::replace_if_null(&_singleton, s)) {
 881         delete s;
 882       }
 883     }
 884     return _singleton;
 885   }
 886   oop lookup(PrimitiveType value) {
 887     if (_low <= value && value <= _high) {
 888       int offset = value - _low;
 889       return objArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset);
 890     }
 891     return NULL;
 892   }
 893   oop lookup_raw(intptr_t raw_value) {
 894     // Have to cast to avoid little/big-endian problems.
 895     if (sizeof(PrimitiveType) > sizeof(jint)) {
 896       jlong value = (jlong)raw_value;
 897       return lookup(value);
 898     }
 899     PrimitiveType value = (PrimitiveType)*((jint*)&raw_value);
 900     return lookup(value);
 901   }
 902 };
 903 
 904 typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache;
 905 typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache;
 906 typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache;
 907 typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache;
 908 typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache;
 909 
 910 template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = NULL;
 911 template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = NULL;
 912 template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = NULL;
 913 template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = NULL;
 914 template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = NULL;
 915 
 916 class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> {
 917   jobject _true_cache;
 918   jobject _false_cache;
 919 protected:
 920   static BooleanBoxCache *_singleton;
 921   BooleanBoxCache(Thread *thread) {
 922     InstanceKlass* ik = find_cache_klass(java_lang_Boolean::symbol(), thread);
 923     _true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik)));
 924     _false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik)));
 925   }
 926   ~BooleanBoxCache() {
 927     JNIHandles::destroy_global(_true_cache);
 928     JNIHandles::destroy_global(_false_cache);
 929   }
 930 public:
 931   static BooleanBoxCache* singleton(Thread* thread) {
 932     if (_singleton == NULL) {
 933       BooleanBoxCache* s = new BooleanBoxCache(thread);
 934       if (!Atomic::replace_if_null(&_singleton, s)) {
 935         delete s;
 936       }
 937     }
 938     return _singleton;
 939   }
 940   oop lookup_raw(intptr_t raw_value) {
 941     // Have to cast to avoid little/big-endian problems.
 942     jboolean value = (jboolean)*((jint*)&raw_value);
 943     return lookup(value);
 944   }
 945   oop lookup(jboolean value) {
 946     if (value != 0) {
 947       return JNIHandles::resolve_non_null(_true_cache);
 948     }
 949     return JNIHandles::resolve_non_null(_false_cache);
 950   }
 951 };
 952 
 953 BooleanBoxCache* BooleanBoxCache::_singleton = NULL;
 954 
 955 oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, TRAPS) {
 956    Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()());
 957    BasicType box_type = SystemDictionary::box_klass_type(k);
 958    if (box_type != T_OBJECT) {
 959      StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0));
 960      switch(box_type) {
 961        case T_INT:     return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
 962        case T_CHAR:    return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
 963        case T_SHORT:   return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
 964        case T_BYTE:    return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
 965        case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
 966        case T_LONG:    return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_int());
 967        default:;
 968      }
 969    }
 970    return NULL;
 971 }
 972 #endif // INCLUDE_JVMCI || INCLUDE_AOT
 973 
 974 #if COMPILER2_OR_JVMCI
 975 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
 976   Handle pending_exception(THREAD, thread->pending_exception());
 977   const char* exception_file = thread->exception_file();
 978   int exception_line = thread->exception_line();
 979   thread->clear_pending_exception();
 980 
 981   bool failures = false;
 982 
 983   for (int i = 0; i < objects->length(); i++) {
 984     assert(objects->at(i)->is_object(), "invalid debug information");
 985     ObjectValue* sv = (ObjectValue*) objects->at(i);
 986 
 987     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
 988     oop obj = NULL;
 989 
 990     if (k->is_instance_klass()) {
 991 #if INCLUDE_JVMCI || INCLUDE_AOT
 992       CompiledMethod* cm = fr->cb()->as_compiled_method_or_null();
 993       if (cm->is_compiled_by_jvmci() && sv->is_auto_box()) {
 994         AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;
 995         obj = get_cached_box(abv, fr, reg_map, THREAD);
 996         if (obj != NULL) {
 997           // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.
 998           abv->set_cached(true);
 999         }
1000       }
1001 #endif // INCLUDE_JVMCI || INCLUDE_AOT
1002       InstanceKlass* ik = InstanceKlass::cast(k);
1003       if (obj == NULL) {
1004         obj = ik->allocate_instance(THREAD);
1005       }
1006     } else if (k->is_typeArray_klass()) {
1007       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1008       assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1009       int len = sv->field_size() / type2size[ak->element_type()];
1010       obj = ak->allocate(len, THREAD);
1011     } else if (k->is_objArray_klass()) {
1012       ObjArrayKlass* ak = ObjArrayKlass::cast(k);
1013       obj = ak->allocate(sv->field_size(), THREAD);
1014     }
1015 
1016     if (obj == NULL) {
1017       failures = true;
1018     }
1019 
1020     assert(sv->value().is_null(), "redundant reallocation");
1021     assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");
1022     CLEAR_PENDING_EXCEPTION;
1023     sv->set_value(obj);
1024   }
1025 
1026   if (failures) {
1027     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1028   } else if (pending_exception.not_null()) {
1029     thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1030   }
1031 
1032   return failures;
1033 }
1034 
1035 #if INCLUDE_JVMCI
1036 /**
1037  * For primitive types whose kind gets "erased" at runtime (shorts become stack ints),
1038  * we need to somehow be able to recover the actual kind to be able to write the correct
1039  * amount of bytes.
1040  * For that purpose, this method assumes that, for an entry spanning n bytes at index i,
1041  * the entries at index n + 1 to n + i are 'markers'.
1042  * For example, if we were writing a short at index 4 of a byte array of size 8, the
1043  * expected form of the array would be:
1044  *
1045  * {b0, b1, b2, b3, INT, marker, b6, b7}
1046  *
1047  * Thus, in order to get back the size of the entry, we simply need to count the number
1048  * of marked entries
1049  *
1050  * @param virtualArray the virtualized byte array
1051  * @param i index of the virtual entry we are recovering
1052  * @return The number of bytes the entry spans
1053  */
1054 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {
1055   int index = i;
1056   while (++index < virtualArray->field_size() &&
1057            virtualArray->field_at(index)->is_marker()) {}
1058   return index - i;
1059 }
1060 
1061 /**
1062  * If there was a guarantee for byte array to always start aligned to a long, we could
1063  * do a simple check on the parity of the index. Unfortunately, that is not always the
1064  * case. Thus, we check alignment of the actual address we are writing to.
1065  * In the unlikely case index 0 is 5-aligned for example, it would then be possible to
1066  * write a long to index 3.
1067  */
1068 static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) {
1069     jbyte* res = obj->byte_at_addr(index);
1070     assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write");
1071     return res;
1072 }
1073 
1074 static void byte_array_put(typeArrayOop obj, intptr_t val, int index, int byte_count) {
1075   switch (byte_count) {
1076     case 1:
1077       obj->byte_at_put(index, (jbyte) *((jint *) &val));
1078       break;
1079     case 2:
1080       *((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) *((jint *) &val);
1081       break;
1082     case 4:
1083       *((jint *) check_alignment_get_addr(obj, index, 4)) = (jint) *((jint *) &val);
1084       break;
1085     case 8: {
1086 #ifdef _LP64
1087         jlong res = (jlong) *((jlong *) &val);
1088 #else
1089 #ifdef SPARC
1090       // For SPARC we have to swap high and low words.
1091       jlong v = (jlong) *((jlong *) &val);
1092       jlong res = 0;
1093       res |= ((v & (jlong) 0xffffffff) << 32);
1094       res |= ((v >> 32) & (jlong) 0xffffffff);
1095 #else
1096       jlong res = (jlong) *((jlong *) &val);
1097 #endif // SPARC
1098 #endif
1099       *((jlong *) check_alignment_get_addr(obj, index, 8)) = res;
1100       break;
1101   }
1102     default:
1103       ShouldNotReachHere();
1104   }
1105 }
1106 #endif // INCLUDE_JVMCI
1107 
1108 
1109 // restore elements of an eliminated type array
1110 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
1111   int index = 0;
1112   intptr_t val;
1113 
1114   for (int i = 0; i < sv->field_size(); i++) {
1115     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1116     switch(type) {
1117     case T_LONG: case T_DOUBLE: {
1118       assert(value->type() == T_INT, "Agreement.");
1119       StackValue* low =
1120         StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1121 #ifdef _LP64
1122       jlong res = (jlong)low->get_int();
1123 #else
1124 #ifdef SPARC
1125       // For SPARC we have to swap high and low words.
1126       jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
1127 #else
1128       jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1129 #endif //SPARC
1130 #endif
1131       obj->long_at_put(index, res);
1132       break;
1133     }
1134 
1135     // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
1136     case T_INT: case T_FLOAT: { // 4 bytes.
1137       assert(value->type() == T_INT, "Agreement.");
1138       bool big_value = false;
1139       if (i + 1 < sv->field_size() && type == T_INT) {
1140         if (sv->field_at(i)->is_location()) {
1141           Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();
1142           if (type == Location::dbl || type == Location::lng) {
1143             big_value = true;
1144           }
1145         } else if (sv->field_at(i)->is_constant_int()) {
1146           ScopeValue* next_scope_field = sv->field_at(i + 1);
1147           if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1148             big_value = true;
1149           }
1150         }
1151       }
1152 
1153       if (big_value) {
1154         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1155   #ifdef _LP64
1156         jlong res = (jlong)low->get_int();
1157   #else
1158   #ifdef SPARC
1159         // For SPARC we have to swap high and low words.
1160         jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
1161   #else
1162         jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1163   #endif //SPARC
1164   #endif
1165         obj->int_at_put(index, (jint)*((jint*)&res));
1166         obj->int_at_put(++index, (jint)*(((jint*)&res) + 1));
1167       } else {
1168         val = value->get_int();
1169         obj->int_at_put(index, (jint)*((jint*)&val));
1170       }
1171       break;
1172     }
1173 
1174     case T_SHORT:
1175       assert(value->type() == T_INT, "Agreement.");
1176       val = value->get_int();
1177       obj->short_at_put(index, (jshort)*((jint*)&val));
1178       break;
1179 
1180     case T_CHAR:
1181       assert(value->type() == T_INT, "Agreement.");
1182       val = value->get_int();
1183       obj->char_at_put(index, (jchar)*((jint*)&val));
1184       break;
1185 
1186     case T_BYTE: {
1187       assert(value->type() == T_INT, "Agreement.");
1188       // The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'.
1189       val = value->get_int();
1190 #if INCLUDE_JVMCI
1191       int byte_count = count_number_of_bytes_for_entry(sv, i);
1192       byte_array_put(obj, val, index, byte_count);
1193       // According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip.
1194       i += byte_count - 1; // Balance the loop counter.
1195       index += byte_count;
1196       // index has been updated so continue at top of loop
1197       continue;
1198 #else
1199       obj->byte_at_put(index, (jbyte)*((jint*)&val));
1200       break;
1201 #endif // INCLUDE_JVMCI
1202     }
1203 
1204     case T_BOOLEAN: {
1205       assert(value->type() == T_INT, "Agreement.");
1206       val = value->get_int();
1207       obj->bool_at_put(index, (jboolean)*((jint*)&val));
1208       break;
1209     }
1210 
1211       default:
1212         ShouldNotReachHere();
1213     }
1214     index++;
1215   }
1216 }
1217 
1218 // restore fields of an eliminated object array
1219 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1220   for (int i = 0; i < sv->field_size(); i++) {
1221     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1222     assert(value->type() == T_OBJECT, "object element expected");
1223     obj->obj_at_put(i, value->get_obj()());
1224   }
1225 }
1226 
1227 class ReassignedField {
1228 public:
1229   int _offset;
1230   BasicType _type;
1231 public:
1232   ReassignedField() {
1233     _offset = 0;
1234     _type = T_ILLEGAL;
1235   }
1236 };
1237 
1238 int compare(ReassignedField* left, ReassignedField* right) {
1239   return left->_offset - right->_offset;
1240 }
1241 
1242 // Restore fields of an eliminated instance object using the same field order
1243 // returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true)
1244 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) {
1245   GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>();
1246   InstanceKlass* ik = klass;
1247   while (ik != NULL) {
1248     for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
1249       if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) {
1250         ReassignedField field;
1251         field._offset = fs.offset();
1252         field._type = Signature::basic_type(fs.signature());
1253         fields->append(field);
1254       }
1255     }
1256     ik = ik->superklass();
1257   }
1258   fields->sort(compare);
1259   for (int i = 0; i < fields->length(); i++) {
1260     intptr_t val;
1261     ScopeValue* scope_field = sv->field_at(svIndex);
1262     StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1263     int offset = fields->at(i)._offset;
1264     BasicType type = fields->at(i)._type;
1265     switch (type) {
1266       case T_OBJECT: case T_ARRAY:
1267         assert(value->type() == T_OBJECT, "Agreement.");
1268         obj->obj_field_put(offset, value->get_obj()());
1269         break;
1270 
1271       // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
1272       case T_INT: case T_FLOAT: { // 4 bytes.
1273         assert(value->type() == T_INT, "Agreement.");
1274         bool big_value = false;
1275         if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1276           if (scope_field->is_location()) {
1277             Location::Type type = ((LocationValue*) scope_field)->location().type();
1278             if (type == Location::dbl || type == Location::lng) {
1279               big_value = true;
1280             }
1281           }
1282           if (scope_field->is_constant_int()) {
1283             ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1284             if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1285               big_value = true;
1286             }
1287           }
1288         }
1289 
1290         if (big_value) {
1291           i++;
1292           assert(i < fields->length(), "second T_INT field needed");
1293           assert(fields->at(i)._type == T_INT, "T_INT field needed");
1294         } else {
1295           val = value->get_int();
1296           obj->int_field_put(offset, (jint)*((jint*)&val));
1297           break;
1298         }
1299       }
1300         /* no break */
1301 
1302       case T_LONG: case T_DOUBLE: {
1303         assert(value->type() == T_INT, "Agreement.");
1304         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));
1305 #ifdef _LP64
1306         jlong res = (jlong)low->get_int();
1307 #else
1308 #ifdef SPARC
1309         // For SPARC we have to swap high and low words.
1310         jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
1311 #else
1312         jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1313 #endif //SPARC
1314 #endif
1315         obj->long_field_put(offset, res);
1316         break;
1317       }
1318 
1319       case T_SHORT:
1320         assert(value->type() == T_INT, "Agreement.");
1321         val = value->get_int();
1322         obj->short_field_put(offset, (jshort)*((jint*)&val));
1323         break;
1324 
1325       case T_CHAR:
1326         assert(value->type() == T_INT, "Agreement.");
1327         val = value->get_int();
1328         obj->char_field_put(offset, (jchar)*((jint*)&val));
1329         break;
1330 
1331       case T_BYTE:
1332         assert(value->type() == T_INT, "Agreement.");
1333         val = value->get_int();
1334         obj->byte_field_put(offset, (jbyte)*((jint*)&val));
1335         break;
1336 
1337       case T_BOOLEAN:
1338         assert(value->type() == T_INT, "Agreement.");
1339         val = value->get_int();
1340         obj->bool_field_put(offset, (jboolean)*((jint*)&val));
1341         break;
1342 
1343       default:
1344         ShouldNotReachHere();
1345     }
1346     svIndex++;
1347   }
1348   return svIndex;
1349 }
1350 
1351 // restore fields of all eliminated objects and arrays
1352 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) {
1353   for (int i = 0; i < objects->length(); i++) {
1354     ObjectValue* sv = (ObjectValue*) objects->at(i);
1355     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1356     Handle obj = sv->value();
1357     assert(obj.not_null() || realloc_failures, "reallocation was missed");
1358     if (PrintDeoptimizationDetails) {
1359       tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1360     }
1361     if (obj.is_null()) {
1362       continue;
1363     }
1364 #if INCLUDE_JVMCI || INCLUDE_AOT
1365     // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1366     if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1367       continue;
1368     }
1369 #endif // INCLUDE_JVMCI || INCLUDE_AOT
1370     if (k->is_instance_klass()) {
1371       InstanceKlass* ik = InstanceKlass::cast(k);
1372       reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal);
1373     } else if (k->is_typeArray_klass()) {
1374       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1375       reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1376     } else if (k->is_objArray_klass()) {
1377       reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1378     }
1379   }
1380 }
1381 
1382 
1383 // relock objects for which synchronization was eliminated
1384 void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread, bool realloc_failures) {
1385   for (int i = 0; i < monitors->length(); i++) {
1386     MonitorInfo* mon_info = monitors->at(i);
1387     if (mon_info->eliminated()) {
1388       assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1389       if (!mon_info->owner_is_scalar_replaced()) {
1390         Handle obj(thread, mon_info->owner());
1391         markWord mark = obj->mark();
1392         if (UseBiasedLocking && mark.has_bias_pattern()) {
1393           // New allocated objects may have the mark set to anonymously biased.
1394           // Also the deoptimized method may called methods with synchronization
1395           // where the thread-local object is bias locked to the current thread.
1396           assert(mark.is_biased_anonymously() ||
1397                  mark.biased_locker() == thread, "should be locked to current thread");
1398           // Reset mark word to unbiased prototype.
1399           markWord unbiased_prototype = markWord::prototype().set_age(mark.age());
1400           obj->set_mark(unbiased_prototype);
1401         }
1402         BasicLock* lock = mon_info->lock();
1403         ObjectSynchronizer::enter(obj, lock, thread);
1404         assert(mon_info->owner()->is_locked(), "object must be locked now");
1405       }
1406     }
1407   }
1408 }
1409 
1410 
1411 #ifndef PRODUCT
1412 // print information about reallocated objects
1413 void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
1414   fieldDescriptor fd;
1415 
1416   for (int i = 0; i < objects->length(); i++) {
1417     ObjectValue* sv = (ObjectValue*) objects->at(i);
1418     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1419     Handle obj = sv->value();
1420 
1421     tty->print("     object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
1422     k->print_value();
1423     assert(obj.not_null() || realloc_failures, "reallocation was missed");
1424     if (obj.is_null()) {
1425       tty->print(" allocation failed");
1426     } else {
1427       tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);
1428     }
1429     tty->cr();
1430 
1431     if (Verbose && !obj.is_null()) {
1432       k->oop_print_on(obj(), tty);
1433     }
1434   }
1435 }
1436 #endif
1437 #endif // COMPILER2_OR_JVMCI
1438 
1439 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
1440   Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));
1441 
1442 #ifndef PRODUCT
1443   if (PrintDeoptimizationDetails) {
1444     ttyLocker ttyl;
1445     tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", p2i(thread));
1446     fr.print_on(tty);
1447     tty->print_cr("     Virtual frames (innermost first):");
1448     for (int index = 0; index < chunk->length(); index++) {
1449       compiledVFrame* vf = chunk->at(index);
1450       tty->print("       %2d - ", index);
1451       vf->print_value();
1452       int bci = chunk->at(index)->raw_bci();
1453       const char* code_name;
1454       if (bci == SynchronizationEntryBCI) {
1455         code_name = "sync entry";
1456       } else {
1457         Bytecodes::Code code = vf->method()->code_at(bci);
1458         code_name = Bytecodes::name(code);
1459       }
1460       tty->print(" - %s", code_name);
1461       tty->print_cr(" @ bci %d ", bci);
1462       if (Verbose) {
1463         vf->print();
1464         tty->cr();
1465       }
1466     }
1467   }
1468 #endif
1469 
1470   // Register map for next frame (used for stack crawl).  We capture
1471   // the state of the deopt'ing frame's caller.  Thus if we need to
1472   // stuff a C2I adapter we can properly fill in the callee-save
1473   // register locations.
1474   frame caller = fr.sender(reg_map);
1475   int frame_size = caller.sp() - fr.sp();
1476 
1477   frame sender = caller;
1478 
1479   // Since the Java thread being deoptimized will eventually adjust it's own stack,
1480   // the vframeArray containing the unpacking information is allocated in the C heap.
1481   // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1482   vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
1483 
1484   // Compare the vframeArray to the collected vframes
1485   assert(array->structural_compare(thread, chunk), "just checking");
1486 
1487 #ifndef PRODUCT
1488   if (PrintDeoptimizationDetails) {
1489     ttyLocker ttyl;
1490     tty->print_cr("     Created vframeArray " INTPTR_FORMAT, p2i(array));
1491   }
1492 #endif // PRODUCT
1493 
1494   return array;
1495 }
1496 
1497 #if COMPILER2_OR_JVMCI
1498 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
1499   // Reallocation of some scalar replaced objects failed. Record
1500   // that we need to pop all the interpreter frames for the
1501   // deoptimized compiled frame.
1502   assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
1503   thread->set_frames_to_pop_failed_realloc(array->frames());
1504   // Unlock all monitors here otherwise the interpreter will see a
1505   // mix of locked and unlocked monitors (because of failed
1506   // reallocations of synchronized objects) and be confused.
1507   for (int i = 0; i < array->frames(); i++) {
1508     MonitorChunk* monitors = array->element(i)->monitors();
1509     if (monitors != NULL) {
1510       for (int j = 0; j < monitors->number_of_monitors(); j++) {
1511         BasicObjectLock* src = monitors->at(j);
1512         if (src->obj() != NULL) {
1513           ObjectSynchronizer::exit(src->obj(), src->lock(), thread);
1514         }
1515       }
1516       array->element(i)->free_monitors(thread);
1517 #ifdef ASSERT
1518       array->element(i)->set_removed_monitors();
1519 #endif
1520     }
1521   }
1522 }
1523 #endif
1524 
1525 static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke) {
1526   GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1527   Thread* thread = Thread::current();
1528   for (int i = 0; i < monitors->length(); i++) {
1529     MonitorInfo* mon_info = monitors->at(i);
1530     if (!mon_info->eliminated() && mon_info->owner() != NULL) {
1531       objects_to_revoke->append(Handle(thread, mon_info->owner()));
1532     }
1533   }
1534 }
1535 
1536 static void get_monitors_from_stack(GrowableArray<Handle>* objects_to_revoke, JavaThread* thread, frame fr, RegisterMap* map) {
1537   // Unfortunately we don't have a RegisterMap available in most of
1538   // the places we want to call this routine so we need to walk the
1539   // stack again to update the register map.
1540   if (map == NULL || !map->update_map()) {
1541     StackFrameStream sfs(thread, true);
1542     bool found = false;
1543     while (!found && !sfs.is_done()) {
1544       frame* cur = sfs.current();
1545       sfs.next();
1546       found = cur->id() == fr.id();
1547     }
1548     assert(found, "frame to be deoptimized not found on target thread's stack");
1549     map = sfs.register_map();
1550   }
1551 
1552   vframe* vf = vframe::new_vframe(&fr, map, thread);
1553   compiledVFrame* cvf = compiledVFrame::cast(vf);
1554   // Revoke monitors' biases in all scopes
1555   while (!cvf->is_top()) {
1556     collect_monitors(cvf, objects_to_revoke);
1557     cvf = compiledVFrame::cast(cvf->sender());
1558   }
1559   collect_monitors(cvf, objects_to_revoke);
1560 }
1561 
1562 void Deoptimization::revoke_from_deopt_handler(JavaThread* thread, frame fr, RegisterMap* map) {
1563   if (!UseBiasedLocking) {
1564     return;
1565   }
1566   GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1567   get_monitors_from_stack(objects_to_revoke, thread, fr, map);
1568 
1569   int len = objects_to_revoke->length();
1570   for (int i = 0; i < len; i++) {
1571     oop obj = (objects_to_revoke->at(i))();
1572     BiasedLocking::revoke_own_lock(objects_to_revoke->at(i), thread);
1573     assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");
1574   }
1575 }
1576 
1577 
1578 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
1579   assert(fr.can_be_deoptimized(), "checking frame type");
1580 
1581   gather_statistics(reason, Action_none, Bytecodes::_illegal);
1582 
1583   if (LogCompilation && xtty != NULL) {
1584     CompiledMethod* cm = fr.cb()->as_compiled_method_or_null();
1585     assert(cm != NULL, "only compiled methods can deopt");
1586 
1587     ttyLocker ttyl;
1588     xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1589     cm->log_identity(xtty);
1590     xtty->end_head();
1591     for (ScopeDesc* sd = cm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1592       xtty->begin_elem("jvms bci='%d'", sd->bci());
1593       xtty->method(sd->method());
1594       xtty->end_elem();
1595       if (sd->is_top())  break;
1596     }
1597     xtty->tail("deoptimized");
1598   }
1599 
1600   // Patch the compiled method so that when execution returns to it we will
1601   // deopt the execution state and return to the interpreter.
1602   fr.deoptimize(thread);
1603 }
1604 
1605 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1606   // Deoptimize only if the frame comes from compile code.
1607   // Do not deoptimize the frame which is already patched
1608   // during the execution of the loops below.
1609   if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1610     return;
1611   }
1612   ResourceMark rm;
1613   DeoptimizationMarker dm;
1614   deoptimize_single_frame(thread, fr, reason);
1615 }
1616 
1617 #if INCLUDE_JVMCI
1618 address Deoptimization::deoptimize_for_missing_exception_handler(CompiledMethod* cm) {
1619   // there is no exception handler for this pc => deoptimize
1620   cm->make_not_entrant();
1621 
1622   // Use Deoptimization::deoptimize for all of its side-effects:
1623   // gathering traps statistics, logging...
1624   // it also patches the return pc but we do not care about that
1625   // since we return a continuation to the deopt_blob below.
1626   JavaThread* thread = JavaThread::current();
1627   RegisterMap reg_map(thread, false);
1628   frame runtime_frame = thread->last_frame();
1629   frame caller_frame = runtime_frame.sender(&reg_map);
1630   assert(caller_frame.cb()->as_compiled_method_or_null() == cm, "expect top frame compiled method");
1631   Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler);
1632 
1633   MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, cm->method()), true);
1634   if (trap_mdo != NULL) {
1635     trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler);
1636   }
1637 
1638   return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
1639 }
1640 #endif
1641 
1642 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1643   assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
1644          "can only deoptimize other thread at a safepoint");
1645   // Compute frame and register map based on thread and sp.
1646   RegisterMap reg_map(thread, false);
1647   frame fr = thread->last_frame();
1648   while (fr.id() != id) {
1649     fr = fr.sender(&reg_map);
1650   }
1651   deoptimize(thread, fr, reason);
1652 }
1653 
1654 
1655 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1656   if (thread == Thread::current()) {
1657     Deoptimization::deoptimize_frame_internal(thread, id, reason);
1658   } else {
1659     VM_DeoptimizeFrame deopt(thread, id, reason);
1660     VMThread::execute(&deopt);
1661   }
1662 }
1663 
1664 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
1665   deoptimize_frame(thread, id, Reason_constraint);
1666 }
1667 
1668 // JVMTI PopFrame support
1669 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
1670 {
1671   thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
1672 }
1673 JRT_END
1674 
1675 MethodData*
1676 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m,
1677                                 bool create_if_missing) {
1678   Thread* THREAD = thread;
1679   MethodData* mdo = m()->method_data();
1680   if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {
1681     // Build an MDO.  Ignore errors like OutOfMemory;
1682     // that simply means we won't have an MDO to update.
1683     Method::build_interpreter_method_data(m, THREAD);
1684     if (HAS_PENDING_EXCEPTION) {
1685       assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1686       CLEAR_PENDING_EXCEPTION;
1687     }
1688     mdo = m()->method_data();
1689   }
1690   return mdo;
1691 }
1692 
1693 #if COMPILER2_OR_JVMCI
1694 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {
1695   // In case of an unresolved klass entry, load the class.
1696   // This path is exercised from case _ldc in Parse::do_one_bytecode,
1697   // and probably nowhere else.
1698   // Even that case would benefit from simply re-interpreting the
1699   // bytecode, without paying special attention to the class index.
1700   // So this whole "class index" feature should probably be removed.
1701 
1702   if (constant_pool->tag_at(index).is_unresolved_klass()) {
1703     Klass* tk = constant_pool->klass_at_ignore_error(index, CHECK);
1704     return;
1705   }
1706 
1707   assert(!constant_pool->tag_at(index).is_symbol(),
1708          "no symbolic names here, please");
1709 }
1710 
1711 
1712 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index) {
1713   EXCEPTION_MARK;
1714   load_class_by_index(constant_pool, index, THREAD);
1715   if (HAS_PENDING_EXCEPTION) {
1716     // Exception happened during classloading. We ignore the exception here, since it
1717     // is going to be rethrown since the current activation is going to be deoptimized and
1718     // the interpreter will re-execute the bytecode.
1719     CLEAR_PENDING_EXCEPTION;
1720     // Class loading called java code which may have caused a stack
1721     // overflow. If the exception was thrown right before the return
1722     // to the runtime the stack is no longer guarded. Reguard the
1723     // stack otherwise if we return to the uncommon trap blob and the
1724     // stack bang causes a stack overflow we crash.
1725     assert(THREAD->is_Java_thread(), "only a java thread can be here");
1726     JavaThread* thread = (JavaThread*)THREAD;
1727     bool guard_pages_enabled = thread->stack_guards_enabled();
1728     if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
1729     assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
1730   }
1731 }
1732 
1733 #if INCLUDE_JFR
1734 
1735 class DeoptReasonSerializer : public JfrSerializer {
1736  public:
1737   void serialize(JfrCheckpointWriter& writer) {
1738     writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1)
1739     for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) {
1740       writer.write_key((u8)i);
1741       writer.write(Deoptimization::trap_reason_name(i));
1742     }
1743   }
1744 };
1745 
1746 class DeoptActionSerializer : public JfrSerializer {
1747  public:
1748   void serialize(JfrCheckpointWriter& writer) {
1749     static const u4 nof_actions = Deoptimization::Action_LIMIT;
1750     writer.write_count(nof_actions);
1751     for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) {
1752       writer.write_key(i);
1753       writer.write(Deoptimization::trap_action_name((int)i));
1754     }
1755   }
1756 };
1757 
1758 static void register_serializers() {
1759   static int critical_section = 0;
1760   if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) {
1761     return;
1762   }
1763   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer());
1764   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer());
1765 }
1766 
1767 static void post_deoptimization_event(CompiledMethod* nm,
1768                                       const Method* method,
1769                                       int trap_bci,
1770                                       int instruction,
1771                                       Deoptimization::DeoptReason reason,
1772                                       Deoptimization::DeoptAction action) {
1773   assert(nm != NULL, "invariant");
1774   assert(method != NULL, "invariant");
1775   if (EventDeoptimization::is_enabled()) {
1776     static bool serializers_registered = false;
1777     if (!serializers_registered) {
1778       register_serializers();
1779       serializers_registered = true;
1780     }
1781     EventDeoptimization event;
1782     event.set_compileId(nm->compile_id());
1783     event.set_compiler(nm->compiler_type());
1784     event.set_method(method);
1785     event.set_lineNumber(method->line_number_from_bci(trap_bci));
1786     event.set_bci(trap_bci);
1787     event.set_instruction(instruction);
1788     event.set_reason(reason);
1789     event.set_action(action);
1790     event.commit();
1791   }
1792 }
1793 
1794 #endif // INCLUDE_JFR
1795 
1796 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) {
1797   HandleMark hm;
1798 
1799   // uncommon_trap() is called at the beginning of the uncommon trap
1800   // handler. Note this fact before we start generating temporary frames
1801   // that can confuse an asynchronous stack walker. This counter is
1802   // decremented at the end of unpack_frames().
1803   thread->inc_in_deopt_handler();
1804 
1805   // We need to update the map if we have biased locking.
1806 #if INCLUDE_JVMCI
1807   // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid
1808   RegisterMap reg_map(thread, true);
1809 #else
1810   RegisterMap reg_map(thread, UseBiasedLocking);
1811 #endif
1812   frame stub_frame = thread->last_frame();
1813   frame fr = stub_frame.sender(&reg_map);
1814   // Make sure the calling nmethod is not getting deoptimized and removed
1815   // before we are done with it.
1816   nmethodLocker nl(fr.pc());
1817 
1818   // Log a message
1819   Events::log_deopt_message(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,
1820               trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());
1821 
1822   {
1823     ResourceMark rm;
1824 
1825     DeoptReason reason = trap_request_reason(trap_request);
1826     DeoptAction action = trap_request_action(trap_request);
1827 #if INCLUDE_JVMCI
1828     int debug_id = trap_request_debug_id(trap_request);
1829 #endif
1830     jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
1831 
1832     vframe*  vf  = vframe::new_vframe(&fr, &reg_map, thread);
1833     compiledVFrame* cvf = compiledVFrame::cast(vf);
1834 
1835     CompiledMethod* nm = cvf->code();
1836 
1837     ScopeDesc*      trap_scope  = cvf->scope();
1838 
1839     if (TraceDeoptimization) {
1840       ttyLocker ttyl;
1841       tty->print_cr("  bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT ", method=%s" JVMCI_ONLY(", debug_id=%d"), trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin(), trap_scope->method()->name_and_sig_as_C_string()
1842 #if INCLUDE_JVMCI
1843           , debug_id
1844 #endif
1845           );
1846     }
1847 
1848     methodHandle    trap_method(THREAD, trap_scope->method());
1849     int             trap_bci    = trap_scope->bci();
1850 #if INCLUDE_JVMCI
1851     jlong           speculation = thread->pending_failed_speculation();
1852     if (nm->is_compiled_by_jvmci() && nm->is_nmethod()) { // Exclude AOTed methods
1853       nm->as_nmethod()->update_speculation(thread);
1854     } else {
1855       assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");
1856     }
1857 
1858     if (trap_bci == SynchronizationEntryBCI) {
1859       trap_bci = 0;
1860       thread->set_pending_monitorenter(true);
1861     }
1862 
1863     if (reason == Deoptimization::Reason_transfer_to_interpreter) {
1864       thread->set_pending_transfer_to_interpreter(true);
1865     }
1866 #endif
1867 
1868     Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
1869     // Record this event in the histogram.
1870     gather_statistics(reason, action, trap_bc);
1871 
1872     // Ensure that we can record deopt. history:
1873     // Need MDO to record RTM code generation state.
1874     bool create_if_missing = ProfileTraps || UseCodeAging RTM_OPT_ONLY( || UseRTMLocking );
1875 
1876     methodHandle profiled_method;
1877 #if INCLUDE_JVMCI
1878     if (nm->is_compiled_by_jvmci()) {
1879       profiled_method = methodHandle(THREAD, nm->method());
1880     } else {
1881       profiled_method = trap_method;
1882     }
1883 #else
1884     profiled_method = trap_method;
1885 #endif
1886 
1887     MethodData* trap_mdo =
1888       get_method_data(thread, profiled_method, create_if_missing);
1889 
1890     JFR_ONLY(post_deoptimization_event(nm, trap_method(), trap_bci, trap_bc, reason, action);)
1891 
1892     // Log a message
1893     Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s",
1894                               trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()),
1895                               trap_method->name_and_sig_as_C_string(), trap_bci, nm->compiler_name());
1896 
1897     // Print a bunch of diagnostics, if requested.
1898     if (TraceDeoptimization || LogCompilation) {
1899       ResourceMark rm;
1900       ttyLocker ttyl;
1901       char buf[100];
1902       if (xtty != NULL) {
1903         xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",
1904                          os::current_thread_id(),
1905                          format_trap_request(buf, sizeof(buf), trap_request));
1906 #if INCLUDE_JVMCI
1907         if (speculation != 0) {
1908           xtty->print(" speculation='" JLONG_FORMAT "'", speculation);
1909         }
1910 #endif
1911         nm->log_identity(xtty);
1912       }
1913       Symbol* class_name = NULL;
1914       bool unresolved = false;
1915       if (unloaded_class_index >= 0) {
1916         constantPoolHandle constants (THREAD, trap_method->constants());
1917         if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
1918           class_name = constants->klass_name_at(unloaded_class_index);
1919           unresolved = true;
1920           if (xtty != NULL)
1921             xtty->print(" unresolved='1'");
1922         } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
1923           class_name = constants->symbol_at(unloaded_class_index);
1924         }
1925         if (xtty != NULL)
1926           xtty->name(class_name);
1927       }
1928       if (xtty != NULL && trap_mdo != NULL && (int)reason < (int)MethodData::_trap_hist_limit) {
1929         // Dump the relevant MDO state.
1930         // This is the deopt count for the current reason, any previous
1931         // reasons or recompiles seen at this point.
1932         int dcnt = trap_mdo->trap_count(reason);
1933         if (dcnt != 0)
1934           xtty->print(" count='%d'", dcnt);
1935         ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
1936         int dos = (pdata == NULL)? 0: pdata->trap_state();
1937         if (dos != 0) {
1938           xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
1939           if (trap_state_is_recompiled(dos)) {
1940             int recnt2 = trap_mdo->overflow_recompile_count();
1941             if (recnt2 != 0)
1942               xtty->print(" recompiles2='%d'", recnt2);
1943           }
1944         }
1945       }
1946       if (xtty != NULL) {
1947         xtty->stamp();
1948         xtty->end_head();
1949       }
1950       if (TraceDeoptimization) {  // make noise on the tty
1951         tty->print("Uncommon trap occurred in");
1952         nm->method()->print_short_name(tty);
1953         tty->print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id());
1954 #if INCLUDE_JVMCI
1955         if (nm->is_nmethod()) {
1956           const char* installed_code_name = nm->as_nmethod()->jvmci_name();
1957           if (installed_code_name != NULL) {
1958             tty->print(" (JVMCI: installed code name=%s) ", installed_code_name);
1959           }
1960         }
1961 #endif
1962         tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"),
1963                    p2i(fr.pc()),
1964                    os::current_thread_id(),
1965                    trap_reason_name(reason),
1966                    trap_action_name(action),
1967                    unloaded_class_index
1968 #if INCLUDE_JVMCI
1969                    , debug_id
1970 #endif
1971                    );
1972         if (class_name != NULL) {
1973           tty->print(unresolved ? " unresolved class: " : " symbol: ");
1974           class_name->print_symbol_on(tty);
1975         }
1976         tty->cr();
1977       }
1978       if (xtty != NULL) {
1979         // Log the precise location of the trap.
1980         for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
1981           xtty->begin_elem("jvms bci='%d'", sd->bci());
1982           xtty->method(sd->method());
1983           xtty->end_elem();
1984           if (sd->is_top())  break;
1985         }
1986         xtty->tail("uncommon_trap");
1987       }
1988     }
1989     // (End diagnostic printout.)
1990 
1991     // Load class if necessary
1992     if (unloaded_class_index >= 0) {
1993       constantPoolHandle constants(THREAD, trap_method->constants());
1994       load_class_by_index(constants, unloaded_class_index);
1995     }
1996 
1997     // Flush the nmethod if necessary and desirable.
1998     //
1999     // We need to avoid situations where we are re-flushing the nmethod
2000     // because of a hot deoptimization site.  Repeated flushes at the same
2001     // point need to be detected by the compiler and avoided.  If the compiler
2002     // cannot avoid them (or has a bug and "refuses" to avoid them), this
2003     // module must take measures to avoid an infinite cycle of recompilation
2004     // and deoptimization.  There are several such measures:
2005     //
2006     //   1. If a recompilation is ordered a second time at some site X
2007     //   and for the same reason R, the action is adjusted to 'reinterpret',
2008     //   to give the interpreter time to exercise the method more thoroughly.
2009     //   If this happens, the method's overflow_recompile_count is incremented.
2010     //
2011     //   2. If the compiler fails to reduce the deoptimization rate, then
2012     //   the method's overflow_recompile_count will begin to exceed the set
2013     //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
2014     //   is adjusted to 'make_not_compilable', and the method is abandoned
2015     //   to the interpreter.  This is a performance hit for hot methods,
2016     //   but is better than a disastrous infinite cycle of recompilations.
2017     //   (Actually, only the method containing the site X is abandoned.)
2018     //
2019     //   3. In parallel with the previous measures, if the total number of
2020     //   recompilations of a method exceeds the much larger set limit
2021     //   PerMethodRecompilationCutoff, the method is abandoned.
2022     //   This should only happen if the method is very large and has
2023     //   many "lukewarm" deoptimizations.  The code which enforces this
2024     //   limit is elsewhere (class nmethod, class Method).
2025     //
2026     // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
2027     // to recompile at each bytecode independently of the per-BCI cutoff.
2028     //
2029     // The decision to update code is up to the compiler, and is encoded
2030     // in the Action_xxx code.  If the compiler requests Action_none
2031     // no trap state is changed, no compiled code is changed, and the
2032     // computation suffers along in the interpreter.
2033     //
2034     // The other action codes specify various tactics for decompilation
2035     // and recompilation.  Action_maybe_recompile is the loosest, and
2036     // allows the compiled code to stay around until enough traps are seen,
2037     // and until the compiler gets around to recompiling the trapping method.
2038     //
2039     // The other actions cause immediate removal of the present code.
2040 
2041     // Traps caused by injected profile shouldn't pollute trap counts.
2042     bool injected_profile_trap = trap_method->has_injected_profile() &&
2043                                  (reason == Reason_intrinsic || reason == Reason_unreached);
2044 
2045     bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;
2046     bool make_not_entrant = false;
2047     bool make_not_compilable = false;
2048     bool reprofile = false;
2049     switch (action) {
2050     case Action_none:
2051       // Keep the old code.
2052       update_trap_state = false;
2053       break;
2054     case Action_maybe_recompile:
2055       // Do not need to invalidate the present code, but we can
2056       // initiate another
2057       // Start compiler without (necessarily) invalidating the nmethod.
2058       // The system will tolerate the old code, but new code should be
2059       // generated when possible.
2060       break;
2061     case Action_reinterpret:
2062       // Go back into the interpreter for a while, and then consider
2063       // recompiling form scratch.
2064       make_not_entrant = true;
2065       // Reset invocation counter for outer most method.
2066       // This will allow the interpreter to exercise the bytecodes
2067       // for a while before recompiling.
2068       // By contrast, Action_make_not_entrant is immediate.
2069       //
2070       // Note that the compiler will track null_check, null_assert,
2071       // range_check, and class_check events and log them as if they
2072       // had been traps taken from compiled code.  This will update
2073       // the MDO trap history so that the next compilation will
2074       // properly detect hot trap sites.
2075       reprofile = true;
2076       break;
2077     case Action_make_not_entrant:
2078       // Request immediate recompilation, and get rid of the old code.
2079       // Make them not entrant, so next time they are called they get
2080       // recompiled.  Unloaded classes are loaded now so recompile before next
2081       // time they are called.  Same for uninitialized.  The interpreter will
2082       // link the missing class, if any.
2083       make_not_entrant = true;
2084       break;
2085     case Action_make_not_compilable:
2086       // Give up on compiling this method at all.
2087       make_not_entrant = true;
2088       make_not_compilable = true;
2089       break;
2090     default:
2091       ShouldNotReachHere();
2092     }
2093 
2094     // Setting +ProfileTraps fixes the following, on all platforms:
2095     // 4852688: ProfileInterpreter is off by default for ia64.  The result is
2096     // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
2097     // recompile relies on a MethodData* to record heroic opt failures.
2098 
2099     // Whether the interpreter is producing MDO data or not, we also need
2100     // to use the MDO to detect hot deoptimization points and control
2101     // aggressive optimization.
2102     bool inc_recompile_count = false;
2103     ProfileData* pdata = NULL;
2104     if (ProfileTraps && !is_client_compilation_mode_vm() && update_trap_state && trap_mdo != NULL) {
2105       assert(trap_mdo == get_method_data(thread, profiled_method, false), "sanity");
2106       uint this_trap_count = 0;
2107       bool maybe_prior_trap = false;
2108       bool maybe_prior_recompile = false;
2109       pdata = query_update_method_data(trap_mdo, trap_bci, reason, true,
2110 #if INCLUDE_JVMCI
2111                                    nm->is_compiled_by_jvmci() && nm->is_osr_method(),
2112 #endif
2113                                    nm->method(),
2114                                    //outputs:
2115                                    this_trap_count,
2116                                    maybe_prior_trap,
2117                                    maybe_prior_recompile);
2118       // Because the interpreter also counts null, div0, range, and class
2119       // checks, these traps from compiled code are double-counted.
2120       // This is harmless; it just means that the PerXTrapLimit values
2121       // are in effect a little smaller than they look.
2122 
2123       DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2124       if (per_bc_reason != Reason_none) {
2125         // Now take action based on the partially known per-BCI history.
2126         if (maybe_prior_trap
2127             && this_trap_count >= (uint)PerBytecodeTrapLimit) {
2128           // If there are too many traps at this BCI, force a recompile.
2129           // This will allow the compiler to see the limit overflow, and
2130           // take corrective action, if possible.  The compiler generally
2131           // does not use the exact PerBytecodeTrapLimit value, but instead
2132           // changes its tactics if it sees any traps at all.  This provides
2133           // a little hysteresis, delaying a recompile until a trap happens
2134           // several times.
2135           //
2136           // Actually, since there is only one bit of counter per BCI,
2137           // the possible per-BCI counts are {0,1,(per-method count)}.
2138           // This produces accurate results if in fact there is only
2139           // one hot trap site, but begins to get fuzzy if there are
2140           // many sites.  For example, if there are ten sites each
2141           // trapping two or more times, they each get the blame for
2142           // all of their traps.
2143           make_not_entrant = true;
2144         }
2145 
2146         // Detect repeated recompilation at the same BCI, and enforce a limit.
2147         if (make_not_entrant && maybe_prior_recompile) {
2148           // More than one recompile at this point.
2149           inc_recompile_count = maybe_prior_trap;
2150         }
2151       } else {
2152         // For reasons which are not recorded per-bytecode, we simply
2153         // force recompiles unconditionally.
2154         // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
2155         make_not_entrant = true;
2156       }
2157 
2158       // Go back to the compiler if there are too many traps in this method.
2159       if (this_trap_count >= per_method_trap_limit(reason)) {
2160         // If there are too many traps in this method, force a recompile.
2161         // This will allow the compiler to see the limit overflow, and
2162         // take corrective action, if possible.
2163         // (This condition is an unlikely backstop only, because the
2164         // PerBytecodeTrapLimit is more likely to take effect first,
2165         // if it is applicable.)
2166         make_not_entrant = true;
2167       }
2168 
2169       // Here's more hysteresis:  If there has been a recompile at
2170       // this trap point already, run the method in the interpreter
2171       // for a while to exercise it more thoroughly.
2172       if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
2173         reprofile = true;
2174       }
2175     }
2176 
2177     // Take requested actions on the method:
2178 
2179     // Recompile
2180     if (make_not_entrant) {
2181       if (!nm->make_not_entrant()) {
2182         return; // the call did not change nmethod's state
2183       }
2184 
2185       if (pdata != NULL) {
2186         // Record the recompilation event, if any.
2187         int tstate0 = pdata->trap_state();
2188         int tstate1 = trap_state_set_recompiled(tstate0, true);
2189         if (tstate1 != tstate0)
2190           pdata->set_trap_state(tstate1);
2191       }
2192 
2193 #if INCLUDE_RTM_OPT
2194       // Restart collecting RTM locking abort statistic if the method
2195       // is recompiled for a reason other than RTM state change.
2196       // Assume that in new recompiled code the statistic could be different,
2197       // for example, due to different inlining.
2198       if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&
2199           UseRTMDeopt && (nm->as_nmethod()->rtm_state() != ProfileRTM)) {
2200         trap_mdo->atomic_set_rtm_state(ProfileRTM);
2201       }
2202 #endif
2203       // For code aging we count traps separately here, using make_not_entrant()
2204       // as a guard against simultaneous deopts in multiple threads.
2205       if (reason == Reason_tenured && trap_mdo != NULL) {
2206         trap_mdo->inc_tenure_traps();
2207       }
2208     }
2209 
2210     if (inc_recompile_count) {
2211       trap_mdo->inc_overflow_recompile_count();
2212       if ((uint)trap_mdo->overflow_recompile_count() >
2213           (uint)PerBytecodeRecompilationCutoff) {
2214         // Give up on the method containing the bad BCI.
2215         if (trap_method() == nm->method()) {
2216           make_not_compilable = true;
2217         } else {
2218           trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization);
2219           // But give grace to the enclosing nm->method().
2220         }
2221       }
2222     }
2223 
2224     // Reprofile
2225     if (reprofile) {
2226       CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method());
2227     }
2228 
2229     // Give up compiling
2230     if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
2231       assert(make_not_entrant, "consistent");
2232       nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization);
2233     }
2234 
2235   } // Free marked resources
2236 
2237 }
2238 JRT_END
2239 
2240 ProfileData*
2241 Deoptimization::query_update_method_data(MethodData* trap_mdo,
2242                                          int trap_bci,
2243                                          Deoptimization::DeoptReason reason,
2244                                          bool update_total_trap_count,
2245 #if INCLUDE_JVMCI
2246                                          bool is_osr,
2247 #endif
2248                                          Method* compiled_method,
2249                                          //outputs:
2250                                          uint& ret_this_trap_count,
2251                                          bool& ret_maybe_prior_trap,
2252                                          bool& ret_maybe_prior_recompile) {
2253   bool maybe_prior_trap = false;
2254   bool maybe_prior_recompile = false;
2255   uint this_trap_count = 0;
2256   if (update_total_trap_count) {
2257     uint idx = reason;
2258 #if INCLUDE_JVMCI
2259     if (is_osr) {
2260       idx += Reason_LIMIT;
2261     }
2262 #endif
2263     uint prior_trap_count = trap_mdo->trap_count(idx);
2264     this_trap_count  = trap_mdo->inc_trap_count(idx);
2265 
2266     // If the runtime cannot find a place to store trap history,
2267     // it is estimated based on the general condition of the method.
2268     // If the method has ever been recompiled, or has ever incurred
2269     // a trap with the present reason , then this BCI is assumed
2270     // (pessimistically) to be the culprit.
2271     maybe_prior_trap      = (prior_trap_count != 0);
2272     maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
2273   }
2274   ProfileData* pdata = NULL;
2275 
2276 
2277   // For reasons which are recorded per bytecode, we check per-BCI data.
2278   DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2279   assert(per_bc_reason != Reason_none || update_total_trap_count, "must be");
2280   if (per_bc_reason != Reason_none) {
2281     // Find the profile data for this BCI.  If there isn't one,
2282     // try to allocate one from the MDO's set of spares.
2283     // This will let us detect a repeated trap at this point.
2284     pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);
2285 
2286     if (pdata != NULL) {
2287       if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
2288         if (LogCompilation && xtty != NULL) {
2289           ttyLocker ttyl;
2290           // no more room for speculative traps in this MDO
2291           xtty->elem("speculative_traps_oom");
2292         }
2293       }
2294       // Query the trap state of this profile datum.
2295       int tstate0 = pdata->trap_state();
2296       if (!trap_state_has_reason(tstate0, per_bc_reason))
2297         maybe_prior_trap = false;
2298       if (!trap_state_is_recompiled(tstate0))
2299         maybe_prior_recompile = false;
2300 
2301       // Update the trap state of this profile datum.
2302       int tstate1 = tstate0;
2303       // Record the reason.
2304       tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
2305       // Store the updated state on the MDO, for next time.
2306       if (tstate1 != tstate0)
2307         pdata->set_trap_state(tstate1);
2308     } else {
2309       if (LogCompilation && xtty != NULL) {
2310         ttyLocker ttyl;
2311         // Missing MDP?  Leave a small complaint in the log.
2312         xtty->elem("missing_mdp bci='%d'", trap_bci);
2313       }
2314     }
2315   }
2316 
2317   // Return results:
2318   ret_this_trap_count = this_trap_count;
2319   ret_maybe_prior_trap = maybe_prior_trap;
2320   ret_maybe_prior_recompile = maybe_prior_recompile;
2321   return pdata;
2322 }
2323 
2324 void
2325 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2326   ResourceMark rm;
2327   // Ignored outputs:
2328   uint ignore_this_trap_count;
2329   bool ignore_maybe_prior_trap;
2330   bool ignore_maybe_prior_recompile;
2331   assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
2332   // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts
2333   bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);
2334   query_update_method_data(trap_mdo, trap_bci,
2335                            (DeoptReason)reason,
2336                            update_total_counts,
2337 #if INCLUDE_JVMCI
2338                            false,
2339 #endif
2340                            NULL,
2341                            ignore_this_trap_count,
2342                            ignore_maybe_prior_trap,
2343                            ignore_maybe_prior_recompile);
2344 }
2345 
2346 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request, jint exec_mode) {
2347   if (TraceDeoptimization) {
2348     tty->print("Uncommon trap ");
2349   }
2350   // Still in Java no safepoints
2351   {
2352     // This enters VM and may safepoint
2353     uncommon_trap_inner(thread, trap_request);
2354   }
2355   return fetch_unroll_info_helper(thread, exec_mode);
2356 }
2357 
2358 // Local derived constants.
2359 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2360 const int DS_REASON_MASK   = ((uint)DataLayout::trap_mask) >> 1;
2361 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2362 
2363 //---------------------------trap_state_reason---------------------------------
2364 Deoptimization::DeoptReason
2365 Deoptimization::trap_state_reason(int trap_state) {
2366   // This assert provides the link between the width of DataLayout::trap_bits
2367   // and the encoding of "recorded" reasons.  It ensures there are enough
2368   // bits to store all needed reasons in the per-BCI MDO profile.
2369   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2370   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2371   trap_state -= recompile_bit;
2372   if (trap_state == DS_REASON_MASK) {
2373     return Reason_many;
2374   } else {
2375     assert((int)Reason_none == 0, "state=0 => Reason_none");
2376     return (DeoptReason)trap_state;
2377   }
2378 }
2379 //-------------------------trap_state_has_reason-------------------------------
2380 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2381   assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
2382   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2383   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2384   trap_state -= recompile_bit;
2385   if (trap_state == DS_REASON_MASK) {
2386     return -1;  // true, unspecifically (bottom of state lattice)
2387   } else if (trap_state == reason) {
2388     return 1;   // true, definitely
2389   } else if (trap_state == 0) {
2390     return 0;   // false, definitely (top of state lattice)
2391   } else {
2392     return 0;   // false, definitely
2393   }
2394 }
2395 //-------------------------trap_state_add_reason-------------------------------
2396 int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
2397   assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
2398   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2399   trap_state -= recompile_bit;
2400   if (trap_state == DS_REASON_MASK) {
2401     return trap_state + recompile_bit;     // already at state lattice bottom
2402   } else if (trap_state == reason) {
2403     return trap_state + recompile_bit;     // the condition is already true
2404   } else if (trap_state == 0) {
2405     return reason + recompile_bit;          // no condition has yet been true
2406   } else {
2407     return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
2408   }
2409 }
2410 //-----------------------trap_state_is_recompiled------------------------------
2411 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2412   return (trap_state & DS_RECOMPILE_BIT) != 0;
2413 }
2414 //-----------------------trap_state_set_recompiled-----------------------------
2415 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
2416   if (z)  return trap_state |  DS_RECOMPILE_BIT;
2417   else    return trap_state & ~DS_RECOMPILE_BIT;
2418 }
2419 //---------------------------format_trap_state---------------------------------
2420 // This is used for debugging and diagnostics, including LogFile output.
2421 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2422                                               int trap_state) {
2423   assert(buflen > 0, "sanity");
2424   DeoptReason reason      = trap_state_reason(trap_state);
2425   bool        recomp_flag = trap_state_is_recompiled(trap_state);
2426   // Re-encode the state from its decoded components.
2427   int decoded_state = 0;
2428   if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
2429     decoded_state = trap_state_add_reason(decoded_state, reason);
2430   if (recomp_flag)
2431     decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
2432   // If the state re-encodes properly, format it symbolically.
2433   // Because this routine is used for debugging and diagnostics,
2434   // be robust even if the state is a strange value.
2435   size_t len;
2436   if (decoded_state != trap_state) {
2437     // Random buggy state that doesn't decode??
2438     len = jio_snprintf(buf, buflen, "#%d", trap_state);
2439   } else {
2440     len = jio_snprintf(buf, buflen, "%s%s",
2441                        trap_reason_name(reason),
2442                        recomp_flag ? " recompiled" : "");
2443   }
2444   return buf;
2445 }
2446 
2447 
2448 //--------------------------------statics--------------------------------------
2449 const char* Deoptimization::_trap_reason_name[] = {
2450   // Note:  Keep this in sync. with enum DeoptReason.
2451   "none",
2452   "null_check",
2453   "null_assert" JVMCI_ONLY("_or_unreached0"),
2454   "range_check",
2455   "class_check",
2456   "array_check",
2457   "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),
2458   "bimorphic" JVMCI_ONLY("_or_optimized_type_check"),
2459   "profile_predicate",
2460   "unloaded",
2461   "uninitialized",
2462   "initialized",
2463   "unreached",
2464   "unhandled",
2465   "constraint",
2466   "div0_check",
2467   "age",
2468   "predicate",
2469   "loop_limit_check",
2470   "speculate_class_check",
2471   "speculate_null_check",
2472   "speculate_null_assert",
2473   "rtm_state_change",
2474   "unstable_if",
2475   "unstable_fused_if",
2476 #if INCLUDE_JVMCI
2477   "aliasing",
2478   "transfer_to_interpreter",
2479   "not_compiled_exception_handler",
2480   "unresolved",
2481   "jsr_mismatch",
2482 #endif
2483   "tenured"
2484 };
2485 const char* Deoptimization::_trap_action_name[] = {
2486   // Note:  Keep this in sync. with enum DeoptAction.
2487   "none",
2488   "maybe_recompile",
2489   "reinterpret",
2490   "make_not_entrant",
2491   "make_not_compilable"
2492 };
2493 
2494 const char* Deoptimization::trap_reason_name(int reason) {
2495   // Check that every reason has a name
2496   STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);
2497 
2498   if (reason == Reason_many)  return "many";
2499   if ((uint)reason < Reason_LIMIT)
2500     return _trap_reason_name[reason];
2501   static char buf[20];
2502   sprintf(buf, "reason%d", reason);
2503   return buf;
2504 }
2505 const char* Deoptimization::trap_action_name(int action) {
2506   // Check that every action has a name
2507   STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);
2508 
2509   if ((uint)action < Action_LIMIT)
2510     return _trap_action_name[action];
2511   static char buf[20];
2512   sprintf(buf, "action%d", action);
2513   return buf;
2514 }
2515 
2516 // This is used for debugging and diagnostics, including LogFile output.
2517 const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
2518                                                 int trap_request) {
2519   jint unloaded_class_index = trap_request_index(trap_request);
2520   const char* reason = trap_reason_name(trap_request_reason(trap_request));
2521   const char* action = trap_action_name(trap_request_action(trap_request));
2522 #if INCLUDE_JVMCI
2523   int debug_id = trap_request_debug_id(trap_request);
2524 #endif
2525   size_t len;
2526   if (unloaded_class_index < 0) {
2527     len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),
2528                        reason, action
2529 #if INCLUDE_JVMCI
2530                        ,debug_id
2531 #endif
2532                        );
2533   } else {
2534     len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),
2535                        reason, action, unloaded_class_index
2536 #if INCLUDE_JVMCI
2537                        ,debug_id
2538 #endif
2539                        );
2540   }
2541   return buf;
2542 }
2543 
2544 juint Deoptimization::_deoptimization_hist
2545         [Deoptimization::Reason_LIMIT]
2546     [1 + Deoptimization::Action_LIMIT]
2547         [Deoptimization::BC_CASE_LIMIT]
2548   = {0};
2549 
2550 enum {
2551   LSB_BITS = 8,
2552   LSB_MASK = right_n_bits(LSB_BITS)
2553 };
2554 
2555 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2556                                        Bytecodes::Code bc) {
2557   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2558   assert(action >= 0 && action < Action_LIMIT, "oob");
2559   _deoptimization_hist[Reason_none][0][0] += 1;  // total
2560   _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
2561   juint* cases = _deoptimization_hist[reason][1+action];
2562   juint* bc_counter_addr = NULL;
2563   juint  bc_counter      = 0;
2564   // Look for an unused counter, or an exact match to this BC.
2565   if (bc != Bytecodes::_illegal) {
2566     for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2567       juint* counter_addr = &cases[bc_case];
2568       juint  counter = *counter_addr;
2569       if ((counter == 0 && bc_counter_addr == NULL)
2570           || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
2571         // this counter is either free or is already devoted to this BC
2572         bc_counter_addr = counter_addr;
2573         bc_counter = counter | bc;
2574       }
2575     }
2576   }
2577   if (bc_counter_addr == NULL) {
2578     // Overflow, or no given bytecode.
2579     bc_counter_addr = &cases[BC_CASE_LIMIT-1];
2580     bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
2581   }
2582   *bc_counter_addr = bc_counter + (1 << LSB_BITS);
2583 }
2584 
2585 jint Deoptimization::total_deoptimization_count() {
2586   return _deoptimization_hist[Reason_none][0][0];
2587 }
2588 
2589 void Deoptimization::print_statistics() {
2590   juint total = total_deoptimization_count();
2591   juint account = total;
2592   if (total != 0) {
2593     ttyLocker ttyl;
2594     if (xtty != NULL)  xtty->head("statistics type='deoptimization'");
2595     tty->print_cr("Deoptimization traps recorded:");
2596     #define PRINT_STAT_LINE(name, r) \
2597       tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
2598     PRINT_STAT_LINE("total", total);
2599     // For each non-zero entry in the histogram, print the reason,
2600     // the action, and (if specifically known) the type of bytecode.
2601     for (int reason = 0; reason < Reason_LIMIT; reason++) {
2602       for (int action = 0; action < Action_LIMIT; action++) {
2603         juint* cases = _deoptimization_hist[reason][1+action];
2604         for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2605           juint counter = cases[bc_case];
2606           if (counter != 0) {
2607             char name[1*K];
2608             Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
2609             if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
2610               bc = Bytecodes::_illegal;
2611             sprintf(name, "%s/%s/%s",
2612                     trap_reason_name(reason),
2613                     trap_action_name(action),
2614                     Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
2615             juint r = counter >> LSB_BITS;
2616             tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
2617             account -= r;
2618           }
2619         }
2620       }
2621     }
2622     if (account != 0) {
2623       PRINT_STAT_LINE("unaccounted", account);
2624     }
2625     #undef PRINT_STAT_LINE
2626     if (xtty != NULL)  xtty->tail("statistics");
2627   }
2628 }
2629 #else // COMPILER2_OR_JVMCI
2630 
2631 
2632 // Stubs for C1 only system.
2633 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2634   return false;
2635 }
2636 
2637 const char* Deoptimization::trap_reason_name(int reason) {
2638   return "unknown";
2639 }
2640 
2641 void Deoptimization::print_statistics() {
2642   // no output
2643 }
2644 
2645 void
2646 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2647   // no udpate
2648 }
2649 
2650 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2651   return 0;
2652 }
2653 
2654 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2655                                        Bytecodes::Code bc) {
2656   // no update
2657 }
2658 
2659 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2660                                               int trap_state) {
2661   jio_snprintf(buf, buflen, "#%d", trap_state);
2662   return buf;
2663 }
2664 
2665 #endif // COMPILER2_OR_JVMCI