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