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