1 /*
   2  * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "classfile/javaClasses.inline.hpp"
  26 #include "classfile/symbolTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmClasses.hpp"
  29 #include "code/codeCache.hpp"
  30 #include "code/debugInfoRec.hpp"
  31 #include "code/nmethod.hpp"
  32 #include "code/pcDesc.hpp"
  33 #include "code/scopeDesc.hpp"
  34 #include "compiler/compilationPolicy.hpp"
  35 #include "compiler/compilerDefinitions.inline.hpp"
  36 #include "gc/shared/collectedHeap.hpp"
  37 #include "gc/shared/memAllocator.hpp"
  38 #include "interpreter/bytecode.inline.hpp"
  39 #include "interpreter/bytecodeStream.hpp"
  40 #include "interpreter/interpreter.hpp"
  41 #include "interpreter/oopMapCache.hpp"
  42 #include "jvm.h"
  43 #include "logging/log.hpp"
  44 #include "logging/logLevel.hpp"
  45 #include "logging/logMessage.hpp"
  46 #include "logging/logStream.hpp"
  47 #include "memory/allocation.inline.hpp"
  48 #include "memory/oopFactory.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.hpp"

  51 #include "oops/constantPool.hpp"
  52 #include "oops/fieldStreams.inline.hpp"



  53 #include "oops/method.hpp"
  54 #include "oops/objArrayKlass.hpp"
  55 #include "oops/objArrayOop.inline.hpp"
  56 #include "oops/oop.inline.hpp"
  57 #include "oops/typeArrayOop.inline.hpp"
  58 #include "oops/verifyOopClosure.hpp"
  59 #include "prims/jvmtiDeferredUpdates.hpp"
  60 #include "prims/jvmtiExport.hpp"
  61 #include "prims/jvmtiThreadState.hpp"
  62 #include "prims/methodHandles.hpp"
  63 #include "prims/vectorSupport.hpp"

  64 #include "runtime/atomicAccess.hpp"
  65 #include "runtime/basicLock.inline.hpp"
  66 #include "runtime/continuation.hpp"
  67 #include "runtime/continuationEntry.inline.hpp"
  68 #include "runtime/deoptimization.hpp"
  69 #include "runtime/escapeBarrier.hpp"
  70 #include "runtime/fieldDescriptor.inline.hpp"
  71 #include "runtime/frame.inline.hpp"
  72 #include "runtime/handles.inline.hpp"
  73 #include "runtime/interfaceSupport.inline.hpp"
  74 #include "runtime/javaThread.hpp"
  75 #include "runtime/jniHandles.inline.hpp"
  76 #include "runtime/keepStackGCProcessed.hpp"
  77 #include "runtime/lockStack.inline.hpp"
  78 #include "runtime/objectMonitor.inline.hpp"
  79 #include "runtime/osThread.hpp"
  80 #include "runtime/safepointVerifiers.hpp"
  81 #include "runtime/sharedRuntime.hpp"
  82 #include "runtime/signature.hpp"
  83 #include "runtime/stackFrameStream.inline.hpp"
  84 #include "runtime/stackValue.hpp"
  85 #include "runtime/stackWatermarkSet.hpp"
  86 #include "runtime/stubRoutines.hpp"
  87 #include "runtime/synchronizer.hpp"
  88 #include "runtime/threadSMR.hpp"
  89 #include "runtime/threadWXSetters.inline.hpp"
  90 #include "runtime/vframe.hpp"
  91 #include "runtime/vframe_hp.hpp"
  92 #include "runtime/vframeArray.hpp"
  93 #include "runtime/vmOperations.hpp"
  94 #include "utilities/checkedCast.hpp"
  95 #include "utilities/events.hpp"
  96 #include "utilities/growableArray.hpp"
  97 #include "utilities/macros.hpp"
  98 #include "utilities/preserveException.hpp"
  99 #include "utilities/xmlstream.hpp"
 100 #if INCLUDE_JFR
 101 #include "jfr/jfr.inline.hpp"
 102 #include "jfr/jfrEvents.hpp"
 103 #include "jfr/metadata/jfrSerializer.hpp"
 104 #endif
 105 
 106 uint64_t DeoptimizationScope::_committed_deopt_gen = 0;
 107 uint64_t DeoptimizationScope::_active_deopt_gen    = 1;
 108 bool     DeoptimizationScope::_committing_in_progress = false;
 109 
 110 DeoptimizationScope::DeoptimizationScope() : _required_gen(0) {
 111   DEBUG_ONLY(_deopted = false;)
 112 
 113   MutexLocker ml(NMethodState_lock, Mutex::_no_safepoint_check_flag);
 114   // If there is nothing to deopt _required_gen is the same as comitted.
 115   _required_gen = DeoptimizationScope::_committed_deopt_gen;
 116 }
 117 
 118 DeoptimizationScope::~DeoptimizationScope() {
 119   assert(_deopted, "Deopt not executed");
 120 }
 121 
 122 void DeoptimizationScope::mark(nmethod* nm, bool inc_recompile_counts) {
 123   if (!nm->can_be_deoptimized()) {
 124     return;
 125   }
 126 
 127   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 128 
 129   // If it's already marked but we still need it to be deopted.
 130   if (nm->is_marked_for_deoptimization()) {
 131     dependent(nm);
 132     return;
 133   }
 134 
 135   MACOS_AARCH64_ONLY(os::thread_wx_enable_write());
 136   nmethod::DeoptimizationStatus status =
 137     inc_recompile_counts ? nmethod::deoptimize : nmethod::deoptimize_noupdate;
 138   AtomicAccess::store(&nm->_deoptimization_status, status);
 139 
 140   // Make sure active is not committed
 141   assert(DeoptimizationScope::_committed_deopt_gen < DeoptimizationScope::_active_deopt_gen, "Must be");
 142   assert(nm->_deoptimization_generation == 0, "Is already marked");
 143 
 144   nm->_deoptimization_generation = DeoptimizationScope::_active_deopt_gen;
 145   _required_gen                  = DeoptimizationScope::_active_deopt_gen;
 146 }
 147 
 148 void DeoptimizationScope::dependent(nmethod* nm) {
 149   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 150 
 151   // A method marked by someone else may have a _required_gen lower than what we marked with.
 152   // Therefore only store it if it's higher than _required_gen.
 153   if (_required_gen < nm->_deoptimization_generation) {
 154     _required_gen = nm->_deoptimization_generation;
 155   }
 156 }
 157 
 158 void DeoptimizationScope::deoptimize_marked() {
 159   assert(!_deopted, "Already deopted");
 160 
 161   // We are not alive yet.
 162   if (!Universe::is_fully_initialized()) {
 163     DEBUG_ONLY(_deopted = true;)
 164     return;
 165   }
 166 
 167   // Safepoints are a special case, handled here.
 168   if (SafepointSynchronize::is_at_safepoint()) {
 169     DeoptimizationScope::_committed_deopt_gen = DeoptimizationScope::_active_deopt_gen;
 170     DeoptimizationScope::_active_deopt_gen++;
 171     Deoptimization::deoptimize_all_marked();
 172     DEBUG_ONLY(_deopted = true;)
 173     return;
 174   }
 175 
 176   uint64_t comitting = 0;
 177   bool wait = false;
 178   while (true) {
 179     {
 180       ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 181 
 182       // First we check if we or someone else already deopted the gen we want.
 183       if (DeoptimizationScope::_committed_deopt_gen >= _required_gen) {
 184         DEBUG_ONLY(_deopted = true;)
 185         return;
 186       }
 187       if (!_committing_in_progress) {
 188         // The version we are about to commit.
 189         comitting = DeoptimizationScope::_active_deopt_gen;
 190         // Make sure new marks use a higher gen.
 191         DeoptimizationScope::_active_deopt_gen++;
 192         _committing_in_progress = true;
 193         wait = false;
 194       } else {
 195         // Another thread is handshaking and committing a gen.
 196         wait = true;
 197       }
 198     }
 199     if (wait) {
 200       // Wait and let the concurrent handshake be performed.
 201       ThreadBlockInVM tbivm(JavaThread::current());
 202       os::naked_yield();
 203     } else {
 204       // Performs the handshake.
 205       Deoptimization::deoptimize_all_marked(); // May safepoint and an additional deopt may have occurred.
 206       DEBUG_ONLY(_deopted = true;)
 207       {
 208         ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 209 
 210         // Make sure that committed doesn't go backwards.
 211         // Should only happen if we did a deopt during a safepoint above.
 212         if (DeoptimizationScope::_committed_deopt_gen < comitting) {
 213           DeoptimizationScope::_committed_deopt_gen = comitting;
 214         }
 215         _committing_in_progress = false;
 216 
 217         assert(DeoptimizationScope::_committed_deopt_gen >= _required_gen, "Must be");
 218 
 219         return;
 220       }
 221     }
 222   }
 223 }
 224 
 225 Deoptimization::UnrollBlock::UnrollBlock(int  size_of_deoptimized_frame,
 226                                          int  caller_adjustment,
 227                                          int  caller_actual_parameters,
 228                                          int  number_of_frames,
 229                                          intptr_t* frame_sizes,
 230                                          address* frame_pcs,
 231                                          BasicType return_type,
 232                                          int exec_mode) {
 233   _size_of_deoptimized_frame = size_of_deoptimized_frame;
 234   _caller_adjustment         = caller_adjustment;
 235   _caller_actual_parameters  = caller_actual_parameters;
 236   _number_of_frames          = number_of_frames;
 237   _frame_sizes               = frame_sizes;
 238   _frame_pcs                 = frame_pcs;
 239   _register_block            = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
 240   _return_type               = return_type;
 241   _initial_info              = 0;
 242   // PD (x86 only)
 243   _counter_temp              = 0;
 244   _unpack_kind               = exec_mode;
 245   _sender_sp_temp            = 0;
 246 
 247   _total_frame_sizes         = size_of_frames();
 248   assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");
 249 }
 250 
 251 Deoptimization::UnrollBlock::~UnrollBlock() {
 252   FREE_C_HEAP_ARRAY(_frame_sizes);
 253   FREE_C_HEAP_ARRAY(_frame_pcs);
 254   FREE_C_HEAP_ARRAY(_register_block);
 255 }
 256 
 257 int Deoptimization::UnrollBlock::size_of_frames() const {
 258   // Account first for the adjustment of the initial frame
 259   intptr_t result = _caller_adjustment;
 260   for (int index = 0; index < number_of_frames(); index++) {
 261     result += frame_sizes()[index];
 262   }
 263   return checked_cast<int>(result);
 264 }
 265 
 266 void Deoptimization::UnrollBlock::print() {
 267   ResourceMark rm;
 268   stringStream st;
 269   st.print_cr("UnrollBlock");
 270   st.print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
 271   st.print(   "  frame_sizes: ");
 272   for (int index = 0; index < number_of_frames(); index++) {
 273     st.print("%zd ", frame_sizes()[index]);
 274   }
 275   st.cr();
 276   tty->print_raw(st.freeze());
 277 }
 278 
 279 // In order to make fetch_unroll_info work properly with escape
 280 // analysis, the method was changed from JRT_LEAF to JRT_BLOCK_ENTRY.
 281 // The actual reallocation of previously eliminated objects occurs in realloc_objects,
 282 // which is called from the method fetch_unroll_info_helper below.
 283 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))
 284   // fetch_unroll_info() is called at the beginning of the deoptimization
 285   // handler. Note this fact before we start generating temporary frames
 286   // that can confuse an asynchronous stack walker. This counter is
 287   // decremented at the end of unpack_frames().
 288   current->inc_in_deopt_handler();
 289 
 290   if (exec_mode == Unpack_exception) {
 291     // When we get here, a callee has thrown an exception into a deoptimized
 292     // frame. That throw might have deferred stack watermark checking until
 293     // after unwinding. So we deal with such deferred requests here.
 294     StackWatermarkSet::after_unwind(current);
 295   }
 296 
 297   return fetch_unroll_info_helper(current, exec_mode);
 298 JRT_END
 299 
 300 #ifdef COMPILER2













 301 // print information about reallocated objects
 302 static void print_objects(JavaThread* deoptee_thread,
 303                           GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
 304   ResourceMark rm;
 305   stringStream st;  // change to logStream with logging
 306   st.print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));
 307   fieldDescriptor fd;
 308 
 309   for (int i = 0; i < objects->length(); i++) {
 310     ObjectValue* sv = (ObjectValue*) objects->at(i);
 311     Handle obj = sv->value();
 312 
 313     if (obj.is_null()) {
 314       st.print_cr("     nullptr");
 315       continue;
 316     }
 317 
 318     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());

 319 
 320     st.print("     object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
 321     k->print_value_on(&st);
 322     st.print_cr(" allocated (%zu bytes)", obj->size() * HeapWordSize);
 323 
 324     if (Verbose && k != nullptr) {
 325       k->oop_print_on(obj(), &st);
 326     }
 327   }
 328   tty->print_raw(st.freeze());
 329 }
 330 
 331 static bool rematerialize_objects(JavaThread* thread, int exec_mode, nmethod* compiled_method,
 332                                   frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,
 333                                   bool& deoptimized_objects) {
 334   bool realloc_failures = false;
 335   assert (chunk->at(0)->scope() != nullptr,"expect only compiled java frames");
 336 
 337   JavaThread* deoptee_thread = chunk->at(0)->thread();
 338   assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread),
 339          "a frame can only be deoptimized by the owner thread");
 340 
 341   GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects_to_rematerialize(deoptee, map);
 342 
 343   // The flag return_oop() indicates call sites which return oop
 344   // in compiled code. Such sites include java method calls,
 345   // runtime calls (for example, used to allocate new objects/arrays
 346   // on slow code path) and any other calls generated in compiled code.
 347   // It is not guaranteed that we can get such information here only
 348   // by analyzing bytecode in deoptimized frames. This is why this flag
 349   // is set during method compilation (see Compile::Process_OopMap_Node()).
 350   // If the previous frame was popped or if we are dispatching an exception,
 351   // we don't have an oop result.
 352   bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);
 353   Handle return_value;











 354   if (save_oop_result) {
 355     // Reallocation may trigger GC. If deoptimization happened on return from
 356     // call which returns oop we need to save it since it is not in oopmap.
 357     oop result = deoptee.saved_oop_result(&map);
 358     assert(oopDesc::is_oop_or_null(result), "must be oop");
 359     return_value = Handle(thread, result);
 360     assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
 361     if (TraceDeoptimization) {
 362       tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
 363       tty->cr();
 364     }
 365   }
 366   if (objects != nullptr) {
 367     if (exec_mode == Deoptimization::Unpack_none) {
 368       assert(thread->thread_state() == _thread_in_vm, "assumption");
 369       JavaThread* THREAD = thread; // For exception macros.
 370       // Clear pending OOM if reallocation fails and return true indicating allocation failure
 371       realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));







 372       deoptimized_objects = true;
 373     } else {
 374       JavaThread* current = thread; // For JRT_BLOCK
 375       JRT_BLOCK
 376       realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);







 377       JRT_END
 378     }
 379     guarantee(compiled_method != nullptr, "deopt must be associated with an nmethod");
 380     Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures);
 381     if (TraceDeoptimization) {
 382       print_objects(deoptee_thread, objects, realloc_failures);
 383     }
 384   }
 385   if (save_oop_result) {
 386     // Restore result.
 387     deoptee.set_saved_oop_result(&map, return_value());

 388   }
 389   return realloc_failures;
 390 }
 391 
 392 static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,
 393                                      frame& deoptee, int exec_mode, bool& deoptimized_objects) {
 394   JavaThread* deoptee_thread = chunk->at(0)->thread();
 395   assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");
 396   assert(thread == Thread::current(), "should be");
 397   HandleMark hm(thread);
 398 #ifndef PRODUCT
 399   bool first = true;
 400 #endif // !PRODUCT
 401   // Start locking from outermost/oldest frame
 402   for (int i = (chunk->length() - 1); i >= 0; i--) {
 403     compiledVFrame* cvf = chunk->at(i);
 404     assert (cvf->scope() != nullptr,"expect only compiled java frames");
 405     GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
 406     if (monitors->is_nonempty()) {
 407       bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee,
 408                                                      exec_mode, realloc_failures);
 409       deoptimized_objects = deoptimized_objects || relocked;
 410 #ifndef PRODUCT
 411       if (PrintDeoptimizationDetails) {
 412         ResourceMark rm;
 413         stringStream st;
 414         for (int j = 0; j < monitors->length(); j++) {
 415           MonitorInfo* mi = monitors->at(j);
 416           if (mi->eliminated()) {
 417             if (first) {
 418               first = false;
 419               st.print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread));
 420             }
 421             if (exec_mode == Deoptimization::Unpack_none) {
 422               ObjectMonitor* monitor = deoptee_thread->current_waiting_monitor();
 423               if (monitor != nullptr && monitor->object() == mi->owner()) {
 424                 st.print_cr("     object <" INTPTR_FORMAT "> DEFERRED relocking after wait", p2i(mi->owner()));
 425                 continue;
 426               }
 427             }
 428             if (mi->owner_is_scalar_replaced()) {
 429               Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
 430               st.print_cr("     failed reallocation for klass %s", k->external_name());
 431             } else {
 432               st.print_cr("     object <" INTPTR_FORMAT "> locked", p2i(mi->owner()));
 433             }
 434           }
 435         }
 436         tty->print_raw(st.freeze());
 437       }
 438 #endif // !PRODUCT
 439     }
 440   }
 441 }
 442 
 443 // Deoptimize objects, that is reallocate and relock them, just before they escape through JVMTI.
 444 // The given vframes cover one physical frame.
 445 bool Deoptimization::deoptimize_objects_internal(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk,
 446                                                  bool& realloc_failures) {
 447   frame deoptee = chunk->at(0)->fr();
 448   JavaThread* deoptee_thread = chunk->at(0)->thread();
 449   nmethod* nm = deoptee.cb()->as_nmethod_or_null();
 450   RegisterMap map(chunk->at(0)->register_map());
 451   bool deoptimized_objects = false;
 452 
 453   // Reallocate the non-escaping objects and restore their fields.
 454   if ((DoEscapeAnalysis && EliminateAllocations) || EliminateAutoBox || EnableVectorAggressiveReboxing) {

 455     realloc_failures = rematerialize_objects(thread, Unpack_none, nm, deoptee, map, chunk, deoptimized_objects);
 456   }
 457 
 458   // MonitorInfo structures used in eliminate_locks are not GC safe.
 459   NoSafepointVerifier no_safepoint;
 460 
 461   // Now relock objects if synchronization on them was eliminated.
 462   if ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) {
 463     restore_eliminated_locks(thread, chunk, realloc_failures, deoptee, Unpack_none, deoptimized_objects);
 464   }
 465   return deoptimized_objects;
 466 }
 467 #endif // COMPILER2
 468 
 469 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
 470 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* current, int exec_mode) {
 471   JFR_ONLY(Jfr::check_and_process_sample_request(current);)
 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   if (exec_mode == Unpack_deopt) {
 499     assert(deoptee.is_deoptimized_frame(), "frame is not marked for deoptimization");
 500   }
 501   // Set the deoptee nmethod
 502   assert(current->deopt_compiled_method() == nullptr, "Pending deopt!");
 503   nmethod* nm = deoptee.cb()->as_nmethod_or_null();
 504   current->set_deopt_compiled_method(nm);
 505 
 506   if (VerifyStack) {
 507     current->validate_frame_layout();
 508   }
 509 
 510   // Create a growable array of VFrames where each VFrame represents an inlined
 511   // Java frame.  This storage is allocated with the usual system arena.
 512   assert(deoptee.is_compiled_frame(), "Wrong frame type");
 513   GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
 514   vframe* vf = vframe::new_vframe(&deoptee, &map, current);
 515   while (!vf->is_top()) {
 516     assert(vf->is_compiled_frame(), "Wrong frame type");
 517     chunk->push(compiledVFrame::cast(vf));
 518     vf = vf->sender();
 519   }
 520   assert(vf->is_compiled_frame(), "Wrong frame type");
 521   chunk->push(compiledVFrame::cast(vf));
 522 
 523   bool realloc_failures = false;
 524 
 525 #ifdef COMPILER2
 526   // Reallocate the non-escaping objects and restore their fields. Then
 527   // relock objects if synchronization on them was eliminated.
 528   if ((DoEscapeAnalysis && EliminateAllocations) || EliminateAutoBox || EnableVectorAggressiveReboxing) {

 529     bool unused;
 530     realloc_failures = rematerialize_objects(current, exec_mode, nm, deoptee, map, chunk, unused);
 531   }
 532 #endif // COMPILER2
 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 #ifdef COMPILER2
 541   if (((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
 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() == 1, "should have only exception on stack");
 559     guarantee(exec_mode != Unpack_exception, "rethrow_exception set with Unpack_exception");
 560     ScopeValue* topOfStack = expressions->top();
 561     exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();
 562     guarantee(exceptionObject() != nullptr, "exception oop can not be null");
 563   }
 564 
 565   vframeArray* array = create_vframeArray(current, deoptee, &map, chunk, realloc_failures);
 566 #ifdef COMPILER2
 567   if (realloc_failures) {
 568     // This destroys all ScopedValue bindings.
 569     current->clear_scopedValueBindings();
 570     pop_frames_failed_reallocs(current, array);
 571   }
 572 #endif // COMPILER2
 573 
 574   assert(current->vframe_array_head() == nullptr, "Pending deopt!");
 575   current->set_vframe_array_head(array);
 576 
 577   // Now that the vframeArray has been created if we have any deferred local writes
 578   // added by jvmti then we can free up that structure as the data is now in the
 579   // vframeArray
 580 
 581   JvmtiDeferredUpdates::delete_updates_for_frame(current, array->original().id());
 582 
 583   // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
 584   CodeBlob* cb = stub_frame.cb();
 585   // Verify we have the right vframeArray
 586   assert(cb->frame_size() >= 0, "Unexpected frame size");
 587   intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
 588   assert(unpack_sp == deoptee.unextended_sp(), "must be");
 589 
 590 #ifdef ASSERT
 591   assert(cb->is_deoptimization_stub() ||
 592          cb->is_uncommon_trap_stub() ||
 593          strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||
 594          strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,
 595          "unexpected code blob: %s", cb->name());
 596 #endif
 597 
 598   // This is a guarantee instead of an assert because if vframe doesn't match
 599   // we will unpack the wrong deoptimized frame and wind up in strange places
 600   // where it will be very difficult to figure out what went wrong. Better
 601   // to die an early death here than some very obscure death later when the
 602   // trail is cold.
 603   guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
 604 
 605   int number_of_frames = array->frames();
 606 
 607   // Compute the vframes' sizes.  Note that frame_sizes[] entries are ordered from outermost to innermost
 608   // virtual activation, which is the reverse of the elements in the vframes array.
 609   intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
 610   // +1 because we always have an interpreter return address for the final slot.
 611   address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
 612   int popframe_extra_args = 0;
 613   // Create an interpreter return address for the stub to use as its return
 614   // address so the skeletal frames are perfectly walkable
 615   frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
 616 
 617   // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
 618   // activation be put back on the expression stack of the caller for reexecution
 619   if (JvmtiExport::can_pop_frame() && current->popframe_forcing_deopt_reexecution()) {
 620     popframe_extra_args = in_words(current->popframe_preserved_args_size_in_words());
 621   }
 622 
 623   // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
 624   // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
 625   // than simply use array->sender.pc(). This requires us to walk the current set of frames
 626   //
 627   frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
 628   deopt_sender = deopt_sender.sender(&dummy_map);     // Now deoptee caller
 629 
 630   // It's possible that the number of parameters at the call site is
 631   // different than number of arguments in the callee when method
 632   // handles are used.  If the caller is interpreted get the real
 633   // value so that the proper amount of space can be added to it's
 634   // frame.
 635   bool caller_was_method_handle = false;
 636   if (deopt_sender.is_interpreted_frame()) {
 637     methodHandle method(current, deopt_sender.interpreter_frame_method());
 638     Bytecode_invoke cur(method, deopt_sender.interpreter_frame_bci());
 639     if (cur.has_member_arg()) {
 640       // This should cover all real-world cases.  One exception is a pathological chain of
 641       // MH.linkToXXX() linker calls, which only trusted code could do anyway.  To handle that case, we
 642       // would need to get the size from the resolved method entry.  Another exception would
 643       // be an invokedynamic with an adapter that is really a MethodHandle linker.
 644       caller_was_method_handle = true;
 645     }
 646   }
 647 
 648   //
 649   // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
 650   // frame_sizes/frame_pcs[1] next oldest frame (int)
 651   // frame_sizes/frame_pcs[n] youngest frame (int)
 652   //
 653   // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
 654   // owns the space for the return address to it's caller).  Confusing ain't it.
 655   //
 656   // The vframe array can address vframes with indices running from
 657   // 0.._frames-1. Index  0 is the youngest frame and _frame - 1 is the oldest (root) frame.
 658   // When we create the skeletal frames we need the oldest frame to be in the zero slot
 659   // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
 660   // so things look a little strange in this loop.
 661   //
 662   int callee_parameters = 0;
 663   int callee_locals = 0;
 664   for (int index = 0; index < array->frames(); index++ ) {
 665     // frame[number_of_frames - 1 ] = on_stack_size(youngest)
 666     // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
 667     // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
 668     frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
 669                                                                                                     callee_locals,
 670                                                                                                     index == 0,
 671                                                                                                     popframe_extra_args);
 672     // This pc doesn't have to be perfect just good enough to identify the frame
 673     // as interpreted so the skeleton frame will be walkable
 674     // The correct pc will be set when the skeleton frame is completely filled out
 675     // The final pc we store in the loop is wrong and will be overwritten below
 676     frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
 677 
 678     callee_parameters = array->element(index)->method()->size_of_parameters();
 679     callee_locals = array->element(index)->method()->max_locals();
 680     popframe_extra_args = 0;
 681   }
 682 
 683   // Compute whether the root vframe returns a float or double value.
 684   BasicType return_type;
 685   {
 686     methodHandle method(current, array->element(0)->method());
 687     Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
 688     return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
 689   }
 690 
 691   // Compute information for handling adapters and adjusting the frame size of the caller.
 692   int caller_adjustment = 0;
 693 
 694   // Compute the amount the oldest interpreter frame will have to adjust
 695   // its caller's stack by. If the caller is a compiled frame then
 696   // we pretend that the callee has no parameters so that the
 697   // extension counts for the full amount of locals and not just
 698   // locals-parms. This is because without a c2i adapter the parm
 699   // area as created by the compiled frame will not be usable by
 700   // the interpreter. (Depending on the calling convention there
 701   // may not even be enough space).
 702 
 703   // QQQ I'd rather see this pushed down into last_frame_adjust
 704   // and have it take the sender (aka caller).
 705 
 706   if (!deopt_sender.is_interpreted_frame() || caller_was_method_handle) {
 707     caller_adjustment = last_frame_adjust(0, callee_locals);
 708   } else if (callee_locals > callee_parameters) {
 709     // The caller frame may need extending to accommodate
 710     // non-parameter locals of the first unpacked interpreted frame.
 711     // Compute that adjustment.
 712     caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
 713   }
 714 
 715   // If the sender is deoptimized the we must retrieve the address of the handler
 716   // since the frame will "magically" show the original pc before the deopt
 717   // and we'd undo the deopt.
 718 
 719   frame_pcs[0] = Continuation::is_cont_barrier_frame(deoptee) ? StubRoutines::cont_returnBarrier() : deopt_sender.raw_pc();
 720   if (Continuation::is_continuation_enterSpecial(deopt_sender)) {
 721     ContinuationEntry::from_frame(deopt_sender)->set_argsize(0);
 722   }
 723 
 724   assert(CodeCache::find_blob(frame_pcs[0]) != nullptr, "bad pc");
 725 
 726   if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {
 727     assert(current->has_pending_exception(), "should have thrown OOME");
 728     current->set_exception_oop(current->pending_exception());
 729     current->clear_pending_exception();
 730     exec_mode = Unpack_exception;
 731   }
 732 
 733   int caller_actual_parameters = -1; // value not used except for interpreted frames, see below
 734   if (deopt_sender.is_interpreted_frame()) {
 735     caller_actual_parameters = callee_parameters + (caller_was_method_handle ? 1 : 0);
 736   }
 737 
 738   UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
 739                                       caller_adjustment * BytesPerWord,
 740                                       caller_actual_parameters,
 741                                       number_of_frames,
 742                                       frame_sizes,
 743                                       frame_pcs,
 744                                       return_type,
 745                                       exec_mode);
 746   // On some platforms, we need a way to pass some platform dependent
 747   // information to the unpacking code so the skeletal frames come out
 748   // correct (initial fp value, unextended sp, ...)
 749   info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
 750 
 751   if (array->frames() > 1) {
 752     if (VerifyStack && TraceDeoptimization) {
 753       tty->print_cr("Deoptimizing method containing inlining");
 754     }
 755   }
 756 
 757   array->set_unroll_block(info);
 758   return info;
 759 }
 760 
 761 // Called to cleanup deoptimization data structures in normal case
 762 // after unpacking to stack and when stack overflow error occurs
 763 void Deoptimization::cleanup_deopt_info(JavaThread *thread,
 764                                         vframeArray *array) {
 765 
 766   // Get array if coming from exception
 767   if (array == nullptr) {
 768     array = thread->vframe_array_head();
 769   }
 770   thread->set_vframe_array_head(nullptr);
 771 
 772   // Free the previous UnrollBlock
 773   vframeArray* old_array = thread->vframe_array_last();
 774   thread->set_vframe_array_last(array);
 775 
 776   if (old_array != nullptr) {
 777     UnrollBlock* old_info = old_array->unroll_block();
 778     old_array->set_unroll_block(nullptr);
 779     delete old_info;
 780     delete old_array;
 781   }
 782 
 783   // Deallocate any resource creating in this routine and any ResourceObjs allocated
 784   // inside the vframeArray (StackValueCollections)
 785 
 786   delete thread->deopt_mark();
 787   thread->set_deopt_mark(nullptr);
 788   thread->set_deopt_compiled_method(nullptr);
 789 
 790 
 791   if (JvmtiExport::can_pop_frame()) {
 792     // Regardless of whether we entered this routine with the pending
 793     // popframe condition bit set, we should always clear it now
 794     thread->clear_popframe_condition();
 795   }
 796 
 797   // unpack_frames() is called at the end of the deoptimization handler
 798   // and (in C2) at the end of the uncommon trap handler. Note this fact
 799   // so that an asynchronous stack walker can work again. This counter is
 800   // incremented at the beginning of fetch_unroll_info() and (in C2) at
 801   // the beginning of uncommon_trap().
 802   thread->dec_in_deopt_handler();
 803 }
 804 
 805 // Moved from cpu directories because none of the cpus has callee save values.
 806 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.
 807 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {
 808 
 809   // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in
 810   // the days we had adapter frames. When we deoptimize a situation where a
 811   // compiled caller calls a compiled caller will have registers it expects
 812   // to survive the call to the callee. If we deoptimize the callee the only
 813   // way we can restore these registers is to have the oldest interpreter
 814   // frame that we create restore these values. That is what this routine
 815   // will accomplish.
 816 
 817   // At the moment we have modified c2 to not have any callee save registers
 818   // so this problem does not exist and this routine is just a place holder.
 819 
 820   assert(f->is_interpreted_frame(), "must be interpreted");
 821 }
 822 
 823 #ifndef PRODUCT
 824 #ifdef ASSERT
 825 // Return true if the execution after the provided bytecode continues at the
 826 // next bytecode in the code. This is not the case for gotos, returns, and
 827 // throws.
 828 static bool falls_through(Bytecodes::Code bc) {
 829   switch (bc) {
 830     case Bytecodes::_goto:
 831     case Bytecodes::_goto_w:
 832     case Bytecodes::_athrow:
 833     case Bytecodes::_areturn:
 834     case Bytecodes::_dreturn:
 835     case Bytecodes::_freturn:
 836     case Bytecodes::_ireturn:
 837     case Bytecodes::_lreturn:
 838     case Bytecodes::_jsr:
 839     case Bytecodes::_ret:
 840     case Bytecodes::_return:
 841     case Bytecodes::_lookupswitch:
 842     case Bytecodes::_tableswitch:
 843       return false;
 844     default:
 845       return true;
 846   }
 847 }
 848 #endif
 849 #endif
 850 
 851 // Return BasicType of value being returned
 852 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
 853   assert(thread == JavaThread::current(), "pre-condition");
 854 
 855   // We are already active in the special DeoptResourceMark any ResourceObj's we
 856   // allocate will be freed at the end of the routine.
 857 
 858   // JRT_LEAF methods don't normally allocate handles and there is a
 859   // NoHandleMark to enforce that. It is actually safe to use Handles
 860   // in a JRT_LEAF method, and sometimes desirable, but to do so we
 861   // must use ResetNoHandleMark to bypass the NoHandleMark, and
 862   // then use a HandleMark to ensure any Handles we do create are
 863   // cleaned up in this scope.
 864   ResetNoHandleMark rnhm;
 865   HandleMark hm(thread);
 866 
 867   frame stub_frame = thread->last_frame();
 868 
 869   Continuation::notify_deopt(thread, stub_frame.sp());
 870 
 871   // Since the frame to unpack is the top frame of this thread, the vframe_array_head
 872   // must point to the vframeArray for the unpack frame.
 873   vframeArray* array = thread->vframe_array_head();
 874   UnrollBlock* info = array->unroll_block();
 875 
 876   // We set the last_Java frame. But the stack isn't really parsable here. So we
 877   // clear it to make sure JFR understands not to try and walk stacks from events
 878   // in here.
 879   intptr_t* sp = thread->frame_anchor()->last_Java_sp();
 880   thread->frame_anchor()->set_last_Java_sp(nullptr);
 881 
 882   // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
 883   array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
 884 
 885   thread->frame_anchor()->set_last_Java_sp(sp);
 886 
 887   BasicType bt = info->return_type();
 888 
 889   // If we have an exception pending, claim that the return type is an oop
 890   // so the deopt_blob does not overwrite the exception_oop.
 891 
 892   if (exec_mode == Unpack_exception)
 893     bt = T_OBJECT;
 894 
 895   // Cleanup thread deopt data
 896   cleanup_deopt_info(thread, array);
 897 
 898 #ifndef PRODUCT
 899   if (VerifyStack) {
 900     ResourceMark res_mark;
 901     // Clear pending exception to not break verification code (restored afterwards)
 902     PreserveExceptionMark pm(thread);
 903 
 904     thread->validate_frame_layout();
 905 
 906     // Verify that the just-unpacked frames match the interpreter's
 907     // notions of expression stack and locals
 908     vframeArray* cur_array = thread->vframe_array_last();
 909     RegisterMap rm(thread,
 910                    RegisterMap::UpdateMap::skip,
 911                    RegisterMap::ProcessFrames::include,
 912                    RegisterMap::WalkContinuation::skip);
 913     rm.set_include_argument_oops(false);
 914     int callee_size_of_parameters = 0;
 915     for (int frame_idx = 0; frame_idx < cur_array->frames(); frame_idx++) {
 916       bool is_top_frame = (frame_idx == 0);
 917       vframeArrayElement* el = cur_array->element(frame_idx);
 918       frame* iframe = el->iframe();
 919       guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
 920       methodHandle mh(thread, iframe->interpreter_frame_method());
 921       bool reexecute = el->should_reexecute();
 922 
 923       int cur_invoke_parameter_size = 0;
 924       int top_frame_expression_stack_adjustment = 0;
 925       int max_bci = mh->code_size();
 926       BytecodeStream str(mh, iframe->interpreter_frame_bci());
 927       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
 928       Bytecodes::Code cur_code = str.next();
 929 
 930       if (!reexecute && !Bytecodes::is_invoke(cur_code)) {
 931         // We can only compute OopMaps for the before state, so we need to roll forward
 932         // to the next bytecode.
 933         assert(is_top_frame, "must be");
 934         assert(falls_through(cur_code), "must be");
 935         assert(cur_code != Bytecodes::_illegal, "illegal bytecode");
 936         assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
 937 
 938         // Need to subtract off the size of the result type of
 939         // the bytecode because this is not described in the
 940         // debug info but returned to the interpreter in the TOS
 941         // caching register
 942         BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
 943         if (bytecode_result_type != T_ILLEGAL) {
 944           top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
 945         }
 946         assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive");
 947 
 948         cur_code = str.next();
 949         // Reflect the fact that we have rolled forward and now need
 950         // top_frame_expression_stack_adjustment
 951         reexecute = true;
 952       }
 953 
 954       assert(cur_code != Bytecodes::_illegal, "illegal bytecode");
 955       assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
 956 
 957       // Get the oop map for this bci
 958       InterpreterOopMap mask;
 959       OopMapCache::compute_one_oop_map(mh, str.bci(), &mask);
 960       // Check to see if we can grab the number of outgoing arguments
 961       // at an uncommon trap for an invoke (where the compiler
 962       // generates debug info before the invoke has executed)
 963       if (Bytecodes::is_invoke(cur_code)) {
 964         Bytecode_invoke invoke(mh, str.bci());
 965         cur_invoke_parameter_size = invoke.size_of_parameters();
 966         if (!is_top_frame && invoke.has_member_arg()) {
 967           callee_size_of_parameters++;
 968         }
 969       }
 970 
 971       // Verify stack depth and oops in frame
 972       auto match = [&]() {
 973         int iframe_expr_ssize = iframe->interpreter_frame_expression_stack_size();
 974         // This should only be needed for C1
 975         if (is_top_frame && exec_mode == Unpack_exception && iframe_expr_ssize == 0) {
 976           return true;
 977         }
 978         if (reexecute) {
 979           int expr_ssize_before = iframe_expr_ssize + top_frame_expression_stack_adjustment;
 980           int oopmap_expr_invoke_ssize = mask.expression_stack_size() + cur_invoke_parameter_size;
 981           return expr_ssize_before == oopmap_expr_invoke_ssize;
 982         } else {
 983           int oopmap_expr_callee_ssize = mask.expression_stack_size() + callee_size_of_parameters;
 984           return iframe_expr_ssize == oopmap_expr_callee_ssize;
 985         }
 986       };
 987       if (!match()) {
 988         // Print out some information that will help us debug the problem
 989         tty->print_cr("Wrong number of expression stack elements during deoptimization");
 990         tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", frame_idx, cur_array->frames() - 1);
 991         tty->print_cr("  Current code %s", Bytecodes::name(cur_code));
 992         tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
 993                       iframe->interpreter_frame_expression_stack_size());
 994         tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
 995         tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
 996         tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
 997         tty->print_cr("  exec_mode = %d", exec_mode);
 998         tty->print_cr("  original should_reexecute = %s", el->should_reexecute() ? "true" : "false");
 999         tty->print_cr("  reexecute = %s%s", reexecute ? "true" : "false",
1000                       (reexecute != el->should_reexecute()) ? " (changed)" : "");
1001         tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
1002         tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());
1003         tty->print_cr("  Interpreted frames:");
1004         for (int k = 0; k < cur_array->frames(); k++) {
1005           vframeArrayElement* el = cur_array->element(k);
1006           tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
1007         }
1008         cur_array->print_on_2(tty);
1009         guarantee(false, "wrong number of expression stack elements during deopt");
1010       }
1011       VerifyOopClosure verify;
1012       iframe->oops_interpreted_do(&verify, &rm, false);
1013       callee_size_of_parameters = mh->size_of_parameters();
1014     }
1015   }
1016 #endif // !PRODUCT
1017 
1018   return bt;
1019 JRT_END
1020 
1021 class DeoptimizeMarkedHandshakeClosure : public HandshakeClosure {
1022  public:
1023   DeoptimizeMarkedHandshakeClosure() : HandshakeClosure("Deoptimize") {}
1024   void do_thread(Thread* thread) {
1025     JavaThread* jt = JavaThread::cast(thread);
1026     jt->deoptimize_marked_methods();
1027   }
1028 };
1029 
1030 void Deoptimization::deoptimize_all_marked() {
1031   ResourceMark rm;
1032 
1033   // Make the dependent methods not entrant
1034   CodeCache::make_marked_nmethods_deoptimized();
1035 
1036   DeoptimizeMarkedHandshakeClosure deopt;
1037   if (SafepointSynchronize::is_at_safepoint()) {
1038     Threads::java_threads_do(&deopt);
1039   } else {
1040     Handshake::execute(&deopt);
1041   }
1042 }
1043 
1044 Deoptimization::DeoptAction Deoptimization::_unloaded_action
1045   = Deoptimization::Action_reinterpret;
1046 
1047 #ifdef COMPILER2
1048 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
1049   Handle pending_exception(THREAD, thread->pending_exception());
1050   const char* exception_file = thread->exception_file();
1051   int exception_line = thread->exception_line();
1052   thread->clear_pending_exception();
1053 
1054   bool failures = false;
1055 
1056   for (int i = 0; i < objects->length(); i++) {
1057     assert(objects->at(i)->is_object(), "invalid debug information");
1058     ObjectValue* sv = (ObjectValue*) objects->at(i);
1059 
1060     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1061     oop obj = nullptr;
1062 












1063     bool cache_init_error = false;
1064     if (k->is_instance_klass()) {
1065       InstanceKlass* ik = InstanceKlass::cast(k);
1066       if (obj == nullptr && !cache_init_error) {
1067         InternalOOMEMark iom(THREAD);
1068         if (EnableVectorSupport && VectorSupport::is_vector(ik)) {
1069           obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);
1070         } else {
1071           obj = ik->allocate_instance(THREAD);
1072         }
1073       }





1074     } else if (k->is_typeArray_klass()) {
1075       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1076       assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1077       int len = sv->field_size() / type2size[ak->element_type()];
1078       InternalOOMEMark iom(THREAD);
1079       obj = ak->allocate_instance(len, THREAD);
1080     } else if (k->is_objArray_klass()) {
1081       ObjArrayKlass* ak = ObjArrayKlass::cast(k);
1082       InternalOOMEMark iom(THREAD);
1083       obj = ak->allocate_instance(sv->field_size(), THREAD);
1084     }
1085 
1086     if (obj == nullptr) {
1087       failures = true;
1088     }
1089 
1090     assert(sv->value().is_null(), "redundant reallocation");
1091     assert(obj != nullptr || HAS_PENDING_EXCEPTION || cache_init_error, "allocation should succeed or we should get an exception");
1092     CLEAR_PENDING_EXCEPTION;
1093     sv->set_value(obj);
1094   }
1095 
1096   if (failures) {
1097     THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1098   } else if (pending_exception.not_null()) {
1099     thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1100   }
1101 
1102   return failures;
1103 }
1104 















1105 // restore elements of an eliminated type array
1106 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
1107   int index = 0;
1108 
1109   for (int i = 0; i < sv->field_size(); i++) {
1110     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1111     switch(type) {
1112     case T_LONG: case T_DOUBLE: {
1113       assert(value->type() == T_INT, "Agreement.");
1114       StackValue* low =
1115         StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1116 #ifdef _LP64
1117       jlong res = (jlong)low->get_intptr();
1118 #else
1119       jlong res = jlong_from(value->get_jint(), low->get_jint());
1120 #endif
1121       obj->long_at_put(index, res);
1122       break;
1123     }
1124 
1125     case T_INT: case T_FLOAT: { // 4 bytes.
1126       assert(value->type() == T_INT, "Agreement.");
1127       obj->int_at_put(index, value->get_jint());
1128       break;
1129     }
1130 
1131     case T_SHORT:
1132       assert(value->type() == T_INT, "Agreement.");
1133       obj->short_at_put(index, (jshort)value->get_jint());
1134       break;
1135 
1136     case T_CHAR:
1137       assert(value->type() == T_INT, "Agreement.");
1138       obj->char_at_put(index, (jchar)value->get_jint());
1139       break;
1140 
1141     case T_BYTE: {
1142       assert(value->type() == T_INT, "Agreement.");
1143       obj->byte_at_put(index, (jbyte)value->get_jint());
1144       break;
1145     }
1146 
1147     case T_BOOLEAN: {
1148       assert(value->type() == T_INT, "Agreement.");
1149       obj->bool_at_put(index, (jboolean)value->get_jint());
1150       break;
1151     }
1152 
1153       default:
1154         ShouldNotReachHere();
1155     }
1156     index++;
1157   }
1158 }
1159 
1160 // restore fields of an eliminated object array
1161 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1162   for (int i = 0; i < sv->field_size(); i++) {
1163     StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1164     assert(value->type() == T_OBJECT, "object element expected");
1165     obj->obj_at_put(i, value->get_obj()());
1166   }
1167 }
1168 
1169 class ReassignedField {
1170 public:
1171   int _offset;
1172   BasicType _type;



1173 public:
1174   ReassignedField() {
1175     _offset = 0;
1176     _type = T_ILLEGAL;
1177   }
1178 };
1179 
1180 // Gets the fields of `klass` that are eliminated by escape analysis and need to be reassigned
1181 static GrowableArray<ReassignedField>* get_reassigned_fields(InstanceKlass* klass, GrowableArray<ReassignedField>* fields) {
1182   InstanceKlass* super = klass->super();
1183   if (super != nullptr) {
1184     get_reassigned_fields(super, fields);
1185   }
1186   for (AllFieldStream fs(klass); !fs.done(); fs.next()) {
1187     if (!fs.access_flags().is_static() && !fs.field_flags().is_injected()) {
1188       ReassignedField field;
1189       field._offset = fs.offset();
1190       field._type = Signature::basic_type(fs.signature());






1191       fields->append(field);
1192     }
1193   }
1194   return fields;
1195 }
1196 
1197 // Restore fields of an eliminated instance object employing the same field order used by the compiler.
1198 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj) {

1199   GrowableArray<ReassignedField>* fields = get_reassigned_fields(klass, new GrowableArray<ReassignedField>());
1200   for (int i = 0; i < fields->length(); i++) {



















1201     ScopeValue* scope_field = sv->field_at(svIndex);
1202     StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1203     int offset = fields->at(i)._offset;
1204     BasicType type = fields->at(i)._type;
1205     switch (type) {
1206       case T_OBJECT: case T_ARRAY:
1207         assert(value->type() == T_OBJECT, "Agreement.");
1208         obj->obj_field_put(offset, value->get_obj()());
1209         break;
1210 
1211       case T_INT: case T_FLOAT: { // 4 bytes.
1212         assert(value->type() == T_INT, "Agreement.");
1213         bool big_value = false;
1214         if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1215           if (scope_field->is_location()) {
1216             Location::Type type = ((LocationValue*) scope_field)->location().type();
1217             if (type == Location::dbl || type == Location::lng) {
1218               big_value = true;
1219             }
1220           }
1221           if (scope_field->is_constant_int()) {
1222             ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1223             if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1224               big_value = true;
1225             }
1226           }
1227         }
1228 
1229         if (big_value) {
1230           i++;
1231           assert(i < fields->length(), "second T_INT field needed");
1232           assert(fields->at(i)._type == T_INT, "T_INT field needed");
1233         } else {
1234           obj->int_field_put(offset, value->get_jint());
1235           break;
1236         }
1237       }
1238         /* no break */
1239 
1240       case T_LONG: case T_DOUBLE: {
1241         assert(value->type() == T_INT, "Agreement.");
1242         StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));
1243 #ifdef _LP64
1244         jlong res = (jlong)low->get_intptr();
1245 #else
1246         jlong res = jlong_from(value->get_jint(), low->get_jint());
1247 #endif
1248         obj->long_field_put(offset, res);
1249         break;
1250       }
1251 
1252       case T_SHORT:
1253         assert(value->type() == T_INT, "Agreement.");
1254         obj->short_field_put(offset, (jshort)value->get_jint());
1255         break;
1256 
1257       case T_CHAR:
1258         assert(value->type() == T_INT, "Agreement.");
1259         obj->char_field_put(offset, (jchar)value->get_jint());
1260         break;
1261 
1262       case T_BYTE:
1263         assert(value->type() == T_INT, "Agreement.");
1264         obj->byte_field_put(offset, (jbyte)value->get_jint());
1265         break;
1266 
1267       case T_BOOLEAN:
1268         assert(value->type() == T_INT, "Agreement.");
1269         obj->bool_field_put(offset, (jboolean)value->get_jint());
1270         break;
1271 
1272       default:
1273         ShouldNotReachHere();
1274     }
1275     svIndex++;
1276   }
1277   return svIndex;
1278 }
1279 























