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