src/share/vm/runtime/deoptimization.cpp

Thu, 29 Sep 2016 09:54:38 +0800

author
aoqi
date
Thu, 29 Sep 2016 09:54:38 +0800
changeset 123
c7fdbe297c7c
parent 1
2d8a650513c2
child 6876
710a3c8b516e
permissions
-rw-r--r--

8049252: VerifyStack logic in Deoptimization::unpack_frames does not expect to see invoke bc at the top frame during normal deoptimization
see: http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/rev/e0c6fadce66e

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

mercurial