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