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