1280 // restore fields of all eliminated objects and arrays
1281 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
1282   for (int i = 0; i < objects->length(); i++) {
1283     assert(objects->at(i)->is_object(), "invalid debug information");
1284     ObjectValue* sv = (ObjectValue*) objects->at(i);
1285     Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());


1286     Handle obj = sv->value();
1287     assert(obj.not_null() || realloc_failures, "reallocation was missed");
1288 #ifndef PRODUCT
1289     if (PrintDeoptimizationDetails) {
1290       tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1291     }
1292 #endif // !PRODUCT
1293 
1294     if (obj.is_null()) {
1295       continue;
1296     }
1297 
1298     if (EnableVectorSupport && VectorSupport::is_vector(k)) {
1299       assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());
1300       ScopeValue* payload = sv->field_at(0);
1301       if (payload->is_location() &&
1302           payload->as_LocationValue()->location().type() == Location::vector) {
1303 #ifndef PRODUCT
1304         if (PrintDeoptimizationDetails) {
1305           tty->print_cr("skip field reassignment for this vector - it should be assigned already");
1306           if (Verbose) {
1307             Handle obj = sv->value();
1308             k->oop_print_on(obj(), tty);
1309           }
1310         }
1311 #endif // !PRODUCT
1312         continue; // Such vector's value was already restored in VectorSupport::allocate_vector().
1313       }
1314       // Else fall-through to do assignment for scalar-replaced boxed vector representation
1315       // which could be restored after vector object allocation.
1316     }
1317     if (k->is_instance_klass()) {
1318       InstanceKlass* ik = InstanceKlass::cast(k);
1319       reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj());



