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