src/share/vm/runtime/deoptimization.cpp

changeset 0
f90c822e73f8
child 1
2d8a650513c2
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/share/vm/runtime/deoptimization.cpp	Wed Apr 27 01:25:04 2016 +0800
     1.3 @@ -0,0 +1,2010 @@
     1.4 +/*
     1.5 + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.
    1.11 + *
    1.12 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.13 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.14 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.15 + * version 2 for more details (a copy is included in the LICENSE file that
    1.16 + * accompanied this code).
    1.17 + *
    1.18 + * You should have received a copy of the GNU General Public License version
    1.19 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.20 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.21 + *
    1.22 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.23 + * or visit www.oracle.com if you need additional information or have any
    1.24 + * questions.
    1.25 + *
    1.26 + */
    1.27 +
    1.28 +#include "precompiled.hpp"
    1.29 +#include "classfile/systemDictionary.hpp"
    1.30 +#include "code/debugInfoRec.hpp"
    1.31 +#include "code/nmethod.hpp"
    1.32 +#include "code/pcDesc.hpp"
    1.33 +#include "code/scopeDesc.hpp"
    1.34 +#include "interpreter/bytecode.hpp"
    1.35 +#include "interpreter/interpreter.hpp"
    1.36 +#include "interpreter/oopMapCache.hpp"
    1.37 +#include "memory/allocation.inline.hpp"
    1.38 +#include "memory/oopFactory.hpp"
    1.39 +#include "memory/resourceArea.hpp"
    1.40 +#include "oops/method.hpp"
    1.41 +#include "oops/oop.inline.hpp"
    1.42 +#include "prims/jvmtiThreadState.hpp"
    1.43 +#include "runtime/biasedLocking.hpp"
    1.44 +#include "runtime/compilationPolicy.hpp"
    1.45 +#include "runtime/deoptimization.hpp"
    1.46 +#include "runtime/interfaceSupport.hpp"
    1.47 +#include "runtime/sharedRuntime.hpp"
    1.48 +#include "runtime/signature.hpp"
    1.49 +#include "runtime/stubRoutines.hpp"
    1.50 +#include "runtime/thread.hpp"
    1.51 +#include "runtime/vframe.hpp"
    1.52 +#include "runtime/vframeArray.hpp"
    1.53 +#include "runtime/vframe_hp.hpp"
    1.54 +#include "utilities/events.hpp"
    1.55 +#include "utilities/xmlstream.hpp"
    1.56 +#ifdef TARGET_ARCH_x86
    1.57 +# include "vmreg_x86.inline.hpp"
    1.58 +#endif
    1.59 +#ifdef TARGET_ARCH_sparc
    1.60 +# include "vmreg_sparc.inline.hpp"
    1.61 +#endif
    1.62 +#ifdef TARGET_ARCH_zero
    1.63 +# include "vmreg_zero.inline.hpp"
    1.64 +#endif
    1.65 +#ifdef TARGET_ARCH_arm
    1.66 +# include "vmreg_arm.inline.hpp"
    1.67 +#endif
    1.68 +#ifdef TARGET_ARCH_ppc
    1.69 +# include "vmreg_ppc.inline.hpp"
    1.70 +#endif
    1.71 +#ifdef COMPILER2
    1.72 +#ifdef TARGET_ARCH_MODEL_x86_32
    1.73 +# include "adfiles/ad_x86_32.hpp"
    1.74 +#endif
    1.75 +#ifdef TARGET_ARCH_MODEL_x86_64
    1.76 +# include "adfiles/ad_x86_64.hpp"
    1.77 +#endif
    1.78 +#ifdef TARGET_ARCH_MODEL_sparc
    1.79 +# include "adfiles/ad_sparc.hpp"
    1.80 +#endif
    1.81 +#ifdef TARGET_ARCH_MODEL_zero
    1.82 +# include "adfiles/ad_zero.hpp"
    1.83 +#endif
    1.84 +#ifdef TARGET_ARCH_MODEL_arm
    1.85 +# include "adfiles/ad_arm.hpp"
    1.86 +#endif
    1.87 +#ifdef TARGET_ARCH_MODEL_ppc_32
    1.88 +# include "adfiles/ad_ppc_32.hpp"
    1.89 +#endif
    1.90 +#ifdef TARGET_ARCH_MODEL_ppc_64
    1.91 +# include "adfiles/ad_ppc_64.hpp"
    1.92 +#endif
    1.93 +#endif // COMPILER2
    1.94 +
    1.95 +PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    1.96 +
    1.97 +bool DeoptimizationMarker::_is_active = false;
    1.98 +
    1.99 +Deoptimization::UnrollBlock::UnrollBlock(int  size_of_deoptimized_frame,
   1.100 +                                         int  caller_adjustment,
   1.101 +                                         int  caller_actual_parameters,
   1.102 +                                         int  number_of_frames,
   1.103 +                                         intptr_t* frame_sizes,
   1.104 +                                         address* frame_pcs,
   1.105 +                                         BasicType return_type) {
   1.106 +  _size_of_deoptimized_frame = size_of_deoptimized_frame;
   1.107 +  _caller_adjustment         = caller_adjustment;
   1.108 +  _caller_actual_parameters  = caller_actual_parameters;
   1.109 +  _number_of_frames          = number_of_frames;
   1.110 +  _frame_sizes               = frame_sizes;
   1.111 +  _frame_pcs                 = frame_pcs;
   1.112 +  _register_block            = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
   1.113 +  _return_type               = return_type;
   1.114 +  _initial_info              = 0;
   1.115 +  // PD (x86 only)
   1.116 +  _counter_temp              = 0;
   1.117 +  _unpack_kind               = 0;
   1.118 +  _sender_sp_temp            = 0;
   1.119 +
   1.120 +  _total_frame_sizes         = size_of_frames();
   1.121 +}
   1.122 +
   1.123 +
   1.124 +Deoptimization::UnrollBlock::~UnrollBlock() {
   1.125 +  FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes, mtCompiler);
   1.126 +  FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs, mtCompiler);
   1.127 +  FREE_C_HEAP_ARRAY(intptr_t, _register_block, mtCompiler);
   1.128 +}
   1.129 +
   1.130 +
   1.131 +intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {
   1.132 +  assert(register_number < RegisterMap::reg_count, "checking register number");
   1.133 +  return &_register_block[register_number * 2];
   1.134 +}
   1.135 +
   1.136 +
   1.137 +
   1.138 +int Deoptimization::UnrollBlock::size_of_frames() const {
   1.139 +  // Acount first for the adjustment of the initial frame
   1.140 +  int result = _caller_adjustment;
   1.141 +  for (int index = 0; index < number_of_frames(); index++) {
   1.142 +    result += frame_sizes()[index];
   1.143 +  }
   1.144 +  return result;
   1.145 +}
   1.146 +
   1.147 +
   1.148 +void Deoptimization::UnrollBlock::print() {
   1.149 +  ttyLocker ttyl;
   1.150 +  tty->print_cr("UnrollBlock");
   1.151 +  tty->print_cr("  size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
   1.152 +  tty->print(   "  frame_sizes: ");
   1.153 +  for (int index = 0; index < number_of_frames(); index++) {
   1.154 +    tty->print("%d ", frame_sizes()[index]);
   1.155 +  }
   1.156 +  tty->cr();
   1.157 +}
   1.158 +
   1.159 +
   1.160 +// In order to make fetch_unroll_info work properly with escape
   1.161 +// analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and
   1.162 +// ResetNoHandleMark and HandleMark were removed from it. The actual reallocation
   1.163 +// of previously eliminated objects occurs in realloc_objects, which is
   1.164 +// called from the method fetch_unroll_info_helper below.
   1.165 +JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread))
   1.166 +  // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
   1.167 +  // but makes the entry a little slower. There is however a little dance we have to
   1.168 +  // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
   1.169 +
   1.170 +  // fetch_unroll_info() is called at the beginning of the deoptimization
   1.171 +  // handler. Note this fact before we start generating temporary frames
   1.172 +  // that can confuse an asynchronous stack walker. This counter is
   1.173 +  // decremented at the end of unpack_frames().
   1.174 +  thread->inc_in_deopt_handler();
   1.175 +
   1.176 +  return fetch_unroll_info_helper(thread);
   1.177 +JRT_END
   1.178 +
   1.179 +
   1.180 +// This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
   1.181 +Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread) {
   1.182 +
   1.183 +  // Note: there is a safepoint safety issue here. No matter whether we enter
   1.184 +  // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
   1.185 +  // the vframeArray is created.
   1.186 +  //
   1.187 +
   1.188 +  // Allocate our special deoptimization ResourceMark
   1.189 +  DeoptResourceMark* dmark = new DeoptResourceMark(thread);
   1.190 +  assert(thread->deopt_mark() == NULL, "Pending deopt!");
   1.191 +  thread->set_deopt_mark(dmark);
   1.192 +
   1.193 +  frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect
   1.194 +  RegisterMap map(thread, true);
   1.195 +  RegisterMap dummy_map(thread, false);
   1.196 +  // Now get the deoptee with a valid map
   1.197 +  frame deoptee = stub_frame.sender(&map);
   1.198 +  // Set the deoptee nmethod
   1.199 +  assert(thread->deopt_nmethod() == NULL, "Pending deopt!");
   1.200 +  thread->set_deopt_nmethod(deoptee.cb()->as_nmethod_or_null());
   1.201 +
   1.202 +  if (VerifyStack) {
   1.203 +    thread->validate_frame_layout();
   1.204 +  }
   1.205 +
   1.206 +  // Create a growable array of VFrames where each VFrame represents an inlined
   1.207 +  // Java frame.  This storage is allocated with the usual system arena.
   1.208 +  assert(deoptee.is_compiled_frame(), "Wrong frame type");
   1.209 +  GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
   1.210 +  vframe* vf = vframe::new_vframe(&deoptee, &map, thread);
   1.211 +  while (!vf->is_top()) {
   1.212 +    assert(vf->is_compiled_frame(), "Wrong frame type");
   1.213 +    chunk->push(compiledVFrame::cast(vf));
   1.214 +    vf = vf->sender();
   1.215 +  }
   1.216 +  assert(vf->is_compiled_frame(), "Wrong frame type");
   1.217 +  chunk->push(compiledVFrame::cast(vf));
   1.218 +
   1.219 +#ifdef COMPILER2
   1.220 +  // Reallocate the non-escaping objects and restore their fields. Then
   1.221 +  // relock objects if synchronization on them was eliminated.
   1.222 +  if (DoEscapeAnalysis || EliminateNestedLocks) {
   1.223 +    if (EliminateAllocations) {
   1.224 +      assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");
   1.225 +      GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
   1.226 +
   1.227 +      // The flag return_oop() indicates call sites which return oop
   1.228 +      // in compiled code. Such sites include java method calls,
   1.229 +      // runtime calls (for example, used to allocate new objects/arrays
   1.230 +      // on slow code path) and any other calls generated in compiled code.
   1.231 +      // It is not guaranteed that we can get such information here only
   1.232 +      // by analyzing bytecode in deoptimized frames. This is why this flag
   1.233 +      // is set during method compilation (see Compile::Process_OopMap_Node()).
   1.234 +      bool save_oop_result = chunk->at(0)->scope()->return_oop();
   1.235 +      Handle return_value;
   1.236 +      if (save_oop_result) {
   1.237 +        // Reallocation may trigger GC. If deoptimization happened on return from
   1.238 +        // call which returns oop we need to save it since it is not in oopmap.
   1.239 +        oop result = deoptee.saved_oop_result(&map);
   1.240 +        assert(result == NULL || result->is_oop(), "must be oop");
   1.241 +        return_value = Handle(thread, result);
   1.242 +        assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
   1.243 +        if (TraceDeoptimization) {
   1.244 +          ttyLocker ttyl;
   1.245 +          tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, (void *)result, thread);
   1.246 +        }
   1.247 +      }
   1.248 +      bool reallocated = false;
   1.249 +      if (objects != NULL) {
   1.250 +        JRT_BLOCK
   1.251 +          reallocated = realloc_objects(thread, &deoptee, objects, THREAD);
   1.252 +        JRT_END
   1.253 +      }
   1.254 +      if (reallocated) {
   1.255 +        reassign_fields(&deoptee, &map, objects);
   1.256 +#ifndef PRODUCT
   1.257 +        if (TraceDeoptimization) {
   1.258 +          ttyLocker ttyl;
   1.259 +          tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, thread);
   1.260 +          print_objects(objects);
   1.261 +        }
   1.262 +#endif
   1.263 +      }
   1.264 +      if (save_oop_result) {
   1.265 +        // Restore result.
   1.266 +        deoptee.set_saved_oop_result(&map, return_value());
   1.267 +      }
   1.268 +    }
   1.269 +    if (EliminateLocks) {
   1.270 +#ifndef PRODUCT
   1.271 +      bool first = true;
   1.272 +#endif
   1.273 +      for (int i = 0; i < chunk->length(); i++) {
   1.274 +        compiledVFrame* cvf = chunk->at(i);
   1.275 +        assert (cvf->scope() != NULL,"expect only compiled java frames");
   1.276 +        GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
   1.277 +        if (monitors->is_nonempty()) {
   1.278 +          relock_objects(monitors, thread);
   1.279 +#ifndef PRODUCT
   1.280 +          if (TraceDeoptimization) {
   1.281 +            ttyLocker ttyl;
   1.282 +            for (int j = 0; j < monitors->length(); j++) {
   1.283 +              MonitorInfo* mi = monitors->at(j);
   1.284 +              if (mi->eliminated()) {
   1.285 +                if (first) {
   1.286 +                  first = false;
   1.287 +                  tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread);
   1.288 +                }
   1.289 +                tty->print_cr("     object <" INTPTR_FORMAT "> locked", (void *)mi->owner());
   1.290 +              }
   1.291 +            }
   1.292 +          }
   1.293 +#endif
   1.294 +        }
   1.295 +      }
   1.296 +    }
   1.297 +  }
   1.298 +#endif // COMPILER2
   1.299 +  // Ensure that no safepoint is taken after pointers have been stored
   1.300 +  // in fields of rematerialized objects.  If a safepoint occurs from here on
   1.301 +  // out the java state residing in the vframeArray will be missed.
   1.302 +  No_Safepoint_Verifier no_safepoint;
   1.303 +
   1.304 +  vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk);
   1.305 +
   1.306 +  assert(thread->vframe_array_head() == NULL, "Pending deopt!");;
   1.307 +  thread->set_vframe_array_head(array);
   1.308 +
   1.309 +  // Now that the vframeArray has been created if we have any deferred local writes
   1.310 +  // added by jvmti then we can free up that structure as the data is now in the
   1.311 +  // vframeArray
   1.312 +
   1.313 +  if (thread->deferred_locals() != NULL) {
   1.314 +    GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals();
   1.315 +    int i = 0;
   1.316 +    do {
   1.317 +      // Because of inlining we could have multiple vframes for a single frame
   1.318 +      // and several of the vframes could have deferred writes. Find them all.
   1.319 +      if (list->at(i)->id() == array->original().id()) {
   1.320 +        jvmtiDeferredLocalVariableSet* dlv = list->at(i);
   1.321 +        list->remove_at(i);
   1.322 +        // individual jvmtiDeferredLocalVariableSet are CHeapObj's
   1.323 +        delete dlv;
   1.324 +      } else {
   1.325 +        i++;
   1.326 +      }
   1.327 +    } while ( i < list->length() );
   1.328 +    if (list->length() == 0) {
   1.329 +      thread->set_deferred_locals(NULL);
   1.330 +      // free the list and elements back to C heap.
   1.331 +      delete list;
   1.332 +    }
   1.333 +
   1.334 +  }
   1.335 +
   1.336 +#ifndef SHARK
   1.337 +  // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
   1.338 +  CodeBlob* cb = stub_frame.cb();
   1.339 +  // Verify we have the right vframeArray
   1.340 +  assert(cb->frame_size() >= 0, "Unexpected frame size");
   1.341 +  intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
   1.342 +
   1.343 +  // If the deopt call site is a MethodHandle invoke call site we have
   1.344 +  // to adjust the unpack_sp.
   1.345 +  nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
   1.346 +  if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))
   1.347 +    unpack_sp = deoptee.unextended_sp();
   1.348 +
   1.349 +#ifdef ASSERT
   1.350 +  assert(cb->is_deoptimization_stub() || cb->is_uncommon_trap_stub(), "just checking");
   1.351 +#endif
   1.352 +#else
   1.353 +  intptr_t* unpack_sp = stub_frame.sender(&dummy_map).unextended_sp();
   1.354 +#endif // !SHARK
   1.355 +
   1.356 +  // This is a guarantee instead of an assert because if vframe doesn't match
   1.357 +  // we will unpack the wrong deoptimized frame and wind up in strange places
   1.358 +  // where it will be very difficult to figure out what went wrong. Better
   1.359 +  // to die an early death here than some very obscure death later when the
   1.360 +  // trail is cold.
   1.361 +  // Note: on ia64 this guarantee can be fooled by frames with no memory stack
   1.362 +  // in that it will fail to detect a problem when there is one. This needs
   1.363 +  // more work in tiger timeframe.
   1.364 +  guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
   1.365 +
   1.366 +  int number_of_frames = array->frames();
   1.367 +
   1.368 +  // Compute the vframes' sizes.  Note that frame_sizes[] entries are ordered from outermost to innermost
   1.369 +  // virtual activation, which is the reverse of the elements in the vframes array.
   1.370 +  intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
   1.371 +  // +1 because we always have an interpreter return address for the final slot.
   1.372 +  address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
   1.373 +  int popframe_extra_args = 0;
   1.374 +  // Create an interpreter return address for the stub to use as its return
   1.375 +  // address so the skeletal frames are perfectly walkable
   1.376 +  frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
   1.377 +
   1.378 +  // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
   1.379 +  // activation be put back on the expression stack of the caller for reexecution
   1.380 +  if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {
   1.381 +    popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words());
   1.382 +  }
   1.383 +
   1.384 +  // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
   1.385 +  // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
   1.386 +  // than simply use array->sender.pc(). This requires us to walk the current set of frames
   1.387 +  //
   1.388 +  frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
   1.389 +  deopt_sender = deopt_sender.sender(&dummy_map);     // Now deoptee caller
   1.390 +
   1.391 +  // It's possible that the number of paramters at the call site is
   1.392 +  // different than number of arguments in the callee when method
   1.393 +  // handles are used.  If the caller is interpreted get the real
   1.394 +  // value so that the proper amount of space can be added to it's
   1.395 +  // frame.
   1.396 +  bool caller_was_method_handle = false;
   1.397 +  if (deopt_sender.is_interpreted_frame()) {
   1.398 +    methodHandle method = deopt_sender.interpreter_frame_method();
   1.399 +    Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
   1.400 +    if (cur.is_invokedynamic() || cur.is_invokehandle()) {
   1.401 +      // Method handle invokes may involve fairly arbitrary chains of
   1.402 +      // calls so it's impossible to know how much actual space the
   1.403 +      // caller has for locals.
   1.404 +      caller_was_method_handle = true;
   1.405 +    }
   1.406 +  }
   1.407 +
   1.408 +  //
   1.409 +  // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
   1.410 +  // frame_sizes/frame_pcs[1] next oldest frame (int)
   1.411 +  // frame_sizes/frame_pcs[n] youngest frame (int)
   1.412 +  //
   1.413 +  // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
   1.414 +  // owns the space for the return address to it's caller).  Confusing ain't it.
   1.415 +  //
   1.416 +  // The vframe array can address vframes with indices running from
   1.417 +  // 0.._frames-1. Index  0 is the youngest frame and _frame - 1 is the oldest (root) frame.
   1.418 +  // When we create the skeletal frames we need the oldest frame to be in the zero slot
   1.419 +  // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
   1.420 +  // so things look a little strange in this loop.
   1.421 +  //
   1.422 +  int callee_parameters = 0;
   1.423 +  int callee_locals = 0;
   1.424 +  for (int index = 0; index < array->frames(); index++ ) {
   1.425 +    // frame[number_of_frames - 1 ] = on_stack_size(youngest)
   1.426 +    // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
   1.427 +    // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
   1.428 +    frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
   1.429 +                                                                                                    callee_locals,
   1.430 +                                                                                                    index == 0,
   1.431 +                                                                                                    popframe_extra_args);
   1.432 +    // This pc doesn't have to be perfect just good enough to identify the frame
   1.433 +    // as interpreted so the skeleton frame will be walkable
   1.434 +    // The correct pc will be set when the skeleton frame is completely filled out
   1.435 +    // The final pc we store in the loop is wrong and will be overwritten below
   1.436 +    frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
   1.437 +
   1.438 +    callee_parameters = array->element(index)->method()->size_of_parameters();
   1.439 +    callee_locals = array->element(index)->method()->max_locals();
   1.440 +    popframe_extra_args = 0;
   1.441 +  }
   1.442 +
   1.443 +  // Compute whether the root vframe returns a float or double value.
   1.444 +  BasicType return_type;
   1.445 +  {
   1.446 +    HandleMark hm;
   1.447 +    methodHandle method(thread, array->element(0)->method());
   1.448 +    Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
   1.449 +    return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
   1.450 +  }
   1.451 +
   1.452 +  // Compute information for handling adapters and adjusting the frame size of the caller.
   1.453 +  int caller_adjustment = 0;
   1.454 +
   1.455 +  // Compute the amount the oldest interpreter frame will have to adjust
   1.456 +  // its caller's stack by. If the caller is a compiled frame then
   1.457 +  // we pretend that the callee has no parameters so that the
   1.458 +  // extension counts for the full amount of locals and not just
   1.459 +  // locals-parms. This is because without a c2i adapter the parm
   1.460 +  // area as created by the compiled frame will not be usable by
   1.461 +  // the interpreter. (Depending on the calling convention there
   1.462 +  // may not even be enough space).
   1.463 +
   1.464 +  // QQQ I'd rather see this pushed down into last_frame_adjust
   1.465 +  // and have it take the sender (aka caller).
   1.466 +
   1.467 +  if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {
   1.468 +    caller_adjustment = last_frame_adjust(0, callee_locals);
   1.469 +  } else if (callee_locals > callee_parameters) {
   1.470 +    // The caller frame may need extending to accommodate
   1.471 +    // non-parameter locals of the first unpacked interpreted frame.
   1.472 +    // Compute that adjustment.
   1.473 +    caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
   1.474 +  }
   1.475 +
   1.476 +  // If the sender is deoptimized the we must retrieve the address of the handler
   1.477 +  // since the frame will "magically" show the original pc before the deopt
   1.478 +  // and we'd undo the deopt.
   1.479 +
   1.480 +  frame_pcs[0] = deopt_sender.raw_pc();
   1.481 +
   1.482 +#ifndef SHARK
   1.483 +  assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");
   1.484 +#endif // SHARK
   1.485 +
   1.486 +  UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
   1.487 +                                      caller_adjustment * BytesPerWord,
   1.488 +                                      caller_was_method_handle ? 0 : callee_parameters,
   1.489 +                                      number_of_frames,
   1.490 +                                      frame_sizes,
   1.491 +                                      frame_pcs,
   1.492 +                                      return_type);
   1.493 +  // On some platforms, we need a way to pass some platform dependent
   1.494 +  // information to the unpacking code so the skeletal frames come out
   1.495 +  // correct (initial fp value, unextended sp, ...)
   1.496 +  info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
   1.497 +
   1.498 +  if (array->frames() > 1) {
   1.499 +    if (VerifyStack && TraceDeoptimization) {
   1.500 +      ttyLocker ttyl;
   1.501 +      tty->print_cr("Deoptimizing method containing inlining");
   1.502 +    }
   1.503 +  }
   1.504 +
   1.505 +  array->set_unroll_block(info);
   1.506 +  return info;
   1.507 +}
   1.508 +
   1.509 +// Called to cleanup deoptimization data structures in normal case
   1.510 +// after unpacking to stack and when stack overflow error occurs
   1.511 +void Deoptimization::cleanup_deopt_info(JavaThread *thread,
   1.512 +                                        vframeArray *array) {
   1.513 +
   1.514 +  // Get array if coming from exception
   1.515 +  if (array == NULL) {
   1.516 +    array = thread->vframe_array_head();
   1.517 +  }
   1.518 +  thread->set_vframe_array_head(NULL);
   1.519 +
   1.520 +  // Free the previous UnrollBlock
   1.521 +  vframeArray* old_array = thread->vframe_array_last();
   1.522 +  thread->set_vframe_array_last(array);
   1.523 +
   1.524 +  if (old_array != NULL) {
   1.525 +    UnrollBlock* old_info = old_array->unroll_block();
   1.526 +    old_array->set_unroll_block(NULL);
   1.527 +    delete old_info;
   1.528 +    delete old_array;
   1.529 +  }
   1.530 +
   1.531 +  // Deallocate any resource creating in this routine and any ResourceObjs allocated
   1.532 +  // inside the vframeArray (StackValueCollections)
   1.533 +
   1.534 +  delete thread->deopt_mark();
   1.535 +  thread->set_deopt_mark(NULL);
   1.536 +  thread->set_deopt_nmethod(NULL);
   1.537 +
   1.538 +
   1.539 +  if (JvmtiExport::can_pop_frame()) {
   1.540 +#ifndef CC_INTERP
   1.541 +    // Regardless of whether we entered this routine with the pending
   1.542 +    // popframe condition bit set, we should always clear it now
   1.543 +    thread->clear_popframe_condition();
   1.544 +#else
   1.545 +    // C++ interpeter will clear has_pending_popframe when it enters
   1.546 +    // with method_resume. For deopt_resume2 we clear it now.
   1.547 +    if (thread->popframe_forcing_deopt_reexecution())
   1.548 +        thread->clear_popframe_condition();
   1.549 +#endif /* CC_INTERP */
   1.550 +  }
   1.551 +
   1.552 +  // unpack_frames() is called at the end of the deoptimization handler
   1.553 +  // and (in C2) at the end of the uncommon trap handler. Note this fact
   1.554 +  // so that an asynchronous stack walker can work again. This counter is
   1.555 +  // incremented at the beginning of fetch_unroll_info() and (in C2) at
   1.556 +  // the beginning of uncommon_trap().
   1.557 +  thread->dec_in_deopt_handler();
   1.558 +}
   1.559 +
   1.560 +
   1.561 +// Return BasicType of value being returned
   1.562 +JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
   1.563 +
   1.564 +  // We are already active int he special DeoptResourceMark any ResourceObj's we
   1.565 +  // allocate will be freed at the end of the routine.
   1.566 +
   1.567 +  // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
   1.568 +  // but makes the entry a little slower. There is however a little dance we have to
   1.569 +  // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
   1.570 +  ResetNoHandleMark rnhm; // No-op in release/product versions
   1.571 +  HandleMark hm;
   1.572 +
   1.573 +  frame stub_frame = thread->last_frame();
   1.574 +
   1.575 +  // Since the frame to unpack is the top frame of this thread, the vframe_array_head
   1.576 +  // must point to the vframeArray for the unpack frame.
   1.577 +  vframeArray* array = thread->vframe_array_head();
   1.578 +
   1.579 +#ifndef PRODUCT
   1.580 +  if (TraceDeoptimization) {
   1.581 +    ttyLocker ttyl;
   1.582 +    tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", thread, array, exec_mode);
   1.583 +  }
   1.584 +#endif
   1.585 +  Events::log(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
   1.586 +              stub_frame.pc(), stub_frame.sp(), exec_mode);
   1.587 +
   1.588 +  UnrollBlock* info = array->unroll_block();
   1.589 +
   1.590 +  // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
   1.591 +  array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
   1.592 +
   1.593 +  BasicType bt = info->return_type();
   1.594 +
   1.595 +  // If we have an exception pending, claim that the return type is an oop
   1.596 +  // so the deopt_blob does not overwrite the exception_oop.
   1.597 +
   1.598 +  if (exec_mode == Unpack_exception)
   1.599 +    bt = T_OBJECT;
   1.600 +
   1.601 +  // Cleanup thread deopt data
   1.602 +  cleanup_deopt_info(thread, array);
   1.603 +
   1.604 +#ifndef PRODUCT
   1.605 +  if (VerifyStack) {
   1.606 +    ResourceMark res_mark;
   1.607 +
   1.608 +    thread->validate_frame_layout();
   1.609 +
   1.610 +    // Verify that the just-unpacked frames match the interpreter's
   1.611 +    // notions of expression stack and locals
   1.612 +    vframeArray* cur_array = thread->vframe_array_last();
   1.613 +    RegisterMap rm(thread, false);
   1.614 +    rm.set_include_argument_oops(false);
   1.615 +    bool is_top_frame = true;
   1.616 +    int callee_size_of_parameters = 0;
   1.617 +    int callee_max_locals = 0;
   1.618 +    for (int i = 0; i < cur_array->frames(); i++) {
   1.619 +      vframeArrayElement* el = cur_array->element(i);
   1.620 +      frame* iframe = el->iframe();
   1.621 +      guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
   1.622 +
   1.623 +      // Get the oop map for this bci
   1.624 +      InterpreterOopMap mask;
   1.625 +      int cur_invoke_parameter_size = 0;
   1.626 +      bool try_next_mask = false;
   1.627 +      int next_mask_expression_stack_size = -1;
   1.628 +      int top_frame_expression_stack_adjustment = 0;
   1.629 +      methodHandle mh(thread, iframe->interpreter_frame_method());
   1.630 +      OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
   1.631 +      BytecodeStream str(mh);
   1.632 +      str.set_start(iframe->interpreter_frame_bci());
   1.633 +      int max_bci = mh->code_size();
   1.634 +      // Get to the next bytecode if possible
   1.635 +      assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
   1.636 +      // Check to see if we can grab the number of outgoing arguments
   1.637 +      // at an uncommon trap for an invoke (where the compiler
   1.638 +      // generates debug info before the invoke has executed)
   1.639 +      Bytecodes::Code cur_code = str.next();
   1.640 +      if (cur_code == Bytecodes::_invokevirtual   ||
   1.641 +          cur_code == Bytecodes::_invokespecial   ||
   1.642 +          cur_code == Bytecodes::_invokestatic    ||
   1.643 +          cur_code == Bytecodes::_invokeinterface ||
   1.644 +          cur_code == Bytecodes::_invokedynamic) {
   1.645 +        Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
   1.646 +        Symbol* signature = invoke.signature();
   1.647 +        ArgumentSizeComputer asc(signature);
   1.648 +        cur_invoke_parameter_size = asc.size();
   1.649 +        if (invoke.has_receiver()) {
   1.650 +          // Add in receiver
   1.651 +          ++cur_invoke_parameter_size;
   1.652 +        }
   1.653 +        if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
   1.654 +          callee_size_of_parameters++;
   1.655 +        }
   1.656 +      }
   1.657 +      if (str.bci() < max_bci) {
   1.658 +        Bytecodes::Code bc = str.next();
   1.659 +        if (bc >= 0) {
   1.660 +          // The interpreter oop map generator reports results before
   1.661 +          // the current bytecode has executed except in the case of
   1.662 +          // calls. It seems to be hard to tell whether the compiler
   1.663 +          // has emitted debug information matching the "state before"
   1.664 +          // a given bytecode or the state after, so we try both
   1.665 +          switch (cur_code) {
   1.666 +            case Bytecodes::_invokevirtual:
   1.667 +            case Bytecodes::_invokespecial:
   1.668 +            case Bytecodes::_invokestatic:
   1.669 +            case Bytecodes::_invokeinterface:
   1.670 +            case Bytecodes::_invokedynamic:
   1.671 +            case Bytecodes::_athrow:
   1.672 +              break;
   1.673 +            default: {
   1.674 +              InterpreterOopMap next_mask;
   1.675 +              OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
   1.676 +              next_mask_expression_stack_size = next_mask.expression_stack_size();
   1.677 +              // Need to subtract off the size of the result type of
   1.678 +              // the bytecode because this is not described in the
   1.679 +              // debug info but returned to the interpreter in the TOS
   1.680 +              // caching register
   1.681 +              BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
   1.682 +              if (bytecode_result_type != T_ILLEGAL) {
   1.683 +                top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
   1.684 +              }
   1.685 +              assert(top_frame_expression_stack_adjustment >= 0, "");
   1.686 +              try_next_mask = true;
   1.687 +              break;
   1.688 +            }
   1.689 +          }
   1.690 +        }
   1.691 +      }
   1.692 +
   1.693 +      // Verify stack depth and oops in frame
   1.694 +      // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
   1.695 +      if (!(
   1.696 +            /* SPARC */
   1.697 +            (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
   1.698 +            /* x86 */
   1.699 +            (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
   1.700 +            (try_next_mask &&
   1.701 +             (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
   1.702 +                                                                    top_frame_expression_stack_adjustment))) ||
   1.703 +            (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
   1.704 +            (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute) &&
   1.705 +             (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
   1.706 +            )) {
   1.707 +        ttyLocker ttyl;
   1.708 +
   1.709 +        // Print out some information that will help us debug the problem
   1.710 +        tty->print_cr("Wrong number of expression stack elements during deoptimization");
   1.711 +        tty->print_cr("  Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
   1.712 +        tty->print_cr("  Fabricated interpreter frame had %d expression stack elements",
   1.713 +                      iframe->interpreter_frame_expression_stack_size());
   1.714 +        tty->print_cr("  Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
   1.715 +        tty->print_cr("  try_next_mask = %d", try_next_mask);
   1.716 +        tty->print_cr("  next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
   1.717 +        tty->print_cr("  callee_size_of_parameters = %d", callee_size_of_parameters);
   1.718 +        tty->print_cr("  callee_max_locals = %d", callee_max_locals);
   1.719 +        tty->print_cr("  top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
   1.720 +        tty->print_cr("  exec_mode = %d", exec_mode);
   1.721 +        tty->print_cr("  cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
   1.722 +        tty->print_cr("  Thread = " INTPTR_FORMAT ", thread ID = " UINTX_FORMAT, thread, thread->osthread()->thread_id());
   1.723 +        tty->print_cr("  Interpreted frames:");
   1.724 +        for (int k = 0; k < cur_array->frames(); k++) {
   1.725 +          vframeArrayElement* el = cur_array->element(k);
   1.726 +          tty->print_cr("    %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
   1.727 +        }
   1.728 +        cur_array->print_on_2(tty);
   1.729 +        guarantee(false, "wrong number of expression stack elements during deopt");
   1.730 +      }
   1.731 +      VerifyOopClosure verify;
   1.732 +      iframe->oops_interpreted_do(&verify, NULL, &rm, false);
   1.733 +      callee_size_of_parameters = mh->size_of_parameters();
   1.734 +      callee_max_locals = mh->max_locals();
   1.735 +      is_top_frame = false;
   1.736 +    }
   1.737 +  }
   1.738 +#endif /* !PRODUCT */
   1.739 +
   1.740 +
   1.741 +  return bt;
   1.742 +JRT_END
   1.743 +
   1.744 +
   1.745 +int Deoptimization::deoptimize_dependents() {
   1.746 +  Threads::deoptimized_wrt_marked_nmethods();
   1.747 +  return 0;
   1.748 +}
   1.749 +
   1.750 +
   1.751 +#ifdef COMPILER2
   1.752 +bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, GrowableArray<ScopeValue*>* objects, TRAPS) {
   1.753 +  Handle pending_exception(thread->pending_exception());
   1.754 +  const char* exception_file = thread->exception_file();
   1.755 +  int exception_line = thread->exception_line();
   1.756 +  thread->clear_pending_exception();
   1.757 +
   1.758 +  for (int i = 0; i < objects->length(); i++) {
   1.759 +    assert(objects->at(i)->is_object(), "invalid debug information");
   1.760 +    ObjectValue* sv = (ObjectValue*) objects->at(i);
   1.761 +
   1.762 +    KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
   1.763 +    oop obj = NULL;
   1.764 +
   1.765 +    if (k->oop_is_instance()) {
   1.766 +      InstanceKlass* ik = InstanceKlass::cast(k());
   1.767 +      obj = ik->allocate_instance(CHECK_(false));
   1.768 +    } else if (k->oop_is_typeArray()) {
   1.769 +      TypeArrayKlass* ak = TypeArrayKlass::cast(k());
   1.770 +      assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
   1.771 +      int len = sv->field_size() / type2size[ak->element_type()];
   1.772 +      obj = ak->allocate(len, CHECK_(false));
   1.773 +    } else if (k->oop_is_objArray()) {
   1.774 +      ObjArrayKlass* ak = ObjArrayKlass::cast(k());
   1.775 +      obj = ak->allocate(sv->field_size(), CHECK_(false));
   1.776 +    }
   1.777 +
   1.778 +    assert(obj != NULL, "allocation failed");
   1.779 +    assert(sv->value().is_null(), "redundant reallocation");
   1.780 +    sv->set_value(obj);
   1.781 +  }
   1.782 +
   1.783 +  if (pending_exception.not_null()) {
   1.784 +    thread->set_pending_exception(pending_exception(), exception_file, exception_line);
   1.785 +  }
   1.786 +
   1.787 +  return true;
   1.788 +}
   1.789 +
   1.790 +// This assumes that the fields are stored in ObjectValue in the same order
   1.791 +// they are yielded by do_nonstatic_fields.
   1.792 +class FieldReassigner: public FieldClosure {
   1.793 +  frame* _fr;
   1.794 +  RegisterMap* _reg_map;
   1.795 +  ObjectValue* _sv;
   1.796 +  InstanceKlass* _ik;
   1.797 +  oop _obj;
   1.798 +
   1.799 +  int _i;
   1.800 +public:
   1.801 +  FieldReassigner(frame* fr, RegisterMap* reg_map, ObjectValue* sv, oop obj) :
   1.802 +    _fr(fr), _reg_map(reg_map), _sv(sv), _obj(obj), _i(0) {}
   1.803 +
   1.804 +  int i() const { return _i; }
   1.805 +
   1.806 +
   1.807 +  void do_field(fieldDescriptor* fd) {
   1.808 +    intptr_t val;
   1.809 +    StackValue* value =
   1.810 +      StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(i()));
   1.811 +    int offset = fd->offset();
   1.812 +    switch (fd->field_type()) {
   1.813 +    case T_OBJECT: case T_ARRAY:
   1.814 +      assert(value->type() == T_OBJECT, "Agreement.");
   1.815 +      _obj->obj_field_put(offset, value->get_obj()());
   1.816 +      break;
   1.817 +
   1.818 +    case T_LONG: case T_DOUBLE: {
   1.819 +      assert(value->type() == T_INT, "Agreement.");
   1.820 +      StackValue* low =
   1.821 +        StackValue::create_stack_value(_fr, _reg_map, _sv->field_at(++_i));
   1.822 +#ifdef _LP64
   1.823 +      jlong res = (jlong)low->get_int();
   1.824 +#else
   1.825 +#ifdef SPARC
   1.826 +      // For SPARC we have to swap high and low words.
   1.827 +      jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
   1.828 +#else
   1.829 +      jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
   1.830 +#endif //SPARC
   1.831 +#endif
   1.832 +      _obj->long_field_put(offset, res);
   1.833 +      break;
   1.834 +    }
   1.835 +    // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
   1.836 +    case T_INT: case T_FLOAT: // 4 bytes.
   1.837 +      assert(value->type() == T_INT, "Agreement.");
   1.838 +      val = value->get_int();
   1.839 +      _obj->int_field_put(offset, (jint)*((jint*)&val));
   1.840 +      break;
   1.841 +
   1.842 +    case T_SHORT: case T_CHAR: // 2 bytes
   1.843 +      assert(value->type() == T_INT, "Agreement.");
   1.844 +      val = value->get_int();
   1.845 +      _obj->short_field_put(offset, (jshort)*((jint*)&val));
   1.846 +      break;
   1.847 +
   1.848 +    case T_BOOLEAN: case T_BYTE: // 1 byte
   1.849 +      assert(value->type() == T_INT, "Agreement.");
   1.850 +      val = value->get_int();
   1.851 +      _obj->bool_field_put(offset, (jboolean)*((jint*)&val));
   1.852 +      break;
   1.853 +
   1.854 +    default:
   1.855 +      ShouldNotReachHere();
   1.856 +    }
   1.857 +    _i++;
   1.858 +  }
   1.859 +};
   1.860 +
   1.861 +// restore elements of an eliminated type array
   1.862 +void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
   1.863 +  int index = 0;
   1.864 +  intptr_t val;
   1.865 +
   1.866 +  for (int i = 0; i < sv->field_size(); i++) {
   1.867 +    StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
   1.868 +    switch(type) {
   1.869 +    case T_LONG: case T_DOUBLE: {
   1.870 +      assert(value->type() == T_INT, "Agreement.");
   1.871 +      StackValue* low =
   1.872 +        StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
   1.873 +#ifdef _LP64
   1.874 +      jlong res = (jlong)low->get_int();
   1.875 +#else
   1.876 +#ifdef SPARC
   1.877 +      // For SPARC we have to swap high and low words.
   1.878 +      jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
   1.879 +#else
   1.880 +      jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
   1.881 +#endif //SPARC
   1.882 +#endif
   1.883 +      obj->long_at_put(index, res);
   1.884 +      break;
   1.885 +    }
   1.886 +
   1.887 +    // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
   1.888 +    case T_INT: case T_FLOAT: // 4 bytes.
   1.889 +      assert(value->type() == T_INT, "Agreement.");
   1.890 +      val = value->get_int();
   1.891 +      obj->int_at_put(index, (jint)*((jint*)&val));
   1.892 +      break;
   1.893 +
   1.894 +    case T_SHORT: case T_CHAR: // 2 bytes
   1.895 +      assert(value->type() == T_INT, "Agreement.");
   1.896 +      val = value->get_int();
   1.897 +      obj->short_at_put(index, (jshort)*((jint*)&val));
   1.898 +      break;
   1.899 +
   1.900 +    case T_BOOLEAN: case T_BYTE: // 1 byte
   1.901 +      assert(value->type() == T_INT, "Agreement.");
   1.902 +      val = value->get_int();
   1.903 +      obj->bool_at_put(index, (jboolean)*((jint*)&val));
   1.904 +      break;
   1.905 +
   1.906 +      default:
   1.907 +        ShouldNotReachHere();
   1.908 +    }
   1.909 +    index++;
   1.910 +  }
   1.911 +}
   1.912 +
   1.913 +
   1.914 +// restore fields of an eliminated object array
   1.915 +void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
   1.916 +  for (int i = 0; i < sv->field_size(); i++) {
   1.917 +    StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
   1.918 +    assert(value->type() == T_OBJECT, "object element expected");
   1.919 +    obj->obj_at_put(i, value->get_obj()());
   1.920 +  }
   1.921 +}
   1.922 +
   1.923 +
   1.924 +// restore fields of all eliminated objects and arrays
   1.925 +void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects) {
   1.926 +  for (int i = 0; i < objects->length(); i++) {
   1.927 +    ObjectValue* sv = (ObjectValue*) objects->at(i);
   1.928 +    KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
   1.929 +    Handle obj = sv->value();
   1.930 +    assert(obj.not_null(), "reallocation was missed");
   1.931 +
   1.932 +    if (k->oop_is_instance()) {
   1.933 +      InstanceKlass* ik = InstanceKlass::cast(k());
   1.934 +      FieldReassigner reassign(fr, reg_map, sv, obj());
   1.935 +      ik->do_nonstatic_fields(&reassign);
   1.936 +    } else if (k->oop_is_typeArray()) {
   1.937 +      TypeArrayKlass* ak = TypeArrayKlass::cast(k());
   1.938 +      reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
   1.939 +    } else if (k->oop_is_objArray()) {
   1.940 +      reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
   1.941 +    }
   1.942 +  }
   1.943 +}
   1.944 +
   1.945 +
   1.946 +// relock objects for which synchronization was eliminated
   1.947 +void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread) {
   1.948 +  for (int i = 0; i < monitors->length(); i++) {
   1.949 +    MonitorInfo* mon_info = monitors->at(i);
   1.950 +    if (mon_info->eliminated()) {
   1.951 +      assert(mon_info->owner() != NULL, "reallocation was missed");
   1.952 +      Handle obj = Handle(mon_info->owner());
   1.953 +      markOop mark = obj->mark();
   1.954 +      if (UseBiasedLocking && mark->has_bias_pattern()) {
   1.955 +        // New allocated objects may have the mark set to anonymously biased.
   1.956 +        // Also the deoptimized method may called methods with synchronization
   1.957 +        // where the thread-local object is bias locked to the current thread.
   1.958 +        assert(mark->is_biased_anonymously() ||
   1.959 +               mark->biased_locker() == thread, "should be locked to current thread");
   1.960 +        // Reset mark word to unbiased prototype.
   1.961 +        markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
   1.962 +        obj->set_mark(unbiased_prototype);
   1.963 +      }
   1.964 +      BasicLock* lock = mon_info->lock();
   1.965 +      ObjectSynchronizer::slow_enter(obj, lock, thread);
   1.966 +    }
   1.967 +    assert(mon_info->owner()->is_locked(), "object must be locked now");
   1.968 +  }
   1.969 +}
   1.970 +
   1.971 +
   1.972 +#ifndef PRODUCT
   1.973 +// print information about reallocated objects
   1.974 +void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects) {
   1.975 +  fieldDescriptor fd;
   1.976 +
   1.977 +  for (int i = 0; i < objects->length(); i++) {
   1.978 +    ObjectValue* sv = (ObjectValue*) objects->at(i);
   1.979 +    KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
   1.980 +    Handle obj = sv->value();
   1.981 +
   1.982 +    tty->print("     object <" INTPTR_FORMAT "> of type ", (void *)sv->value()());
   1.983 +    k->print_value();
   1.984 +    tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);
   1.985 +    tty->cr();
   1.986 +
   1.987 +    if (Verbose) {
   1.988 +      k->oop_print_on(obj(), tty);
   1.989 +    }
   1.990 +  }
   1.991 +}
   1.992 +#endif
   1.993 +#endif // COMPILER2
   1.994 +
   1.995 +vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk) {
   1.996 +  Events::log(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, fr.pc(), fr.sp());
   1.997 +
   1.998 +#ifndef PRODUCT
   1.999 +  if (TraceDeoptimization) {
  1.1000 +    ttyLocker ttyl;
  1.1001 +    tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", thread);
  1.1002 +    fr.print_on(tty);
  1.1003 +    tty->print_cr("     Virtual frames (innermost first):");
  1.1004 +    for (int index = 0; index < chunk->length(); index++) {
  1.1005 +      compiledVFrame* vf = chunk->at(index);
  1.1006 +      tty->print("       %2d - ", index);
  1.1007 +      vf->print_value();
  1.1008 +      int bci = chunk->at(index)->raw_bci();
  1.1009 +      const char* code_name;
  1.1010 +      if (bci == SynchronizationEntryBCI) {
  1.1011 +        code_name = "sync entry";
  1.1012 +      } else {
  1.1013 +        Bytecodes::Code code = vf->method()->code_at(bci);
  1.1014 +        code_name = Bytecodes::name(code);
  1.1015 +      }
  1.1016 +      tty->print(" - %s", code_name);
  1.1017 +      tty->print_cr(" @ bci %d ", bci);
  1.1018 +      if (Verbose) {
  1.1019 +        vf->print();
  1.1020 +        tty->cr();
  1.1021 +      }
  1.1022 +    }
  1.1023 +  }
  1.1024 +#endif
  1.1025 +
  1.1026 +  // Register map for next frame (used for stack crawl).  We capture
  1.1027 +  // the state of the deopt'ing frame's caller.  Thus if we need to
  1.1028 +  // stuff a C2I adapter we can properly fill in the callee-save
  1.1029 +  // register locations.
  1.1030 +  frame caller = fr.sender(reg_map);
  1.1031 +  int frame_size = caller.sp() - fr.sp();
  1.1032 +
  1.1033 +  frame sender = caller;
  1.1034 +
  1.1035 +  // Since the Java thread being deoptimized will eventually adjust it's own stack,
  1.1036 +  // the vframeArray containing the unpacking information is allocated in the C heap.
  1.1037 +  // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
  1.1038 +  vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr);
  1.1039 +
  1.1040 +  // Compare the vframeArray to the collected vframes
  1.1041 +  assert(array->structural_compare(thread, chunk), "just checking");
  1.1042 +
  1.1043 +#ifndef PRODUCT
  1.1044 +  if (TraceDeoptimization) {
  1.1045 +    ttyLocker ttyl;
  1.1046 +    tty->print_cr("     Created vframeArray " INTPTR_FORMAT, array);
  1.1047 +  }
  1.1048 +#endif // PRODUCT
  1.1049 +
  1.1050 +  return array;
  1.1051 +}
  1.1052 +
  1.1053 +
  1.1054 +static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke) {
  1.1055 +  GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
  1.1056 +  for (int i = 0; i < monitors->length(); i++) {
  1.1057 +    MonitorInfo* mon_info = monitors->at(i);
  1.1058 +    if (!mon_info->eliminated() && mon_info->owner() != NULL) {
  1.1059 +      objects_to_revoke->append(Handle(mon_info->owner()));
  1.1060 +    }
  1.1061 +  }
  1.1062 +}
  1.1063 +
  1.1064 +
  1.1065 +void Deoptimization::revoke_biases_of_monitors(JavaThread* thread, frame fr, RegisterMap* map) {
  1.1066 +  if (!UseBiasedLocking) {
  1.1067 +    return;
  1.1068 +  }
  1.1069 +
  1.1070 +  GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
  1.1071 +
  1.1072 +  // Unfortunately we don't have a RegisterMap available in most of
  1.1073 +  // the places we want to call this routine so we need to walk the
  1.1074 +  // stack again to update the register map.
  1.1075 +  if (map == NULL || !map->update_map()) {
  1.1076 +    StackFrameStream sfs(thread, true);
  1.1077 +    bool found = false;
  1.1078 +    while (!found && !sfs.is_done()) {
  1.1079 +      frame* cur = sfs.current();
  1.1080 +      sfs.next();
  1.1081 +      found = cur->id() == fr.id();
  1.1082 +    }
  1.1083 +    assert(found, "frame to be deoptimized not found on target thread's stack");
  1.1084 +    map = sfs.register_map();
  1.1085 +  }
  1.1086 +
  1.1087 +  vframe* vf = vframe::new_vframe(&fr, map, thread);
  1.1088 +  compiledVFrame* cvf = compiledVFrame::cast(vf);
  1.1089 +  // Revoke monitors' biases in all scopes
  1.1090 +  while (!cvf->is_top()) {
  1.1091 +    collect_monitors(cvf, objects_to_revoke);
  1.1092 +    cvf = compiledVFrame::cast(cvf->sender());
  1.1093 +  }
  1.1094 +  collect_monitors(cvf, objects_to_revoke);
  1.1095 +
  1.1096 +  if (SafepointSynchronize::is_at_safepoint()) {
  1.1097 +    BiasedLocking::revoke_at_safepoint(objects_to_revoke);
  1.1098 +  } else {
  1.1099 +    BiasedLocking::revoke(objects_to_revoke);
  1.1100 +  }
  1.1101 +}
  1.1102 +
  1.1103 +
  1.1104 +void Deoptimization::revoke_biases_of_monitors(CodeBlob* cb) {
  1.1105 +  if (!UseBiasedLocking) {
  1.1106 +    return;
  1.1107 +  }
  1.1108 +
  1.1109 +  assert(SafepointSynchronize::is_at_safepoint(), "must only be called from safepoint");
  1.1110 +  GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
  1.1111 +  for (JavaThread* jt = Threads::first(); jt != NULL ; jt = jt->next()) {
  1.1112 +    if (jt->has_last_Java_frame()) {
  1.1113 +      StackFrameStream sfs(jt, true);
  1.1114 +      while (!sfs.is_done()) {
  1.1115 +        frame* cur = sfs.current();
  1.1116 +        if (cb->contains(cur->pc())) {
  1.1117 +          vframe* vf = vframe::new_vframe(cur, sfs.register_map(), jt);
  1.1118 +          compiledVFrame* cvf = compiledVFrame::cast(vf);
  1.1119 +          // Revoke monitors' biases in all scopes
  1.1120 +          while (!cvf->is_top()) {
  1.1121 +            collect_monitors(cvf, objects_to_revoke);
  1.1122 +            cvf = compiledVFrame::cast(cvf->sender());
  1.1123 +          }
  1.1124 +          collect_monitors(cvf, objects_to_revoke);
  1.1125 +        }
  1.1126 +        sfs.next();
  1.1127 +      }
  1.1128 +    }
  1.1129 +  }
  1.1130 +  BiasedLocking::revoke_at_safepoint(objects_to_revoke);
  1.1131 +}
  1.1132 +
  1.1133 +
  1.1134 +void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr) {
  1.1135 +  assert(fr.can_be_deoptimized(), "checking frame type");
  1.1136 +
  1.1137 +  gather_statistics(Reason_constraint, Action_none, Bytecodes::_illegal);
  1.1138 +
  1.1139 +  // Patch the nmethod so that when execution returns to it we will
  1.1140 +  // deopt the execution state and return to the interpreter.
  1.1141 +  fr.deoptimize(thread);
  1.1142 +}
  1.1143 +
  1.1144 +void Deoptimization::deoptimize(JavaThread* thread, frame fr, RegisterMap *map) {
  1.1145 +  // Deoptimize only if the frame comes from compile code.
  1.1146 +  // Do not deoptimize the frame which is already patched
  1.1147 +  // during the execution of the loops below.
  1.1148 +  if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
  1.1149 +    return;
  1.1150 +  }
  1.1151 +  ResourceMark rm;
  1.1152 +  DeoptimizationMarker dm;
  1.1153 +  if (UseBiasedLocking) {
  1.1154 +    revoke_biases_of_monitors(thread, fr, map);
  1.1155 +  }
  1.1156 +  deoptimize_single_frame(thread, fr);
  1.1157 +
  1.1158 +}
  1.1159 +
  1.1160 +
  1.1161 +void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id) {
  1.1162 +  assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
  1.1163 +         "can only deoptimize other thread at a safepoint");
  1.1164 +  // Compute frame and register map based on thread and sp.
  1.1165 +  RegisterMap reg_map(thread, UseBiasedLocking);
  1.1166 +  frame fr = thread->last_frame();
  1.1167 +  while (fr.id() != id) {
  1.1168 +    fr = fr.sender(&reg_map);
  1.1169 +  }
  1.1170 +  deoptimize(thread, fr, &reg_map);
  1.1171 +}
  1.1172 +
  1.1173 +
  1.1174 +void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
  1.1175 +  if (thread == Thread::current()) {
  1.1176 +    Deoptimization::deoptimize_frame_internal(thread, id);
  1.1177 +  } else {
  1.1178 +    VM_DeoptimizeFrame deopt(thread, id);
  1.1179 +    VMThread::execute(&deopt);
  1.1180 +  }
  1.1181 +}
  1.1182 +
  1.1183 +
  1.1184 +// JVMTI PopFrame support
  1.1185 +JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
  1.1186 +{
  1.1187 +  thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
  1.1188 +}
  1.1189 +JRT_END
  1.1190 +
  1.1191 +
  1.1192 +#if defined(COMPILER2) || defined(SHARK)
  1.1193 +void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index, TRAPS) {
  1.1194 +  // in case of an unresolved klass entry, load the class.
  1.1195 +  if (constant_pool->tag_at(index).is_unresolved_klass()) {
  1.1196 +    Klass* tk = constant_pool->klass_at(index, CHECK);
  1.1197 +    return;
  1.1198 +  }
  1.1199 +
  1.1200 +  if (!constant_pool->tag_at(index).is_symbol()) return;
  1.1201 +
  1.1202 +  Handle class_loader (THREAD, constant_pool->pool_holder()->class_loader());
  1.1203 +  Symbol*  symbol  = constant_pool->symbol_at(index);
  1.1204 +
  1.1205 +  // class name?
  1.1206 +  if (symbol->byte_at(0) != '(') {
  1.1207 +    Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());
  1.1208 +    SystemDictionary::resolve_or_null(symbol, class_loader, protection_domain, CHECK);
  1.1209 +    return;
  1.1210 +  }
  1.1211 +
  1.1212 +  // then it must be a signature!
  1.1213 +  ResourceMark rm(THREAD);
  1.1214 +  for (SignatureStream ss(symbol); !ss.is_done(); ss.next()) {
  1.1215 +    if (ss.is_object()) {
  1.1216 +      Symbol* class_name = ss.as_symbol(CHECK);
  1.1217 +      Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());
  1.1218 +      SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK);
  1.1219 +    }
  1.1220 +  }
  1.1221 +}
  1.1222 +
  1.1223 +
  1.1224 +void Deoptimization::load_class_by_index(constantPoolHandle constant_pool, int index) {
  1.1225 +  EXCEPTION_MARK;
  1.1226 +  load_class_by_index(constant_pool, index, THREAD);
  1.1227 +  if (HAS_PENDING_EXCEPTION) {
  1.1228 +    // Exception happened during classloading. We ignore the exception here, since it
  1.1229 +    // is going to be rethrown since the current activation is going to be deoptimized and
  1.1230 +    // the interpreter will re-execute the bytecode.
  1.1231 +    CLEAR_PENDING_EXCEPTION;
  1.1232 +    // Class loading called java code which may have caused a stack
  1.1233 +    // overflow. If the exception was thrown right before the return
  1.1234 +    // to the runtime the stack is no longer guarded. Reguard the
  1.1235 +    // stack otherwise if we return to the uncommon trap blob and the
  1.1236 +    // stack bang causes a stack overflow we crash.
  1.1237 +    assert(THREAD->is_Java_thread(), "only a java thread can be here");
  1.1238 +    JavaThread* thread = (JavaThread*)THREAD;
  1.1239 +    bool guard_pages_enabled = thread->stack_yellow_zone_enabled();
  1.1240 +    if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
  1.1241 +    assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
  1.1242 +  }
  1.1243 +}
  1.1244 +
  1.1245 +JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) {
  1.1246 +  HandleMark hm;
  1.1247 +
  1.1248 +  // uncommon_trap() is called at the beginning of the uncommon trap
  1.1249 +  // handler. Note this fact before we start generating temporary frames
  1.1250 +  // that can confuse an asynchronous stack walker. This counter is
  1.1251 +  // decremented at the end of unpack_frames().
  1.1252 +  thread->inc_in_deopt_handler();
  1.1253 +
  1.1254 +  // We need to update the map if we have biased locking.
  1.1255 +  RegisterMap reg_map(thread, UseBiasedLocking);
  1.1256 +  frame stub_frame = thread->last_frame();
  1.1257 +  frame fr = stub_frame.sender(&reg_map);
  1.1258 +  // Make sure the calling nmethod is not getting deoptimized and removed
  1.1259 +  // before we are done with it.
  1.1260 +  nmethodLocker nl(fr.pc());
  1.1261 +
  1.1262 +  // Log a message
  1.1263 +  Events::log(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT,
  1.1264 +              trap_request, fr.pc());
  1.1265 +
  1.1266 +  {
  1.1267 +    ResourceMark rm;
  1.1268 +
  1.1269 +    // Revoke biases of any monitors in the frame to ensure we can migrate them
  1.1270 +    revoke_biases_of_monitors(thread, fr, &reg_map);
  1.1271 +
  1.1272 +    DeoptReason reason = trap_request_reason(trap_request);
  1.1273 +    DeoptAction action = trap_request_action(trap_request);
  1.1274 +    jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
  1.1275 +
  1.1276 +    vframe*  vf  = vframe::new_vframe(&fr, &reg_map, thread);
  1.1277 +    compiledVFrame* cvf = compiledVFrame::cast(vf);
  1.1278 +
  1.1279 +    nmethod* nm = cvf->code();
  1.1280 +
  1.1281 +    ScopeDesc*      trap_scope  = cvf->scope();
  1.1282 +    methodHandle    trap_method = trap_scope->method();
  1.1283 +    int             trap_bci    = trap_scope->bci();
  1.1284 +    Bytecodes::Code trap_bc     = trap_method->java_code_at(trap_bci);
  1.1285 +
  1.1286 +    // Record this event in the histogram.
  1.1287 +    gather_statistics(reason, action, trap_bc);
  1.1288 +
  1.1289 +    // Ensure that we can record deopt. history:
  1.1290 +    // Need MDO to record RTM code generation state.
  1.1291 +    bool create_if_missing = ProfileTraps RTM_OPT_ONLY( || UseRTMLocking );
  1.1292 +
  1.1293 +    MethodData* trap_mdo =
  1.1294 +      get_method_data(thread, trap_method, create_if_missing);
  1.1295 +
  1.1296 +    // Log a message
  1.1297 +    Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d",
  1.1298 +                              trap_reason_name(reason), trap_action_name(action), fr.pc(),
  1.1299 +                              trap_method->name_and_sig_as_C_string(), trap_bci);
  1.1300 +
  1.1301 +    // Print a bunch of diagnostics, if requested.
  1.1302 +    if (TraceDeoptimization || LogCompilation) {
  1.1303 +      ResourceMark rm;
  1.1304 +      ttyLocker ttyl;
  1.1305 +      char buf[100];
  1.1306 +      if (xtty != NULL) {
  1.1307 +        xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT"' %s",
  1.1308 +                         os::current_thread_id(),
  1.1309 +                         format_trap_request(buf, sizeof(buf), trap_request));
  1.1310 +        nm->log_identity(xtty);
  1.1311 +      }
  1.1312 +      Symbol* class_name = NULL;
  1.1313 +      bool unresolved = false;
  1.1314 +      if (unloaded_class_index >= 0) {
  1.1315 +        constantPoolHandle constants (THREAD, trap_method->constants());
  1.1316 +        if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
  1.1317 +          class_name = constants->klass_name_at(unloaded_class_index);
  1.1318 +          unresolved = true;
  1.1319 +          if (xtty != NULL)
  1.1320 +            xtty->print(" unresolved='1'");
  1.1321 +        } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
  1.1322 +          class_name = constants->symbol_at(unloaded_class_index);
  1.1323 +        }
  1.1324 +        if (xtty != NULL)
  1.1325 +          xtty->name(class_name);
  1.1326 +      }
  1.1327 +      if (xtty != NULL && trap_mdo != NULL) {
  1.1328 +        // Dump the relevant MDO state.
  1.1329 +        // This is the deopt count for the current reason, any previous
  1.1330 +        // reasons or recompiles seen at this point.
  1.1331 +        int dcnt = trap_mdo->trap_count(reason);
  1.1332 +        if (dcnt != 0)
  1.1333 +          xtty->print(" count='%d'", dcnt);
  1.1334 +        ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
  1.1335 +        int dos = (pdata == NULL)? 0: pdata->trap_state();
  1.1336 +        if (dos != 0) {
  1.1337 +          xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
  1.1338 +          if (trap_state_is_recompiled(dos)) {
  1.1339 +            int recnt2 = trap_mdo->overflow_recompile_count();
  1.1340 +            if (recnt2 != 0)
  1.1341 +              xtty->print(" recompiles2='%d'", recnt2);
  1.1342 +          }
  1.1343 +        }
  1.1344 +      }
  1.1345 +      if (xtty != NULL) {
  1.1346 +        xtty->stamp();
  1.1347 +        xtty->end_head();
  1.1348 +      }
  1.1349 +      if (TraceDeoptimization) {  // make noise on the tty
  1.1350 +        tty->print("Uncommon trap occurred in");
  1.1351 +        nm->method()->print_short_name(tty);
  1.1352 +        tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d",
  1.1353 +                   fr.pc(),
  1.1354 +                   os::current_thread_id(),
  1.1355 +                   trap_reason_name(reason),
  1.1356 +                   trap_action_name(action),
  1.1357 +                   unloaded_class_index);
  1.1358 +        if (class_name != NULL) {
  1.1359 +          tty->print(unresolved ? " unresolved class: " : " symbol: ");
  1.1360 +          class_name->print_symbol_on(tty);
  1.1361 +        }
  1.1362 +        tty->cr();
  1.1363 +      }
  1.1364 +      if (xtty != NULL) {
  1.1365 +        // Log the precise location of the trap.
  1.1366 +        for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
  1.1367 +          xtty->begin_elem("jvms bci='%d'", sd->bci());
  1.1368 +          xtty->method(sd->method());
  1.1369 +          xtty->end_elem();
  1.1370 +          if (sd->is_top())  break;
  1.1371 +        }
  1.1372 +        xtty->tail("uncommon_trap");
  1.1373 +      }
  1.1374 +    }
  1.1375 +    // (End diagnostic printout.)
  1.1376 +
  1.1377 +    // Load class if necessary
  1.1378 +    if (unloaded_class_index >= 0) {
  1.1379 +      constantPoolHandle constants(THREAD, trap_method->constants());
  1.1380 +      load_class_by_index(constants, unloaded_class_index);
  1.1381 +    }
  1.1382 +
  1.1383 +    // Flush the nmethod if necessary and desirable.
  1.1384 +    //
  1.1385 +    // We need to avoid situations where we are re-flushing the nmethod
  1.1386 +    // because of a hot deoptimization site.  Repeated flushes at the same
  1.1387 +    // point need to be detected by the compiler and avoided.  If the compiler
  1.1388 +    // cannot avoid them (or has a bug and "refuses" to avoid them), this
  1.1389 +    // module must take measures to avoid an infinite cycle of recompilation
  1.1390 +    // and deoptimization.  There are several such measures:
  1.1391 +    //
  1.1392 +    //   1. If a recompilation is ordered a second time at some site X
  1.1393 +    //   and for the same reason R, the action is adjusted to 'reinterpret',
  1.1394 +    //   to give the interpreter time to exercise the method more thoroughly.
  1.1395 +    //   If this happens, the method's overflow_recompile_count is incremented.
  1.1396 +    //
  1.1397 +    //   2. If the compiler fails to reduce the deoptimization rate, then
  1.1398 +    //   the method's overflow_recompile_count will begin to exceed the set
  1.1399 +    //   limit PerBytecodeRecompilationCutoff.  If this happens, the action
  1.1400 +    //   is adjusted to 'make_not_compilable', and the method is abandoned
  1.1401 +    //   to the interpreter.  This is a performance hit for hot methods,
  1.1402 +    //   but is better than a disastrous infinite cycle of recompilations.
  1.1403 +    //   (Actually, only the method containing the site X is abandoned.)
  1.1404 +    //
  1.1405 +    //   3. In parallel with the previous measures, if the total number of
  1.1406 +    //   recompilations of a method exceeds the much larger set limit
  1.1407 +    //   PerMethodRecompilationCutoff, the method is abandoned.
  1.1408 +    //   This should only happen if the method is very large and has
  1.1409 +    //   many "lukewarm" deoptimizations.  The code which enforces this
  1.1410 +    //   limit is elsewhere (class nmethod, class Method).
  1.1411 +    //
  1.1412 +    // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
  1.1413 +    // to recompile at each bytecode independently of the per-BCI cutoff.
  1.1414 +    //
  1.1415 +    // The decision to update code is up to the compiler, and is encoded
  1.1416 +    // in the Action_xxx code.  If the compiler requests Action_none
  1.1417 +    // no trap state is changed, no compiled code is changed, and the
  1.1418 +    // computation suffers along in the interpreter.
  1.1419 +    //
  1.1420 +    // The other action codes specify various tactics for decompilation
  1.1421 +    // and recompilation.  Action_maybe_recompile is the loosest, and
  1.1422 +    // allows the compiled code to stay around until enough traps are seen,
  1.1423 +    // and until the compiler gets around to recompiling the trapping method.
  1.1424 +    //
  1.1425 +    // The other actions cause immediate removal of the present code.
  1.1426 +
  1.1427 +    bool update_trap_state = true;
  1.1428 +    bool make_not_entrant = false;
  1.1429 +    bool make_not_compilable = false;
  1.1430 +    bool reprofile = false;
  1.1431 +    switch (action) {
  1.1432 +    case Action_none:
  1.1433 +      // Keep the old code.
  1.1434 +      update_trap_state = false;
  1.1435 +      break;
  1.1436 +    case Action_maybe_recompile:
  1.1437 +      // Do not need to invalidate the present code, but we can
  1.1438 +      // initiate another
  1.1439 +      // Start compiler without (necessarily) invalidating the nmethod.
  1.1440 +      // The system will tolerate the old code, but new code should be
  1.1441 +      // generated when possible.
  1.1442 +      break;
  1.1443 +    case Action_reinterpret:
  1.1444 +      // Go back into the interpreter for a while, and then consider
  1.1445 +      // recompiling form scratch.
  1.1446 +      make_not_entrant = true;
  1.1447 +      // Reset invocation counter for outer most method.
  1.1448 +      // This will allow the interpreter to exercise the bytecodes
  1.1449 +      // for a while before recompiling.
  1.1450 +      // By contrast, Action_make_not_entrant is immediate.
  1.1451 +      //
  1.1452 +      // Note that the compiler will track null_check, null_assert,
  1.1453 +      // range_check, and class_check events and log them as if they
  1.1454 +      // had been traps taken from compiled code.  This will update
  1.1455 +      // the MDO trap history so that the next compilation will
  1.1456 +      // properly detect hot trap sites.
  1.1457 +      reprofile = true;
  1.1458 +      break;
  1.1459 +    case Action_make_not_entrant:
  1.1460 +      // Request immediate recompilation, and get rid of the old code.
  1.1461 +      // Make them not entrant, so next time they are called they get
  1.1462 +      // recompiled.  Unloaded classes are loaded now so recompile before next
  1.1463 +      // time they are called.  Same for uninitialized.  The interpreter will
  1.1464 +      // link the missing class, if any.
  1.1465 +      make_not_entrant = true;
  1.1466 +      break;
  1.1467 +    case Action_make_not_compilable:
  1.1468 +      // Give up on compiling this method at all.
  1.1469 +      make_not_entrant = true;
  1.1470 +      make_not_compilable = true;
  1.1471 +      break;
  1.1472 +    default:
  1.1473 +      ShouldNotReachHere();
  1.1474 +    }
  1.1475 +
  1.1476 +    // Setting +ProfileTraps fixes the following, on all platforms:
  1.1477 +    // 4852688: ProfileInterpreter is off by default for ia64.  The result is
  1.1478 +    // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
  1.1479 +    // recompile relies on a MethodData* to record heroic opt failures.
  1.1480 +
  1.1481 +    // Whether the interpreter is producing MDO data or not, we also need
  1.1482 +    // to use the MDO to detect hot deoptimization points and control
  1.1483 +    // aggressive optimization.
  1.1484 +    bool inc_recompile_count = false;
  1.1485 +    ProfileData* pdata = NULL;
  1.1486 +    if (ProfileTraps && update_trap_state && trap_mdo != NULL) {
  1.1487 +      assert(trap_mdo == get_method_data(thread, trap_method, false), "sanity");
  1.1488 +      uint this_trap_count = 0;
  1.1489 +      bool maybe_prior_trap = false;
  1.1490 +      bool maybe_prior_recompile = false;
  1.1491 +      pdata = query_update_method_data(trap_mdo, trap_bci, reason,
  1.1492 +                                   nm->method(),
  1.1493 +                                   //outputs:
  1.1494 +                                   this_trap_count,
  1.1495 +                                   maybe_prior_trap,
  1.1496 +                                   maybe_prior_recompile);
  1.1497 +      // Because the interpreter also counts null, div0, range, and class
  1.1498 +      // checks, these traps from compiled code are double-counted.
  1.1499 +      // This is harmless; it just means that the PerXTrapLimit values
  1.1500 +      // are in effect a little smaller than they look.
  1.1501 +
  1.1502 +      DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
  1.1503 +      if (per_bc_reason != Reason_none) {
  1.1504 +        // Now take action based on the partially known per-BCI history.
  1.1505 +        if (maybe_prior_trap
  1.1506 +            && this_trap_count >= (uint)PerBytecodeTrapLimit) {
  1.1507 +          // If there are too many traps at this BCI, force a recompile.
  1.1508 +          // This will allow the compiler to see the limit overflow, and
  1.1509 +          // take corrective action, if possible.  The compiler generally
  1.1510 +          // does not use the exact PerBytecodeTrapLimit value, but instead
  1.1511 +          // changes its tactics if it sees any traps at all.  This provides
  1.1512 +          // a little hysteresis, delaying a recompile until a trap happens
  1.1513 +          // several times.
  1.1514 +          //
  1.1515 +          // Actually, since there is only one bit of counter per BCI,
  1.1516 +          // the possible per-BCI counts are {0,1,(per-method count)}.
  1.1517 +          // This produces accurate results if in fact there is only
  1.1518 +          // one hot trap site, but begins to get fuzzy if there are
  1.1519 +          // many sites.  For example, if there are ten sites each
  1.1520 +          // trapping two or more times, they each get the blame for
  1.1521 +          // all of their traps.
  1.1522 +          make_not_entrant = true;
  1.1523 +        }
  1.1524 +
  1.1525 +        // Detect repeated recompilation at the same BCI, and enforce a limit.
  1.1526 +        if (make_not_entrant && maybe_prior_recompile) {
  1.1527 +          // More than one recompile at this point.
  1.1528 +          inc_recompile_count = maybe_prior_trap;
  1.1529 +        }
  1.1530 +      } else {
  1.1531 +        // For reasons which are not recorded per-bytecode, we simply
  1.1532 +        // force recompiles unconditionally.
  1.1533 +        // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
  1.1534 +        make_not_entrant = true;
  1.1535 +      }
  1.1536 +
  1.1537 +      // Go back to the compiler if there are too many traps in this method.
  1.1538 +      if (this_trap_count >= per_method_trap_limit(reason)) {
  1.1539 +        // If there are too many traps in this method, force a recompile.
  1.1540 +        // This will allow the compiler to see the limit overflow, and
  1.1541 +        // take corrective action, if possible.
  1.1542 +        // (This condition is an unlikely backstop only, because the
  1.1543 +        // PerBytecodeTrapLimit is more likely to take effect first,
  1.1544 +        // if it is applicable.)
  1.1545 +        make_not_entrant = true;
  1.1546 +      }
  1.1547 +
  1.1548 +      // Here's more hysteresis:  If there has been a recompile at
  1.1549 +      // this trap point already, run the method in the interpreter
  1.1550 +      // for a while to exercise it more thoroughly.
  1.1551 +      if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
  1.1552 +        reprofile = true;
  1.1553 +      }
  1.1554 +
  1.1555 +    }
  1.1556 +
  1.1557 +    // Take requested actions on the method:
  1.1558 +
  1.1559 +    // Recompile
  1.1560 +    if (make_not_entrant) {
  1.1561 +      if (!nm->make_not_entrant()) {
  1.1562 +        return; // the call did not change nmethod's state
  1.1563 +      }
  1.1564 +
  1.1565 +      if (pdata != NULL) {
  1.1566 +        // Record the recompilation event, if any.
  1.1567 +        int tstate0 = pdata->trap_state();
  1.1568 +        int tstate1 = trap_state_set_recompiled(tstate0, true);
  1.1569 +        if (tstate1 != tstate0)
  1.1570 +          pdata->set_trap_state(tstate1);
  1.1571 +      }
  1.1572 +
  1.1573 +#if INCLUDE_RTM_OPT
  1.1574 +      // Restart collecting RTM locking abort statistic if the method
  1.1575 +      // is recompiled for a reason other than RTM state change.
  1.1576 +      // Assume that in new recompiled code the statistic could be different,
  1.1577 +      // for example, due to different inlining.
  1.1578 +      if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&
  1.1579 +          UseRTMDeopt && (nm->rtm_state() != ProfileRTM)) {
  1.1580 +        trap_mdo->atomic_set_rtm_state(ProfileRTM);
  1.1581 +      }
  1.1582 +#endif
  1.1583 +    }
  1.1584 +
  1.1585 +    if (inc_recompile_count) {
  1.1586 +      trap_mdo->inc_overflow_recompile_count();
  1.1587 +      if ((uint)trap_mdo->overflow_recompile_count() >
  1.1588 +          (uint)PerBytecodeRecompilationCutoff) {
  1.1589 +        // Give up on the method containing the bad BCI.
  1.1590 +        if (trap_method() == nm->method()) {
  1.1591 +          make_not_compilable = true;
  1.1592 +        } else {
  1.1593 +          trap_method->set_not_compilable(CompLevel_full_optimization, true, "overflow_recompile_count > PerBytecodeRecompilationCutoff");
  1.1594 +          // But give grace to the enclosing nm->method().
  1.1595 +        }
  1.1596 +      }
  1.1597 +    }
  1.1598 +
  1.1599 +    // Reprofile
  1.1600 +    if (reprofile) {
  1.1601 +      CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method());
  1.1602 +    }
  1.1603 +
  1.1604 +    // Give up compiling
  1.1605 +    if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
  1.1606 +      assert(make_not_entrant, "consistent");
  1.1607 +      nm->method()->set_not_compilable(CompLevel_full_optimization);
  1.1608 +    }
  1.1609 +
  1.1610 +  } // Free marked resources
  1.1611 +
  1.1612 +}
  1.1613 +JRT_END
  1.1614 +
  1.1615 +MethodData*
  1.1616 +Deoptimization::get_method_data(JavaThread* thread, methodHandle m,
  1.1617 +                                bool create_if_missing) {
  1.1618 +  Thread* THREAD = thread;
  1.1619 +  MethodData* mdo = m()->method_data();
  1.1620 +  if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {
  1.1621 +    // Build an MDO.  Ignore errors like OutOfMemory;
  1.1622 +    // that simply means we won't have an MDO to update.
  1.1623 +    Method::build_interpreter_method_data(m, THREAD);
  1.1624 +    if (HAS_PENDING_EXCEPTION) {
  1.1625 +      assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
  1.1626 +      CLEAR_PENDING_EXCEPTION;
  1.1627 +    }
  1.1628 +    mdo = m()->method_data();
  1.1629 +  }
  1.1630 +  return mdo;
  1.1631 +}
  1.1632 +
  1.1633 +ProfileData*
  1.1634 +Deoptimization::query_update_method_data(MethodData* trap_mdo,
  1.1635 +                                         int trap_bci,
  1.1636 +                                         Deoptimization::DeoptReason reason,
  1.1637 +                                         Method* compiled_method,
  1.1638 +                                         //outputs:
  1.1639 +                                         uint& ret_this_trap_count,
  1.1640 +                                         bool& ret_maybe_prior_trap,
  1.1641 +                                         bool& ret_maybe_prior_recompile) {
  1.1642 +  uint prior_trap_count = trap_mdo->trap_count(reason);
  1.1643 +  uint this_trap_count  = trap_mdo->inc_trap_count(reason);
  1.1644 +
  1.1645 +  // If the runtime cannot find a place to store trap history,
  1.1646 +  // it is estimated based on the general condition of the method.
  1.1647 +  // If the method has ever been recompiled, or has ever incurred
  1.1648 +  // a trap with the present reason , then this BCI is assumed
  1.1649 +  // (pessimistically) to be the culprit.
  1.1650 +  bool maybe_prior_trap      = (prior_trap_count != 0);
  1.1651 +  bool maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
  1.1652 +  ProfileData* pdata = NULL;
  1.1653 +
  1.1654 +
  1.1655 +  // For reasons which are recorded per bytecode, we check per-BCI data.
  1.1656 +  DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
  1.1657 +  if (per_bc_reason != Reason_none) {
  1.1658 +    // Find the profile data for this BCI.  If there isn't one,
  1.1659 +    // try to allocate one from the MDO's set of spares.
  1.1660 +    // This will let us detect a repeated trap at this point.
  1.1661 +    pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);
  1.1662 +
  1.1663 +    if (pdata != NULL) {
  1.1664 +      if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
  1.1665 +        if (LogCompilation && xtty != NULL) {
  1.1666 +          ttyLocker ttyl;
  1.1667 +          // no more room for speculative traps in this MDO
  1.1668 +          xtty->elem("speculative_traps_oom");
  1.1669 +        }
  1.1670 +      }
  1.1671 +      // Query the trap state of this profile datum.
  1.1672 +      int tstate0 = pdata->trap_state();
  1.1673 +      if (!trap_state_has_reason(tstate0, per_bc_reason))
  1.1674 +        maybe_prior_trap = false;
  1.1675 +      if (!trap_state_is_recompiled(tstate0))
  1.1676 +        maybe_prior_recompile = false;
  1.1677 +
  1.1678 +      // Update the trap state of this profile datum.
  1.1679 +      int tstate1 = tstate0;
  1.1680 +      // Record the reason.
  1.1681 +      tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
  1.1682 +      // Store the updated state on the MDO, for next time.
  1.1683 +      if (tstate1 != tstate0)
  1.1684 +        pdata->set_trap_state(tstate1);
  1.1685 +    } else {
  1.1686 +      if (LogCompilation && xtty != NULL) {
  1.1687 +        ttyLocker ttyl;
  1.1688 +        // Missing MDP?  Leave a small complaint in the log.
  1.1689 +        xtty->elem("missing_mdp bci='%d'", trap_bci);
  1.1690 +      }
  1.1691 +    }
  1.1692 +  }
  1.1693 +
  1.1694 +  // Return results:
  1.1695 +  ret_this_trap_count = this_trap_count;
  1.1696 +  ret_maybe_prior_trap = maybe_prior_trap;
  1.1697 +  ret_maybe_prior_recompile = maybe_prior_recompile;
  1.1698 +  return pdata;
  1.1699 +}
  1.1700 +
  1.1701 +void
  1.1702 +Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
  1.1703 +  ResourceMark rm;
  1.1704 +  // Ignored outputs:
  1.1705 +  uint ignore_this_trap_count;
  1.1706 +  bool ignore_maybe_prior_trap;
  1.1707 +  bool ignore_maybe_prior_recompile;
  1.1708 +  assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
  1.1709 +  query_update_method_data(trap_mdo, trap_bci,
  1.1710 +                           (DeoptReason)reason,
  1.1711 +                           NULL,
  1.1712 +                           ignore_this_trap_count,
  1.1713 +                           ignore_maybe_prior_trap,
  1.1714 +                           ignore_maybe_prior_recompile);
  1.1715 +}
  1.1716 +
  1.1717 +Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request) {
  1.1718 +
  1.1719 +  // Still in Java no safepoints
  1.1720 +  {
  1.1721 +    // This enters VM and may safepoint
  1.1722 +    uncommon_trap_inner(thread, trap_request);
  1.1723 +  }
  1.1724 +  return fetch_unroll_info_helper(thread);
  1.1725 +}
  1.1726 +
  1.1727 +// Local derived constants.
  1.1728 +// Further breakdown of DataLayout::trap_state, as promised by DataLayout.
  1.1729 +const int DS_REASON_MASK   = DataLayout::trap_mask >> 1;
  1.1730 +const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
  1.1731 +
  1.1732 +//---------------------------trap_state_reason---------------------------------
  1.1733 +Deoptimization::DeoptReason
  1.1734 +Deoptimization::trap_state_reason(int trap_state) {
  1.1735 +  // This assert provides the link between the width of DataLayout::trap_bits
  1.1736 +  // and the encoding of "recorded" reasons.  It ensures there are enough
  1.1737 +  // bits to store all needed reasons in the per-BCI MDO profile.
  1.1738 +  assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
  1.1739 +  int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
  1.1740 +  trap_state -= recompile_bit;
  1.1741 +  if (trap_state == DS_REASON_MASK) {
  1.1742 +    return Reason_many;
  1.1743 +  } else {
  1.1744 +    assert((int)Reason_none == 0, "state=0 => Reason_none");
  1.1745 +    return (DeoptReason)trap_state;
  1.1746 +  }
  1.1747 +}
  1.1748 +//-------------------------trap_state_has_reason-------------------------------
  1.1749 +int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
  1.1750 +  assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
  1.1751 +  assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
  1.1752 +  int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
  1.1753 +  trap_state -= recompile_bit;
  1.1754 +  if (trap_state == DS_REASON_MASK) {
  1.1755 +    return -1;  // true, unspecifically (bottom of state lattice)
  1.1756 +  } else if (trap_state == reason) {
  1.1757 +    return 1;   // true, definitely
  1.1758 +  } else if (trap_state == 0) {
  1.1759 +    return 0;   // false, definitely (top of state lattice)
  1.1760 +  } else {
  1.1761 +    return 0;   // false, definitely
  1.1762 +  }
  1.1763 +}
  1.1764 +//-------------------------trap_state_add_reason-------------------------------
  1.1765 +int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
  1.1766 +  assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
  1.1767 +  int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
  1.1768 +  trap_state -= recompile_bit;
  1.1769 +  if (trap_state == DS_REASON_MASK) {
  1.1770 +    return trap_state + recompile_bit;     // already at state lattice bottom
  1.1771 +  } else if (trap_state == reason) {
  1.1772 +    return trap_state + recompile_bit;     // the condition is already true
  1.1773 +  } else if (trap_state == 0) {
  1.1774 +    return reason + recompile_bit;          // no condition has yet been true
  1.1775 +  } else {
  1.1776 +    return DS_REASON_MASK + recompile_bit;  // fall to state lattice bottom
  1.1777 +  }
  1.1778 +}
  1.1779 +//-----------------------trap_state_is_recompiled------------------------------
  1.1780 +bool Deoptimization::trap_state_is_recompiled(int trap_state) {
  1.1781 +  return (trap_state & DS_RECOMPILE_BIT) != 0;
  1.1782 +}
  1.1783 +//-----------------------trap_state_set_recompiled-----------------------------
  1.1784 +int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
  1.1785 +  if (z)  return trap_state |  DS_RECOMPILE_BIT;
  1.1786 +  else    return trap_state & ~DS_RECOMPILE_BIT;
  1.1787 +}
  1.1788 +//---------------------------format_trap_state---------------------------------
  1.1789 +// This is used for debugging and diagnostics, including LogFile output.
  1.1790 +const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
  1.1791 +                                              int trap_state) {
  1.1792 +  DeoptReason reason      = trap_state_reason(trap_state);
  1.1793 +  bool        recomp_flag = trap_state_is_recompiled(trap_state);
  1.1794 +  // Re-encode the state from its decoded components.
  1.1795 +  int decoded_state = 0;
  1.1796 +  if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
  1.1797 +    decoded_state = trap_state_add_reason(decoded_state, reason);
  1.1798 +  if (recomp_flag)
  1.1799 +    decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
  1.1800 +  // If the state re-encodes properly, format it symbolically.
  1.1801 +  // Because this routine is used for debugging and diagnostics,
  1.1802 +  // be robust even if the state is a strange value.
  1.1803 +  size_t len;
  1.1804 +  if (decoded_state != trap_state) {
  1.1805 +    // Random buggy state that doesn't decode??
  1.1806 +    len = jio_snprintf(buf, buflen, "#%d", trap_state);
  1.1807 +  } else {
  1.1808 +    len = jio_snprintf(buf, buflen, "%s%s",
  1.1809 +                       trap_reason_name(reason),
  1.1810 +                       recomp_flag ? " recompiled" : "");
  1.1811 +  }
  1.1812 +  if (len >= buflen)
  1.1813 +    buf[buflen-1] = '\0';
  1.1814 +  return buf;
  1.1815 +}
  1.1816 +
  1.1817 +
  1.1818 +//--------------------------------statics--------------------------------------
  1.1819 +Deoptimization::DeoptAction Deoptimization::_unloaded_action
  1.1820 +  = Deoptimization::Action_reinterpret;
  1.1821 +const char* Deoptimization::_trap_reason_name[Reason_LIMIT] = {
  1.1822 +  // Note:  Keep this in sync. with enum DeoptReason.
  1.1823 +  "none",
  1.1824 +  "null_check",
  1.1825 +  "null_assert",
  1.1826 +  "range_check",
  1.1827 +  "class_check",
  1.1828 +  "array_check",
  1.1829 +  "intrinsic",
  1.1830 +  "bimorphic",
  1.1831 +  "unloaded",
  1.1832 +  "uninitialized",
  1.1833 +  "unreached",
  1.1834 +  "unhandled",
  1.1835 +  "constraint",
  1.1836 +  "div0_check",
  1.1837 +  "age",
  1.1838 +  "predicate",
  1.1839 +  "loop_limit_check",
  1.1840 +  "speculate_class_check",
  1.1841 +  "rtm_state_change"
  1.1842 +};
  1.1843 +const char* Deoptimization::_trap_action_name[Action_LIMIT] = {
  1.1844 +  // Note:  Keep this in sync. with enum DeoptAction.
  1.1845 +  "none",
  1.1846 +  "maybe_recompile",
  1.1847 +  "reinterpret",
  1.1848 +  "make_not_entrant",
  1.1849 +  "make_not_compilable"
  1.1850 +};
  1.1851 +
  1.1852 +const char* Deoptimization::trap_reason_name(int reason) {
  1.1853 +  if (reason == Reason_many)  return "many";
  1.1854 +  if ((uint)reason < Reason_LIMIT)
  1.1855 +    return _trap_reason_name[reason];
  1.1856 +  static char buf[20];
  1.1857 +  sprintf(buf, "reason%d", reason);
  1.1858 +  return buf;
  1.1859 +}
  1.1860 +const char* Deoptimization::trap_action_name(int action) {
  1.1861 +  if ((uint)action < Action_LIMIT)
  1.1862 +    return _trap_action_name[action];
  1.1863 +  static char buf[20];
  1.1864 +  sprintf(buf, "action%d", action);
  1.1865 +  return buf;
  1.1866 +}
  1.1867 +
  1.1868 +// This is used for debugging and diagnostics, including LogFile output.
  1.1869 +const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
  1.1870 +                                                int trap_request) {
  1.1871 +  jint unloaded_class_index = trap_request_index(trap_request);
  1.1872 +  const char* reason = trap_reason_name(trap_request_reason(trap_request));
  1.1873 +  const char* action = trap_action_name(trap_request_action(trap_request));
  1.1874 +  size_t len;
  1.1875 +  if (unloaded_class_index < 0) {
  1.1876 +    len = jio_snprintf(buf, buflen, "reason='%s' action='%s'",
  1.1877 +                       reason, action);
  1.1878 +  } else {
  1.1879 +    len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'",
  1.1880 +                       reason, action, unloaded_class_index);
  1.1881 +  }
  1.1882 +  if (len >= buflen)
  1.1883 +    buf[buflen-1] = '\0';
  1.1884 +  return buf;
  1.1885 +}
  1.1886 +
  1.1887 +juint Deoptimization::_deoptimization_hist
  1.1888 +        [Deoptimization::Reason_LIMIT]
  1.1889 +    [1 + Deoptimization::Action_LIMIT]
  1.1890 +        [Deoptimization::BC_CASE_LIMIT]
  1.1891 +  = {0};
  1.1892 +
  1.1893 +enum {
  1.1894 +  LSB_BITS = 8,
  1.1895 +  LSB_MASK = right_n_bits(LSB_BITS)
  1.1896 +};
  1.1897 +
  1.1898 +void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
  1.1899 +                                       Bytecodes::Code bc) {
  1.1900 +  assert(reason >= 0 && reason < Reason_LIMIT, "oob");
  1.1901 +  assert(action >= 0 && action < Action_LIMIT, "oob");
  1.1902 +  _deoptimization_hist[Reason_none][0][0] += 1;  // total
  1.1903 +  _deoptimization_hist[reason][0][0]      += 1;  // per-reason total
  1.1904 +  juint* cases = _deoptimization_hist[reason][1+action];
  1.1905 +  juint* bc_counter_addr = NULL;
  1.1906 +  juint  bc_counter      = 0;
  1.1907 +  // Look for an unused counter, or an exact match to this BC.
  1.1908 +  if (bc != Bytecodes::_illegal) {
  1.1909 +    for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
  1.1910 +      juint* counter_addr = &cases[bc_case];
  1.1911 +      juint  counter = *counter_addr;
  1.1912 +      if ((counter == 0 && bc_counter_addr == NULL)
  1.1913 +          || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
  1.1914 +        // this counter is either free or is already devoted to this BC
  1.1915 +        bc_counter_addr = counter_addr;
  1.1916 +        bc_counter = counter | bc;
  1.1917 +      }
  1.1918 +    }
  1.1919 +  }
  1.1920 +  if (bc_counter_addr == NULL) {
  1.1921 +    // Overflow, or no given bytecode.
  1.1922 +    bc_counter_addr = &cases[BC_CASE_LIMIT-1];
  1.1923 +    bc_counter = (*bc_counter_addr & ~LSB_MASK);  // clear LSB
  1.1924 +  }
  1.1925 +  *bc_counter_addr = bc_counter + (1 << LSB_BITS);
  1.1926 +}
  1.1927 +
  1.1928 +jint Deoptimization::total_deoptimization_count() {
  1.1929 +  return _deoptimization_hist[Reason_none][0][0];
  1.1930 +}
  1.1931 +
  1.1932 +jint Deoptimization::deoptimization_count(DeoptReason reason) {
  1.1933 +  assert(reason >= 0 && reason < Reason_LIMIT, "oob");
  1.1934 +  return _deoptimization_hist[reason][0][0];
  1.1935 +}
  1.1936 +
  1.1937 +void Deoptimization::print_statistics() {
  1.1938 +  juint total = total_deoptimization_count();
  1.1939 +  juint account = total;
  1.1940 +  if (total != 0) {
  1.1941 +    ttyLocker ttyl;
  1.1942 +    if (xtty != NULL)  xtty->head("statistics type='deoptimization'");
  1.1943 +    tty->print_cr("Deoptimization traps recorded:");
  1.1944 +    #define PRINT_STAT_LINE(name, r) \
  1.1945 +      tty->print_cr("  %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
  1.1946 +    PRINT_STAT_LINE("total", total);
  1.1947 +    // For each non-zero entry in the histogram, print the reason,
  1.1948 +    // the action, and (if specifically known) the type of bytecode.
  1.1949 +    for (int reason = 0; reason < Reason_LIMIT; reason++) {
  1.1950 +      for (int action = 0; action < Action_LIMIT; action++) {
  1.1951 +        juint* cases = _deoptimization_hist[reason][1+action];
  1.1952 +        for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
  1.1953 +          juint counter = cases[bc_case];
  1.1954 +          if (counter != 0) {
  1.1955 +            char name[1*K];
  1.1956 +            Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
  1.1957 +            if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
  1.1958 +              bc = Bytecodes::_illegal;
  1.1959 +            sprintf(name, "%s/%s/%s",
  1.1960 +                    trap_reason_name(reason),
  1.1961 +                    trap_action_name(action),
  1.1962 +                    Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
  1.1963 +            juint r = counter >> LSB_BITS;
  1.1964 +            tty->print_cr("  %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
  1.1965 +            account -= r;
  1.1966 +          }
  1.1967 +        }
  1.1968 +      }
  1.1969 +    }
  1.1970 +    if (account != 0) {
  1.1971 +      PRINT_STAT_LINE("unaccounted", account);
  1.1972 +    }
  1.1973 +    #undef PRINT_STAT_LINE
  1.1974 +    if (xtty != NULL)  xtty->tail("statistics");
  1.1975 +  }
  1.1976 +}
  1.1977 +#else // COMPILER2 || SHARK
  1.1978 +
  1.1979 +
  1.1980 +// Stubs for C1 only system.
  1.1981 +bool Deoptimization::trap_state_is_recompiled(int trap_state) {
  1.1982 +  return false;
  1.1983 +}
  1.1984 +
  1.1985 +const char* Deoptimization::trap_reason_name(int reason) {
  1.1986 +  return "unknown";
  1.1987 +}
  1.1988 +
  1.1989 +void Deoptimization::print_statistics() {
  1.1990 +  // no output
  1.1991 +}
  1.1992 +
  1.1993 +void
  1.1994 +Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
  1.1995 +  // no udpate
  1.1996 +}
  1.1997 +
  1.1998 +int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
  1.1999 +  return 0;
  1.2000 +}
  1.2001 +
  1.2002 +void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
  1.2003 +                                       Bytecodes::Code bc) {
  1.2004 +  // no update
  1.2005 +}
  1.2006 +
  1.2007 +const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
  1.2008 +                                              int trap_state) {
  1.2009 +  jio_snprintf(buf, buflen, "#%d", trap_state);
  1.2010 +  return buf;
  1.2011 +}
  1.2012 +
  1.2013 +#endif // COMPILER2 || SHARK

mercurial