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