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