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