1320     } else if (k->is_typeArray_klass()) {
1321       TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1322       reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1323     } else if (k->is_objArray_klass()) {
1324       reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1325     }
1326   }
1327   // These objects may escape when we return to Interpreter after deoptimization.
1328   // We need barrier so that stores that initialize these objects can't be reordered
1329   // with subsequent stores that make these objects accessible by other threads.
1330   OrderAccess::storestore();
1331 }
1332 
1333 
1334 // relock objects for which synchronization was eliminated
1335 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,
1336                                     JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {
1337   bool relocked_objects = false;
1338   for (int i = 0; i < monitors->length(); i++) {
1339     MonitorInfo* mon_info = monitors->at(i);
1340     if (mon_info->eliminated()) {
1341       assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1342       relocked_objects = true;
1343       if (!mon_info->owner_is_scalar_replaced()) {
1344         Handle obj(thread, mon_info->owner());
1345         markWord mark = obj->mark();
1346         if (exec_mode == Unpack_none) {
1347           if (mark.has_monitor()) {
1348             // defer relocking if the deoptee thread is currently waiting for obj
1349             ObjectMonitor* waiting_monitor = deoptee_thread->current_waiting_monitor();
1350             if (waiting_monitor != nullptr && waiting_monitor->object() == obj()) {
1351               assert(fr.is_deoptimized_frame(), "frame must be scheduled for deoptimization");
1352               if (UseObjectMonitorTable) {
1353                 mon_info->lock()->clear_object_monitor_cache();
1354               }
1355 #ifdef ASSERT
1356               else {
1357                 assert(!UseObjectMonitorTable, "must be");
1358                 mon_info->lock()->set_bad_monitor_deopt();
1359               }
1360 #endif
1361               JvmtiDeferredUpdates::inc_relock_count_after_wait(deoptee_thread);
1362               continue;
1363             }
1364           }
1365         }
1366         BasicLock* lock = mon_info->lock();
1367         // We have lost information about the correct state of the lock stack.
1368         // Entering may create an invalid lock stack. Inflate the lock if it
1369         // was fast_locked to restore the valid lock stack.
1370         if (UseObjectMonitorTable) {
1371           // UseObjectMonitorTable expects the BasicLock cache to be either a
1372           // valid ObjectMonitor* or nullptr. Right now it is garbage, set it
1373           // to nullptr.
1374           lock->clear_object_monitor_cache();
1375         }
1376         ObjectSynchronizer::enter_for(obj, lock, deoptee_thread);
1377         if (deoptee_thread->lock_stack().contains(obj())) {
1378             ObjectSynchronizer::inflate_fast_locked_object(obj(), ObjectSynchronizer::InflateCause::inflate_cause_vm_internal,
1379                                                            deoptee_thread, thread);
1380         }
1381         assert(mon_info->owner()->is_locked(), "object must be locked now");
1382         assert(obj->mark().has_monitor(), "must be");
1383         assert(!deoptee_thread->lock_stack().contains(obj()), "must be");
1384         assert(ObjectSynchronizer::read_monitor(obj(), obj->mark())->has_owner(deoptee_thread), "must be");
1385       }
1386     }
1387   }
1388   return relocked_objects;
1389 }
1390 #endif // COMPILER2
1391 
1392 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
1393   Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));
1394 
1395   // Register map for next frame (used for stack crawl).  We capture
1396   // the state of the deopt'ing frame's caller.  Thus if we need to
1397   // stuff a C2I adapter we can properly fill in the callee-save
1398   // register locations.
1399   frame caller = fr.sender(reg_map);
1400   int frame_size = pointer_delta_as_int(caller.sp(), fr.sp());
1401 
1402   frame sender = caller;
1403 
1404   // Since the Java thread being deoptimized will eventually adjust it's own stack,
1405   // the vframeArray containing the unpacking information is allocated in the C heap.
1406   // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1407   vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
1408 
1409   // Compare the vframeArray to the collected vframes
1410   assert(array->structural_compare(thread, chunk), "just checking");
1411 
1412   if (TraceDeoptimization) {
1413     ResourceMark rm;
1414     stringStream st;
1415     st.print_cr("DEOPT PACKING thread=" INTPTR_FORMAT " vframeArray=" INTPTR_FORMAT, p2i(thread), p2i(array));
1416     st.print("   ");
1417     fr.print_on(&st);
1418     st.print_cr("   Virtual frames (innermost/newest first):");
1419     for (int index = 0; index < chunk->length(); index++) {
1420       compiledVFrame* vf = chunk->at(index);
1421       int bci = vf->raw_bci();
1422       const char* code_name;
1423       if (bci == SynchronizationEntryBCI) {
1424         code_name = "sync entry";
1425       } else {
1426         Bytecodes::Code code = vf->method()->code_at(bci);
1427         code_name = Bytecodes::name(code);
1428       }
1429 
1430       st.print("      VFrame %d (" INTPTR_FORMAT ")", index, p2i(vf));
1431       st.print(" - %s", vf->method()->name_and_sig_as_C_string());
1432       st.print(" - %s", code_name);
1433       st.print_cr(" @ bci=%d ", bci);
1434     }
1435     tty->print_raw(st.freeze());
1436     tty->cr();
1437   }
1438 
1439   return array;
1440 }
1441 
1442 #ifdef COMPILER2
1443 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
1444   // Reallocation of some scalar replaced objects failed. Record
1445   // that we need to pop all the interpreter frames for the
1446   // deoptimized compiled frame.
1447   assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
1448   thread->set_frames_to_pop_failed_realloc(array->frames());
1449   // Unlock all monitors here otherwise the interpreter will see a
1450   // mix of locked and unlocked monitors (because of failed
1451   // reallocations of synchronized objects) and be confused.
1452   for (int i = 0; i < array->frames(); i++) {
1453     MonitorChunk* monitors = array->element(i)->monitors();
1454     if (monitors != nullptr) {
1455       // Unlock in reverse order starting from most nested monitor.
1456       for (int j = (monitors->number_of_monitors() - 1); j >= 0; j--) {
1457         BasicObjectLock* src = monitors->at(j);
1458         if (src->obj() != nullptr) {
1459           ObjectSynchronizer::exit(src->obj(), src->lock(), thread);
1460         }
1461       }
1462       array->element(i)->free_monitors();
1463 #ifdef ASSERT
1464       array->element(i)->set_removed_monitors();
1465 #endif // ASSERT
1466     }
1467   }
1468 }
1469 #endif // COMPILER2
1470 
1471 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
1472   assert(fr.can_be_deoptimized(), "checking frame type");
1473 
1474   gather_statistics(reason, Action_none, Bytecodes::_illegal);
1475 
1476   if (LogCompilation && xtty != nullptr) {
1477     nmethod* nm = fr.cb()->as_nmethod_or_null();
1478     assert(nm != nullptr, "only compiled methods can deopt");
1479 
1480     ttyLocker ttyl;
1481     xtty->begin_head("deoptimized thread='%zu' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1482     nm->log_identity(xtty);
1483     xtty->end_head();
1484     for (ScopeDesc* sd = nm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1485       xtty->begin_elem("jvms bci='%d'", sd->bci());
1486       xtty->method(sd->method());
1487       xtty->end_elem();
1488       if (sd->is_top())  break;
1489     }
1490     xtty->tail("deoptimized");
1491   }
1492 
1493   Continuation::notify_deopt(thread, fr.sp());
1494 
1495   // Patch the compiled method so that when execution returns to it we will
1496   // deopt the execution state and return to the interpreter.
1497   fr.deoptimize(thread);
1498 }
1499 
1500 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1501   // Deoptimize only if the frame comes from compile code.
1502   // Do not deoptimize the frame which is already patched
1503   // during the execution of the loops below.
1504   if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1505     return;
1506   }
1507   ResourceMark rm;
1508   deoptimize_single_frame(thread, fr, reason);
1509 }
1510 
1511 address Deoptimization::deoptimize_for_missing_exception_handler(nmethod* nm, bool make_not_entrant) {
1512   // there is no exception handler for this pc => deoptimize
1513   if (make_not_entrant) {
1514     nm->make_not_entrant(nmethod::InvalidationReason::MISSING_EXCEPTION_HANDLER);
1515   }
1516 
1517   // Use Deoptimization::deoptimize for all of its side-effects:
1518   // gathering traps statistics, logging...
1519   // it also patches the return pc but we do not care about that
1520   // since we return a continuation to the deopt_blob below.
1521   JavaThread* thread = JavaThread::current();
1522   RegisterMap reg_map(thread,
1523                       RegisterMap::UpdateMap::skip,
1524                       RegisterMap::ProcessFrames::include,
1525                       RegisterMap::WalkContinuation::skip);
1526   frame runtime_frame = thread->last_frame();
1527   frame caller_frame = runtime_frame.sender(&reg_map);
1528   assert(caller_frame.cb()->as_nmethod_or_null() == nm, "expect top frame compiled method");
1529 
1530   Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler);
1531 
1532   return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
1533 }
1534 
1535 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1536   assert(thread == Thread::current() ||
1537          thread->is_handshake_safe_for(Thread::current()) ||
1538          SafepointSynchronize::is_at_safepoint(),
1539          "can only deoptimize other thread at a safepoint/handshake");
1540   // Compute frame and register map based on thread and sp.
1541   RegisterMap reg_map(thread,
1542                       RegisterMap::UpdateMap::skip,
1543                       RegisterMap::ProcessFrames::include,
1544                       RegisterMap::WalkContinuation::skip);
1545   frame fr = thread->last_frame();
1546   while (fr.id() != id) {
1547     fr = fr.sender(&reg_map);
1548   }
1549   deoptimize(thread, fr, reason);
1550 }
1551 
1552 
1553 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1554   Thread* current = Thread::current();
1555   if (thread == current || thread->is_handshake_safe_for(current)) {
1556     Deoptimization::deoptimize_frame_internal(thread, id, reason);
1557   } else {
1558     VM_DeoptimizeFrame deopt(thread, id, reason);
1559     VMThread::execute(&deopt);
1560   }
1561 }
1562 
1563 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
1564   deoptimize_frame(thread, id, Reason_constraint);
1565 }
1566 
1567 // JVMTI PopFrame support
1568 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
1569 {
1570   assert(thread == JavaThread::current(), "pre-condition");
1571   thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
1572 }
1573 JRT_END
1574 
1575 MethodData*
1576 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m,
1577                                 bool create_if_missing) {
1578   JavaThread* THREAD = thread; // For exception macros.
1579   MethodData* mdo = m()->method_data();
1580   if (mdo == nullptr && create_if_missing && !HAS_PENDING_EXCEPTION) {
1581     // Build an MDO.  Ignore errors like OutOfMemory;
1582     // that simply means we won't have an MDO to update.
1583     Method::build_profiling_method_data(m, THREAD);
1584     if (HAS_PENDING_EXCEPTION) {
1585       // Only metaspace OOM is expected. No Java code executed.
1586       assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");
1587       CLEAR_PENDING_EXCEPTION;
1588     }
1589     mdo = m()->method_data();
1590   }
1591   return mdo;
1592 }
1593 
1594 #ifdef COMPILER2
1595 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {
1596   // In case of an unresolved klass entry, load the class.
1597   // This path is exercised from case _ldc in Parse::do_one_bytecode,
1598   // and probably nowhere else.
1599   // Even that case would benefit from simply re-interpreting the
1600   // bytecode, without paying special attention to the class index.
1601   // So this whole "class index" feature should probably be removed.
1602 
1603   if (constant_pool->tag_at(index).is_unresolved_klass()) {
1604     Klass* tk = constant_pool->klass_at(index, THREAD);
1605     if (HAS_PENDING_EXCEPTION) {
1606       // Exception happened during classloading. We ignore the exception here, since it
1607       // is going to be rethrown since the current activation is going to be deoptimized and
1608       // the interpreter will re-execute the bytecode.
1609       // Do not clear probable Async Exceptions.
1610       CLEAR_PENDING_NONASYNC_EXCEPTION;
1611       // Class loading called java code which may have caused a stack
1612       // overflow. If the exception was thrown right before the return
1613       // to the runtime the stack is no longer guarded. Reguard the
1614       // stack otherwise if we return to the uncommon trap blob and the
1615       // stack bang causes a stack overflow we crash.
1616       JavaThread* jt = THREAD;
1617       bool guard_pages_enabled = jt->stack_overflow_state()->reguard_stack_if_needed();
1618       assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
1619     }
1620     return;
1621   }
1622 
1623   assert(!constant_pool->tag_at(index).is_symbol(),
1624          "no symbolic names here, please");
1625 }
1626 
1627 #if INCLUDE_JFR
1628 
1629 class DeoptReasonSerializer : public JfrSerializer {
1630  public:
1631   void serialize(JfrCheckpointWriter& writer) {
1632     writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1)
1633     for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) {
1634       writer.write_key((u8)i);
1635       writer.write(Deoptimization::trap_reason_name(i));
1636     }
1637   }
1638 };
1639 
1640 class DeoptActionSerializer : public JfrSerializer {
1641  public:
1642   void serialize(JfrCheckpointWriter& writer) {
1643     static const u4 nof_actions = Deoptimization::Action_LIMIT;
1644     writer.write_count(nof_actions);
1645     for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) {
1646       writer.write_key(i);
1647       writer.write(Deoptimization::trap_action_name((int)i));
1648     }
1649   }
1650 };
1651 
1652 static void register_serializers() {
1653   static int critical_section = 0;
1654   if (1 == critical_section || AtomicAccess::cmpxchg(&critical_section, 0, 1) == 1) {
1655     return;
1656   }
1657   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer());
1658   JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer());
1659 }
1660 
1661 static void post_deoptimization_event(nmethod* nm,
1662                                       const Method* method,
1663                                       int trap_bci,
1664                                       int instruction,
1665                                       Deoptimization::DeoptReason reason,
1666                                       Deoptimization::DeoptAction action) {
1667   assert(nm != nullptr, "invariant");
1668   assert(method != nullptr, "invariant");
1669   if (EventDeoptimization::is_enabled()) {
1670     static bool serializers_registered = false;
1671     if (!serializers_registered) {
1672       register_serializers();
1673       serializers_registered = true;
1674     }
1675     EventDeoptimization event;
1676     event.set_compileId(nm->compile_id());
1677     event.set_compiler(nm->compiler_type());
1678     event.set_method(method);
1679     event.set_lineNumber(method->line_number_from_bci(trap_bci));
1680     event.set_bci(trap_bci);
1681     event.set_instruction(instruction);
1682     event.set_reason(reason);
1683     event.set_action(action);
1684     event.commit();
1685   }
1686 }
1687 
1688 #endif // INCLUDE_JFR
1689 
1690 static void log_deopt(nmethod* nm, Method* tm, intptr_t pc, frame& fr, int trap_bci,
1691                       const char* reason_name, const char* reason_action, const char* class_name) {
1692   LogTarget(Debug, deoptimization) lt;
1693   if (lt.is_enabled()) {
1694     LogStream ls(lt);
1695     bool is_osr = nm->is_osr_method();
1696     ls.print("cid=%4d %s level=%d",
1697              nm->compile_id(), (is_osr ? "osr" : "   "), nm->comp_level());
1698     ls.print(" %s", tm->name_and_sig_as_C_string());
1699     ls.print(" trap_bci=%d ", trap_bci);
1700     if (is_osr) {
1701       ls.print("osr_bci=%d ", nm->osr_entry_bci());
1702     }
1703     ls.print("%s ", reason_name);
1704     ls.print("%s ", reason_action);
1705     if (class_name != nullptr) {
1706       ls.print("%s ", class_name);
1707     }
1708     ls.print_cr("pc=" INTPTR_FORMAT " relative_pc=" INTPTR_FORMAT,
1709              pc, fr.pc() - nm->code_begin());
1710   }
1711 }
1712 
1713 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* current, jint trap_request)) {
1714   HandleMark hm(current);
1715 
1716   // uncommon_trap() is called at the beginning of the uncommon trap
1717   // handler. Note this fact before we start generating temporary frames
1718   // that can confuse an asynchronous stack walker. This counter is
1719   // decremented at the end of unpack_frames().
1720 
1721   current->inc_in_deopt_handler();
1722 
1723   RegisterMap reg_map(current,
1724                       RegisterMap::UpdateMap::skip,
1725                       RegisterMap::ProcessFrames::include,
1726                       RegisterMap::WalkContinuation::skip);
1727   frame stub_frame = current->last_frame();
1728   frame fr = stub_frame.sender(&reg_map);
1729 
1730   // Log a message
1731   Events::log_deopt_message(current, "Uncommon trap: trap_request=" INT32_FORMAT_X_0 " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,
1732               trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());
1733 
1734   {
1735     ResourceMark rm;
1736 
1737     DeoptReason reason = trap_request_reason(trap_request);
1738     DeoptAction action = trap_request_action(trap_request);
1739     jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
1740 
1741     vframe*  vf  = vframe::new_vframe(&fr, &reg_map, current);
1742     compiledVFrame* cvf = compiledVFrame::cast(vf);
1743 
1744     nmethod* nm = cvf->code();
1745 
1746     ScopeDesc*      trap_scope  = cvf->scope();
1747 
1748     bool is_receiver_constraint_failure = COMPILER2_PRESENT(VerifyReceiverTypes &&) (reason == Deoptimization::Reason_receiver_constraint);
1749 
1750     if (is_receiver_constraint_failure) {
1751       tty->print_cr("  bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT ", method=%s", trap_scope->bci(),
1752                     p2i(fr.pc()), fr.pc() - nm->code_begin(), trap_scope->method()->name_and_sig_as_C_string());
1753     }
1754 
1755     methodHandle    trap_method(current, trap_scope->method());
1756     int             trap_bci    = trap_scope->bci();
1757     Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
1758     // Record this event in the histogram.
1759     gather_statistics(reason, action, trap_bc);
1760 
1761     // Ensure that we can record deopt. history:
1762     bool create_if_missing = ProfileTraps;
1763 
1764     methodHandle profiled_method;
1765     profiled_method = trap_method;
1766 
1767     MethodData* trap_mdo =
1768       get_method_data(current, profiled_method, create_if_missing);
1769 
1770     Symbol* class_name = nullptr;
1771     bool unresolved = false;
1772     if (unloaded_class_index >= 0) {
1773       constantPoolHandle constants (current, trap_method->constants());
1774       if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
1775         class_name = constants->klass_name_at(unloaded_class_index);
1776         unresolved = true;
1777       } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
1778         class_name = constants->symbol_at(unloaded_class_index);
1779       }
1780     }
1781     { // Log Deoptimization event for JFR, UL and event system
1782       Method* tm = trap_method();
1783       const char* reason_name = trap_reason_name(reason);
1784       const char* reason_action = trap_action_name(action);
1785       intptr_t pc = p2i(fr.pc());
1786 
1787       JFR_ONLY(post_deoptimization_event(nm, tm, trap_bci, trap_bc, reason, action);)
1788 
1789       ResourceMark rm;
1790 
1791       const char* class_name_str = nullptr;
1792       const char* class_name_msg = nullptr;
1793       stringStream st, stm;
1794       if (class_name != nullptr) {
1795         class_name->print_symbol_on(&st);
1796         class_name_str = st.freeze();
1797         stm.print("class=%s ", class_name_str);
1798         class_name_msg = stm.freeze();
1799       } else {
1800         class_name_msg = "";
1801       }
1802       log_deopt(nm, tm, pc, fr, trap_bci, reason_name, reason_action, class_name_str);
1803       Events::log_deopt_message(current, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s%s",
1804                                 reason_name, reason_action, pc,
1805                                 tm->name_and_sig_as_C_string(), trap_bci, class_name_msg, nm->compiler_name());
1806     }
1807 
1808     // Print a bunch of diagnostics, if requested.
1809     if (TraceDeoptimization || LogCompilation || is_receiver_constraint_failure) {
1810       ResourceMark rm;
1811 
1812       // Lock to read ProfileData, and ensure lock is not broken by a safepoint
1813       // We must do this already now, since we cannot acquire this lock while
1814       // holding the tty lock (lock ordering by rank).
1815       ConditionalMutexLocker ml((trap_mdo != nullptr) ? trap_mdo->extra_data_lock() : nullptr,
1816                                 (trap_mdo != nullptr),
1817                                 Mutex::_no_safepoint_check_flag);
1818 
1819       ttyLocker ttyl;
1820 
1821       char buf[100];
1822       if (xtty != nullptr) {
1823         xtty->begin_head("uncommon_trap thread='%zu' %s",
1824                          os::current_thread_id(),
1825                          format_trap_request(buf, sizeof(buf), trap_request));
1826         nm->log_identity(xtty);
1827       }
1828       if (class_name != nullptr) {
1829         if (xtty != nullptr) {
1830           if (unresolved) {
1831             xtty->print(" unresolved='1'");
1832           }
1833           xtty->name(class_name);
1834         }
1835       }
1836       if (xtty != nullptr && trap_mdo != nullptr && (int)reason < (int)MethodData::_trap_hist_limit) {
1837         // Dump the relevant MDO state.
1838         // This is the deopt count for the current reason, any previous
1839         // reasons or recompiles seen at this point.
1840         int dcnt = trap_mdo->trap_count(reason);
1841         if (dcnt != 0)
1842           xtty->print(" count='%d'", dcnt);
1843 
1844         // We need to lock to read the ProfileData. But to keep the locks ordered, we need to
1845         // lock extra_data_lock before the tty lock.
1846         ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
1847         int dos = (pdata == nullptr)? 0: pdata->trap_state();
1848         if (dos != 0) {
1849           xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
1850           if (trap_state_is_recompiled(dos)) {
1851             int recnt2 = trap_mdo->overflow_recompile_count();
1852             if (recnt2 != 0)
1853               xtty->print(" recompiles2='%d'", recnt2);
1854           }
1855         }
1856       }
1857       if (xtty != nullptr) {
1858         xtty->stamp();
1859         xtty->end_head();
1860       }
1861       if (TraceDeoptimization) {  // make noise on the tty
1862         stringStream st;
1863         st.print("UNCOMMON TRAP method=%s", trap_scope->method()->name_and_sig_as_C_string());
1864         st.print("  bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT,
1865                  trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin());
1866         st.print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id());
1867         st.print(" (@" INTPTR_FORMAT ") thread=%zu reason=%s action=%s unloaded_class_index=%d",
1868                    p2i(fr.pc()),
1869                    os::current_thread_id(),
1870                    trap_reason_name(reason),
1871                    trap_action_name(action),
1872                    unloaded_class_index
1873                    );
1874         if (class_name != nullptr) {
1875           st.print(unresolved ? " unresolved class: " : " symbol: ");
1876           class_name->print_symbol_on(&st);
1877         }
1878         st.cr();
1879         tty->print_raw(st.freeze());
1880       }
1881       if (xtty != nullptr) {
1882         // Log the precise location of the trap.
1883         for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
1884           xtty->begin_elem("jvms bci='%d'", sd->bci());
1885           xtty->method(sd->method());
1886           xtty->end_elem();
1887           if (sd->is_top())  break;
1888         }
1889         xtty->tail("uncommon_trap");
1890       }
1891     }
1892     // (End diagnostic printout.)
1893 
1894     if (is_receiver_constraint_failure) {
1895       fatal("missing receiver type check");
1896     }
1897 
1898     // Load class if necessary
1899     if (unloaded_class_index >= 0) {
1900       constantPoolHandle constants(current, trap_method->constants());
1901       load_class_by_index(constants, unloaded_class_index, THREAD);
1902     }
1903 
1904     // Flush the nmethod if necessary and desirable.
1905     //
1906     // We need to avoid situations where we are re-flushing the nmethod
1907     // because of a hot deoptimization site.  Repeated flushes at the same
1908     // point need to be detected by the compiler and avoided.  If the compiler
1909     // cannot avoid them (or has a bug and "refuses" to avoid them), this
1910     // module must take measures to avoid an infinite cycle of recompilation
1911     // and deoptimization.  There are several such measures:
1912     //
1913     //   1. If a recompilation is ordered a second time at some site X
1914     //   and for the same reason R, the action is adjusted to 'reinterpret',
1915     //   to give the interpreter time to exercise the method more thoroughly.
1916     //   If this happens, the method's overflow_recompile_count is incremented.
1917     //
1918     //   2. If the compiler fails to reduce the deoptimization rate, then
1919     //   the method's overflow_recompile_count will begin to exceed the set
1920     //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
1921     //   is adjusted to 'make_not_compilable', and the method is abandoned
1922     //   to the interpreter.  This is a performance hit for hot methods,
1923     //   but is better than a disastrous infinite cycle of recompilations.
1924     //   (Actually, only the method containing the site X is abandoned.)
1925     //
1926     //   3. In parallel with the previous measures, if the total number of
1927     //   recompilations of a method exceeds the much larger set limit
1928     //   PerMethodRecompilationCutoff, the method is abandoned.
1929     //   This should only happen if the method is very large and has
1930     //   many "lukewarm" deoptimizations.  The code which enforces this
1931     //   limit is elsewhere (class nmethod, class Method).
1932     //
1933     // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
1934     // to recompile at each bytecode independently of the per-BCI cutoff.
1935     //
1936     // The decision to update code is up to the compiler, and is encoded
1937     // in the Action_xxx code.  If the compiler requests Action_none
1938     // no trap state is changed, no compiled code is changed, and the
1939     // computation suffers along in the interpreter.
1940     //
1941     // The other action codes specify various tactics for decompilation
1942     // and recompilation.  Action_maybe_recompile is the loosest, and
1943     // allows the compiled code to stay around until enough traps are seen,
1944     // and until the compiler gets around to recompiling the trapping method.
1945     //
1946     // The other actions cause immediate removal of the present code.
1947 
1948     // Traps caused by injected profile shouldn't pollute trap counts.
1949     bool injected_profile_trap = trap_method->has_injected_profile() &&
1950                                  (reason == Reason_intrinsic || reason == Reason_unreached);
1951 
1952     bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;
1953     bool make_not_entrant = false;
1954     bool make_not_compilable = false;
1955     bool reprofile = false;
1956     switch (action) {
1957     case Action_none:
1958       // Keep the old code.
1959       update_trap_state = false;
1960       break;
1961     case Action_maybe_recompile:
1962       // Do not need to invalidate the present code, but we can
1963       // initiate another
1964       // Start compiler without (necessarily) invalidating the nmethod.
1965       // The system will tolerate the old code, but new code should be
1966       // generated when possible.
1967       break;
1968     case Action_reinterpret:
1969       // Go back into the interpreter for a while, and then consider
1970       // recompiling form scratch.
1971       make_not_entrant = true;
1972       // Reset invocation counter for outer most method.
1973       // This will allow the interpreter to exercise the bytecodes
1974       // for a while before recompiling.
1975       // By contrast, Action_make_not_entrant is immediate.
1976       //
1977       // Note that the compiler will track null_check, null_assert,
1978       // range_check, and class_check events and log them as if they
1979       // had been traps taken from compiled code.  This will update
1980       // the MDO trap history so that the next compilation will
1981       // properly detect hot trap sites.
1982       reprofile = true;
1983       break;
1984     case Action_make_not_entrant:
1985       // Request immediate recompilation, and get rid of the old code.
1986       // Make them not entrant, so next time they are called they get
1987       // recompiled.  Unloaded classes are loaded now so recompile before next
1988       // time they are called.  Same for uninitialized.  The interpreter will
1989       // link the missing class, if any.
1990       make_not_entrant = true;
1991       break;
1992     case Action_make_not_compilable:
1993       // Give up on compiling this method at all.
1994       make_not_entrant = true;
1995       make_not_compilable = true;
1996       break;
1997     default:
1998       ShouldNotReachHere();
1999     }
2000 
2001     // Setting +ProfileTraps fixes the following, on all platforms:
2002     // The result is infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
2003     // recompile relies on a MethodData* to record heroic opt failures.
2004 
2005     // Whether the interpreter is producing MDO data or not, we also need
2006     // to use the MDO to detect hot deoptimization points and control
2007     // aggressive optimization.
2008     bool inc_recompile_count = false;
2009 
2010     // Lock to read ProfileData, and ensure lock is not broken by a safepoint
2011     ConditionalMutexLocker ml((trap_mdo != nullptr) ? trap_mdo->extra_data_lock() : nullptr,
2012                               (trap_mdo != nullptr),
2013                               Mutex::_no_safepoint_check_flag);
2014     ProfileData* pdata = nullptr;
2015     if (ProfileTraps && CompilerConfig::is_c2_enabled() && update_trap_state && trap_mdo != nullptr) {
2016       assert(trap_mdo == get_method_data(current, profiled_method, false), "sanity");
2017       uint this_trap_count = 0;
2018       bool maybe_prior_trap = false;
2019       bool maybe_prior_recompile = false;
2020 
2021       pdata = query_update_method_data(trap_mdo, trap_bci, reason, nm->method(),
2022                                    //outputs:
2023                                    this_trap_count,
2024                                    maybe_prior_trap,
2025                                    maybe_prior_recompile);
2026       // Because the interpreter also counts null, div0, range, and class
2027       // checks, these traps from compiled code are double-counted.
2028       // This is harmless; it just means that the PerXTrapLimit values
2029       // are in effect a little smaller than they look.
2030 
2031       DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2032       if (per_bc_reason != Reason_none) {
2033         // Now take action based on the partially known per-BCI history.
2034         if (maybe_prior_trap
2035             && this_trap_count >= (uint)PerBytecodeTrapLimit) {
2036           // If there are too many traps at this BCI, force a recompile.
2037           // This will allow the compiler to see the limit overflow, and
2038           // take corrective action, if possible.  The compiler generally
2039           // does not use the exact PerBytecodeTrapLimit value, but instead
2040           // changes its tactics if it sees any traps at all.  This provides
2041           // a little hysteresis, delaying a recompile until a trap happens
2042           // several times.
2043           //
2044           // Actually, since there is only one bit of counter per BCI,
2045           // the possible per-BCI counts are {0,1,(per-method count)}.
2046           // This produces accurate results if in fact there is only
2047           // one hot trap site, but begins to get fuzzy if there are
2048           // many sites.  For example, if there are ten sites each
2049           // trapping two or more times, they each get the blame for
2050           // all of their traps.
2051           make_not_entrant = true;
2052         }
2053 
2054         // Detect repeated recompilation at the same BCI, and enforce a limit.
2055         if (make_not_entrant && maybe_prior_recompile) {
2056           // More than one recompile at this point.
2057           inc_recompile_count = maybe_prior_trap;
2058         }
2059       } else {
2060         // For reasons which are not recorded per-bytecode, we simply
2061         // force recompiles unconditionally.
2062         // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
2063         make_not_entrant = true;
2064       }
2065 
2066       // Go back to the compiler if there are too many traps in this method.
2067       if (this_trap_count >= per_method_trap_limit(reason)) {
2068         // If there are too many traps in this method, force a recompile.
2069         // This will allow the compiler to see the limit overflow, and
2070         // take corrective action, if possible.
2071         // (This condition is an unlikely backstop only, because the
2072         // PerBytecodeTrapLimit is more likely to take effect first,
2073         // if it is applicable.)
2074         make_not_entrant = true;
2075       }
2076 
2077       // Here's more hysteresis:  If there has been a recompile at
2078       // this trap point already, run the method in the interpreter
2079       // for a while to exercise it more thoroughly.
2080       if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
2081         reprofile = true;
2082       }
2083     }
2084 
2085     // Take requested actions on the method:
2086 
2087     // Recompile
2088     if (make_not_entrant) {
2089       if (!nm->make_not_entrant(nmethod::InvalidationReason::UNCOMMON_TRAP)) {
2090         return; // the call did not change nmethod's state
2091       }
2092 
2093       if (pdata != nullptr) {
2094         // Record the recompilation event, if any.
2095         int tstate0 = pdata->trap_state();
2096         int tstate1 = trap_state_set_recompiled(tstate0, true);
2097         if (tstate1 != tstate0)
2098           pdata->set_trap_state(tstate1);
2099       }
2100 
2101       // For code aging we count traps separately here, using make_not_entrant()
2102       // as a guard against simultaneous deopts in multiple threads.
2103       if (reason == Reason_tenured && trap_mdo != nullptr) {
2104         trap_mdo->inc_tenure_traps();
2105       }
2106     }
2107     if (inc_recompile_count) {
2108       trap_mdo->inc_overflow_recompile_count();
2109       if ((uint)trap_mdo->overflow_recompile_count() >
2110           (uint)PerBytecodeRecompilationCutoff) {
2111         // Give up on the method containing the bad BCI.
2112         if (trap_method() == nm->method()) {
2113           make_not_compilable = true;
2114         } else {
2115           trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization);
2116           // But give grace to the enclosing nm->method().
2117         }
2118       }
2119     }
2120 
2121     // Reprofile
2122     if (reprofile) {
2123       CompilationPolicy::reprofile(trap_scope, nm->is_osr_method());
2124     }
2125 
2126     // Give up compiling
2127     if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
2128       assert(make_not_entrant, "consistent");
2129       nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization);
2130     }
2131 
2132     if (ProfileExceptionHandlers && trap_mdo != nullptr) {
2133       BitData* exception_handler_data = trap_mdo->exception_handler_bci_to_data_or_null(trap_bci);
2134       if (exception_handler_data != nullptr) {
2135         // uncommon trap at the start of an exception handler.
2136         // C2 generates these for un-entered exception handlers.
2137         // mark the handler as entered to avoid generating
2138         // another uncommon trap the next time the handler is compiled
2139         exception_handler_data->set_exception_handler_entered();
2140       }
2141     }
2142 
2143   } // Free marked resources
2144 
2145 }
2146 JRT_END
2147 
2148 ProfileData*
2149 Deoptimization::query_update_method_data(MethodData* trap_mdo,
2150                                          int trap_bci,
2151                                          Deoptimization::DeoptReason reason,
2152                                          Method* compiled_method,
2153                                          //outputs:
2154                                          uint& ret_this_trap_count,
2155                                          bool& ret_maybe_prior_trap,
2156                                          bool& ret_maybe_prior_recompile) {
2157   trap_mdo->check_extra_data_locked();
2158 
2159   bool maybe_prior_trap = false;
2160   bool maybe_prior_recompile = false;
2161   uint this_trap_count = 0;
2162   uint idx = reason;
2163   uint prior_trap_count = trap_mdo->trap_count(idx);
2164   this_trap_count  = trap_mdo->inc_trap_count(idx);
2165 
2166   // If the runtime cannot find a place to store trap history,
2167   // it is estimated based on the general condition of the method.
2168   // If the method has ever been recompiled, or has ever incurred
2169   // a trap with the present reason , then this BCI is assumed
2170   // (pessimistically) to be the culprit.
2171   maybe_prior_trap      = (prior_trap_count != 0);
2172   maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
2173   ProfileData* pdata = nullptr;
2174 
2175 
2176   // For reasons which are recorded per bytecode, we check per-BCI data.
2177   DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2178   if (per_bc_reason != Reason_none) {
2179     // Find the profile data for this BCI.  If there isn't one,
2180     // try to allocate one from the MDO's set of spares.
2181     // This will let us detect a repeated trap at this point.
2182     pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : nullptr);
2183 
2184     if (pdata != nullptr) {
2185       if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
2186         if (LogCompilation && xtty != nullptr) {
2187           ttyLocker ttyl;
2188           // no more room for speculative traps in this MDO
2189           xtty->elem("speculative_traps_oom");
2190         }
2191       }
2192       // Query the trap state of this profile datum.
2193       int tstate0 = pdata->trap_state();
2194       if (!trap_state_has_reason(tstate0, per_bc_reason))
2195         maybe_prior_trap = false;
2196       if (!trap_state_is_recompiled(tstate0))
2197         maybe_prior_recompile = false;
2198 
2199       // Update the trap state of this profile datum.
2200       int tstate1 = tstate0;
2201       // Record the reason.
2202       tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
2203       // Store the updated state on the MDO, for next time.
2204       if (tstate1 != tstate0)
2205         pdata->set_trap_state(tstate1);
2206     } else {
2207       if (LogCompilation && xtty != nullptr) {
2208         ttyLocker ttyl;
2209         // Missing MDP?  Leave a small complaint in the log.
2210         xtty->elem("missing_mdp bci='%d'", trap_bci);
2211       }
2212     }
2213   }
2214 
2215   // Return results:
2216   ret_this_trap_count = this_trap_count;
2217   ret_maybe_prior_trap = maybe_prior_trap;
2218   ret_maybe_prior_recompile = maybe_prior_recompile;
2219   return pdata;
2220 }
2221 
2222 void
2223 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2224   ResourceMark rm;
2225   // Ignored outputs:
2226   uint ignore_this_trap_count;
2227   bool ignore_maybe_prior_trap;
2228   bool ignore_maybe_prior_recompile;
2229   assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
2230 
2231   // Lock to read ProfileData, and ensure lock is not broken by a safepoint
2232   MutexLocker ml(trap_mdo->extra_data_lock(), Mutex::_no_safepoint_check_flag);
2233 
2234   query_update_method_data(trap_mdo, trap_bci,
2235                            (DeoptReason)reason,
2236                            nullptr,
2237                            ignore_this_trap_count,
2238                            ignore_maybe_prior_trap,
2239                            ignore_maybe_prior_recompile);
2240 }
2241 
2242 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* current, jint trap_request, jint exec_mode) {
2243   // Enable WXWrite: current function is called from methods compiled by C2 directly
2244   MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
2245 
2246   // Still in Java no safepoints
2247   {
2248     // This enters VM and may safepoint
2249     uncommon_trap_inner(current, trap_request);
2250   }
2251   HandleMark hm(current);
2252   return fetch_unroll_info_helper(current, exec_mode);
2253 }
2254 
2255 // Local derived constants.
2256 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2257 const int DS_REASON_MASK   = ((uint)DataLayout::trap_mask) >> 1;
2258 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2259 
2260 //---------------------------trap_state_reason---------------------------------
2261 Deoptimization::DeoptReason
2262 Deoptimization::trap_state_reason(int trap_state) {
2263   // This assert provides the link between the width of DataLayout::trap_bits
2264   // and the encoding of "recorded" reasons.  It ensures there are enough
2265   // bits to store all needed reasons in the per-BCI MDO profile.
2266   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2267   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2268   trap_state -= recompile_bit;
2269   if (trap_state == DS_REASON_MASK) {
2270     return Reason_many;
2271   } else {
2272     assert((int)Reason_none == 0, "state=0 => Reason_none");
2273     return (DeoptReason)trap_state;
2274   }
2275 }
2276 //-------------------------trap_state_has_reason-------------------------------
2277 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2278   assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
2279   assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2280   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2281   trap_state -= recompile_bit;
2282   if (trap_state == DS_REASON_MASK) {
2283     return -1;  // true, unspecifically (bottom of state lattice)
2284   } else if (trap_state == reason) {
2285     return 1;   // true, definitely
2286   } else if (trap_state == 0) {
2287     return 0;   // false, definitely (top of state lattice)
2288   } else {
2289     return 0;   // false, definitely
2290   }
2291 }
2292 //-------------------------trap_state_add_reason-------------------------------
2293 int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
2294   assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
2295   int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2296   trap_state -= recompile_bit;
2297   if (trap_state == DS_REASON_MASK) {
2298     return trap_state + recompile_bit;     // already at state lattice bottom
2299   } else if (trap_state == reason) {
2300     return trap_state + recompile_bit;     // the condition is already true
2301   } else if (trap_state == 0) {
2302     return reason + recompile_bit;          // no condition has yet been true
2303   } else {
2304     return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
2305   }
2306 }
2307 //-----------------------trap_state_is_recompiled------------------------------
2308 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2309   return (trap_state & DS_RECOMPILE_BIT) != 0;
2310 }
2311 //-----------------------trap_state_set_recompiled-----------------------------
2312 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
2313   if (z)  return trap_state |  DS_RECOMPILE_BIT;
2314   else    return trap_state & ~DS_RECOMPILE_BIT;
2315 }
2316 //---------------------------format_trap_state---------------------------------
2317 // This is used for debugging and diagnostics, including LogFile output.
2318 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2319                                               int trap_state) {
2320   assert(buflen > 0, "sanity");
2321   DeoptReason reason      = trap_state_reason(trap_state);
2322   bool        recomp_flag = trap_state_is_recompiled(trap_state);
2323   // Re-encode the state from its decoded components.
2324   int decoded_state = 0;
2325   if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
2326     decoded_state = trap_state_add_reason(decoded_state, reason);
2327   if (recomp_flag)
2328     decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
2329   // If the state re-encodes properly, format it symbolically.
2330   // Because this routine is used for debugging and diagnostics,
2331   // be robust even if the state is a strange value.
2332   size_t len;
2333   if (decoded_state != trap_state) {
2334     // Random buggy state that doesn't decode??
2335     len = jio_snprintf(buf, buflen, "#%d", trap_state);
2336   } else {
2337     len = jio_snprintf(buf, buflen, "%s%s",
2338                        trap_reason_name(reason),
2339                        recomp_flag ? " recompiled" : "");
2340   }
2341   return buf;
2342 }
2343 
2344 
2345 //--------------------------------statics--------------------------------------
2346 const char* Deoptimization::_trap_reason_name[] = {
2347   // Note:  Keep this in sync. with enum DeoptReason.
2348   "none",
2349   "null_check",
2350   "null_assert",
2351   "range_check",
2352   "class_check",
2353   "array_check",
2354   "intrinsic",
2355   "bimorphic",
2356   "profile_predicate",
2357   "auto_vectorization_check",
2358   "unloaded",
2359   "uninitialized",
2360   "initialized",
2361   "unreached",
2362   "unhandled",
2363   "constraint",
2364   "div0_check",
2365   "age",
2366   "predicate",
2367   "loop_limit_check",
2368   "speculate_class_check",
2369   "speculate_null_check",
2370   "speculate_null_assert",
2371   "unstable_if",
2372   "unstable_fused_if",
2373   "receiver_constraint",
2374   "not_compiled_exception_handler",
2375   "short_running_loop",
2376   "tenured"
2377 };
2378 const char* Deoptimization::_trap_action_name[] = {
2379   // Note:  Keep this in sync. with enum DeoptAction.
2380   "none",
2381   "maybe_recompile",
2382   "reinterpret",
2383   "make_not_entrant",
2384   "make_not_compilable"
2385 };
2386 
2387 const char* Deoptimization::trap_reason_name(int reason) {
2388   // Check that every reason has a name
2389   STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);
2390 
2391   if (reason == Reason_many)  return "many";
2392   if ((uint)reason < Reason_LIMIT)
2393     return _trap_reason_name[reason];
2394   static char buf[20];
2395   os::snprintf_checked(buf, sizeof(buf), "reason%d", reason);
2396   return buf;
2397 }
2398 const char* Deoptimization::trap_action_name(int action) {
2399   // Check that every action has a name
2400   STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);
2401 
2402   if ((uint)action < Action_LIMIT)
2403     return _trap_action_name[action];
2404   static char buf[20];
2405   os::snprintf_checked(buf, sizeof(buf), "action%d", action);
2406   return buf;
2407 }
2408 
2409 // This is used for debugging and diagnostics, including LogFile output.
2410 const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
2411                                                 int trap_request) {
2412   jint unloaded_class_index = trap_request_index(trap_request);
2413   const char* reason = trap_reason_name(trap_request_reason(trap_request));
2414   const char* action = trap_action_name(trap_request_action(trap_request));
2415   size_t len;
2416   if (unloaded_class_index < 0) {
2417     len = jio_snprintf(buf, buflen, "reason='%s' action='%s'", reason, action);
2418   } else {
2419     len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'",
2420                        reason, action, unloaded_class_index);
2421   }
2422   return buf;
2423 }
2424 
2425 juint Deoptimization::_deoptimization_hist
2426         [Deoptimization::Reason_LIMIT]
2427     [1 + Deoptimization::Action_LIMIT]
2428         [Deoptimization::BC_CASE_LIMIT]
2429   = {0};
2430 
2431 enum {
2432   LSB_BITS = 8,
2433   LSB_MASK = right_n_bits(LSB_BITS)
2434 };
2435 
2436 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2437                                        Bytecodes::Code bc) {
2438   assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2439   assert(action >= 0 && action < Action_LIMIT, "oob");
2440   _deoptimization_hist[Reason_none][0][0] += 1;  // total
2441   _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
2442   juint* cases = _deoptimization_hist[reason][1+action];
2443   juint* bc_counter_addr = nullptr;
2444   juint  bc_counter      = 0;
2445   // Look for an unused counter, or an exact match to this BC.
2446   if (bc != Bytecodes::_illegal) {
2447     for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2448       juint* counter_addr = &cases[bc_case];
2449       juint  counter = *counter_addr;
2450       if ((counter == 0 && bc_counter_addr == nullptr)
2451           || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
2452         // this counter is either free or is already devoted to this BC
2453         bc_counter_addr = counter_addr;
2454         bc_counter = counter | bc;
2455       }
2456     }
2457   }
2458   if (bc_counter_addr == nullptr) {
2459     // Overflow, or no given bytecode.
2460     bc_counter_addr = &cases[BC_CASE_LIMIT-1];
2461     bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
2462   }
2463   *bc_counter_addr = bc_counter + (1 << LSB_BITS);
2464 }
2465 
2466 jint Deoptimization::total_deoptimization_count() {
2467   return _deoptimization_hist[Reason_none][0][0];
2468 }
2469 
2470 // Get the deopt count for a specific reason and a specific action. If either
2471 // one of 'reason' or 'action' is null, the method returns the sum of all
2472 // deoptimizations with the specific 'action' or 'reason' respectively.
2473 // If both arguments are null, the method returns the total deopt count.
2474 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
2475   if (reason_str == nullptr && action_str == nullptr) {
2476     return total_deoptimization_count();
2477   }
2478   juint counter = 0;
2479   for (int reason = 0; reason < Reason_LIMIT; reason++) {
2480     if (reason_str == nullptr || !strcmp(reason_str, trap_reason_name(reason))) {
2481       for (int action = 0; action < Action_LIMIT; action++) {
2482         if (action_str == nullptr || !strcmp(action_str, trap_action_name(action))) {
2483           juint* cases = _deoptimization_hist[reason][1+action];
2484           for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2485             counter += cases[bc_case] >> LSB_BITS;
2486           }
2487         }
2488       }
2489     }
2490   }
2491   return counter;
2492 }
2493 
2494 void Deoptimization::print_statistics() {
2495   juint total = total_deoptimization_count();
2496   juint account = total;
2497   if (total != 0) {
2498     ttyLocker ttyl;
2499     if (xtty != nullptr)  xtty->head("statistics type='deoptimization'");
2500     tty->print_cr("Deoptimization traps recorded:");
2501     #define PRINT_STAT_LINE(name, r) \
2502       tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
2503     PRINT_STAT_LINE("total", total);
2504     // For each non-zero entry in the histogram, print the reason,
2505     // the action, and (if specifically known) the type of bytecode.
2506     for (int reason = 0; reason < Reason_LIMIT; reason++) {
2507       for (int action = 0; action < Action_LIMIT; action++) {
2508         juint* cases = _deoptimization_hist[reason][1+action];
2509         for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2510           juint counter = cases[bc_case];
2511           if (counter != 0) {
2512             char name[1*K];
2513             Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
2514             os::snprintf_checked(name, sizeof(name), "%s/%s/%s",
2515                     trap_reason_name(reason),
2516                     trap_action_name(action),
2517                     Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
2518             juint r = counter >> LSB_BITS;
2519             tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
2520             account -= r;
2521           }
2522         }
2523       }
2524     }
2525     if (account != 0) {
2526       PRINT_STAT_LINE("unaccounted", account);
2527     }
2528     #undef PRINT_STAT_LINE
2529     if (xtty != nullptr)  xtty->tail("statistics");
2530   }
2531 }
2532 
2533 #else // COMPILER2
2534 
2535 // Stubs for C1 only system.
2536 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2537   return false;
2538 }
2539 
2540 const char* Deoptimization::trap_reason_name(int reason) {
2541   return "unknown";
2542 }
2543 
2544 jint Deoptimization::total_deoptimization_count() {
2545   return 0;
2546 }
2547 
2548 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
2549   return 0;
2550 }
2551 
2552 void Deoptimization::print_statistics() {
2553   // no output
2554 }
2555 
2556 void
2557 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2558   // no update
2559 }
2560 
2561 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2562   return 0;
2563 }
2564 
2565 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2566                                        Bytecodes::Code bc) {
2567   // no update
2568 }
2569 
2570 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2571                                               int trap_state) {
2572   jio_snprintf(buf, buflen, "#%d", trap_state);
2573   return buf;
2574 }
2575 
2576 #endif // COMPILER2
--- EOF ---