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