deoptimization.cpp revision 3602:da91efe96a93
18281Sjkh/*
28281Sjkh * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
38281Sjkh * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
48281Sjkh *
58281Sjkh * This code is free software; you can redistribute it and/or modify it
68281Sjkh * under the terms of the GNU General Public License version 2 only, as
739847Sjkh * published by the Free Software Foundation.
88281Sjkh *
98281Sjkh * This code is distributed in the hope that it will be useful, but WITHOUT
108281Sjkh * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
118281Sjkh * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
128281Sjkh * version 2 for more details (a copy is included in the LICENSE file that
138281Sjkh * accompanied this code).
148281Sjkh *
158281Sjkh * You should have received a copy of the GNU General Public License version
168881Srgrimes * 2 along with this work; if not, write to the Free Software Foundation,
178881Srgrimes * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
188281Sjkh *
198281Sjkh * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
208281Sjkh * or visit www.oracle.com if you need additional information or have any
218281Sjkh * questions.
228281Sjkh *
238281Sjkh */
248281Sjkh
258281Sjkh#include "precompiled.hpp"
268281Sjkh#include "classfile/systemDictionary.hpp"
278281Sjkh#include "code/debugInfoRec.hpp"
288281Sjkh#include "code/nmethod.hpp"
298281Sjkh#include "code/pcDesc.hpp"
308281Sjkh#include "code/scopeDesc.hpp"
318281Sjkh#include "interpreter/bytecode.hpp"
328281Sjkh#include "interpreter/interpreter.hpp"
338281Sjkh#include "interpreter/oopMapCache.hpp"
348281Sjkh#include "memory/allocation.inline.hpp"
358281Sjkh#include "memory/oopFactory.hpp"
368281Sjkh#include "memory/resourceArea.hpp"
378281Sjkh#include "oops/method.hpp"
388302Sjkh#include "oops/oop.inline.hpp"
398307Sjkh#include "prims/jvmtiThreadState.hpp"
408281Sjkh#include "runtime/biasedLocking.hpp"
418549Sjkh#include "runtime/compilationPolicy.hpp"
428549Sjkh#include "runtime/deoptimization.hpp"
438302Sjkh#include "runtime/interfaceSupport.hpp"
448549Sjkh#include "runtime/sharedRuntime.hpp"
4512661Speter#include "runtime/signature.hpp"
468302Sjkh#include "runtime/stubRoutines.hpp"
478302Sjkh#include "runtime/thread.hpp"
4830345Sjkh#include "runtime/vframe.hpp"
4926456Sjkh#include "runtime/vframeArray.hpp"
508549Sjkh#include "runtime/vframe_hp.hpp"
518549Sjkh#include "utilities/events.hpp"
528302Sjkh#include "utilities/xmlstream.hpp"
5318650Sjkh#ifdef TARGET_ARCH_x86
548549Sjkh# include "vmreg_x86.inline.hpp"
558549Sjkh#endif
5618650Sjkh#ifdef TARGET_ARCH_sparc
578549Sjkh# include "vmreg_sparc.inline.hpp"
588549Sjkh#endif
5918650Sjkh#ifdef TARGET_ARCH_zero
6012661Speter# include "vmreg_zero.inline.hpp"
618549Sjkh#endif
628549Sjkh#ifdef TARGET_ARCH_arm
638549Sjkh# include "vmreg_arm.inline.hpp"
648549Sjkh#endif
658549Sjkh#ifdef TARGET_ARCH_ppc
668302Sjkh# include "vmreg_ppc.inline.hpp"
678549Sjkh#endif
6818744Sjkh#ifdef COMPILER2
6918744Sjkh#ifdef TARGET_ARCH_MODEL_x86_32
708302Sjkh# include "adfiles/ad_x86_32.hpp"
718302Sjkh#endif
7218744Sjkh#ifdef TARGET_ARCH_MODEL_x86_64
7318744Sjkh# include "adfiles/ad_x86_64.hpp"
748302Sjkh#endif
758549Sjkh#ifdef TARGET_ARCH_MODEL_sparc
768302Sjkh# include "adfiles/ad_sparc.hpp"
778549Sjkh#endif
7818744Sjkh#ifdef TARGET_ARCH_MODEL_zero
798302Sjkh# include "adfiles/ad_zero.hpp"
8018744Sjkh#endif
8118744Sjkh#ifdef TARGET_ARCH_MODEL_arm
8219992Sphk# include "adfiles/ad_arm.hpp"
8317404Sjkh#endif
8417362Sjkh#ifdef TARGET_ARCH_MODEL_ppc
8519992Sphk# include "adfiles/ad_ppc.hpp"
8619992Sphk#endif
8719992Sphk#endif
8823721Sjoerg
8923721Sjoergbool DeoptimizationMarker::_is_active = false;
9025052Sjkh
9125052SjkhDeoptimization::UnrollBlock::UnrollBlock(int  size_of_deoptimized_frame,
9223721Sjoerg                                         int  caller_adjustment,
9319992Sphk                                         int  caller_actual_parameters,
9419992Sphk                                         int  number_of_frames,
9512661Speter                                         intptr_t* frame_sizes,
968302Sjkh                                         address* frame_pcs,
978549Sjkh                                         BasicType return_type) {
988668Sphk  _size_of_deoptimized_frame = size_of_deoptimized_frame;
998549Sjkh  _caller_adjustment         = caller_adjustment;
1009202Srgrimes  _caller_actual_parameters  = caller_actual_parameters;
1018549Sjkh  _number_of_frames          = number_of_frames;
10219992Sphk  _frame_sizes               = frame_sizes;
10319992Sphk  _frame_pcs                 = frame_pcs;
10419992Sphk  _register_block            = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
10529307Sjkh  _return_type               = return_type;
1068549Sjkh  _initial_info              = 0;
1078549Sjkh  // PD (x86 only)
1088549Sjkh  _counter_temp              = 0;
1098302Sjkh  _unpack_kind               = 0;
11016208Sjkh  _sender_sp_temp            = 0;
11129307Sjkh
1128549Sjkh  _total_frame_sizes         = size_of_frames();
1138549Sjkh}
11421969Sobrien
11521969Sobrien
1169202SrgrimesDeoptimization::UnrollBlock::~UnrollBlock() {
1178302Sjkh  FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes, mtCompiler);
1188302Sjkh  FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs, mtCompiler);
1198302Sjkh  FREE_C_HEAP_ARRAY(intptr_t, _register_block, mtCompiler);
1208302Sjkh}
1218302Sjkh
1228302Sjkh
1238302Sjkhintptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {
1248302Sjkh  assert(register_number < RegisterMap::reg_count, "checking register number");
1258549Sjkh  return &_register_block[register_number * 2];
12621971Sjkh}
12721971Sjkh
12829307Sjkh
12914670Sjkh
13021971Sjkhint Deoptimization::UnrollBlock::size_of_frames() const {
13115695Sjkh  // Acount first for the adjustment of the initial frame
1328302Sjkh  int result = _caller_adjustment;
1338302Sjkh  for (int index = 0; index < number_of_frames(); index++) {
1348302Sjkh    result += frame_sizes()[index];
13512661Speter  }
13612661Speter  return result;
13712661Speter}
13812661Speter
13912661Speter
14012661Spetervoid Deoptimization::UnrollBlock::print() {
14112661Speter  ttyLocker ttyl;
14212661Speter  tty->print_cr("UnrollBlock");
14312661Speter  tty->print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
14412661Speter  tty->print(   "  frame_sizes: ");
14512661Speter  for (int index = 0; index < number_of_frames(); index++) {
14612661Speter    tty->print("%d ", frame_sizes()[index]);
14712661Speter  }
14816887Sjkh  tty->cr();
14912661Speter}
15012661Speter
15112661Speter
15212661Speter// In order to make fetch_unroll_info work properly with escape
15312661Speter// analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and
15412661Speter// ResetNoHandleMark and HandleMark were removed from it. The actual reallocation
15512661Speter// of previously eliminated objects occurs in realloc_objects, which is
15612661Speter// called from the method fetch_unroll_info_helper below.
15712661SpeterJRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread))
15812661Speter  // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
15912661Speter  // but makes the entry a little slower. There is however a little dance we have to
16012661Speter  // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
16112661Speter
16212661Speter  // fetch_unroll_info() is called at the beginning of the deoptimization
16312661Speter  // handler. Note this fact before we start generating temporary frames
16412661Speter  // that can confuse an asynchronous stack walker. This counter is
16512661Speter  // decremented at the end of unpack_frames().
16612661Speter  thread->inc_in_deopt_handler();
16712661Speter
16812661Speter  return fetch_unroll_info_helper(thread);
16912661SpeterJRT_END
17012661Speter
17112661Speter
17212661Speter// This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
17312661SpeterDeoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread) {
17430345Sjkh
17530345Sjkh  // Note: there is a safepoint safety issue here. No matter whether we enter
17630345Sjkh  // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
17730345Sjkh  // the vframeArray is created.
17830345Sjkh  //
17930345Sjkh
18030345Sjkh  // Allocate our special deoptimization ResourceMark
18130345Sjkh  DeoptResourceMark* dmark = new DeoptResourceMark(thread);
18230345Sjkh  assert(thread->deopt_mark() == NULL, "Pending deopt!");
18330345Sjkh  thread->set_deopt_mark(dmark);
18430345Sjkh
18530345Sjkh  frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect
18630345Sjkh  RegisterMap map(thread, true);
18730345Sjkh  RegisterMap dummy_map(thread, false);
18830345Sjkh  // Now get the deoptee with a valid map
18930345Sjkh  frame deoptee = stub_frame.sender(&map);
19030345Sjkh  // Set the deoptee nmethod
19130345Sjkh  assert(thread->deopt_nmethod() == NULL, "Pending deopt!");
19230345Sjkh  thread->set_deopt_nmethod(deoptee.cb()->as_nmethod_or_null());
19312661Speter
19430345Sjkh  if (VerifyStack) {
19512661Speter    thread->validate_frame_layout();
19618744Sjkh  }
19718650Sjkh
1988549Sjkh  // Create a growable array of VFrames where each VFrame represents an inlined
1998302Sjkh  // Java frame.  This storage is allocated with the usual system arena.
20012661Speter  assert(deoptee.is_compiled_frame(), "Wrong frame type");
20118650Sjkh  GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
20230345Sjkh  vframe* vf = vframe::new_vframe(&deoptee, &map, thread);
2038302Sjkh  while (!vf->is_top()) {
2048549Sjkh    assert(vf->is_compiled_frame(), "Wrong frame type");
2058302Sjkh    chunk->push(compiledVFrame::cast(vf));
2068302Sjkh    vf = vf->sender();
20718650Sjkh  }
20818650Sjkh  assert(vf->is_compiled_frame(), "Wrong frame type");
20918650Sjkh  chunk->push(compiledVFrame::cast(vf));
21019515Sjkh
21118650Sjkh#ifdef COMPILER2
21218683Sjkh  // Reallocate the non-escaping objects and restore their fields. Then
21318683Sjkh  // relock objects if synchronization on them was eliminated.
21418683Sjkh  if (DoEscapeAnalysis || EliminateNestedLocks) {
2158549Sjkh    if (EliminateAllocations) {
21618744Sjkh      assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");
21718744Sjkh      GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
21818650Sjkh
21921772Sjkh      // The flag return_oop() indicates call sites which return oop
22021772Sjkh      // in compiled code. Such sites include java method calls,
2218302Sjkh      // runtime calls (for example, used to allocate new objects/arrays
2228302Sjkh      // on slow code path) and any other calls generated in compiled code.
22315695Sjkh      // It is not guaranteed that we can get such information here only
2248302Sjkh      // by analyzing bytecode in deoptimized frames. This is why this flag
2258302Sjkh      // is set during method compilation (see Compile::Process_OopMap_Node()).
2268302Sjkh      bool save_oop_result = chunk->at(0)->scope()->return_oop();
22718650Sjkh      Handle return_value;
22818650Sjkh      if (save_oop_result) {
22918650Sjkh        // Reallocation may trigger GC. If deoptimization happened on return from
23018650Sjkh        // call which returns oop we need to save it since it is not in oopmap.
2318549Sjkh        oop result = deoptee.saved_oop_result(&map);
23218650Sjkh        assert(result == NULL || result->is_oop(), "must be oop");
23317398Sjkh        return_value = Handle(thread, result);
23417398Sjkh        assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
23518744Sjkh        if (TraceDeoptimization) {
2368751Sjkh          tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, result, thread);
23718650Sjkh        }
23818650Sjkh      }
23918744Sjkh      bool reallocated = false;
24021698Sjkh      if (objects != NULL) {
2418302Sjkh        JRT_BLOCK
2428302Sjkh          reallocated = realloc_objects(thread, &deoptee, objects, THREAD);
2438302Sjkh        JRT_END
2448302Sjkh      }
2458302Sjkh      if (reallocated) {
24618744Sjkh        reassign_fields(&deoptee, &map, objects);
24721698Sjkh#ifndef PRODUCT
2488302Sjkh        if (TraceDeoptimization) {
2498302Sjkh          ttyLocker ttyl;
2508302Sjkh          tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, thread);
2518302Sjkh          print_objects(objects);
2528549Sjkh        }
2538302Sjkh#endif
2548302Sjkh      }
2558302Sjkh      if (save_oop_result) {
2568302Sjkh        // Restore result.
2578302Sjkh        deoptee.set_saved_oop_result(&map, return_value());
2588302Sjkh      }
2598302Sjkh    }
2608302Sjkh    if (EliminateLocks) {
2618549Sjkh#ifndef PRODUCT
2628302Sjkh      bool first = true;
2638302Sjkh#endif
2648302Sjkh      for (int i = 0; i < chunk->length(); i++) {
2658302Sjkh        compiledVFrame* cvf = chunk->at(i);
2668302Sjkh        assert (cvf->scope() != NULL,"expect only compiled java frames");
26712661Speter        GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
26818612Sjkh        if (monitors->is_nonempty()) {
2698302Sjkh          relock_objects(monitors, thread);
2708302Sjkh#ifndef PRODUCT
27118650Sjkh          if (TraceDeoptimization) {
27239845Sjkh            ttyLocker ttyl;
27339845Sjkh            for (int j = 0; j < monitors->length(); j++) {
27439845Sjkh              MonitorInfo* mi = monitors->at(j);
27525473Spst              if (mi->eliminated()) {
27625665Spst                if (first) {
27725473Spst                  first = false;
27825473Spst                  tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread);
27925473Spst                }
28025473Spst                tty->print_cr("     object <" INTPTR_FORMAT "> locked", mi->owner());
28129204Sjoerg              }
28229204Sjoerg            }
28329204Sjoerg          }
28425473Spst#endif
28525473Spst        }
28612661Speter      }
28739845Sjkh    }
28812661Speter  }
28912661Speter#endif // COMPILER2
29018683Sjkh  // Ensure that no safepoint is taken after pointers have been stored
29118650Sjkh  // in fields of rematerialized objects.  If a safepoint occurs from here on
29218650Sjkh  // out the java state residing in the vframeArray will be missed.
29318744Sjkh  No_Safepoint_Verifier no_safepoint;
2948549Sjkh
2958549Sjkh  vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk);
29621971Sjkh
29712661Speter  assert(thread->vframe_array_head() == NULL, "Pending deopt!");;
29839254Sgibbs  thread->set_vframe_array_head(array);
29912661Speter
30012661Speter  // Now that the vframeArray has been created if we have any deferred local writes
3018589Sjkh  // added by jvmti then we can free up that structure as the data is now in the
3028589Sjkh  // vframeArray
3038589Sjkh
3048589Sjkh  if (thread->deferred_locals() != NULL) {
30512661Speter    GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals();
30618612Sjkh    int i = 0;
3078549Sjkh    do {
30818744Sjkh      // Because of inlining we could have multiple vframes for a single frame
3098302Sjkh      // and several of the vframes could have deferred writes. Find them all.
3108549Sjkh      if (list->at(i)->id() == array->original().id()) {
31121971Sjkh        jvmtiDeferredLocalVariableSet* dlv = list->at(i);
3128302Sjkh        list->remove_at(i);
3138556Sjkh        // individual jvmtiDeferredLocalVariableSet are CHeapObj's
31416204Sjkh        delete dlv;
31516204Sjkh      } else {
31618744Sjkh        i++;
31739183Sjkh      }
31821971Sjkh    } while ( i < list->length() );
31918744Sjkh    if (list->length() == 0) {
3208556Sjkh      thread->set_deferred_locals(NULL);
3218556Sjkh      // free the list and elements back to C heap.
32212661Speter      delete list;
32316204Sjkh    }
32416204Sjkh
32516204Sjkh  }
32621971Sjkh
32716204Sjkh#ifndef SHARK
32816204Sjkh  // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
32916204Sjkh  CodeBlob* cb = stub_frame.cb();
33016204Sjkh  // Verify we have the right vframeArray
33116204Sjkh  assert(cb->frame_size() >= 0, "Unexpected frame size");
33216204Sjkh  intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
33329307Sjkh
33429307Sjkh  // If the deopt call site is a MethodHandle invoke call site we have
33529307Sjkh  // to adjust the unpack_sp.
33629307Sjkh  nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
33716204Sjkh  if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))
33829307Sjkh    unpack_sp = deoptee.unextended_sp();
33939847Sjkh
34039847Sjkh#ifdef ASSERT
34139847Sjkh  assert(cb->is_deoptimization_stub() || cb->is_uncommon_trap_stub(), "just checking");
34239847Sjkh#endif
34339847Sjkh#else
34418744Sjkh  intptr_t* unpack_sp = stub_frame.sender(&dummy_map).unextended_sp();
34518744Sjkh#endif // !SHARK
34618744Sjkh
34718744Sjkh  // This is a guarantee instead of an assert because if vframe doesn't match
34816204Sjkh  // we will unpack the wrong deoptimized frame and wind up in strange places
3498302Sjkh  // where it will be very difficult to figure out what went wrong. Better
35018650Sjkh  // to die an early death here than some very obscure death later when the
3518302Sjkh  // trail is cold.
3528302Sjkh  // Note: on ia64 this guarantee can be fooled by frames with no memory stack
35318744Sjkh  // in that it will fail to detect a problem when there is one. This needs
35417398Sjkh  // more work in tiger timeframe.
3558549Sjkh  guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
3568549Sjkh
35721971Sjkh  int number_of_frames = array->frames();
3588549Sjkh
3598549Sjkh  // Compute the vframes' sizes.  Note that frame_sizes[] entries are ordered from outermost to innermost
36012661Speter  // virtual activation, which is the reverse of the elements in the vframes array.
36118683Sjkh  intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
3628307Sjkh  // +1 because we always have an interpreter return address for the final slot.
3638307Sjkh  address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
36418744Sjkh  int popframe_extra_args = 0;
36529307Sjkh  // Create an interpreter return address for the stub to use as its return
36629307Sjkh  // address so the skeletal frames are perfectly walkable
36729307Sjkh  frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
36829307Sjkh
36929307Sjkh  // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
37029307Sjkh  // activation be put back on the expression stack of the caller for reexecution
37129307Sjkh  if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {
37229307Sjkh    popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words());
37329307Sjkh  }
37429307Sjkh
37529307Sjkh  // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
37629307Sjkh  // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
37729307Sjkh  // than simply use array->sender.pc(). This requires us to walk the current set of frames
37832958Ssteve  //
37929307Sjkh  frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
38029307Sjkh  deopt_sender = deopt_sender.sender(&dummy_map);     // Now deoptee caller
38129307Sjkh
38229307Sjkh  // It's possible that the number of paramters at the call site is
38329307Sjkh  // different than number of arguments in the callee when method
38429307Sjkh  // handles are used.  If the caller is interpreted get the real
38529307Sjkh  // value so that the proper amount of space can be added to it's
38629307Sjkh  // frame.
38729307Sjkh  bool caller_was_method_handle = false;
38829307Sjkh  if (deopt_sender.is_interpreted_frame()) {
38929307Sjkh    methodHandle method = deopt_sender.interpreter_frame_method();
39029307Sjkh    Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
39129307Sjkh    if (cur.is_invokedynamic() || cur.is_invokehandle()) {
39229307Sjkh      // Method handle invokes may involve fairly arbitrary chains of
39329307Sjkh      // calls so it's impossible to know how much actual space the
39429307Sjkh      // caller has for locals.
39529307Sjkh      caller_was_method_handle = true;
39629307Sjkh    }
39729307Sjkh  }
39818744Sjkh
39910882Speter  //
40012661Speter  // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
40112661Speter  // frame_sizes/frame_pcs[1] next oldest frame (int)
40212661Speter  // frame_sizes/frame_pcs[n] youngest frame (int)
4038549Sjkh  //
40419992Sphk  // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
40519992Sphk  // owns the space for the return address to it's caller).  Confusing ain't it.
40619992Sphk  //
40719992Sphk  // The vframe array can address vframes with indices running from
40819992Sphk  // 0.._frames-1. Index  0 is the youngest frame and _frame - 1 is the oldest (root) frame.
4098317Sjkh  // When we create the skeletal frames we need the oldest frame to be in the zero slot
41018612Sjkh  // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
41118744Sjkh  // so things look a little strange in this loop.
41212661Speter  //
41318744Sjkh  int callee_parameters = 0;
41418744Sjkh  int callee_locals = 0;
41518744Sjkh  for (int index = 0; index < array->frames(); index++ ) {
41618744Sjkh    // frame[number_of_frames - 1 ] = on_stack_size(youngest)
41718744Sjkh    // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
41818744Sjkh    // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
41918744Sjkh    int caller_parms = callee_parameters;
42018744Sjkh    if ((index == array->frames() - 1) && caller_was_method_handle) {
42118744Sjkh      caller_parms = 0;
42218612Sjkh    }
42318744Sjkh    frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(caller_parms,
42421772Sjkh                                                                                                    callee_parameters,
42521772Sjkh                                                                                                    callee_locals,
42621772Sjkh                                                                                                    index == 0,
42718744Sjkh                                                                                                    popframe_extra_args);
42821772Sjkh    // This pc doesn't have to be perfect just good enough to identify the frame
42921772Sjkh    // as interpreted so the skeleton frame will be walkable
43021772Sjkh    // The correct pc will be set when the skeleton frame is completely filled out
43118744Sjkh    // The final pc we store in the loop is wrong and will be overwritten below
43218744Sjkh    frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
43318744Sjkh
43421772Sjkh    callee_parameters = array->element(index)->method()->size_of_parameters();
43521772Sjkh    callee_locals = array->element(index)->method()->max_locals();
43612661Speter    popframe_extra_args = 0;
43718612Sjkh  }
4388336Sjkh
4398336Sjkh  // Compute whether the root vframe returns a float or double value.
4408340Sjkh  BasicType return_type;
44134681Sjkh  {
44218744Sjkh    HandleMark hm;
44318744Sjkh    methodHandle method(thread, array->element(0)->method());
44418744Sjkh    Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
44530345Sjkh    return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
44630345Sjkh  }
44718744Sjkh
44812661Speter  // Compute information for handling adapters and adjusting the frame size of the caller.
44918744Sjkh  int caller_adjustment = 0;
45012661Speter
45112661Speter  // Compute the amount the oldest interpreter frame will have to adjust
45212661Speter  // its caller's stack by. If the caller is a compiled frame then
45312661Speter  // we pretend that the callee has no parameters so that the
45434792Sjkh  // extension counts for the full amount of locals and not just
45534792Sjkh  // locals-parms. This is because without a c2i adapter the parm
45634792Sjkh  // area as created by the compiled frame will not be usable by
45712661Speter  // the interpreter. (Depending on the calling convention there
45834792Sjkh  // may not even be enough space).
45934792Sjkh
46034792Sjkh  // QQQ I'd rather see this pushed down into last_frame_adjust
46134792Sjkh  // and have it take the sender (aka caller).
46234792Sjkh
46334792Sjkh  if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {
46434792Sjkh    caller_adjustment = last_frame_adjust(0, callee_locals);
46534792Sjkh  } else if (callee_locals > callee_parameters) {
46634792Sjkh    // The caller frame may need extending to accommodate
46718744Sjkh    // non-parameter locals of the first unpacked interpreted frame.
46815419Sjkh    // Compute that adjustment.
46912661Speter    caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
47015355Sjkh  }
47112661Speter
47212661Speter  // If the sender is deoptimized the we must retrieve the address of the handler
47318612Sjkh  // since the frame will "magically" show the original pc before the deopt
47410882Speter  // and we'd undo the deopt.
47518744Sjkh
47610882Speter  frame_pcs[0] = deopt_sender.raw_pc();
47712661Speter
47812661Speter#ifndef SHARK
47918650Sjkh  assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");
48018650Sjkh#endif // SHARK
4818549Sjkh
48212661Speter  UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
48318683Sjkh                                      caller_adjustment * BytesPerWord,
4848340Sjkh                                      caller_was_method_handle ? 0 : callee_parameters,
4858340Sjkh                                      number_of_frames,
4868549Sjkh                                      frame_sizes,
48718650Sjkh                                      frame_pcs,
4888340Sjkh                                      return_type);
4898340Sjkh  // On some platforms, we need a way to pass some platform dependent
49021698Sjkh  // information to the unpacking code so the skeletal frames come out
4919202Srgrimes  // correct (initial fp value, unextended sp, ...)
4928549Sjkh  info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
49312661Speter
49412661Speter  if (array->frames() > 1) {
49512661Speter    if (VerifyStack && TraceDeoptimization) {
49612661Speter      tty->print_cr("Deoptimizing method containing inlining");
49734811Sjkh    }
49812661Speter  }
49912661Speter
50012661Speter  array->set_unroll_block(info);
50134811Sjkh  return info;
50234811Sjkh}
50334811Sjkh
50434811Sjkh// Called to cleanup deoptimization data structures in normal case
50534811Sjkh// after unpacking to stack and when stack overflow error occurs
50634811Sjkhvoid Deoptimization::cleanup_deopt_info(JavaThread *thread,
50734811Sjkh                                        vframeArray *array) {
50834811Sjkh
50934811Sjkh  // Get array if coming from exception
5108302Sjkh  if (array == NULL) {
51118744Sjkh    array = thread->vframe_array_head();
5128336Sjkh  }
5138336Sjkh  thread->set_vframe_array_head(NULL);
5148336Sjkh
5158336Sjkh  // Free the previous UnrollBlock
5168302Sjkh  vframeArray* old_array = thread->vframe_array_last();
5178302Sjkh  thread->set_vframe_array_last(array);
5188549Sjkh
5198549Sjkh  if (old_array != NULL) {
52015465Sjkh    UnrollBlock* old_info = old_array->unroll_block();
52118744Sjkh    old_array->set_unroll_block(NULL);
52217404Sjkh    delete old_info;
52321971Sjkh    delete old_array;
52415465Sjkh  }
52526717Sjkh
52626717Sjkh  // Deallocate any resource creating in this routine and any ResourceObjs allocated
5278549Sjkh  // inside the vframeArray (StackValueCollections)
5288549Sjkh
52915355Sjkh  delete thread->deopt_mark();
5308281Sjkh  thread->set_deopt_mark(NULL);
5318281Sjkh  thread->set_deopt_nmethod(NULL);
5328549Sjkh
53315242Sjkh
5348281Sjkh  if (JvmtiExport::can_pop_frame()) {
5358556Sjkh#ifndef CC_INTERP
5368281Sjkh    // Regardless of whether we entered this routine with the pending
53715242Sjkh    // popframe condition bit set, we should always clear it now
53815242Sjkh    thread->clear_popframe_condition();
53915242Sjkh#else
54015242Sjkh    // C++ interpeter will clear has_pending_popframe when it enters
5418281Sjkh    // with method_resume. For deopt_resume2 we clear it now.
54215695Sjkh    if (thread->popframe_forcing_deopt_reexecution())
54315695Sjkh        thread->clear_popframe_condition();
54415695Sjkh#endif /* CC_INTERP */
54530345Sjkh  }
54615695Sjkh
54715695Sjkh  // unpack_frames() is called at the end of the deoptimization handler
54815695Sjkh  // and (in C2) at the end of the uncommon trap handler. Note this fact
54930345Sjkh  // so that an asynchronous stack walker can work again. This counter is
5508281Sjkh  // incremented at the beginning of fetch_unroll_info() and (in C2) at
5518549Sjkh  // the beginning of uncommon_trap().
55215242Sjkh  thread->dec_in_deopt_handler();
55315242Sjkh}
55415242Sjkh
55515242Sjkh
55615242Sjkh// Return BasicType of value being returned
55715242SjkhJRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
55815242Sjkh
55915242Sjkh  // We are already active int he special DeoptResourceMark any ResourceObj's we
56015242Sjkh  // allocate will be freed at the end of the routine.
56115242Sjkh
56215242Sjkh  // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
5638549Sjkh  // but makes the entry a little slower. There is however a little dance we have to
56415091Sjkh  // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
5658549Sjkh  ResetNoHandleMark rnhm; // No-op in release/product versions
5668549Sjkh  HandleMark hm;
5679202Srgrimes
56830561Sjkh  frame stub_frame = thread->last_frame();
5698549Sjkh
57030345Sjkh  // Since the frame to unpack is the top frame of this thread, the vframe_array_head
57130561Sjkh  // must point to the vframeArray for the unpack frame.
57230345Sjkh  vframeArray* array = thread->vframe_array_head();
57312661Speter
57412661Speter#ifndef PRODUCT
57512661Speter  if (TraceDeoptimization) {
57630345Sjkh    tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", thread, array, exec_mode);
5778549Sjkh  }
57830345Sjkh#endif
57930345Sjkh  Events::log(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
58030561Sjkh              stub_frame.pc(), stub_frame.sp(), exec_mode);
58130345Sjkh
58230345Sjkh  UnrollBlock* info = array->unroll_block();
58330345Sjkh
58430345Sjkh  // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
58530345Sjkh  array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
58630345Sjkh
58730345Sjkh  BasicType bt = info->return_type();
5889202Srgrimes
5898576Sjkh  // If we have an exception pending, claim that the return type is an oop
59030345Sjkh  // so the deopt_blob does not overwrite the exception_oop.
59130561Sjkh
59230345Sjkh  if (exec_mode == Unpack_exception)
59330345Sjkh    bt = T_OBJECT;
59430345Sjkh
59530345Sjkh  // Cleanup thread deopt data
59630345Sjkh  cleanup_deopt_info(thread, array);
59730345Sjkh
59812661Speter#ifndef PRODUCT
5999202Srgrimes  if (VerifyStack) {
60030345Sjkh    ResourceMark res_mark;
60130345Sjkh
60230345Sjkh    thread->validate_frame_layout();
60330345Sjkh
60430345Sjkh    // Verify that the just-unpacked frames match the interpreter's
60530345Sjkh    // notions of expression stack and locals
60630345Sjkh    vframeArray* cur_array = thread->vframe_array_last();
60730345Sjkh    RegisterMap rm(thread, false);
60830345Sjkh    rm.set_include_argument_oops(false);
60930345Sjkh    bool is_top_frame = true;
61030345Sjkh    int callee_size_of_parameters = 0;
61130345Sjkh    int callee_max_locals = 0;
61230345Sjkh    for (int i = 0; i < cur_array->frames(); i++) {
61330345Sjkh      vframeArrayElement* el = cur_array->element(i);
6149202Srgrimes      frame* iframe = el->iframe();
6158576Sjkh      guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
61633315Sjkh
6178549Sjkh      // Get the oop map for this bci
61810882Speter      InterpreterOopMap mask;
61910882Speter      int cur_invoke_parameter_size = 0;
62015091Sjkh      bool try_next_mask = false;
62110882Speter      int next_mask_expression_stack_size = -1;
62210882Speter      int top_frame_expression_stack_adjustment = 0;
62310882Speter      methodHandle mh(thread, iframe->interpreter_frame_method());
62434681Sjkh      OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
62510882Speter      BytecodeStream str(mh);
62610882Speter      str.set_start(iframe->interpreter_frame_bci());
62710882Speter      int max_bci = mh->code_size();
62810882Speter      // Get to the next bytecode if possible
62915242Sjkh      assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
63010882Speter      // Check to see if we can grab the number of outgoing arguments
63115445Sjkh      // at an uncommon trap for an invoke (where the compiler
63215445Sjkh      // generates debug info before the invoke has executed)
63334681Sjkh      Bytecodes::Code cur_code = str.next();
63434811Sjkh      if (cur_code == Bytecodes::_invokevirtual ||
63534811Sjkh          cur_code == Bytecodes::_invokespecial ||
63634811Sjkh          cur_code == Bytecodes::_invokestatic  ||
63710882Speter          cur_code == Bytecodes::_invokeinterface) {
63810882Speter        Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
63910882Speter        Symbol* signature = invoke.signature();
64010882Speter        ArgumentSizeComputer asc(signature);
64110882Speter        cur_invoke_parameter_size = asc.size();
64210882Speter        if (cur_code != Bytecodes::_invokestatic) {
64310882Speter          // Add in receiver
64410882Speter          ++cur_invoke_parameter_size;
64510882Speter        }
64615439Sjkh      }
64712661Speter      if (str.bci() < max_bci) {
64815242Sjkh        Bytecodes::Code bc = str.next();
64912661Speter        if (bc >= 0) {
65034681Sjkh          // The interpreter oop map generator reports results before
65134681Sjkh          // the current bytecode has executed except in the case of
65234681Sjkh          // calls. It seems to be hard to tell whether the compiler
65334681Sjkh          // has emitted debug information matching the "state before"
65434681Sjkh          // a given bytecode or the state after, so we try both
65510882Speter          switch (cur_code) {
65610882Speter            case Bytecodes::_invokevirtual:
65710882Speter            case Bytecodes::_invokespecial:
65810882Speter            case Bytecodes::_invokestatic:
65910882Speter            case Bytecodes::_invokeinterface:
66021971Sjkh            case Bytecodes::_athrow:
66116718Sjkh              break;
66216718Sjkh            default: {
66316718Sjkh              InterpreterOopMap next_mask;
66416718Sjkh              OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
66516718Sjkh              next_mask_expression_stack_size = next_mask.expression_stack_size();
66616718Sjkh              // Need to subtract off the size of the result type of
66716718Sjkh              // the bytecode because this is not described in the
66816718Sjkh              // debug info but returned to the interpreter in the TOS
66910882Speter              // caching register
67010882Speter              BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
67110882Speter              if (bytecode_result_type != T_ILLEGAL) {
67212661Speter                top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
67312661Speter              }
67415242Sjkh              assert(top_frame_expression_stack_adjustment >= 0, "");
67510882Speter              try_next_mask = true;
67626456Sjkh              break;
67726456Sjkh            }
67826456Sjkh          }
67930345Sjkh        }
68026456Sjkh      }
68126456Sjkh
68226574Sjkh      // Verify stack depth and oops in frame
68326574Sjkh      // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
68430345Sjkh      if (!(
68526456Sjkh            /* SPARC */
68626456Sjkh            (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
68726456Sjkh            /* x86 */
68826456Sjkh            (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
68926456Sjkh            (try_next_mask &&
69026456Sjkh             (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
69126456Sjkh                                                                    top_frame_expression_stack_adjustment))) ||
69226456Sjkh            (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
69326456Sjkh            (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute) &&
69426456Sjkh             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
69526456Sjkh            )) {
69626456Sjkh        ttyLocker ttyl;
69726456Sjkh
69826456Sjkh        // Print out some information that will help us debug the problem
69926456Sjkh        tty->print_cr("Wrong number of expression stack elements during deoptimization");
70026456Sjkh        tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
70126456Sjkh        tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
70226456Sjkh                      iframe->interpreter_frame_expression_stack_size());
70326456Sjkh        tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
70426456Sjkh        tty->print_cr("  try_next_mask = %d", try_next_mask);
70526456Sjkh        tty->print_cr("  next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
70626456Sjkh        tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
70726456Sjkh        tty->print_cr("  callee_max_locals = %d", callee_max_locals);
70826456Sjkh        tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
70926456Sjkh        tty->print_cr("  exec_mode = %d", exec_mode);
71026456Sjkh        tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
71126456Sjkh        tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = " UINTX_FORMAT, thread, thread->osthread()->thread_id());
71226456Sjkh        tty->print_cr("  Interpreted frames:");
71326456Sjkh        for (int k = 0; k < cur_array->frames(); k++) {
71426456Sjkh          vframeArrayElement* el = cur_array->element(k);
71526456Sjkh          tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
71626456Sjkh        }
71726456Sjkh        cur_array->print_on_2(tty);
71826456Sjkh        guarantee(false, "wrong number of expression stack elements during deopt");
71926456Sjkh      }
72026456Sjkh      VerifyOopClosure verify;
72126456Sjkh      iframe->oops_interpreted_do(&verify, &rm, false);
72226456Sjkh      callee_size_of_parameters = mh->size_of_parameters();
72326456Sjkh      callee_max_locals = mh->max_locals();
72426574Sjkh      is_top_frame = false;
72526456Sjkh    }
72626456Sjkh  }
72726456Sjkh#endif /* !PRODUCT */
72826456Sjkh
72926456Sjkh
73026456Sjkh  return bt;
73126456SjkhJRT_END
73226456Sjkh
73326456Sjkh
73426456Sjkhint Deoptimization::deoptimize_dependents() {
73526456Sjkh  Threads::deoptimized_wrt_marked_nmethods();
73626456Sjkh  return 0;
73726456Sjkh}
73826456Sjkh
73926456Sjkh
74026456Sjkh#ifdef COMPILER2
74126456Sjkhbool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, GrowableArray<ScopeValue*>* objects, TRAPS) {
74226456Sjkh  Handle pending_exception(thread->pending_exception());
74326456Sjkh  const char* exception_file = thread->exception_file();
74426456Sjkh  int exception_line = thread->exception_line();
74526456Sjkh  thread->clear_pending_exception();
74626456Sjkh
74726456Sjkh  for (int i = 0; i < objects->length(); i++) {
74826456Sjkh    assert(objects->at(i)->is_object(), "invalid debug information");
74926456Sjkh    ObjectValue* sv = (ObjectValue*) objects->at(i);
75026456Sjkh
75126456Sjkh    KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
75226456Sjkh    oop obj = NULL;
75326456Sjkh
75426456Sjkh    if (k->oop_is_instance()) {
75526456Sjkh      InstanceKlass* ik = InstanceKlass::cast(k());
75626456Sjkh      obj = ik->allocate_instance(CHECK_(false));
75726456Sjkh    } else if (k->oop_is_typeArray()) {
75826456Sjkh      typeArrayKlass* ak = typeArrayKlass::cast(k());
75926456Sjkh      assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
76026456Sjkh      int len = sv->field_size() / type2size[ak->element_type()];
76126574Sjkh      obj = ak->allocate(len, CHECK_(false));
76226574Sjkh    } else if (k->oop_is_objArray()) {
76326574Sjkh      objArrayKlass* ak = objArrayKlass::cast(k());
76426574Sjkh      obj = ak->allocate(sv->field_size(), CHECK_(false));
76526456Sjkh    }
76626456Sjkh
76726456Sjkh    assert(obj != NULL, "allocation failed");
768    assert(sv->value().is_null(), "redundant reallocation");
769    sv->set_value(obj);
770  }
771
772  if (pending_exception.not_null()) {
773    thread->set_pending_exception(pending_exception(), exception_file, exception_line);
774  }
775
776  return true;
777}
778
779// This assumes that the fields are stored in ObjectValue in the same order
780// they are yielded by do_nonstatic_fields.
781class FieldReassigner: public FieldClosure {
782  frame* _fr;
783  RegisterMap* _reg_map;
784  ObjectValue* _sv;
785  InstanceKlass* _ik;
786  oop _obj;
787
788  int _i;
789public:
790  FieldReassigner(frame* fr, RegisterMap* reg_map, ObjectValue* sv, oop obj) :
791    _fr(fr), _reg_map(reg_map), _sv(sv), _obj(obj), _i(0) {}
792
793  int i() const { return _i; }
794
795
796  void do_field(fieldDescriptor* fd) {
797    intptr_t val;
798    StackValue* value =
799      StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(i()));
800    int offset = fd->offset();
801    switch (fd->field_type()) {
802    case T_OBJECT: case T_ARRAY:
803      assert(value->type() == T_OBJECT, "Agreement.");
804      _obj->obj_field_put(offset, value->get_obj()());
805      break;
806
807    case T_LONG: case T_DOUBLE: {
808      assert(value->type() == T_INT, "Agreement.");
809      StackValue* low =
810        StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(++_i));
811#ifdef _LP64
812      jlong res = (jlong)low->get_int();
813#else
814#ifdef SPARC
815      // For SPARC we have to swap high and low words.
816      jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
817#else
818      jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
819#endif //SPARC
820#endif
821      _obj->long_field_put(offset, res);
822      break;
823    }
824    // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
825    case T_INT: case T_FLOAT: // 4 bytes.
826      assert(value->type() == T_INT, "Agreement.");
827      val = value->get_int();
828      _obj->int_field_put(offset, (jint)*((jint*)&val));
829      break;
830
831    case T_SHORT: case T_CHAR: // 2 bytes
832      assert(value->type() == T_INT, "Agreement.");
833      val = value->get_int();
834      _obj->short_field_put(offset, (jshort)*((jint*)&val));
835      break;
836
837    case T_BOOLEAN: case T_BYTE: // 1 byte
838      assert(value->type() == T_INT, "Agreement.");
839      val = value->get_int();
840      _obj->bool_field_put(offset, (jboolean)*((jint*)&val));
841      break;
842
843    default:
844      ShouldNotReachHere();
845    }
846    _i++;
847  }
848};
849
850// restore elements of an eliminated type array
851void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
852  int index = 0;
853  intptr_t val;
854
855  for (int i = 0; i < sv->field_size(); i++) {
856    StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
857    switch(type) {
858    case T_LONG: case T_DOUBLE: {
859      assert(value->type() == T_INT, "Agreement.");
860      StackValue* low =
861        StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
862#ifdef _LP64
863      jlong res = (jlong)low->get_int();
864#else
865#ifdef SPARC
866      // For SPARC we have to swap high and low words.
867      jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
868#else
869      jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
870#endif //SPARC
871#endif
872      obj->long_at_put(index, res);
873      break;
874    }
875
876    // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
877    case T_INT: case T_FLOAT: // 4 bytes.
878      assert(value->type() == T_INT, "Agreement.");
879      val = value->get_int();
880      obj->int_at_put(index, (jint)*((jint*)&val));
881      break;
882
883    case T_SHORT: case T_CHAR: // 2 bytes
884      assert(value->type() == T_INT, "Agreement.");
885      val = value->get_int();
886      obj->short_at_put(index, (jshort)*((jint*)&val));
887      break;
888
889    case T_BOOLEAN: case T_BYTE: // 1 byte
890      assert(value->type() == T_INT, "Agreement.");
891      val = value->get_int();
892      obj->bool_at_put(index, (jboolean)*((jint*)&val));
893      break;
894
895      default:
896        ShouldNotReachHere();
897    }
898    index++;
899  }
900}
901
902
903// restore fields of an eliminated object array
904void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
905  for (int i = 0; i < sv->field_size(); i++) {
906    StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
907    assert(value->type() == T_OBJECT, "object element expected");
908    obj->obj_at_put(i, value->get_obj()());
909  }
910}
911
912
913// restore fields of all eliminated objects and arrays
914void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects) {
915  for (int i = 0; i < objects->length(); i++) {
916    ObjectValue* sv = (ObjectValue*) objects->at(i);
917    KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
918    Handle obj = sv->value();
919    assert(obj.not_null(), "reallocation was missed");
920
921    if (k->oop_is_instance()) {
922      InstanceKlass* ik = InstanceKlass::cast(k());
923      FieldReassigner reassign(fr, reg_map, sv, obj());
924      ik->do_nonstatic_fields(&reassign);
925    } else if (k->oop_is_typeArray()) {
926      typeArrayKlass* ak = typeArrayKlass::cast(k());
927      reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
928    } else if (k->oop_is_objArray()) {
929      reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
930    }
931  }
932}
933
934
935// relock objects for which synchronization was eliminated
936void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread) {
937  for (int i = 0; i < monitors->length(); i++) {
938    MonitorInfo* mon_info = monitors->at(i);
939    if (mon_info->eliminated()) {
940      assert(mon_info->owner() != NULL, "reallocation was missed");
941      Handle obj = Handle(mon_info->owner());
942      markOop mark = obj->mark();
943      if (UseBiasedLocking && mark->has_bias_pattern()) {
944        // New allocated objects may have the mark set to anonymously biased.
945        // Also the deoptimized method may called methods with synchronization
946        // where the thread-local object is bias locked to the current thread.
947        assert(mark->is_biased_anonymously() ||
948               mark->biased_locker() == thread, "should be locked to current thread");
949        // Reset mark word to unbiased prototype.
950        markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
951        obj->set_mark(unbiased_prototype);
952      }
953      BasicLock* lock = mon_info->lock();
954      ObjectSynchronizer::slow_enter(obj, lock, thread);
955    }
956    assert(mon_info->owner()->is_locked(), "object must be locked now");
957  }
958}
959
960
961#ifndef PRODUCT
962// print information about reallocated objects
963void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects) {
964  fieldDescriptor fd;
965
966  for (int i = 0; i < objects->length(); i++) {
967    ObjectValue* sv = (ObjectValue*) objects->at(i);
968    KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
969    Handle obj = sv->value();
970
971    tty->print("     object <" INTPTR_FORMAT "> of type ", sv->value()());
972    k->print_value();
973    tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);
974    tty->cr();
975
976    if (Verbose) {
977      k->oop_print_on(obj(), tty);
978    }
979  }
980}
981#endif
982#endif // COMPILER2
983
984vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk) {
985  Events::log(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, fr.pc(), fr.sp());
986
987#ifndef PRODUCT
988  if (TraceDeoptimization) {
989    ttyLocker ttyl;
990    tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", thread);
991    fr.print_on(tty);
992    tty->print_cr("     Virtual frames (innermost first):");
993    for (int index = 0; index < chunk->length(); index++) {
994      compiledVFrame* vf = chunk->at(index);
995      tty->print("       %2d - ", index);
996      vf->print_value();
997      int bci = chunk->at(index)->raw_bci();
998      const char* code_name;
999      if (bci == SynchronizationEntryBCI) {
1000        code_name = "sync entry";
1001      } else {
1002        Bytecodes::Code code = vf->method()->code_at(bci);
1003        code_name = Bytecodes::name(code);
1004      }
1005      tty->print(" - %s", code_name);
1006      tty->print_cr(" @ bci %d ", bci);
1007      if (Verbose) {
1008        vf->print();
1009        tty->cr();
1010      }
1011    }
1012  }
1013#endif
1014
1015  // Register map for next frame (used for stack crawl).  We capture
1016  // the state of the deopt'ing frame's caller.  Thus if we need to
1017  // stuff a C2I adapter we can properly fill in the callee-save
1018  // register locations.
1019  frame caller = fr.sender(reg_map);
1020  int frame_size = caller.sp() - fr.sp();
1021
1022  frame sender = caller;
1023
1024  // Since the Java thread being deoptimized will eventually adjust it's own stack,
1025  // the vframeArray containing the unpacking information is allocated in the C heap.
1026  // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1027  vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr);
1028
1029  // Compare the vframeArray to the collected vframes
1030  assert(array->structural_compare(thread, chunk), "just checking");
1031
1032#ifndef PRODUCT
1033  if (TraceDeoptimization) {
1034    ttyLocker ttyl;
1035    tty->print_cr("     Created vframeArray " INTPTR_FORMAT, array);
1036  }
1037#endif // PRODUCT
1038
1039  return array;
1040}
1041
1042
1043static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke) {
1044  GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1045  for (int i = 0; i < monitors->length(); i++) {
1046    MonitorInfo* mon_info = monitors->at(i);
1047    if (!mon_info->eliminated() && mon_info->owner() != NULL) {
1048      objects_to_revoke->append(Handle(mon_info->owner()));
1049    }
1050  }
1051}
1052
1053
1054void Deoptimization::revoke_biases_of_monitors(JavaThread* thread, frame fr, RegisterMap* map) {
1055  if (!UseBiasedLocking) {
1056    return;
1057  }
1058
1059  GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1060
1061  // Unfortunately we don't have a RegisterMap available in most of
1062  // the places we want to call this routine so we need to walk the
1063  // stack again to update the register map.
1064  if (map == NULL || !map->update_map()) {
1065    StackFrameStream sfs(thread, true);
1066    bool found = false;
1067    while (!found && !sfs.is_done()) {
1068      frame* cur = sfs.current();
1069      sfs.next();
1070      found = cur->id() == fr.id();
1071    }
1072    assert(found, "frame to be deoptimized not found on target thread's stack");
1073    map = sfs.register_map();
1074  }
1075
1076  vframe* vf = vframe::new_vframe(&fr, map, thread);
1077  compiledVFrame* cvf = compiledVFrame::cast(vf);
1078  // Revoke monitors' biases in all scopes
1079  while (!cvf->is_top()) {
1080    collect_monitors(cvf, objects_to_revoke);
1081    cvf = compiledVFrame::cast(cvf->sender());
1082  }
1083  collect_monitors(cvf, objects_to_revoke);
1084
1085  if (SafepointSynchronize::is_at_safepoint()) {
1086    BiasedLocking::revoke_at_safepoint(objects_to_revoke);
1087  } else {
1088    BiasedLocking::revoke(objects_to_revoke);
1089  }
1090}
1091
1092
1093void Deoptimization::revoke_biases_of_monitors(CodeBlob* cb) {
1094  if (!UseBiasedLocking) {
1095    return;
1096  }
1097
1098  assert(SafepointSynchronize::is_at_safepoint(), "must only be called from safepoint");
1099  GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1100  for (JavaThread* jt = Threads::first(); jt != NULL ; jt = jt->next()) {
1101    if (jt->has_last_Java_frame()) {
1102      StackFrameStream sfs(jt, true);
1103      while (!sfs.is_done()) {
1104        frame* cur = sfs.current();
1105        if (cb->contains(cur->pc())) {
1106          vframe* vf = vframe::new_vframe(cur, sfs.register_map(), jt);
1107          compiledVFrame* cvf = compiledVFrame::cast(vf);
1108          // Revoke monitors' biases in all scopes
1109          while (!cvf->is_top()) {
1110            collect_monitors(cvf, objects_to_revoke);
1111            cvf = compiledVFrame::cast(cvf->sender());
1112          }
1113          collect_monitors(cvf, objects_to_revoke);
1114        }
1115        sfs.next();
1116      }
1117    }
1118  }
1119  BiasedLocking::revoke_at_safepoint(objects_to_revoke);
1120}
1121
1122
1123void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr) {
1124  assert(fr.can_be_deoptimized(), "checking frame type");
1125
1126  gather_statistics(Reason_constraint, Action_none, Bytecodes::_illegal);
1127
1128  // Patch the nmethod so that when execution returns to it we will
1129  // deopt the execution state and return to the interpreter.
1130  fr.deoptimize(thread);
1131}
1132
1133void Deoptimization::deoptimize(JavaThread* thread, frame fr, RegisterMap *map) {
1134  // Deoptimize only if the frame comes from compile code.
1135  // Do not deoptimize the frame which is already patched
1136  // during the execution of the loops below.
1137  if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1138    return;
1139  }
1140  ResourceMark rm;
1141  DeoptimizationMarker dm;
1142  if (UseBiasedLocking) {
1143    revoke_biases_of_monitors(thread, fr, map);
1144  }
1145  deoptimize_single_frame(thread, fr);
1146
1147}
1148
1149
1150void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id) {
1151  assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
1152         "can only deoptimize other thread at a safepoint");
1153  // Compute frame and register map based on thread and sp.
1154  RegisterMap reg_map(thread, UseBiasedLocking);
1155  frame fr = thread->last_frame();
1156  while (fr.id() != id) {
1157    fr = fr.sender(&reg_map);
1158  }
1159  deoptimize(thread, fr, &reg_map);
1160}
1161
1162
1163void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
1164  if (thread == Thread::current()) {
1165    Deoptimization::deoptimize_frame_internal(thread, id);
1166  } else {
1167    VM_DeoptimizeFrame deopt(thread, id);
1168    VMThread::execute(&deopt);
1169  }
1170}
1171
1172
1173// JVMTI PopFrame support
1174JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
1175{
1176  thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
1177}
1178JRT_END
1179
1180
1181#if defined(COMPILER2) || defined(SHARK)
1182void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index, TRAPS) {
1183  // in case of an unresolved klass entry, load the class.
1184  if (constant_pool->tag_at(index).is_unresolved_klass()) {
1185    Klass* tk = constant_pool->klass_at(index, CHECK);
1186    return;
1187  }
1188
1189  if (!constant_pool->tag_at(index).is_symbol()) return;
1190
1191  Handle class_loader (THREAD, InstanceKlass::cast(constant_pool->pool_holder())->class_loader());
1192  Symbol*  symbol  = constant_pool->symbol_at(index);
1193
1194  // class name?
1195  if (symbol->byte_at(0) != '(') {
1196    Handle protection_domain (THREAD, Klass::cast(constant_pool->pool_holder())->protection_domain());
1197    SystemDictionary::resolve_or_null(symbol, class_loader, protection_domain, CHECK);
1198    return;
1199  }
1200
1201  // then it must be a signature!
1202  ResourceMark rm(THREAD);
1203  for (SignatureStream ss(symbol); !ss.is_done(); ss.next()) {
1204    if (ss.is_object()) {
1205      Symbol* class_name = ss.as_symbol(CHECK);
1206      Handle protection_domain (THREAD, Klass::cast(constant_pool->pool_holder())->protection_domain());
1207      SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK);
1208    }
1209  }
1210}
1211
1212
1213void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index) {
1214  EXCEPTION_MARK;
1215  load_class_by_index(constant_pool, index, THREAD);
1216  if (HAS_PENDING_EXCEPTION) {
1217    // Exception happened during classloading. We ignore the exception here, since it
1218    // is going to be rethrown since the current activation is going to be deoptimzied and
1219    // the interpreter will re-execute the bytecode.
1220    CLEAR_PENDING_EXCEPTION;
1221  }
1222}
1223
1224JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) {
1225  HandleMark hm;
1226
1227  // uncommon_trap() is called at the beginning of the uncommon trap
1228  // handler. Note this fact before we start generating temporary frames
1229  // that can confuse an asynchronous stack walker. This counter is
1230  // decremented at the end of unpack_frames().
1231  thread->inc_in_deopt_handler();
1232
1233  // We need to update the map if we have biased locking.
1234  RegisterMap reg_map(thread, UseBiasedLocking);
1235  frame stub_frame = thread->last_frame();
1236  frame fr = stub_frame.sender(&reg_map);
1237  // Make sure the calling nmethod is not getting deoptimized and removed
1238  // before we are done with it.
1239  nmethodLocker nl(fr.pc());
1240
1241  // Log a message
1242  Events::log_deopt_message(thread, "Uncommon trap %d fr.pc " INTPTR_FORMAT,
1243                            trap_request, fr.pc());
1244
1245  {
1246    ResourceMark rm;
1247
1248    // Revoke biases of any monitors in the frame to ensure we can migrate them
1249    revoke_biases_of_monitors(thread, fr, &reg_map);
1250
1251    DeoptReason reason = trap_request_reason(trap_request);
1252    DeoptAction action = trap_request_action(trap_request);
1253    jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
1254
1255    vframe*  vf  = vframe::new_vframe(&fr, &reg_map, thread);
1256    compiledVFrame* cvf = compiledVFrame::cast(vf);
1257
1258    nmethod* nm = cvf->code();
1259
1260    ScopeDesc*      trap_scope  = cvf->scope();
1261    methodHandle    trap_method = trap_scope->method();
1262    int             trap_bci    = trap_scope->bci();
1263    Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
1264
1265    // Record this event in the histogram.
1266    gather_statistics(reason, action, trap_bc);
1267
1268    // Ensure that we can record deopt. history:
1269    bool create_if_missing = ProfileTraps;
1270
1271    MethodData* trap_mdo =
1272      get_method_data(thread, trap_method, create_if_missing);
1273
1274    // Print a bunch of diagnostics, if requested.
1275    if (TraceDeoptimization || LogCompilation) {
1276      ResourceMark rm;
1277      ttyLocker ttyl;
1278      char buf[100];
1279      if (xtty != NULL) {
1280        xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT"' %s",
1281                         os::current_thread_id(),
1282                         format_trap_request(buf, sizeof(buf), trap_request));
1283        nm->log_identity(xtty);
1284      }
1285      Symbol* class_name = NULL;
1286      bool unresolved = false;
1287      if (unloaded_class_index >= 0) {
1288        constantPoolHandle constants (THREAD, trap_method->constants());
1289        if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
1290          class_name = constants->klass_name_at(unloaded_class_index);
1291          unresolved = true;
1292          if (xtty != NULL)
1293            xtty->print(" unresolved='1'");
1294        } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
1295          class_name = constants->symbol_at(unloaded_class_index);
1296        }
1297        if (xtty != NULL)
1298          xtty->name(class_name);
1299      }
1300      if (xtty != NULL && trap_mdo != NULL) {
1301        // Dump the relevant MDO state.
1302        // This is the deopt count for the current reason, any previous
1303        // reasons or recompiles seen at this point.
1304        int dcnt = trap_mdo->trap_count(reason);
1305        if (dcnt != 0)
1306          xtty->print(" count='%d'", dcnt);
1307        ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
1308        int dos = (pdata == NULL)? 0: pdata->trap_state();
1309        if (dos != 0) {
1310          xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
1311          if (trap_state_is_recompiled(dos)) {
1312            int recnt2 = trap_mdo->overflow_recompile_count();
1313            if (recnt2 != 0)
1314              xtty->print(" recompiles2='%d'", recnt2);
1315          }
1316        }
1317      }
1318      if (xtty != NULL) {
1319        xtty->stamp();
1320        xtty->end_head();
1321      }
1322      if (TraceDeoptimization) {  // make noise on the tty
1323        tty->print("Uncommon trap occurred in");
1324        nm->method()->print_short_name(tty);
1325        tty->print(" (@" INTPTR_FORMAT ") thread=%d reason=%s action=%s unloaded_class_index=%d",
1326                   fr.pc(),
1327                   (int) os::current_thread_id(),
1328                   trap_reason_name(reason),
1329                   trap_action_name(action),
1330                   unloaded_class_index);
1331        if (class_name != NULL) {
1332          tty->print(unresolved ? " unresolved class: " : " symbol: ");
1333          class_name->print_symbol_on(tty);
1334        }
1335        tty->cr();
1336      }
1337      if (xtty != NULL) {
1338        // Log the precise location of the trap.
1339        for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
1340          xtty->begin_elem("jvms bci='%d'", sd->bci());
1341          xtty->method(sd->method());
1342          xtty->end_elem();
1343          if (sd->is_top())  break;
1344        }
1345        xtty->tail("uncommon_trap");
1346      }
1347    }
1348    // (End diagnostic printout.)
1349
1350    // Load class if necessary
1351    if (unloaded_class_index >= 0) {
1352      constantPoolHandle constants(THREAD, trap_method->constants());
1353      load_class_by_index(constants, unloaded_class_index);
1354    }
1355
1356    // Flush the nmethod if necessary and desirable.
1357    //
1358    // We need to avoid situations where we are re-flushing the nmethod
1359    // because of a hot deoptimization site.  Repeated flushes at the same
1360    // point need to be detected by the compiler and avoided.  If the compiler
1361    // cannot avoid them (or has a bug and "refuses" to avoid them), this
1362    // module must take measures to avoid an infinite cycle of recompilation
1363    // and deoptimization.  There are several such measures:
1364    //
1365    //   1. If a recompilation is ordered a second time at some site X
1366    //   and for the same reason R, the action is adjusted to 'reinterpret',
1367    //   to give the interpreter time to exercise the method more thoroughly.
1368    //   If this happens, the method's overflow_recompile_count is incremented.
1369    //
1370    //   2. If the compiler fails to reduce the deoptimization rate, then
1371    //   the method's overflow_recompile_count will begin to exceed the set
1372    //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
1373    //   is adjusted to 'make_not_compilable', and the method is abandoned
1374    //   to the interpreter.  This is a performance hit for hot methods,
1375    //   but is better than a disastrous infinite cycle of recompilations.
1376    //   (Actually, only the method containing the site X is abandoned.)
1377    //
1378    //   3. In parallel with the previous measures, if the total number of
1379    //   recompilations of a method exceeds the much larger set limit
1380    //   PerMethodRecompilationCutoff, the method is abandoned.
1381    //   This should only happen if the method is very large and has
1382    //   many "lukewarm" deoptimizations.  The code which enforces this
1383    //   limit is elsewhere (class nmethod, class Method).
1384    //
1385    // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
1386    // to recompile at each bytecode independently of the per-BCI cutoff.
1387    //
1388    // The decision to update code is up to the compiler, and is encoded
1389    // in the Action_xxx code.  If the compiler requests Action_none
1390    // no trap state is changed, no compiled code is changed, and the
1391    // computation suffers along in the interpreter.
1392    //
1393    // The other action codes specify various tactics for decompilation
1394    // and recompilation.  Action_maybe_recompile is the loosest, and
1395    // allows the compiled code to stay around until enough traps are seen,
1396    // and until the compiler gets around to recompiling the trapping method.
1397    //
1398    // The other actions cause immediate removal of the present code.
1399
1400    bool update_trap_state = true;
1401    bool make_not_entrant = false;
1402    bool make_not_compilable = false;
1403    bool reprofile = false;
1404    switch (action) {
1405    case Action_none:
1406      // Keep the old code.
1407      update_trap_state = false;
1408      break;
1409    case Action_maybe_recompile:
1410      // Do not need to invalidate the present code, but we can
1411      // initiate another
1412      // Start compiler without (necessarily) invalidating the nmethod.
1413      // The system will tolerate the old code, but new code should be
1414      // generated when possible.
1415      break;
1416    case Action_reinterpret:
1417      // Go back into the interpreter for a while, and then consider
1418      // recompiling form scratch.
1419      make_not_entrant = true;
1420      // Reset invocation counter for outer most method.
1421      // This will allow the interpreter to exercise the bytecodes
1422      // for a while before recompiling.
1423      // By contrast, Action_make_not_entrant is immediate.
1424      //
1425      // Note that the compiler will track null_check, null_assert,
1426      // range_check, and class_check events and log them as if they
1427      // had been traps taken from compiled code.  This will update
1428      // the MDO trap history so that the next compilation will
1429      // properly detect hot trap sites.
1430      reprofile = true;
1431      break;
1432    case Action_make_not_entrant:
1433      // Request immediate recompilation, and get rid of the old code.
1434      // Make them not entrant, so next time they are called they get
1435      // recompiled.  Unloaded classes are loaded now so recompile before next
1436      // time they are called.  Same for uninitialized.  The interpreter will
1437      // link the missing class, if any.
1438      make_not_entrant = true;
1439      break;
1440    case Action_make_not_compilable:
1441      // Give up on compiling this method at all.
1442      make_not_entrant = true;
1443      make_not_compilable = true;
1444      break;
1445    default:
1446      ShouldNotReachHere();
1447    }
1448
1449    // Setting +ProfileTraps fixes the following, on all platforms:
1450    // 4852688: ProfileInterpreter is off by default for ia64.  The result is
1451    // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
1452    // recompile relies on a MethodData* to record heroic opt failures.
1453
1454    // Whether the interpreter is producing MDO data or not, we also need
1455    // to use the MDO to detect hot deoptimization points and control
1456    // aggressive optimization.
1457    bool inc_recompile_count = false;
1458    ProfileData* pdata = NULL;
1459    if (ProfileTraps && update_trap_state && trap_mdo != NULL) {
1460      assert(trap_mdo == get_method_data(thread, trap_method, false), "sanity");
1461      uint this_trap_count = 0;
1462      bool maybe_prior_trap = false;
1463      bool maybe_prior_recompile = false;
1464      pdata = query_update_method_data(trap_mdo, trap_bci, reason,
1465                                   //outputs:
1466                                   this_trap_count,
1467                                   maybe_prior_trap,
1468                                   maybe_prior_recompile);
1469      // Because the interpreter also counts null, div0, range, and class
1470      // checks, these traps from compiled code are double-counted.
1471      // This is harmless; it just means that the PerXTrapLimit values
1472      // are in effect a little smaller than they look.
1473
1474      DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
1475      if (per_bc_reason != Reason_none) {
1476        // Now take action based on the partially known per-BCI history.
1477        if (maybe_prior_trap
1478            && this_trap_count >= (uint)PerBytecodeTrapLimit) {
1479          // If there are too many traps at this BCI, force a recompile.
1480          // This will allow the compiler to see the limit overflow, and
1481          // take corrective action, if possible.  The compiler generally
1482          // does not use the exact PerBytecodeTrapLimit value, but instead
1483          // changes its tactics if it sees any traps at all.  This provides
1484          // a little hysteresis, delaying a recompile until a trap happens
1485          // several times.
1486          //
1487          // Actually, since there is only one bit of counter per BCI,
1488          // the possible per-BCI counts are {0,1,(per-method count)}.
1489          // This produces accurate results if in fact there is only
1490          // one hot trap site, but begins to get fuzzy if there are
1491          // many sites.  For example, if there are ten sites each
1492          // trapping two or more times, they each get the blame for
1493          // all of their traps.
1494          make_not_entrant = true;
1495        }
1496
1497        // Detect repeated recompilation at the same BCI, and enforce a limit.
1498        if (make_not_entrant && maybe_prior_recompile) {
1499          // More than one recompile at this point.
1500          inc_recompile_count = maybe_prior_trap;
1501        }
1502      } else {
1503        // For reasons which are not recorded per-bytecode, we simply
1504        // force recompiles unconditionally.
1505        // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
1506        make_not_entrant = true;
1507      }
1508
1509      // Go back to the compiler if there are too many traps in this method.
1510      if (this_trap_count >= (uint)PerMethodTrapLimit) {
1511        // If there are too many traps in this method, force a recompile.
1512        // This will allow the compiler to see the limit overflow, and
1513        // take corrective action, if possible.
1514        // (This condition is an unlikely backstop only, because the
1515        // PerBytecodeTrapLimit is more likely to take effect first,
1516        // if it is applicable.)
1517        make_not_entrant = true;
1518      }
1519
1520      // Here's more hysteresis:  If there has been a recompile at
1521      // this trap point already, run the method in the interpreter
1522      // for a while to exercise it more thoroughly.
1523      if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
1524        reprofile = true;
1525      }
1526
1527    }
1528
1529    // Take requested actions on the method:
1530
1531    // Recompile
1532    if (make_not_entrant) {
1533      if (!nm->make_not_entrant()) {
1534        return; // the call did not change nmethod's state
1535      }
1536
1537      if (pdata != NULL) {
1538        // Record the recompilation event, if any.
1539        int tstate0 = pdata->trap_state();
1540        int tstate1 = trap_state_set_recompiled(tstate0, true);
1541        if (tstate1 != tstate0)
1542          pdata->set_trap_state(tstate1);
1543      }
1544    }
1545
1546    if (inc_recompile_count) {
1547      trap_mdo->inc_overflow_recompile_count();
1548      if ((uint)trap_mdo->overflow_recompile_count() >
1549          (uint)PerBytecodeRecompilationCutoff) {
1550        // Give up on the method containing the bad BCI.
1551        if (trap_method() == nm->method()) {
1552          make_not_compilable = true;
1553        } else {
1554          trap_method->set_not_compilable(CompLevel_full_optimization);
1555          // But give grace to the enclosing nm->method().
1556        }
1557      }
1558    }
1559
1560    // Reprofile
1561    if (reprofile) {
1562      CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method());
1563    }
1564
1565    // Give up compiling
1566    if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
1567      assert(make_not_entrant, "consistent");
1568      nm->method()->set_not_compilable(CompLevel_full_optimization);
1569    }
1570
1571  } // Free marked resources
1572
1573}
1574JRT_END
1575
1576MethodData*
1577Deoptimization::get_method_data(JavaThread* thread, methodHandle m,
1578                                bool create_if_missing) {
1579  Thread* THREAD = thread;
1580  MethodData* mdo = m()->method_data();
1581  if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {
1582    // Build an MDO.  Ignore errors like OutOfMemory;
1583    // that simply means we won't have an MDO to update.
1584    Method::build_interpreter_method_data(m, THREAD);
1585    if (HAS_PENDING_EXCEPTION) {
1586      assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1587      CLEAR_PENDING_EXCEPTION;
1588    }
1589    mdo = m()->method_data();
1590  }
1591  return mdo;
1592}
1593
1594ProfileData*
1595Deoptimization::query_update_method_data(MethodData* trap_mdo,
1596                                         int trap_bci,
1597                                         Deoptimization::DeoptReason reason,
1598                                         //outputs:
1599                                         uint& ret_this_trap_count,
1600                                         bool& ret_maybe_prior_trap,
1601                                         bool& ret_maybe_prior_recompile) {
1602  uint prior_trap_count = trap_mdo->trap_count(reason);
1603  uint this_trap_count  = trap_mdo->inc_trap_count(reason);
1604
1605  // If the runtime cannot find a place to store trap history,
1606  // it is estimated based on the general condition of the method.
1607  // If the method has ever been recompiled, or has ever incurred
1608  // a trap with the present reason , then this BCI is assumed
1609  // (pessimistically) to be the culprit.
1610  bool maybe_prior_trap      = (prior_trap_count != 0);
1611  bool maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
1612  ProfileData* pdata = NULL;
1613
1614
1615  // For reasons which are recorded per bytecode, we check per-BCI data.
1616  DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
1617  if (per_bc_reason != Reason_none) {
1618    // Find the profile data for this BCI.  If there isn't one,
1619    // try to allocate one from the MDO's set of spares.
1620    // This will let us detect a repeated trap at this point.
1621    pdata = trap_mdo->allocate_bci_to_data(trap_bci);
1622
1623    if (pdata != NULL) {
1624      // Query the trap state of this profile datum.
1625      int tstate0 = pdata->trap_state();
1626      if (!trap_state_has_reason(tstate0, per_bc_reason))
1627        maybe_prior_trap = false;
1628      if (!trap_state_is_recompiled(tstate0))
1629        maybe_prior_recompile = false;
1630
1631      // Update the trap state of this profile datum.
1632      int tstate1 = tstate0;
1633      // Record the reason.
1634      tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
1635      // Store the updated state on the MDO, for next time.
1636      if (tstate1 != tstate0)
1637        pdata->set_trap_state(tstate1);
1638    } else {
1639      if (LogCompilation && xtty != NULL) {
1640        ttyLocker ttyl;
1641        // Missing MDP?  Leave a small complaint in the log.
1642        xtty->elem("missing_mdp bci='%d'", trap_bci);
1643      }
1644    }
1645  }
1646
1647  // Return results:
1648  ret_this_trap_count = this_trap_count;
1649  ret_maybe_prior_trap = maybe_prior_trap;
1650  ret_maybe_prior_recompile = maybe_prior_recompile;
1651  return pdata;
1652}
1653
1654void
1655Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
1656  ResourceMark rm;
1657  // Ignored outputs:
1658  uint ignore_this_trap_count;
1659  bool ignore_maybe_prior_trap;
1660  bool ignore_maybe_prior_recompile;
1661  query_update_method_data(trap_mdo, trap_bci,
1662                           (DeoptReason)reason,
1663                           ignore_this_trap_count,
1664                           ignore_maybe_prior_trap,
1665                           ignore_maybe_prior_recompile);
1666}
1667
1668Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request) {
1669
1670  // Still in Java no safepoints
1671  {
1672    // This enters VM and may safepoint
1673    uncommon_trap_inner(thread, trap_request);
1674  }
1675  return fetch_unroll_info_helper(thread);
1676}
1677
1678// Local derived constants.
1679// Further breakdown of DataLayout::trap_state, as promised by DataLayout.
1680const int DS_REASON_MASK   = DataLayout::trap_mask >> 1;
1681const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
1682
1683//---------------------------trap_state_reason---------------------------------
1684Deoptimization::DeoptReason
1685Deoptimization::trap_state_reason(int trap_state) {
1686  // This assert provides the link between the width of DataLayout::trap_bits
1687  // and the encoding of "recorded" reasons.  It ensures there are enough
1688  // bits to store all needed reasons in the per-BCI MDO profile.
1689  assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
1690  int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
1691  trap_state -= recompile_bit;
1692  if (trap_state == DS_REASON_MASK) {
1693    return Reason_many;
1694  } else {
1695    assert((int)Reason_none == 0, "state=0 => Reason_none");
1696    return (DeoptReason)trap_state;
1697  }
1698}
1699//-------------------------trap_state_has_reason-------------------------------
1700int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
1701  assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
1702  assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
1703  int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
1704  trap_state -= recompile_bit;
1705  if (trap_state == DS_REASON_MASK) {
1706    return -1;  // true, unspecifically (bottom of state lattice)
1707  } else if (trap_state == reason) {
1708    return 1;   // true, definitely
1709  } else if (trap_state == 0) {
1710    return 0;   // false, definitely (top of state lattice)
1711  } else {
1712    return 0;   // false, definitely
1713  }
1714}
1715//-------------------------trap_state_add_reason-------------------------------
1716int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
1717  assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
1718  int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
1719  trap_state -= recompile_bit;
1720  if (trap_state == DS_REASON_MASK) {
1721    return trap_state + recompile_bit;     // already at state lattice bottom
1722  } else if (trap_state == reason) {
1723    return trap_state + recompile_bit;     // the condition is already true
1724  } else if (trap_state == 0) {
1725    return reason + recompile_bit;          // no condition has yet been true
1726  } else {
1727    return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
1728  }
1729}
1730//-----------------------trap_state_is_recompiled------------------------------
1731bool Deoptimization::trap_state_is_recompiled(int trap_state) {
1732  return (trap_state & DS_RECOMPILE_BIT) != 0;
1733}
1734//-----------------------trap_state_set_recompiled-----------------------------
1735int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
1736  if (z)  return trap_state |  DS_RECOMPILE_BIT;
1737  else    return trap_state & ~DS_RECOMPILE_BIT;
1738}
1739//---------------------------format_trap_state---------------------------------
1740// This is used for debugging and diagnostics, including hotspot.log output.
1741const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
1742                                              int trap_state) {
1743  DeoptReason reason      = trap_state_reason(trap_state);
1744  bool        recomp_flag = trap_state_is_recompiled(trap_state);
1745  // Re-encode the state from its decoded components.
1746  int decoded_state = 0;
1747  if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
1748    decoded_state = trap_state_add_reason(decoded_state, reason);
1749  if (recomp_flag)
1750    decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
1751  // If the state re-encodes properly, format it symbolically.
1752  // Because this routine is used for debugging and diagnostics,
1753  // be robust even if the state is a strange value.
1754  size_t len;
1755  if (decoded_state != trap_state) {
1756    // Random buggy state that doesn't decode??
1757    len = jio_snprintf(buf, buflen, "#%d", trap_state);
1758  } else {
1759    len = jio_snprintf(buf, buflen, "%s%s",
1760                       trap_reason_name(reason),
1761                       recomp_flag ? " recompiled" : "");
1762  }
1763  if (len >= buflen)
1764    buf[buflen-1] = '\0';
1765  return buf;
1766}
1767
1768
1769//--------------------------------statics--------------------------------------
1770Deoptimization::DeoptAction Deoptimization::_unloaded_action
1771  = Deoptimization::Action_reinterpret;
1772const char* Deoptimization::_trap_reason_name[Reason_LIMIT] = {
1773  // Note:  Keep this in sync. with enum DeoptReason.
1774  "none",
1775  "null_check",
1776  "null_assert",
1777  "range_check",
1778  "class_check",
1779  "array_check",
1780  "intrinsic",
1781  "bimorphic",
1782  "unloaded",
1783  "uninitialized",
1784  "unreached",
1785  "unhandled",
1786  "constraint",
1787  "div0_check",
1788  "age",
1789  "predicate",
1790  "loop_limit_check"
1791};
1792const char* Deoptimization::_trap_action_name[Action_LIMIT] = {
1793  // Note:  Keep this in sync. with enum DeoptAction.
1794  "none",
1795  "maybe_recompile",
1796  "reinterpret",
1797  "make_not_entrant",
1798  "make_not_compilable"
1799};
1800
1801const char* Deoptimization::trap_reason_name(int reason) {
1802  if (reason == Reason_many)  return "many";
1803  if ((uint)reason < Reason_LIMIT)
1804    return _trap_reason_name[reason];
1805  static char buf[20];
1806  sprintf(buf, "reason%d", reason);
1807  return buf;
1808}
1809const char* Deoptimization::trap_action_name(int action) {
1810  if ((uint)action < Action_LIMIT)
1811    return _trap_action_name[action];
1812  static char buf[20];
1813  sprintf(buf, "action%d", action);
1814  return buf;
1815}
1816
1817// This is used for debugging and diagnostics, including hotspot.log output.
1818const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
1819                                                int trap_request) {
1820  jint unloaded_class_index = trap_request_index(trap_request);
1821  const char* reason = trap_reason_name(trap_request_reason(trap_request));
1822  const char* action = trap_action_name(trap_request_action(trap_request));
1823  size_t len;
1824  if (unloaded_class_index < 0) {
1825    len = jio_snprintf(buf, buflen, "reason='%s' action='%s'",
1826                       reason, action);
1827  } else {
1828    len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'",
1829                       reason, action, unloaded_class_index);
1830  }
1831  if (len >= buflen)
1832    buf[buflen-1] = '\0';
1833  return buf;
1834}
1835
1836juint Deoptimization::_deoptimization_hist
1837        [Deoptimization::Reason_LIMIT]
1838    [1 + Deoptimization::Action_LIMIT]
1839        [Deoptimization::BC_CASE_LIMIT]
1840  = {0};
1841
1842enum {
1843  LSB_BITS = 8,
1844  LSB_MASK = right_n_bits(LSB_BITS)
1845};
1846
1847void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
1848                                       Bytecodes::Code bc) {
1849  assert(reason >= 0 && reason < Reason_LIMIT, "oob");
1850  assert(action >= 0 && action < Action_LIMIT, "oob");
1851  _deoptimization_hist[Reason_none][0][0] += 1;  // total
1852  _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
1853  juint* cases = _deoptimization_hist[reason][1+action];
1854  juint* bc_counter_addr = NULL;
1855  juint  bc_counter      = 0;
1856  // Look for an unused counter, or an exact match to this BC.
1857  if (bc != Bytecodes::_illegal) {
1858    for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
1859      juint* counter_addr = &cases[bc_case];
1860      juint  counter = *counter_addr;
1861      if ((counter == 0 && bc_counter_addr == NULL)
1862          || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
1863        // this counter is either free or is already devoted to this BC
1864        bc_counter_addr = counter_addr;
1865        bc_counter = counter | bc;
1866      }
1867    }
1868  }
1869  if (bc_counter_addr == NULL) {
1870    // Overflow, or no given bytecode.
1871    bc_counter_addr = &cases[BC_CASE_LIMIT-1];
1872    bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
1873  }
1874  *bc_counter_addr = bc_counter + (1 << LSB_BITS);
1875}
1876
1877jint Deoptimization::total_deoptimization_count() {
1878  return _deoptimization_hist[Reason_none][0][0];
1879}
1880
1881jint Deoptimization::deoptimization_count(DeoptReason reason) {
1882  assert(reason >= 0 && reason < Reason_LIMIT, "oob");
1883  return _deoptimization_hist[reason][0][0];
1884}
1885
1886void Deoptimization::print_statistics() {
1887  juint total = total_deoptimization_count();
1888  juint account = total;
1889  if (total != 0) {
1890    ttyLocker ttyl;
1891    if (xtty != NULL)  xtty->head("statistics type='deoptimization'");
1892    tty->print_cr("Deoptimization traps recorded:");
1893    #define PRINT_STAT_LINE(name, r) \
1894      tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
1895    PRINT_STAT_LINE("total", total);
1896    // For each non-zero entry in the histogram, print the reason,
1897    // the action, and (if specifically known) the type of bytecode.
1898    for (int reason = 0; reason < Reason_LIMIT; reason++) {
1899      for (int action = 0; action < Action_LIMIT; action++) {
1900        juint* cases = _deoptimization_hist[reason][1+action];
1901        for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
1902          juint counter = cases[bc_case];
1903          if (counter != 0) {
1904            char name[1*K];
1905            Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
1906            if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
1907              bc = Bytecodes::_illegal;
1908            sprintf(name, "%s/%s/%s",
1909                    trap_reason_name(reason),
1910                    trap_action_name(action),
1911                    Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
1912            juint r = counter >> LSB_BITS;
1913            tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
1914            account -= r;
1915          }
1916        }
1917      }
1918    }
1919    if (account != 0) {
1920      PRINT_STAT_LINE("unaccounted", account);
1921    }
1922    #undef PRINT_STAT_LINE
1923    if (xtty != NULL)  xtty->tail("statistics");
1924  }
1925}
1926#else // COMPILER2 || SHARK
1927
1928
1929// Stubs for C1 only system.
1930bool Deoptimization::trap_state_is_recompiled(int trap_state) {
1931  return false;
1932}
1933
1934const char* Deoptimization::trap_reason_name(int reason) {
1935  return "unknown";
1936}
1937
1938void Deoptimization::print_statistics() {
1939  // no output
1940}
1941
1942void
1943Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
1944  // no udpate
1945}
1946
1947int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
1948  return 0;
1949}
1950
1951void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
1952                                       Bytecodes::Code bc) {
1953  // no update
1954}
1955
1956const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
1957                                              int trap_state) {
1958  jio_snprintf(buf, buflen, "#%d", trap_state);
1959  return buf;
1960}
1961
1962#endif // COMPILER2 || SHARK
1963