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