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