blob: d380bf6d518d4f0bfe07a9f7e37f873e23e83216 [file] [log] [blame]
J. Duke81537792007-12-01 00:00:00 +00001/*
Goetz Lindenmaierb26df6b2016-01-04 15:41:05 +01002 * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
J. Duke81537792007-12-01 00:00:00 +00003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
Erik Trimbleba7c1732010-05-27 19:08:38 -070019 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
J. Duke81537792007-12-01 00:00:00 +000022 *
23 */
24
Stefan Karlsson8006fe82010-11-23 13:22:55 -080025#include "precompiled.hpp"
26#include "classfile/systemDictionary.hpp"
Goetz Lindenmaier25f33c02014-07-04 11:46:01 +020027#include "code/codeCache.hpp"
Stefan Karlsson8006fe82010-11-23 13:22:55 -080028#include "code/debugInfoRec.hpp"
29#include "code/nmethod.hpp"
30#include "code/pcDesc.hpp"
31#include "code/scopeDesc.hpp"
32#include "interpreter/bytecode.hpp"
33#include "interpreter/interpreter.hpp"
34#include "interpreter/oopMapCache.hpp"
35#include "memory/allocation.inline.hpp"
36#include "memory/oopFactory.hpp"
37#include "memory/resourceArea.hpp"
Jon Masamitsu5c58d272012-09-01 13:25:18 -040038#include "oops/method.hpp"
Goetz Lindenmaierb26df6b2016-01-04 15:41:05 +010039#include "oops/objArrayOop.inline.hpp"
Stefan Karlsson8006fe82010-11-23 13:22:55 -080040#include "oops/oop.inline.hpp"
Christian Thalinger16526e02015-10-08 12:49:30 -100041#include "oops/fieldStreams.hpp"
Stefan Karlsson2e888852015-02-18 08:57:29 +010042#include "oops/verifyOopClosure.hpp"
Stefan Karlsson8006fe82010-11-23 13:22:55 -080043#include "prims/jvmtiThreadState.hpp"
44#include "runtime/biasedLocking.hpp"
45#include "runtime/compilationPolicy.hpp"
46#include "runtime/deoptimization.hpp"
47#include "runtime/interfaceSupport.hpp"
48#include "runtime/sharedRuntime.hpp"
49#include "runtime/signature.hpp"
50#include "runtime/stubRoutines.hpp"
51#include "runtime/thread.hpp"
52#include "runtime/vframe.hpp"
53#include "runtime/vframeArray.hpp"
54#include "runtime/vframe_hp.hpp"
55#include "utilities/events.hpp"
56#include "utilities/xmlstream.hpp"
J. Duke81537792007-12-01 00:00:00 +000057
Christian Thalinger16526e02015-10-08 12:49:30 -100058#if INCLUDE_JVMCI
59#include "jvmci/jvmciRuntime.hpp"
60#include "jvmci/jvmciJavaClasses.hpp"
61#endif
62
63
J. Duke81537792007-12-01 00:00:00 +000064bool DeoptimizationMarker::_is_active = false;
65
66Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame,
67 int caller_adjustment,
Tom Rodrigueze5357d42011-05-12 10:29:02 -070068 int caller_actual_parameters,
J. Duke81537792007-12-01 00:00:00 +000069 int number_of_frames,
70 intptr_t* frame_sizes,
71 address* frame_pcs,
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -100072 BasicType return_type,
73 int exec_mode) {
J. Duke81537792007-12-01 00:00:00 +000074 _size_of_deoptimized_frame = size_of_deoptimized_frame;
75 _caller_adjustment = caller_adjustment;
Tom Rodrigueze5357d42011-05-12 10:29:02 -070076 _caller_actual_parameters = caller_actual_parameters;
J. Duke81537792007-12-01 00:00:00 +000077 _number_of_frames = number_of_frames;
78 _frame_sizes = frame_sizes;
79 _frame_pcs = frame_pcs;
Zhengyu Gua39b1762012-06-28 17:03:16 -040080 _register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
J. Duke81537792007-12-01 00:00:00 +000081 _return_type = return_type;
Bertrand Delsart6141a562011-09-08 10:12:25 +020082 _initial_info = 0;
J. Duke81537792007-12-01 00:00:00 +000083 // PD (x86 only)
84 _counter_temp = 0;
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -100085 _unpack_kind = exec_mode;
J. Duke81537792007-12-01 00:00:00 +000086 _sender_sp_temp = 0;
87
88 _total_frame_sizes = size_of_frames();
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -100089 assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");
J. Duke81537792007-12-01 00:00:00 +000090}
91
92
93Deoptimization::UnrollBlock::~UnrollBlock() {
Max Ockner91dbd4f2014-12-01 12:16:15 -050094 FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes);
95 FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs);
96 FREE_C_HEAP_ARRAY(intptr_t, _register_block);
J. Duke81537792007-12-01 00:00:00 +000097}
98
99
100intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {
101 assert(register_number < RegisterMap::reg_count, "checking register number");
102 return &_register_block[register_number * 2];
103}
104
105
106
107int Deoptimization::UnrollBlock::size_of_frames() const {
108 // Acount first for the adjustment of the initial frame
109 int result = _caller_adjustment;
110 for (int index = 0; index < number_of_frames(); index++) {
111 result += frame_sizes()[index];
112 }
113 return result;
114}
115
116
117void Deoptimization::UnrollBlock::print() {
118 ttyLocker ttyl;
119 tty->print_cr("UnrollBlock");
120 tty->print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
121 tty->print( " frame_sizes: ");
122 for (int index = 0; index < number_of_frames(); index++) {
David Lindholm5770f4e2015-10-09 09:42:33 +0200123 tty->print(INTX_FORMAT " ", frame_sizes()[index]);
J. Duke81537792007-12-01 00:00:00 +0000124 }
125 tty->cr();
126}
127
128
129// In order to make fetch_unroll_info work properly with escape
130// analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and
131// ResetNoHandleMark and HandleMark were removed from it. The actual reallocation
132// of previously eliminated objects occurs in realloc_objects, which is
133// called from the method fetch_unroll_info_helper below.
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -1000134JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread, int exec_mode))
J. Duke81537792007-12-01 00:00:00 +0000135 // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
136 // but makes the entry a little slower. There is however a little dance we have to
137 // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
138
139 // fetch_unroll_info() is called at the beginning of the deoptimization
140 // handler. Note this fact before we start generating temporary frames
141 // that can confuse an asynchronous stack walker. This counter is
142 // decremented at the end of unpack_frames().
Christian Thalinger16526e02015-10-08 12:49:30 -1000143 if (TraceDeoptimization) {
Dean Long344a9be2015-10-17 19:40:30 -0400144 tty->print_cr("Deoptimizing thread " INTPTR_FORMAT, p2i(thread));
Christian Thalinger16526e02015-10-08 12:49:30 -1000145 }
J. Duke81537792007-12-01 00:00:00 +0000146 thread->inc_in_deopt_handler();
147
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -1000148 return fetch_unroll_info_helper(thread, exec_mode);
J. Duke81537792007-12-01 00:00:00 +0000149JRT_END
150
151
152// This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -1000153Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread, int exec_mode) {
J. Duke81537792007-12-01 00:00:00 +0000154
155 // Note: there is a safepoint safety issue here. No matter whether we enter
156 // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
157 // the vframeArray is created.
158 //
159
160 // Allocate our special deoptimization ResourceMark
161 DeoptResourceMark* dmark = new DeoptResourceMark(thread);
162 assert(thread->deopt_mark() == NULL, "Pending deopt!");
163 thread->set_deopt_mark(dmark);
164
165 frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect
166 RegisterMap map(thread, true);
167 RegisterMap dummy_map(thread, false);
168 // Now get the deoptee with a valid map
169 frame deoptee = stub_frame.sender(&map);
Igor Veresov0f315112010-09-21 13:38:35 -0700170 // Set the deoptee nmethod
171 assert(thread->deopt_nmethod() == NULL, "Pending deopt!");
172 thread->set_deopt_nmethod(deoptee.cb()->as_nmethod_or_null());
Christian Thalinger16526e02015-10-08 12:49:30 -1000173 bool skip_internal = thread->deopt_nmethod() != NULL && !thread->deopt_nmethod()->compiler()->is_jvmci();
J. Duke81537792007-12-01 00:00:00 +0000174
Tom Rodriguez33f0e502011-05-02 18:53:37 -0700175 if (VerifyStack) {
176 thread->validate_frame_layout();
177 }
178
J. Duke81537792007-12-01 00:00:00 +0000179 // Create a growable array of VFrames where each VFrame represents an inlined
180 // Java frame. This storage is allocated with the usual system arena.
181 assert(deoptee.is_compiled_frame(), "Wrong frame type");
182 GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
183 vframe* vf = vframe::new_vframe(&deoptee, &map, thread);
184 while (!vf->is_top()) {
185 assert(vf->is_compiled_frame(), "Wrong frame type");
186 chunk->push(compiledVFrame::cast(vf));
187 vf = vf->sender();
188 }
189 assert(vf->is_compiled_frame(), "Wrong frame type");
190 chunk->push(compiledVFrame::cast(vf));
191
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -1000192 ScopeDesc* trap_scope = chunk->at(0)->scope();
193 Handle exceptionObject;
194 if (trap_scope->rethrow_exception()) {
195 if (PrintDeoptimizationDetails) {
196 tty->print_cr("Exception to be rethrown in the interpreter for method %s::%s at bci %d", trap_scope->method()->method_holder()->name()->as_C_string(), trap_scope->method()->name()->as_C_string(), trap_scope->bci());
197 }
198 GrowableArray<ScopeValue*>* expressions = trap_scope->expressions();
199 guarantee(expressions != NULL && expressions->length() > 0, "must have exception to throw");
200 ScopeValue* topOfStack = expressions->top();
201 exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();
202 assert(exceptionObject() != NULL, "exception oop can not be null");
203 }
204
Roland Westrelin15dcd412014-11-25 17:33:59 +0100205 bool realloc_failures = false;
206
Christian Thalinger16526e02015-10-08 12:49:30 -1000207#if defined(COMPILER2) || INCLUDE_JVMCI
J. Duke81537792007-12-01 00:00:00 +0000208 // Reallocate the non-escaping objects and restore their fields. Then
209 // relock objects if synchronization on them was eliminated.
Christian Thalinger16526e02015-10-08 12:49:30 -1000210#ifndef INCLUDE_JVMCI
Vladimir Kozlov94927c32012-01-07 13:26:43 -0800211 if (DoEscapeAnalysis || EliminateNestedLocks) {
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700212 if (EliminateAllocations) {
Christian Thalinger16526e02015-10-08 12:49:30 -1000213#endif // INCLUDE_JVMCI
Vladimir Kozlov659a8dc2008-04-01 16:14:18 -0700214 assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700215 GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
Vladimir Kozlov22409a52010-02-09 01:31:13 -0800216
217 // The flag return_oop() indicates call sites which return oop
218 // in compiled code. Such sites include java method calls,
219 // runtime calls (for example, used to allocate new objects/arrays
220 // on slow code path) and any other calls generated in compiled code.
221 // It is not guaranteed that we can get such information here only
222 // by analyzing bytecode in deoptimized frames. This is why this flag
223 // is set during method compilation (see Compile::Process_OopMap_Node()).
Roland Westrelin9369af82014-08-27 17:37:18 +0200224 // If the previous frame was popped, we don't have a result.
225 bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution();
Vladimir Kozlov22409a52010-02-09 01:31:13 -0800226 Handle return_value;
227 if (save_oop_result) {
228 // Reallocation may trigger GC. If deoptimization happened on return from
229 // call which returns oop we need to save it since it is not in oopmap.
230 oop result = deoptee.saved_oop_result(&map);
231 assert(result == NULL || result->is_oop(), "must be oop");
232 return_value = Handle(thread, result);
233 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
234 if (TraceDeoptimization) {
Vladimir Ivanov822deb62012-10-05 18:57:10 -0700235 ttyLocker ttyl;
David Lindholm5770f4e2015-10-09 09:42:33 +0200236 tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
Vladimir Kozlov22409a52010-02-09 01:31:13 -0800237 }
238 }
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700239 if (objects != NULL) {
240 JRT_BLOCK
Roland Westrelin15dcd412014-11-25 17:33:59 +0100241 realloc_failures = realloc_objects(thread, &deoptee, objects, THREAD);
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700242 JRT_END
Christian Thalinger16526e02015-10-08 12:49:30 -1000243 reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal);
J. Duke81537792007-12-01 00:00:00 +0000244#ifndef PRODUCT
Roland Westrelin0dbf9d72014-12-10 16:45:55 +0100245 if (TraceDeoptimization) {
246 ttyLocker ttyl;
David Lindholm5770f4e2015-10-09 09:42:33 +0200247 tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(thread));
Roland Westrelin0dbf9d72014-12-10 16:45:55 +0100248 print_objects(objects, realloc_failures);
249 }
Roland Westrelin15dcd412014-11-25 17:33:59 +0100250#endif
Roland Westrelin0dbf9d72014-12-10 16:45:55 +0100251 }
Vladimir Kozlov22409a52010-02-09 01:31:13 -0800252 if (save_oop_result) {
253 // Restore result.
254 deoptee.set_saved_oop_result(&map, return_value());
255 }
Christian Thalinger16526e02015-10-08 12:49:30 -1000256#ifndef INCLUDE_JVMCI
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700257 }
258 if (EliminateLocks) {
Christian Thalinger16526e02015-10-08 12:49:30 -1000259#endif // INCLUDE_JVMCI
Vladimir Kozlov659a8dc2008-04-01 16:14:18 -0700260#ifndef PRODUCT
261 bool first = true;
262#endif
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700263 for (int i = 0; i < chunk->length(); i++) {
Vladimir Kozlov659a8dc2008-04-01 16:14:18 -0700264 compiledVFrame* cvf = chunk->at(i);
265 assert (cvf->scope() != NULL,"expect only compiled java frames");
266 GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
267 if (monitors->is_nonempty()) {
Roland Westrelin15dcd412014-11-25 17:33:59 +0100268 relock_objects(monitors, thread, realloc_failures);
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700269#ifndef PRODUCT
Christian Thalinger16526e02015-10-08 12:49:30 -1000270 if (PrintDeoptimizationDetails) {
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700271 ttyLocker ttyl;
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700272 for (int j = 0; j < monitors->length(); j++) {
Vladimir Kozlov659a8dc2008-04-01 16:14:18 -0700273 MonitorInfo* mi = monitors->at(j);
274 if (mi->eliminated()) {
275 if (first) {
276 first = false;
David Lindholm5770f4e2015-10-09 09:42:33 +0200277 tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread));
Vladimir Kozlov659a8dc2008-04-01 16:14:18 -0700278 }
Roland Westrelin15dcd412014-11-25 17:33:59 +0100279 if (mi->owner_is_scalar_replaced()) {
280 Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
281 tty->print_cr(" failed reallocation for klass %s", k->external_name());
282 } else {
David Lindholm5770f4e2015-10-09 09:42:33 +0200283 tty->print_cr(" object <" INTPTR_FORMAT "> locked", p2i(mi->owner()));
Roland Westrelin15dcd412014-11-25 17:33:59 +0100284 }
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700285 }
J. Duke81537792007-12-01 00:00:00 +0000286 }
287 }
Christian Thalinger16526e02015-10-08 12:49:30 -1000288#endif // !PRODUCT
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700289 }
J. Duke81537792007-12-01 00:00:00 +0000290 }
Christian Thalinger16526e02015-10-08 12:49:30 -1000291#ifndef INCLUDE_JVMCI
J. Duke81537792007-12-01 00:00:00 +0000292 }
293 }
Christian Thalinger16526e02015-10-08 12:49:30 -1000294#endif // INCLUDE_JVMCI
295#endif // COMPILER2 || INCLUDE_JVMCI
296
J. Duke81537792007-12-01 00:00:00 +0000297 // Ensure that no safepoint is taken after pointers have been stored
298 // in fields of rematerialized objects. If a safepoint occurs from here on
299 // out the java state residing in the vframeArray will be missed.
David Lindholmad0c2082016-01-14 13:26:19 +0100300 NoSafepointVerifier no_safepoint;
J. Duke81537792007-12-01 00:00:00 +0000301
Roland Westrelin15dcd412014-11-25 17:33:59 +0100302 vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures);
Christian Thalinger16526e02015-10-08 12:49:30 -1000303#if defined(COMPILER2) || INCLUDE_JVMCI
Roland Westrelin15dcd412014-11-25 17:33:59 +0100304 if (realloc_failures) {
305 pop_frames_failed_reallocs(thread, array);
306 }
307#endif
J. Duke81537792007-12-01 00:00:00 +0000308
Roland Westrelin15dcd412014-11-25 17:33:59 +0100309 assert(thread->vframe_array_head() == NULL, "Pending deopt!");
J. Duke81537792007-12-01 00:00:00 +0000310 thread->set_vframe_array_head(array);
311
312 // Now that the vframeArray has been created if we have any deferred local writes
313 // added by jvmti then we can free up that structure as the data is now in the
314 // vframeArray
315
316 if (thread->deferred_locals() != NULL) {
317 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals();
318 int i = 0;
319 do {
320 // Because of inlining we could have multiple vframes for a single frame
321 // and several of the vframes could have deferred writes. Find them all.
322 if (list->at(i)->id() == array->original().id()) {
323 jvmtiDeferredLocalVariableSet* dlv = list->at(i);
324 list->remove_at(i);
325 // individual jvmtiDeferredLocalVariableSet are CHeapObj's
326 delete dlv;
327 } else {
328 i++;
329 }
330 } while ( i < list->length() );
331 if (list->length() == 0) {
332 thread->set_deferred_locals(NULL);
333 // free the list and elements back to C heap.
334 delete list;
335 }
336
337 }
338
Gary Bensond7310fb2010-08-11 05:51:21 -0700339#ifndef SHARK
J. Duke81537792007-12-01 00:00:00 +0000340 // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
341 CodeBlob* cb = stub_frame.cb();
342 // Verify we have the right vframeArray
343 assert(cb->frame_size() >= 0, "Unexpected frame size");
344 intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
345
Christian Thalinger918c7a22010-02-01 19:29:46 +0100346 // If the deopt call site is a MethodHandle invoke call site we have
347 // to adjust the unpack_sp.
348 nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
349 if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))
350 unpack_sp = deoptee.unextended_sp();
351
J. Duke81537792007-12-01 00:00:00 +0000352#ifdef ASSERT
Christian Thalinger16526e02015-10-08 12:49:30 -1000353 assert(cb->is_deoptimization_stub() ||
354 cb->is_uncommon_trap_stub() ||
355 strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||
356 strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,
Dean Long344a9be2015-10-17 19:40:30 -0400357 "unexpected code blob: %s", cb->name());
J. Duke81537792007-12-01 00:00:00 +0000358#endif
Gary Bensond7310fb2010-08-11 05:51:21 -0700359#else
360 intptr_t* unpack_sp = stub_frame.sender(&dummy_map).unextended_sp();
361#endif // !SHARK
362
J. Duke81537792007-12-01 00:00:00 +0000363 // This is a guarantee instead of an assert because if vframe doesn't match
364 // we will unpack the wrong deoptimized frame and wind up in strange places
365 // where it will be very difficult to figure out what went wrong. Better
366 // to die an early death here than some very obscure death later when the
367 // trail is cold.
368 // Note: on ia64 this guarantee can be fooled by frames with no memory stack
369 // in that it will fail to detect a problem when there is one. This needs
370 // more work in tiger timeframe.
371 guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
372
373 int number_of_frames = array->frames();
374
375 // Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost
376 // virtual activation, which is the reverse of the elements in the vframes array.
Zhengyu Gua39b1762012-06-28 17:03:16 -0400377 intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
J. Duke81537792007-12-01 00:00:00 +0000378 // +1 because we always have an interpreter return address for the final slot.
Zhengyu Gua39b1762012-06-28 17:03:16 -0400379 address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
J. Duke81537792007-12-01 00:00:00 +0000380 int popframe_extra_args = 0;
381 // Create an interpreter return address for the stub to use as its return
382 // address so the skeletal frames are perfectly walkable
383 frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
384
385 // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
386 // activation be put back on the expression stack of the caller for reexecution
387 if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) {
388 popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words());
389 }
390
Tom Rodrigueze5357d42011-05-12 10:29:02 -0700391 // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
392 // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
393 // than simply use array->sender.pc(). This requires us to walk the current set of frames
394 //
395 frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
396 deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller
397
Jesper Wilhelmsson81ba2e32014-01-23 14:47:23 +0100398 // It's possible that the number of parameters at the call site is
Tom Rodrigueze5357d42011-05-12 10:29:02 -0700399 // different than number of arguments in the callee when method
400 // handles are used. If the caller is interpreted get the real
401 // value so that the proper amount of space can be added to it's
402 // frame.
Christian Thalingerae64d0b2011-10-24 07:53:17 -0700403 bool caller_was_method_handle = false;
Tom Rodrigueze5357d42011-05-12 10:29:02 -0700404 if (deopt_sender.is_interpreted_frame()) {
405 methodHandle method = deopt_sender.interpreter_frame_method();
Christian Thalinger5a4de972011-11-03 01:43:26 -0700406 Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
Christian Thalinger12901d02012-07-24 10:51:00 -0700407 if (cur.is_invokedynamic() || cur.is_invokehandle()) {
Christian Thalingerae64d0b2011-10-24 07:53:17 -0700408 // Method handle invokes may involve fairly arbitrary chains of
409 // calls so it's impossible to know how much actual space the
410 // caller has for locals.
411 caller_was_method_handle = true;
412 }
Tom Rodrigueze5357d42011-05-12 10:29:02 -0700413 }
414
J. Duke81537792007-12-01 00:00:00 +0000415 //
416 // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
417 // frame_sizes/frame_pcs[1] next oldest frame (int)
418 // frame_sizes/frame_pcs[n] youngest frame (int)
419 //
420 // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
421 // owns the space for the return address to it's caller). Confusing ain't it.
422 //
423 // The vframe array can address vframes with indices running from
424 // 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame.
425 // When we create the skeletal frames we need the oldest frame to be in the zero slot
426 // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
427 // so things look a little strange in this loop.
428 //
Christian Thalingerae64d0b2011-10-24 07:53:17 -0700429 int callee_parameters = 0;
430 int callee_locals = 0;
J. Duke81537792007-12-01 00:00:00 +0000431 for (int index = 0; index < array->frames(); index++ ) {
432 // frame[number_of_frames - 1 ] = on_stack_size(youngest)
433 // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
434 // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
Roland Westrelinf5adc572014-04-01 09:36:49 +0200435 frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
J. Duke81537792007-12-01 00:00:00 +0000436 callee_locals,
437 index == 0,
438 popframe_extra_args);
439 // This pc doesn't have to be perfect just good enough to identify the frame
440 // as interpreted so the skeleton frame will be walkable
441 // The correct pc will be set when the skeleton frame is completely filled out
442 // The final pc we store in the loop is wrong and will be overwritten below
443 frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
444
445 callee_parameters = array->element(index)->method()->size_of_parameters();
446 callee_locals = array->element(index)->method()->max_locals();
447 popframe_extra_args = 0;
448 }
449
450 // Compute whether the root vframe returns a float or double value.
451 BasicType return_type;
452 {
453 HandleMark hm;
454 methodHandle method(thread, array->element(0)->method());
Tom Rodriguez423f5872011-01-13 22:15:41 -0800455 Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
Coleen Phillimore7b4f8072011-01-27 16:11:27 -0800456 return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
J. Duke81537792007-12-01 00:00:00 +0000457 }
458
459 // Compute information for handling adapters and adjusting the frame size of the caller.
460 int caller_adjustment = 0;
461
J. Duke81537792007-12-01 00:00:00 +0000462 // Compute the amount the oldest interpreter frame will have to adjust
463 // its caller's stack by. If the caller is a compiled frame then
464 // we pretend that the callee has no parameters so that the
465 // extension counts for the full amount of locals and not just
466 // locals-parms. This is because without a c2i adapter the parm
467 // area as created by the compiled frame will not be usable by
468 // the interpreter. (Depending on the calling convention there
469 // may not even be enough space).
470
471 // QQQ I'd rather see this pushed down into last_frame_adjust
472 // and have it take the sender (aka caller).
473
Christian Thalingerae64d0b2011-10-24 07:53:17 -0700474 if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {
J. Duke81537792007-12-01 00:00:00 +0000475 caller_adjustment = last_frame_adjust(0, callee_locals);
Christian Thalingerae64d0b2011-10-24 07:53:17 -0700476 } else if (callee_locals > callee_parameters) {
J. Duke81537792007-12-01 00:00:00 +0000477 // The caller frame may need extending to accommodate
478 // non-parameter locals of the first unpacked interpreted frame.
479 // Compute that adjustment.
Christian Thalingerae64d0b2011-10-24 07:53:17 -0700480 caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
J. Duke81537792007-12-01 00:00:00 +0000481 }
482
J. Duke81537792007-12-01 00:00:00 +0000483 // If the sender is deoptimized the we must retrieve the address of the handler
484 // since the frame will "magically" show the original pc before the deopt
485 // and we'd undo the deopt.
486
487 frame_pcs[0] = deopt_sender.raw_pc();
488
Gary Bensond7310fb2010-08-11 05:51:21 -0700489#ifndef SHARK
J. Duke81537792007-12-01 00:00:00 +0000490 assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");
Gary Bensond7310fb2010-08-11 05:51:21 -0700491#endif // SHARK
J. Duke81537792007-12-01 00:00:00 +0000492
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -1000493#ifdef INCLUDE_JVMCI
494 if (exceptionObject() != NULL) {
495 thread->set_exception_oop(exceptionObject());
496 exec_mode = Unpack_exception;
497 }
498#endif
499
J. Duke81537792007-12-01 00:00:00 +0000500 UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
501 caller_adjustment * BytesPerWord,
Christian Thalingerae64d0b2011-10-24 07:53:17 -0700502 caller_was_method_handle ? 0 : callee_parameters,
J. Duke81537792007-12-01 00:00:00 +0000503 number_of_frames,
504 frame_sizes,
505 frame_pcs,
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -1000506 return_type,
507 exec_mode);
Bertrand Delsart6141a562011-09-08 10:12:25 +0200508 // On some platforms, we need a way to pass some platform dependent
509 // information to the unpacking code so the skeletal frames come out
510 // correct (initial fp value, unextended sp, ...)
511 info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
J. Duke81537792007-12-01 00:00:00 +0000512
513 if (array->frames() > 1) {
514 if (VerifyStack && TraceDeoptimization) {
Vladimir Ivanov822deb62012-10-05 18:57:10 -0700515 ttyLocker ttyl;
J. Duke81537792007-12-01 00:00:00 +0000516 tty->print_cr("Deoptimizing method containing inlining");
517 }
518 }
519
520 array->set_unroll_block(info);
521 return info;
522}
523
524// Called to cleanup deoptimization data structures in normal case
525// after unpacking to stack and when stack overflow error occurs
526void Deoptimization::cleanup_deopt_info(JavaThread *thread,
527 vframeArray *array) {
528
529 // Get array if coming from exception
530 if (array == NULL) {
531 array = thread->vframe_array_head();
532 }
533 thread->set_vframe_array_head(NULL);
534
535 // Free the previous UnrollBlock
536 vframeArray* old_array = thread->vframe_array_last();
537 thread->set_vframe_array_last(array);
538
539 if (old_array != NULL) {
540 UnrollBlock* old_info = old_array->unroll_block();
541 old_array->set_unroll_block(NULL);
542 delete old_info;
543 delete old_array;
544 }
545
546 // Deallocate any resource creating in this routine and any ResourceObjs allocated
547 // inside the vframeArray (StackValueCollections)
548
549 delete thread->deopt_mark();
550 thread->set_deopt_mark(NULL);
Igor Veresov0f315112010-09-21 13:38:35 -0700551 thread->set_deopt_nmethod(NULL);
J. Duke81537792007-12-01 00:00:00 +0000552
553
554 if (JvmtiExport::can_pop_frame()) {
555#ifndef CC_INTERP
556 // Regardless of whether we entered this routine with the pending
557 // popframe condition bit set, we should always clear it now
558 thread->clear_popframe_condition();
559#else
Jesper Wilhelmsson81ba2e32014-01-23 14:47:23 +0100560 // C++ interpreter will clear has_pending_popframe when it enters
J. Duke81537792007-12-01 00:00:00 +0000561 // with method_resume. For deopt_resume2 we clear it now.
562 if (thread->popframe_forcing_deopt_reexecution())
563 thread->clear_popframe_condition();
564#endif /* CC_INTERP */
565 }
566
567 // unpack_frames() is called at the end of the deoptimization handler
568 // and (in C2) at the end of the uncommon trap handler. Note this fact
569 // so that an asynchronous stack walker can work again. This counter is
570 // incremented at the beginning of fetch_unroll_info() and (in C2) at
571 // the beginning of uncommon_trap().
572 thread->dec_in_deopt_handler();
573}
574
Coleen Phillimore5f07c2b2015-12-05 10:40:22 -0500575// Moved from cpu directories because none of the cpus has callee save values.
576// If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.
577void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {
578
579 // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in
580 // the days we had adapter frames. When we deoptimize a situation where a
581 // compiled caller calls a compiled caller will have registers it expects
582 // to survive the call to the callee. If we deoptimize the callee the only
583 // way we can restore these registers is to have the oldest interpreter
584 // frame that we create restore these values. That is what this routine
585 // will accomplish.
586
587 // At the moment we have modified c2 to not have any callee save registers
588 // so this problem does not exist and this routine is just a place holder.
589
590 assert(f->is_interpreted_frame(), "must be interpreted");
591}
J. Duke81537792007-12-01 00:00:00 +0000592
593// Return BasicType of value being returned
594JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
595
596 // We are already active int he special DeoptResourceMark any ResourceObj's we
597 // allocate will be freed at the end of the routine.
598
599 // It is actually ok to allocate handles in a leaf method. It causes no safepoints,
600 // but makes the entry a little slower. There is however a little dance we have to
601 // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro
602 ResetNoHandleMark rnhm; // No-op in release/product versions
603 HandleMark hm;
604
605 frame stub_frame = thread->last_frame();
606
607 // Since the frame to unpack is the top frame of this thread, the vframe_array_head
608 // must point to the vframeArray for the unpack frame.
609 vframeArray* array = thread->vframe_array_head();
610
611#ifndef PRODUCT
612 if (TraceDeoptimization) {
Vladimir Ivanov822deb62012-10-05 18:57:10 -0700613 ttyLocker ttyl;
David Lindholm5770f4e2015-10-09 09:42:33 +0200614 tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d",
615 p2i(thread), p2i(array), exec_mode);
J. Duke81537792007-12-01 00:00:00 +0000616 }
617#endif
Tom Rodriguez5a414272012-02-01 07:59:01 -0800618 Events::log(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",
David Lindholm5770f4e2015-10-09 09:42:33 +0200619 p2i(stub_frame.pc()), p2i(stub_frame.sp()), exec_mode);
J. Duke81537792007-12-01 00:00:00 +0000620
621 UnrollBlock* info = array->unroll_block();
622
623 // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
Tom Rodrigueze5357d42011-05-12 10:29:02 -0700624 array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
J. Duke81537792007-12-01 00:00:00 +0000625
626 BasicType bt = info->return_type();
627
628 // If we have an exception pending, claim that the return type is an oop
629 // so the deopt_blob does not overwrite the exception_oop.
630
631 if (exec_mode == Unpack_exception)
632 bt = T_OBJECT;
633
634 // Cleanup thread deopt data
635 cleanup_deopt_info(thread, array);
636
637#ifndef PRODUCT
638 if (VerifyStack) {
639 ResourceMark res_mark;
640
Tom Rodriguez33f0e502011-05-02 18:53:37 -0700641 thread->validate_frame_layout();
642
J. Duke81537792007-12-01 00:00:00 +0000643 // Verify that the just-unpacked frames match the interpreter's
644 // notions of expression stack and locals
645 vframeArray* cur_array = thread->vframe_array_last();
646 RegisterMap rm(thread, false);
647 rm.set_include_argument_oops(false);
648 bool is_top_frame = true;
649 int callee_size_of_parameters = 0;
650 int callee_max_locals = 0;
651 for (int i = 0; i < cur_array->frames(); i++) {
652 vframeArrayElement* el = cur_array->element(i);
653 frame* iframe = el->iframe();
654 guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
655
656 // Get the oop map for this bci
657 InterpreterOopMap mask;
658 int cur_invoke_parameter_size = 0;
659 bool try_next_mask = false;
660 int next_mask_expression_stack_size = -1;
661 int top_frame_expression_stack_adjustment = 0;
662 methodHandle mh(thread, iframe->interpreter_frame_method());
663 OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
664 BytecodeStream str(mh);
665 str.set_start(iframe->interpreter_frame_bci());
666 int max_bci = mh->code_size();
667 // Get to the next bytecode if possible
668 assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
669 // Check to see if we can grab the number of outgoing arguments
670 // at an uncommon trap for an invoke (where the compiler
671 // generates debug info before the invoke has executed)
672 Bytecodes::Code cur_code = str.next();
Roland Westrelin6a177462013-05-31 14:40:26 +0200673 if (cur_code == Bytecodes::_invokevirtual ||
674 cur_code == Bytecodes::_invokespecial ||
675 cur_code == Bytecodes::_invokestatic ||
676 cur_code == Bytecodes::_invokeinterface ||
677 cur_code == Bytecodes::_invokedynamic) {
Tom Rodriguez423f5872011-01-13 22:15:41 -0800678 Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
Coleen Phillimore7b4f8072011-01-27 16:11:27 -0800679 Symbol* signature = invoke.signature();
J. Duke81537792007-12-01 00:00:00 +0000680 ArgumentSizeComputer asc(signature);
681 cur_invoke_parameter_size = asc.size();
Roland Westrelin6a177462013-05-31 14:40:26 +0200682 if (invoke.has_receiver()) {
J. Duke81537792007-12-01 00:00:00 +0000683 // Add in receiver
684 ++cur_invoke_parameter_size;
685 }
Roland Westrelin6a177462013-05-31 14:40:26 +0200686 if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
687 callee_size_of_parameters++;
688 }
J. Duke81537792007-12-01 00:00:00 +0000689 }
690 if (str.bci() < max_bci) {
691 Bytecodes::Code bc = str.next();
692 if (bc >= 0) {
693 // The interpreter oop map generator reports results before
694 // the current bytecode has executed except in the case of
695 // calls. It seems to be hard to tell whether the compiler
696 // has emitted debug information matching the "state before"
697 // a given bytecode or the state after, so we try both
698 switch (cur_code) {
699 case Bytecodes::_invokevirtual:
700 case Bytecodes::_invokespecial:
701 case Bytecodes::_invokestatic:
702 case Bytecodes::_invokeinterface:
Roland Westrelin6a177462013-05-31 14:40:26 +0200703 case Bytecodes::_invokedynamic:
J. Duke81537792007-12-01 00:00:00 +0000704 case Bytecodes::_athrow:
705 break;
706 default: {
707 InterpreterOopMap next_mask;
708 OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
709 next_mask_expression_stack_size = next_mask.expression_stack_size();
710 // Need to subtract off the size of the result type of
711 // the bytecode because this is not described in the
712 // debug info but returned to the interpreter in the TOS
713 // caching register
714 BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
715 if (bytecode_result_type != T_ILLEGAL) {
716 top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
717 }
718 assert(top_frame_expression_stack_adjustment >= 0, "");
719 try_next_mask = true;
720 break;
721 }
722 }
723 }
724 }
725
726 // Verify stack depth and oops in frame
727 // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
728 if (!(
729 /* SPARC */
730 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
731 /* x86 */
732 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
733 (try_next_mask &&
734 (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
735 top_frame_expression_stack_adjustment))) ||
736 (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
Vladimir Kozlov4e83db42014-07-29 13:40:58 -0700737 (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&
J. Duke81537792007-12-01 00:00:00 +0000738 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
739 )) {
740 ttyLocker ttyl;
741
742 // Print out some information that will help us debug the problem
743 tty->print_cr("Wrong number of expression stack elements during deoptimization");
744 tty->print_cr(" Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
745 tty->print_cr(" Fabricated interpreter frame had %d expression stack elements",
746 iframe->interpreter_frame_expression_stack_size());
747 tty->print_cr(" Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
748 tty->print_cr(" try_next_mask = %d", try_next_mask);
749 tty->print_cr(" next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
750 tty->print_cr(" callee_size_of_parameters = %d", callee_size_of_parameters);
751 tty->print_cr(" callee_max_locals = %d", callee_max_locals);
752 tty->print_cr(" top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
753 tty->print_cr(" exec_mode = %d", exec_mode);
754 tty->print_cr(" cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
David Lindholm5770f4e2015-10-09 09:42:33 +0200755 tty->print_cr(" Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());
J. Duke81537792007-12-01 00:00:00 +0000756 tty->print_cr(" Interpreted frames:");
757 for (int k = 0; k < cur_array->frames(); k++) {
758 vframeArrayElement* el = cur_array->element(k);
759 tty->print_cr(" %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
760 }
761 cur_array->print_on_2(tty);
762 guarantee(false, "wrong number of expression stack elements during deopt");
763 }
764 VerifyOopClosure verify;
Stefan Karlsson3c2f3a32012-11-27 10:13:20 +0100765 iframe->oops_interpreted_do(&verify, NULL, &rm, false);
J. Duke81537792007-12-01 00:00:00 +0000766 callee_size_of_parameters = mh->size_of_parameters();
767 callee_max_locals = mh->max_locals();
768 is_top_frame = false;
769 }
770 }
771#endif /* !PRODUCT */
772
773
774 return bt;
775JRT_END
776
777
778int Deoptimization::deoptimize_dependents() {
779 Threads::deoptimized_wrt_marked_nmethods();
780 return 0;
781}
782
Igor Veresov54db2c22014-05-13 11:32:10 -0700783Deoptimization::DeoptAction Deoptimization::_unloaded_action
784 = Deoptimization::Action_reinterpret;
J. Duke81537792007-12-01 00:00:00 +0000785
Christian Thalinger16526e02015-10-08 12:49:30 -1000786#if defined(COMPILER2) || INCLUDE_JVMCI
J. Duke81537792007-12-01 00:00:00 +0000787bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, GrowableArray<ScopeValue*>* objects, TRAPS) {
788 Handle pending_exception(thread->pending_exception());
789 const char* exception_file = thread->exception_file();
790 int exception_line = thread->exception_line();
791 thread->clear_pending_exception();
792
Roland Westrelin15dcd412014-11-25 17:33:59 +0100793 bool failures = false;
794
J. Duke81537792007-12-01 00:00:00 +0000795 for (int i = 0; i < objects->length(); i++) {
796 assert(objects->at(i)->is_object(), "invalid debug information");
797 ObjectValue* sv = (ObjectValue*) objects->at(i);
798
Jon Masamitsu5c58d272012-09-01 13:25:18 -0400799 KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
J. Duke81537792007-12-01 00:00:00 +0000800 oop obj = NULL;
801
Coleen Phillimorefc037192015-10-28 09:47:23 -0400802 if (k->is_instance_klass()) {
Jon Masamitsu5c58d272012-09-01 13:25:18 -0400803 InstanceKlass* ik = InstanceKlass::cast(k());
Roland Westrelin15dcd412014-11-25 17:33:59 +0100804 obj = ik->allocate_instance(THREAD);
Coleen Phillimorefc037192015-10-28 09:47:23 -0400805 } else if (k->is_typeArray_klass()) {
Coleen Phillimore28047d62012-09-29 06:40:00 -0400806 TypeArrayKlass* ak = TypeArrayKlass::cast(k());
J. Duke81537792007-12-01 00:00:00 +0000807 assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
808 int len = sv->field_size() / type2size[ak->element_type()];
Roland Westrelin15dcd412014-11-25 17:33:59 +0100809 obj = ak->allocate(len, THREAD);
Coleen Phillimorefc037192015-10-28 09:47:23 -0400810 } else if (k->is_objArray_klass()) {
Coleen Phillimore28047d62012-09-29 06:40:00 -0400811 ObjArrayKlass* ak = ObjArrayKlass::cast(k());
Roland Westrelin15dcd412014-11-25 17:33:59 +0100812 obj = ak->allocate(sv->field_size(), THREAD);
J. Duke81537792007-12-01 00:00:00 +0000813 }
814
Roland Westrelin15dcd412014-11-25 17:33:59 +0100815 if (obj == NULL) {
816 failures = true;
817 }
818
J. Duke81537792007-12-01 00:00:00 +0000819 assert(sv->value().is_null(), "redundant reallocation");
Roland Westrelin15dcd412014-11-25 17:33:59 +0100820 assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");
821 CLEAR_PENDING_EXCEPTION;
J. Duke81537792007-12-01 00:00:00 +0000822 sv->set_value(obj);
823 }
824
Roland Westrelin15dcd412014-11-25 17:33:59 +0100825 if (failures) {
826 THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
827 } else if (pending_exception.not_null()) {
J. Duke81537792007-12-01 00:00:00 +0000828 thread->set_pending_exception(pending_exception(), exception_file, exception_line);
829 }
830
Roland Westrelin15dcd412014-11-25 17:33:59 +0100831 return failures;
J. Duke81537792007-12-01 00:00:00 +0000832}
833
J. Duke81537792007-12-01 00:00:00 +0000834// restore elements of an eliminated type array
835void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
J. Duke81537792007-12-01 00:00:00 +0000836 int index = 0;
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700837 intptr_t val;
J. Duke81537792007-12-01 00:00:00 +0000838
839 for (int i = 0; i < sv->field_size(); i++) {
840 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
841 switch(type) {
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700842 case T_LONG: case T_DOUBLE: {
843 assert(value->type() == T_INT, "Agreement.");
844 StackValue* low =
845 StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
846#ifdef _LP64
847 jlong res = (jlong)low->get_int();
848#else
849#ifdef SPARC
850 // For SPARC we have to swap high and low words.
851 jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
852#else
853 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
854#endif //SPARC
855#endif
856 obj->long_at_put(index, res);
857 break;
858 }
859
860 // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
Christian Thalinger16526e02015-10-08 12:49:30 -1000861 case T_INT: case T_FLOAT: { // 4 bytes.
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700862 assert(value->type() == T_INT, "Agreement.");
Christian Thalinger16526e02015-10-08 12:49:30 -1000863 bool big_value = false;
864 if (i + 1 < sv->field_size() && type == T_INT) {
865 if (sv->field_at(i)->is_location()) {
866 Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();
867 if (type == Location::dbl || type == Location::lng) {
868 big_value = true;
869 }
870 } else if (sv->field_at(i)->is_constant_int()) {
871 ScopeValue* next_scope_field = sv->field_at(i + 1);
872 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
873 big_value = true;
874 }
875 }
876 }
877
878 if (big_value) {
879 StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
880 #ifdef _LP64
881 jlong res = (jlong)low->get_int();
882 #else
883 #ifdef SPARC
884 // For SPARC we have to swap high and low words.
885 jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
886 #else
887 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
888 #endif //SPARC
889 #endif
890 obj->int_at_put(index, (jint)*((jint*)&res));
891 obj->int_at_put(++index, (jint)*(((jint*)&res) + 1));
892 } else {
893 val = value->get_int();
894 obj->int_at_put(index, (jint)*((jint*)&val));
895 }
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700896 break;
Christian Thalinger16526e02015-10-08 12:49:30 -1000897 }
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700898
Vladimir Kozlovf1b44952016-02-20 14:11:18 -0800899 case T_SHORT:
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700900 assert(value->type() == T_INT, "Agreement.");
901 val = value->get_int();
902 obj->short_at_put(index, (jshort)*((jint*)&val));
903 break;
904
Vladimir Kozlovf1b44952016-02-20 14:11:18 -0800905 case T_CHAR:
906 assert(value->type() == T_INT, "Agreement.");
907 val = value->get_int();
908 obj->char_at_put(index, (jchar)*((jint*)&val));
909 break;
910
911 case T_BYTE:
912 assert(value->type() == T_INT, "Agreement.");
913 val = value->get_int();
914 obj->byte_at_put(index, (jbyte)*((jint*)&val));
915 break;
916
917 case T_BOOLEAN:
Vladimir Kozlov96e8bcb2008-03-11 11:25:13 -0700918 assert(value->type() == T_INT, "Agreement.");
919 val = value->get_int();
920 obj->bool_at_put(index, (jboolean)*((jint*)&val));
921 break;
922
J. Duke81537792007-12-01 00:00:00 +0000923 default:
924 ShouldNotReachHere();
925 }
926 index++;
927 }
928}
929
930
931// restore fields of an eliminated object array
932void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
933 for (int i = 0; i < sv->field_size(); i++) {
934 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
935 assert(value->type() == T_OBJECT, "object element expected");
936 obj->obj_at_put(i, value->get_obj()());
937 }
938}
939
Christian Thalinger16526e02015-10-08 12:49:30 -1000940class ReassignedField {
941public:
942 int _offset;
943 BasicType _type;
944public:
945 ReassignedField() {
946 _offset = 0;
947 _type = T_ILLEGAL;
948 }
949};
950
951int compare(ReassignedField* left, ReassignedField* right) {
952 return left->_offset - right->_offset;
953}
954
955// Restore fields of an eliminated instance object using the same field order
956// returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true)
957static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) {
958 if (klass->superklass() != NULL) {
959 svIndex = reassign_fields_by_klass(klass->superklass(), fr, reg_map, sv, svIndex, obj, skip_internal);
960 }
961
962 GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>();
963 for (AllFieldStream fs(klass); !fs.done(); fs.next()) {
964 if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) {
965 ReassignedField field;
966 field._offset = fs.offset();
967 field._type = FieldType::basic_type(fs.signature());
968 fields->append(field);
969 }
970 }
971 fields->sort(compare);
972 for (int i = 0; i < fields->length(); i++) {
973 intptr_t val;
974 ScopeValue* scope_field = sv->field_at(svIndex);
975 StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
976 int offset = fields->at(i)._offset;
977 BasicType type = fields->at(i)._type;
978 switch (type) {
979 case T_OBJECT: case T_ARRAY:
980 assert(value->type() == T_OBJECT, "Agreement.");
981 obj->obj_field_put(offset, value->get_obj()());
982 break;
983
984 // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
985 case T_INT: case T_FLOAT: { // 4 bytes.
986 assert(value->type() == T_INT, "Agreement.");
987 bool big_value = false;
988 if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
989 if (scope_field->is_location()) {
990 Location::Type type = ((LocationValue*) scope_field)->location().type();
991 if (type == Location::dbl || type == Location::lng) {
992 big_value = true;
993 }
994 }
995 if (scope_field->is_constant_int()) {
996 ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
997 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
998 big_value = true;
999 }
1000 }
1001 }
1002
1003 if (big_value) {
1004 i++;
1005 assert(i < fields->length(), "second T_INT field needed");
1006 assert(fields->at(i)._type == T_INT, "T_INT field needed");
1007 } else {
1008 val = value->get_int();
1009 obj->int_field_put(offset, (jint)*((jint*)&val));
1010 break;
1011 }
1012 }
1013 /* no break */
1014
1015 case T_LONG: case T_DOUBLE: {
1016 assert(value->type() == T_INT, "Agreement.");
1017 StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));
1018#ifdef _LP64
1019 jlong res = (jlong)low->get_int();
1020#else
1021#ifdef SPARC
1022 // For SPARC we have to swap high and low words.
1023 jlong res = jlong_from((jint)low->get_int(), (jint)value->get_int());
1024#else
1025 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1026#endif //SPARC
1027#endif
1028 obj->long_field_put(offset, res);
1029 break;
1030 }
1031
Vladimir Kozlovf1b44952016-02-20 14:11:18 -08001032 case T_SHORT:
Christian Thalinger16526e02015-10-08 12:49:30 -10001033 assert(value->type() == T_INT, "Agreement.");
1034 val = value->get_int();
1035 obj->short_field_put(offset, (jshort)*((jint*)&val));
1036 break;
1037
Vladimir Kozlovf1b44952016-02-20 14:11:18 -08001038 case T_CHAR:
1039 assert(value->type() == T_INT, "Agreement.");
1040 val = value->get_int();
1041 obj->char_field_put(offset, (jchar)*((jint*)&val));
1042 break;
1043
1044 case T_BYTE:
1045 assert(value->type() == T_INT, "Agreement.");
1046 val = value->get_int();
1047 obj->byte_field_put(offset, (jbyte)*((jint*)&val));
1048 break;
1049
1050 case T_BOOLEAN:
Christian Thalinger16526e02015-10-08 12:49:30 -10001051 assert(value->type() == T_INT, "Agreement.");
1052 val = value->get_int();
1053 obj->bool_field_put(offset, (jboolean)*((jint*)&val));
1054 break;
1055
1056 default:
1057 ShouldNotReachHere();
1058 }
1059 svIndex++;
1060 }
1061 return svIndex;
1062}
J. Duke81537792007-12-01 00:00:00 +00001063
1064// restore fields of all eliminated objects and arrays
Christian Thalinger16526e02015-10-08 12:49:30 -10001065void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) {
J. Duke81537792007-12-01 00:00:00 +00001066 for (int i = 0; i < objects->length(); i++) {
1067 ObjectValue* sv = (ObjectValue*) objects->at(i);
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001068 KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
J. Duke81537792007-12-01 00:00:00 +00001069 Handle obj = sv->value();
Roland Westrelin15dcd412014-11-25 17:33:59 +01001070 assert(obj.not_null() || realloc_failures, "reallocation was missed");
Christian Thalinger16526e02015-10-08 12:49:30 -10001071 if (PrintDeoptimizationDetails) {
1072 tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1073 }
Roland Westrelin15dcd412014-11-25 17:33:59 +01001074 if (obj.is_null()) {
1075 continue;
1076 }
J. Duke81537792007-12-01 00:00:00 +00001077
Coleen Phillimorefc037192015-10-28 09:47:23 -04001078 if (k->is_instance_klass()) {
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001079 InstanceKlass* ik = InstanceKlass::cast(k());
Christian Thalinger16526e02015-10-08 12:49:30 -10001080 reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal);
Coleen Phillimorefc037192015-10-28 09:47:23 -04001081 } else if (k->is_typeArray_klass()) {
Coleen Phillimore28047d62012-09-29 06:40:00 -04001082 TypeArrayKlass* ak = TypeArrayKlass::cast(k());
J. Duke81537792007-12-01 00:00:00 +00001083 reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
Coleen Phillimorefc037192015-10-28 09:47:23 -04001084 } else if (k->is_objArray_klass()) {
J. Duke81537792007-12-01 00:00:00 +00001085 reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1086 }
1087 }
1088}
1089
1090
1091// relock objects for which synchronization was eliminated
Roland Westrelin15dcd412014-11-25 17:33:59 +01001092void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread, bool realloc_failures) {
J. Duke81537792007-12-01 00:00:00 +00001093 for (int i = 0; i < monitors->length(); i++) {
Vladimir Kozlov659a8dc2008-04-01 16:14:18 -07001094 MonitorInfo* mon_info = monitors->at(i);
1095 if (mon_info->eliminated()) {
Roland Westrelin15dcd412014-11-25 17:33:59 +01001096 assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1097 if (!mon_info->owner_is_scalar_replaced()) {
1098 Handle obj = Handle(mon_info->owner());
1099 markOop mark = obj->mark();
1100 if (UseBiasedLocking && mark->has_bias_pattern()) {
1101 // New allocated objects may have the mark set to anonymously biased.
1102 // Also the deoptimized method may called methods with synchronization
1103 // where the thread-local object is bias locked to the current thread.
1104 assert(mark->is_biased_anonymously() ||
1105 mark->biased_locker() == thread, "should be locked to current thread");
1106 // Reset mark word to unbiased prototype.
1107 markOop unbiased_prototype = markOopDesc::prototype()->set_age(mark->age());
1108 obj->set_mark(unbiased_prototype);
1109 }
1110 BasicLock* lock = mon_info->lock();
1111 ObjectSynchronizer::slow_enter(obj, lock, thread);
1112 assert(mon_info->owner()->is_locked(), "object must be locked now");
Vladimir Kozlov659a8dc2008-04-01 16:14:18 -07001113 }
J. Duke81537792007-12-01 00:00:00 +00001114 }
J. Duke81537792007-12-01 00:00:00 +00001115 }
1116}
1117
1118
1119#ifndef PRODUCT
1120// print information about reallocated objects
Roland Westrelin15dcd412014-11-25 17:33:59 +01001121void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
J. Duke81537792007-12-01 00:00:00 +00001122 fieldDescriptor fd;
1123
1124 for (int i = 0; i < objects->length(); i++) {
1125 ObjectValue* sv = (ObjectValue*) objects->at(i);
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001126 KlassHandle k(java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()));
J. Duke81537792007-12-01 00:00:00 +00001127 Handle obj = sv->value();
1128
David Lindholm5770f4e2015-10-09 09:42:33 +02001129 tty->print(" object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001130 k->print_value();
Roland Westrelin15dcd412014-11-25 17:33:59 +01001131 assert(obj.not_null() || realloc_failures, "reallocation was missed");
1132 if (obj.is_null()) {
1133 tty->print(" allocation failed");
1134 } else {
1135 tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);
1136 }
J. Duke81537792007-12-01 00:00:00 +00001137 tty->cr();
1138
Roland Westrelin15dcd412014-11-25 17:33:59 +01001139 if (Verbose && !obj.is_null()) {
J. Duke81537792007-12-01 00:00:00 +00001140 k->oop_print_on(obj(), tty);
1141 }
1142 }
1143}
1144#endif
Christian Thalinger16526e02015-10-08 12:49:30 -10001145#endif // COMPILER2 || INCLUDE_JVMCI
J. Duke81537792007-12-01 00:00:00 +00001146
Roland Westrelin15dcd412014-11-25 17:33:59 +01001147vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
David Lindholm5770f4e2015-10-09 09:42:33 +02001148 Events::log(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));
J. Duke81537792007-12-01 00:00:00 +00001149
1150#ifndef PRODUCT
Christian Thalinger16526e02015-10-08 12:49:30 -10001151 if (PrintDeoptimizationDetails) {
J. Duke81537792007-12-01 00:00:00 +00001152 ttyLocker ttyl;
David Lindholm5770f4e2015-10-09 09:42:33 +02001153 tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", p2i(thread));
J. Duke81537792007-12-01 00:00:00 +00001154 fr.print_on(tty);
1155 tty->print_cr(" Virtual frames (innermost first):");
1156 for (int index = 0; index < chunk->length(); index++) {
1157 compiledVFrame* vf = chunk->at(index);
1158 tty->print(" %2d - ", index);
1159 vf->print_value();
1160 int bci = chunk->at(index)->raw_bci();
1161 const char* code_name;
1162 if (bci == SynchronizationEntryBCI) {
1163 code_name = "sync entry";
1164 } else {
Tom Rodriguez423f5872011-01-13 22:15:41 -08001165 Bytecodes::Code code = vf->method()->code_at(bci);
J. Duke81537792007-12-01 00:00:00 +00001166 code_name = Bytecodes::name(code);
1167 }
1168 tty->print(" - %s", code_name);
1169 tty->print_cr(" @ bci %d ", bci);
1170 if (Verbose) {
1171 vf->print();
1172 tty->cr();
1173 }
1174 }
1175 }
1176#endif
1177
1178 // Register map for next frame (used for stack crawl). We capture
1179 // the state of the deopt'ing frame's caller. Thus if we need to
1180 // stuff a C2I adapter we can properly fill in the callee-save
1181 // register locations.
1182 frame caller = fr.sender(reg_map);
1183 int frame_size = caller.sp() - fr.sp();
1184
1185 frame sender = caller;
1186
1187 // Since the Java thread being deoptimized will eventually adjust it's own stack,
1188 // the vframeArray containing the unpacking information is allocated in the C heap.
1189 // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
Roland Westrelin15dcd412014-11-25 17:33:59 +01001190 vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
J. Duke81537792007-12-01 00:00:00 +00001191
1192 // Compare the vframeArray to the collected vframes
1193 assert(array->structural_compare(thread, chunk), "just checking");
J. Duke81537792007-12-01 00:00:00 +00001194
1195#ifndef PRODUCT
Christian Thalinger16526e02015-10-08 12:49:30 -10001196 if (PrintDeoptimizationDetails) {
J. Duke81537792007-12-01 00:00:00 +00001197 ttyLocker ttyl;
David Lindholm5770f4e2015-10-09 09:42:33 +02001198 tty->print_cr(" Created vframeArray " INTPTR_FORMAT, p2i(array));
J. Duke81537792007-12-01 00:00:00 +00001199 }
1200#endif // PRODUCT
1201
1202 return array;
1203}
1204
Christian Thalinger16526e02015-10-08 12:49:30 -10001205#if defined(COMPILER2) || INCLUDE_JVMCI
Roland Westrelin15dcd412014-11-25 17:33:59 +01001206void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
1207 // Reallocation of some scalar replaced objects failed. Record
1208 // that we need to pop all the interpreter frames for the
1209 // deoptimized compiled frame.
1210 assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
1211 thread->set_frames_to_pop_failed_realloc(array->frames());
1212 // Unlock all monitors here otherwise the interpreter will see a
1213 // mix of locked and unlocked monitors (because of failed
1214 // reallocations of synchronized objects) and be confused.
1215 for (int i = 0; i < array->frames(); i++) {
1216 MonitorChunk* monitors = array->element(i)->monitors();
1217 if (monitors != NULL) {
1218 for (int j = 0; j < monitors->number_of_monitors(); j++) {
1219 BasicObjectLock* src = monitors->at(j);
1220 if (src->obj() != NULL) {
1221 ObjectSynchronizer::fast_exit(src->obj(), src->lock(), thread);
1222 }
1223 }
1224 array->element(i)->free_monitors(thread);
1225#ifdef ASSERT
1226 array->element(i)->set_removed_monitors();
1227#endif
1228 }
1229 }
1230}
1231#endif
J. Duke81537792007-12-01 00:00:00 +00001232
1233static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke) {
1234 GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
1235 for (int i = 0; i < monitors->length(); i++) {
1236 MonitorInfo* mon_info = monitors->at(i);
Vladimir Kozlov7b9d6a72009-06-09 16:19:10 -07001237 if (!mon_info->eliminated() && mon_info->owner() != NULL) {
J. Duke81537792007-12-01 00:00:00 +00001238 objects_to_revoke->append(Handle(mon_info->owner()));
1239 }
1240 }
1241}
1242
1243
1244void Deoptimization::revoke_biases_of_monitors(JavaThread* thread, frame fr, RegisterMap* map) {
1245 if (!UseBiasedLocking) {
1246 return;
1247 }
1248
1249 GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1250
1251 // Unfortunately we don't have a RegisterMap available in most of
1252 // the places we want to call this routine so we need to walk the
1253 // stack again to update the register map.
1254 if (map == NULL || !map->update_map()) {
1255 StackFrameStream sfs(thread, true);
1256 bool found = false;
1257 while (!found && !sfs.is_done()) {
1258 frame* cur = sfs.current();
1259 sfs.next();
1260 found = cur->id() == fr.id();
1261 }
1262 assert(found, "frame to be deoptimized not found on target thread's stack");
1263 map = sfs.register_map();
1264 }
1265
1266 vframe* vf = vframe::new_vframe(&fr, map, thread);
1267 compiledVFrame* cvf = compiledVFrame::cast(vf);
1268 // Revoke monitors' biases in all scopes
1269 while (!cvf->is_top()) {
1270 collect_monitors(cvf, objects_to_revoke);
1271 cvf = compiledVFrame::cast(cvf->sender());
1272 }
1273 collect_monitors(cvf, objects_to_revoke);
1274
1275 if (SafepointSynchronize::is_at_safepoint()) {
1276 BiasedLocking::revoke_at_safepoint(objects_to_revoke);
1277 } else {
1278 BiasedLocking::revoke(objects_to_revoke);
1279 }
1280}
1281
1282
1283void Deoptimization::revoke_biases_of_monitors(CodeBlob* cb) {
1284 if (!UseBiasedLocking) {
1285 return;
1286 }
1287
1288 assert(SafepointSynchronize::is_at_safepoint(), "must only be called from safepoint");
1289 GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
1290 for (JavaThread* jt = Threads::first(); jt != NULL ; jt = jt->next()) {
1291 if (jt->has_last_Java_frame()) {
1292 StackFrameStream sfs(jt, true);
1293 while (!sfs.is_done()) {
1294 frame* cur = sfs.current();
1295 if (cb->contains(cur->pc())) {
1296 vframe* vf = vframe::new_vframe(cur, sfs.register_map(), jt);
1297 compiledVFrame* cvf = compiledVFrame::cast(vf);
1298 // Revoke monitors' biases in all scopes
1299 while (!cvf->is_top()) {
1300 collect_monitors(cvf, objects_to_revoke);
1301 cvf = compiledVFrame::cast(cvf->sender());
1302 }
1303 collect_monitors(cvf, objects_to_revoke);
1304 }
1305 sfs.next();
1306 }
1307 }
1308 }
1309 BiasedLocking::revoke_at_safepoint(objects_to_revoke);
1310}
1311
1312
Christian Thalinger16526e02015-10-08 12:49:30 -10001313void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
J. Duke81537792007-12-01 00:00:00 +00001314 assert(fr.can_be_deoptimized(), "checking frame type");
1315
Christian Thalinger16526e02015-10-08 12:49:30 -10001316 gather_statistics(reason, Action_none, Bytecodes::_illegal);
J. Duke81537792007-12-01 00:00:00 +00001317
Christian Thalinger16526e02015-10-08 12:49:30 -10001318 if (LogCompilation && xtty != NULL) {
1319 nmethod* nm = fr.cb()->as_nmethod_or_null();
1320 assert(nm != NULL, "only compiled methods can deopt");
1321
1322 ttyLocker ttyl;
Dean Long344a9be2015-10-17 19:40:30 -04001323 xtty->begin_head("deoptimized thread='" UINTX_FORMAT "'", (uintx)thread->osthread()->thread_id());
Christian Thalinger16526e02015-10-08 12:49:30 -10001324 nm->log_identity(xtty);
1325 xtty->end_head();
1326 for (ScopeDesc* sd = nm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1327 xtty->begin_elem("jvms bci='%d'", sd->bci());
1328 xtty->method(sd->method());
1329 xtty->end_elem();
1330 if (sd->is_top()) break;
1331 }
1332 xtty->tail("deoptimized");
1333 }
1334
1335 // Patch the compiled method so that when execution returns to it we will
J. Duke81537792007-12-01 00:00:00 +00001336 // deopt the execution state and return to the interpreter.
1337 fr.deoptimize(thread);
1338}
1339
1340void Deoptimization::deoptimize(JavaThread* thread, frame fr, RegisterMap *map) {
Christian Thalinger16526e02015-10-08 12:49:30 -10001341 deoptimize(thread, fr, map, Reason_constraint);
1342}
1343
1344void Deoptimization::deoptimize(JavaThread* thread, frame fr, RegisterMap *map, DeoptReason reason) {
J. Duke81537792007-12-01 00:00:00 +00001345 // Deoptimize only if the frame comes from compile code.
1346 // Do not deoptimize the frame which is already patched
1347 // during the execution of the loops below.
1348 if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1349 return;
1350 }
1351 ResourceMark rm;
1352 DeoptimizationMarker dm;
1353 if (UseBiasedLocking) {
1354 revoke_biases_of_monitors(thread, fr, map);
1355 }
Christian Thalinger16526e02015-10-08 12:49:30 -10001356 deoptimize_single_frame(thread, fr, reason);
J. Duke81537792007-12-01 00:00:00 +00001357
1358}
1359
1360
Christian Thalinger16526e02015-10-08 12:49:30 -10001361void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {
Tom Rodriguez1d8c6772010-10-19 16:14:34 -07001362 assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(),
1363 "can only deoptimize other thread at a safepoint");
J. Duke81537792007-12-01 00:00:00 +00001364 // Compute frame and register map based on thread and sp.
1365 RegisterMap reg_map(thread, UseBiasedLocking);
1366 frame fr = thread->last_frame();
1367 while (fr.id() != id) {
1368 fr = fr.sender(&reg_map);
1369 }
Christian Thalinger16526e02015-10-08 12:49:30 -10001370 deoptimize(thread, fr, &reg_map, reason);
J. Duke81537792007-12-01 00:00:00 +00001371}
1372
1373
Christian Thalinger16526e02015-10-08 12:49:30 -10001374void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {
Tom Rodriguez1d8c6772010-10-19 16:14:34 -07001375 if (thread == Thread::current()) {
Christian Thalinger16526e02015-10-08 12:49:30 -10001376 Deoptimization::deoptimize_frame_internal(thread, id, reason);
Tom Rodriguez1d8c6772010-10-19 16:14:34 -07001377 } else {
Christian Thalinger16526e02015-10-08 12:49:30 -10001378 VM_DeoptimizeFrame deopt(thread, id, reason);
Tom Rodriguez1d8c6772010-10-19 16:14:34 -07001379 VMThread::execute(&deopt);
1380 }
1381}
1382
Christian Thalinger16526e02015-10-08 12:49:30 -10001383void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
1384 deoptimize_frame(thread, id, Reason_constraint);
1385}
Tom Rodriguez1d8c6772010-10-19 16:14:34 -07001386
J. Duke81537792007-12-01 00:00:00 +00001387// JVMTI PopFrame support
1388JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
1389{
1390 thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
1391}
1392JRT_END
1393
Igor Veresov54db2c22014-05-13 11:32:10 -07001394MethodData*
1395Deoptimization::get_method_data(JavaThread* thread, methodHandle m,
1396 bool create_if_missing) {
1397 Thread* THREAD = thread;
1398 MethodData* mdo = m()->method_data();
1399 if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {
1400 // Build an MDO. Ignore errors like OutOfMemory;
1401 // that simply means we won't have an MDO to update.
1402 Method::build_interpreter_method_data(m, THREAD);
1403 if (HAS_PENDING_EXCEPTION) {
1404 assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
1405 CLEAR_PENDING_EXCEPTION;
1406 }
1407 mdo = m()->method_data();
1408 }
1409 return mdo;
1410}
J. Duke81537792007-12-01 00:00:00 +00001411
Christian Thalinger16526e02015-10-08 12:49:30 -10001412#if defined(COMPILER2) || defined(SHARK) || INCLUDE_JVMCI
Coleen Phillimoref1e89ea2015-10-23 16:48:38 -04001413void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {
J. Duke81537792007-12-01 00:00:00 +00001414 // in case of an unresolved klass entry, load the class.
1415 if (constant_pool->tag_at(index).is_unresolved_klass()) {
Coleen Phillimore63080522014-10-28 17:02:08 -04001416 Klass* tk = constant_pool->klass_at_ignore_error(index, CHECK);
J. Duke81537792007-12-01 00:00:00 +00001417 return;
1418 }
1419
1420 if (!constant_pool->tag_at(index).is_symbol()) return;
1421
Harold Seigel7fee66f2012-11-06 15:09:37 -05001422 Handle class_loader (THREAD, constant_pool->pool_holder()->class_loader());
Coleen Phillimore7b4f8072011-01-27 16:11:27 -08001423 Symbol* symbol = constant_pool->symbol_at(index);
J. Duke81537792007-12-01 00:00:00 +00001424
1425 // class name?
1426 if (symbol->byte_at(0) != '(') {
Harold Seigel7fee66f2012-11-06 15:09:37 -05001427 Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());
J. Duke81537792007-12-01 00:00:00 +00001428 SystemDictionary::resolve_or_null(symbol, class_loader, protection_domain, CHECK);
1429 return;
1430 }
1431
1432 // then it must be a signature!
Coleen Phillimore7b4f8072011-01-27 16:11:27 -08001433 ResourceMark rm(THREAD);
J. Duke81537792007-12-01 00:00:00 +00001434 for (SignatureStream ss(symbol); !ss.is_done(); ss.next()) {
1435 if (ss.is_object()) {
Coleen Phillimore7b4f8072011-01-27 16:11:27 -08001436 Symbol* class_name = ss.as_symbol(CHECK);
Harold Seigel7fee66f2012-11-06 15:09:37 -05001437 Handle protection_domain (THREAD, constant_pool->pool_holder()->protection_domain());
J. Duke81537792007-12-01 00:00:00 +00001438 SystemDictionary::resolve_or_null(class_name, class_loader, protection_domain, CHECK);
1439 }
1440 }
1441}
1442
1443
Coleen Phillimoref1e89ea2015-10-23 16:48:38 -04001444void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index) {
J. Duke81537792007-12-01 00:00:00 +00001445 EXCEPTION_MARK;
1446 load_class_by_index(constant_pool, index, THREAD);
1447 if (HAS_PENDING_EXCEPTION) {
1448 // Exception happened during classloading. We ignore the exception here, since it
Roland Westrelincb781492014-01-08 09:49:31 +01001449 // is going to be rethrown since the current activation is going to be deoptimized and
J. Duke81537792007-12-01 00:00:00 +00001450 // the interpreter will re-execute the bytecode.
1451 CLEAR_PENDING_EXCEPTION;
Roland Westrelincb781492014-01-08 09:49:31 +01001452 // Class loading called java code which may have caused a stack
1453 // overflow. If the exception was thrown right before the return
1454 // to the runtime the stack is no longer guarded. Reguard the
1455 // stack otherwise if we return to the uncommon trap blob and the
1456 // stack bang causes a stack overflow we crash.
1457 assert(THREAD->is_Java_thread(), "only a java thread can be here");
1458 JavaThread* thread = (JavaThread*)THREAD;
Frederic Parainef800bd2015-12-11 09:07:07 -08001459 bool guard_pages_enabled = thread->stack_guards_enabled();
Roland Westrelincb781492014-01-08 09:49:31 +01001460 if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
1461 assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
J. Duke81537792007-12-01 00:00:00 +00001462 }
1463}
1464
1465JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) {
1466 HandleMark hm;
1467
1468 // uncommon_trap() is called at the beginning of the uncommon trap
1469 // handler. Note this fact before we start generating temporary frames
1470 // that can confuse an asynchronous stack walker. This counter is
1471 // decremented at the end of unpack_frames().
1472 thread->inc_in_deopt_handler();
1473
1474 // We need to update the map if we have biased locking.
Christian Thalinger16526e02015-10-08 12:49:30 -10001475#if INCLUDE_JVMCI
1476 // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid
1477 RegisterMap reg_map(thread, true);
1478#else
J. Duke81537792007-12-01 00:00:00 +00001479 RegisterMap reg_map(thread, UseBiasedLocking);
Christian Thalinger16526e02015-10-08 12:49:30 -10001480#endif
J. Duke81537792007-12-01 00:00:00 +00001481 frame stub_frame = thread->last_frame();
1482 frame fr = stub_frame.sender(&reg_map);
1483 // Make sure the calling nmethod is not getting deoptimized and removed
1484 // before we are done with it.
1485 nmethodLocker nl(fr.pc());
1486
Tom Rodriguez5a414272012-02-01 07:59:01 -08001487 // Log a message
Christian Thalinger16526e02015-10-08 12:49:30 -10001488 Events::log(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,
Dean Long344a9be2015-10-17 19:40:30 -04001489 trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());
Tom Rodriguez5a414272012-02-01 07:59:01 -08001490
J. Duke81537792007-12-01 00:00:00 +00001491 {
1492 ResourceMark rm;
1493
1494 // Revoke biases of any monitors in the frame to ensure we can migrate them
1495 revoke_biases_of_monitors(thread, fr, &reg_map);
1496
1497 DeoptReason reason = trap_request_reason(trap_request);
1498 DeoptAction action = trap_request_action(trap_request);
Christian Thalinger16526e02015-10-08 12:49:30 -10001499#if INCLUDE_JVMCI
1500 int debug_id = trap_request_debug_id(trap_request);
1501#endif
J. Duke81537792007-12-01 00:00:00 +00001502 jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
1503
J. Duke81537792007-12-01 00:00:00 +00001504 vframe* vf = vframe::new_vframe(&fr, &reg_map, thread);
1505 compiledVFrame* cvf = compiledVFrame::cast(vf);
1506
1507 nmethod* nm = cvf->code();
1508
1509 ScopeDesc* trap_scope = cvf->scope();
Christian Thalinger16526e02015-10-08 12:49:30 -10001510
1511 if (TraceDeoptimization) {
1512 ttyLocker ttyl;
Dean Long344a9be2015-10-17 19:40:30 -04001513 tty->print_cr(" bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT ", method=%s" JVMCI_ONLY(", debug_id=%d"), trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin(), trap_scope->method()->name_and_sig_as_C_string()
Christian Thalinger16526e02015-10-08 12:49:30 -10001514#if INCLUDE_JVMCI
1515 , debug_id
1516#endif
1517 );
1518 }
1519
J. Duke81537792007-12-01 00:00:00 +00001520 methodHandle trap_method = trap_scope->method();
1521 int trap_bci = trap_scope->bci();
Christian Thalinger16526e02015-10-08 12:49:30 -10001522#if INCLUDE_JVMCI
1523 oop speculation = thread->pending_failed_speculation();
1524 if (nm->is_compiled_by_jvmci()) {
1525 if (speculation != NULL) {
1526 oop speculation_log = nm->speculation_log();
1527 if (speculation_log != NULL) {
1528 if (TraceDeoptimization || TraceUncollectedSpeculations) {
Christian Thalingera38ea492015-11-04 07:23:23 -10001529 if (HotSpotSpeculationLog::lastFailed(speculation_log) != NULL) {
Christian Thalinger16526e02015-10-08 12:49:30 -10001530 tty->print_cr("A speculation that was not collected by the compiler is being overwritten");
1531 }
1532 }
1533 if (TraceDeoptimization) {
1534 tty->print_cr("Saving speculation to speculation log");
1535 }
Christian Thalingera38ea492015-11-04 07:23:23 -10001536 HotSpotSpeculationLog::set_lastFailed(speculation_log, speculation);
Christian Thalinger16526e02015-10-08 12:49:30 -10001537 } else {
1538 if (TraceDeoptimization) {
1539 tty->print_cr("Speculation present but no speculation log");
1540 }
1541 }
1542 thread->set_pending_failed_speculation(NULL);
1543 } else {
1544 if (TraceDeoptimization) {
1545 tty->print_cr("No speculation");
1546 }
1547 }
1548 } else {
1549 assert(speculation == NULL, "There should not be a speculation for method compiled by non-JVMCI compilers");
1550 }
1551
1552 if (trap_bci == SynchronizationEntryBCI) {
1553 trap_bci = 0;
1554 thread->set_pending_monitorenter(true);
1555 }
1556
1557 if (reason == Deoptimization::Reason_transfer_to_interpreter) {
1558 thread->set_pending_transfer_to_interpreter(true);
1559 }
1560#endif
1561
Tom Rodriguez423f5872011-01-13 22:15:41 -08001562 Bytecodes::Code trap_bc = trap_method->java_code_at(trap_bci);
J. Duke81537792007-12-01 00:00:00 +00001563 // Record this event in the histogram.
1564 gather_statistics(reason, action, trap_bc);
1565
1566 // Ensure that we can record deopt. history:
Vladimir Kozlov97a51c52014-03-20 17:49:27 -07001567 // Need MDO to record RTM code generation state.
Igor Veresov54db2c22014-05-13 11:32:10 -07001568 bool create_if_missing = ProfileTraps || UseCodeAging RTM_OPT_ONLY( || UseRTMLocking );
J. Duke81537792007-12-01 00:00:00 +00001569
Christian Thalinger16526e02015-10-08 12:49:30 -10001570 methodHandle profiled_method;
1571#if INCLUDE_JVMCI
1572 if (nm->is_compiled_by_jvmci()) {
1573 profiled_method = nm->method();
1574 } else {
1575 profiled_method = trap_method;
1576 }
1577#else
1578 profiled_method = trap_method;
1579#endif
1580
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001581 MethodData* trap_mdo =
Christian Thalinger16526e02015-10-08 12:49:30 -10001582 get_method_data(thread, profiled_method, create_if_missing);
J. Duke81537792007-12-01 00:00:00 +00001583
Vladimir Ivanov7f0d3fe2012-11-21 05:57:12 -08001584 // Log a message
1585 Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d",
David Lindholm5770f4e2015-10-09 09:42:33 +02001586 trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()),
Vladimir Ivanov7f0d3fe2012-11-21 05:57:12 -08001587 trap_method->name_and_sig_as_C_string(), trap_bci);
1588
J. Duke81537792007-12-01 00:00:00 +00001589 // Print a bunch of diagnostics, if requested.
1590 if (TraceDeoptimization || LogCompilation) {
1591 ResourceMark rm;
1592 ttyLocker ttyl;
1593 char buf[100];
1594 if (xtty != NULL) {
Bill Pittore304b59b2015-06-24 12:12:25 -04001595 xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",
J. Duke81537792007-12-01 00:00:00 +00001596 os::current_thread_id(),
1597 format_trap_request(buf, sizeof(buf), trap_request));
1598 nm->log_identity(xtty);
1599 }
Coleen Phillimore7b4f8072011-01-27 16:11:27 -08001600 Symbol* class_name = NULL;
J. Duke81537792007-12-01 00:00:00 +00001601 bool unresolved = false;
1602 if (unloaded_class_index >= 0) {
1603 constantPoolHandle constants (THREAD, trap_method->constants());
1604 if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
Coleen Phillimore7b4f8072011-01-27 16:11:27 -08001605 class_name = constants->klass_name_at(unloaded_class_index);
J. Duke81537792007-12-01 00:00:00 +00001606 unresolved = true;
1607 if (xtty != NULL)
1608 xtty->print(" unresolved='1'");
1609 } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
Coleen Phillimore7b4f8072011-01-27 16:11:27 -08001610 class_name = constants->symbol_at(unloaded_class_index);
J. Duke81537792007-12-01 00:00:00 +00001611 }
1612 if (xtty != NULL)
1613 xtty->name(class_name);
1614 }
Igor Veresova2eea472014-05-15 10:37:52 -07001615 if (xtty != NULL && trap_mdo != NULL && (int)reason < (int)MethodData::_trap_hist_limit) {
J. Duke81537792007-12-01 00:00:00 +00001616 // Dump the relevant MDO state.
1617 // This is the deopt count for the current reason, any previous
1618 // reasons or recompiles seen at this point.
1619 int dcnt = trap_mdo->trap_count(reason);
1620 if (dcnt != 0)
1621 xtty->print(" count='%d'", dcnt);
1622 ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
1623 int dos = (pdata == NULL)? 0: pdata->trap_state();
1624 if (dos != 0) {
1625 xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
1626 if (trap_state_is_recompiled(dos)) {
1627 int recnt2 = trap_mdo->overflow_recompile_count();
1628 if (recnt2 != 0)
1629 xtty->print(" recompiles2='%d'", recnt2);
1630 }
1631 }
1632 }
1633 if (xtty != NULL) {
1634 xtty->stamp();
1635 xtty->end_head();
1636 }
1637 if (TraceDeoptimization) { // make noise on the tty
1638 tty->print("Uncommon trap occurred in");
1639 nm->method()->print_short_name(tty);
Christian Thalinger16526e02015-10-08 12:49:30 -10001640 tty->print(" compiler=%s compile_id=%d", nm->compiler() == NULL ? "" : nm->compiler()->name(), nm->compile_id());
1641#if INCLUDE_JVMCI
1642 oop installedCode = nm->jvmci_installed_code();
1643 if (installedCode != NULL) {
1644 oop installedCodeName = NULL;
1645 if (installedCode->is_a(InstalledCode::klass())) {
1646 installedCodeName = InstalledCode::name(installedCode);
1647 }
1648 if (installedCodeName != NULL) {
1649 tty->print(" (JVMCI: installedCodeName=%s) ", java_lang_String::as_utf8_string(installedCodeName));
1650 } else {
1651 tty->print(" (JVMCI: installed code has no name) ");
1652 }
1653 } else if (nm->is_compiled_by_jvmci()) {
1654 tty->print(" (JVMCI: no installed code) ");
1655 }
1656#endif
1657 tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"),
David Lindholm5770f4e2015-10-09 09:42:33 +02001658 p2i(fr.pc()),
Vladimir Ivanov822deb62012-10-05 18:57:10 -07001659 os::current_thread_id(),
J. Duke81537792007-12-01 00:00:00 +00001660 trap_reason_name(reason),
1661 trap_action_name(action),
Christian Thalinger16526e02015-10-08 12:49:30 -10001662 unloaded_class_index
1663#if INCLUDE_JVMCI
1664 , debug_id
1665#endif
1666 );
Coleen Phillimore7b4f8072011-01-27 16:11:27 -08001667 if (class_name != NULL) {
J. Duke81537792007-12-01 00:00:00 +00001668 tty->print(unresolved ? " unresolved class: " : " symbol: ");
1669 class_name->print_symbol_on(tty);
1670 }
1671 tty->cr();
1672 }
1673 if (xtty != NULL) {
1674 // Log the precise location of the trap.
1675 for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
1676 xtty->begin_elem("jvms bci='%d'", sd->bci());
1677 xtty->method(sd->method());
1678 xtty->end_elem();
1679 if (sd->is_top()) break;
1680 }
1681 xtty->tail("uncommon_trap");
1682 }
1683 }
1684 // (End diagnostic printout.)
1685
1686 // Load class if necessary
1687 if (unloaded_class_index >= 0) {
1688 constantPoolHandle constants(THREAD, trap_method->constants());
1689 load_class_by_index(constants, unloaded_class_index);
1690 }
1691
1692 // Flush the nmethod if necessary and desirable.
1693 //
1694 // We need to avoid situations where we are re-flushing the nmethod
1695 // because of a hot deoptimization site. Repeated flushes at the same
1696 // point need to be detected by the compiler and avoided. If the compiler
1697 // cannot avoid them (or has a bug and "refuses" to avoid them), this
1698 // module must take measures to avoid an infinite cycle of recompilation
1699 // and deoptimization. There are several such measures:
1700 //
1701 // 1. If a recompilation is ordered a second time at some site X
1702 // and for the same reason R, the action is adjusted to 'reinterpret',
1703 // to give the interpreter time to exercise the method more thoroughly.
1704 // If this happens, the method's overflow_recompile_count is incremented.
1705 //
1706 // 2. If the compiler fails to reduce the deoptimization rate, then
1707 // the method's overflow_recompile_count will begin to exceed the set
1708 // limit PerBytecodeRecompilationCutoff. If this happens, the action
1709 // is adjusted to 'make_not_compilable', and the method is abandoned
1710 // to the interpreter. This is a performance hit for hot methods,
1711 // but is better than a disastrous infinite cycle of recompilations.
1712 // (Actually, only the method containing the site X is abandoned.)
1713 //
1714 // 3. In parallel with the previous measures, if the total number of
1715 // recompilations of a method exceeds the much larger set limit
1716 // PerMethodRecompilationCutoff, the method is abandoned.
1717 // This should only happen if the method is very large and has
1718 // many "lukewarm" deoptimizations. The code which enforces this
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001719 // limit is elsewhere (class nmethod, class Method).
J. Duke81537792007-12-01 00:00:00 +00001720 //
1721 // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
1722 // to recompile at each bytecode independently of the per-BCI cutoff.
1723 //
1724 // The decision to update code is up to the compiler, and is encoded
1725 // in the Action_xxx code. If the compiler requests Action_none
1726 // no trap state is changed, no compiled code is changed, and the
1727 // computation suffers along in the interpreter.
1728 //
1729 // The other action codes specify various tactics for decompilation
1730 // and recompilation. Action_maybe_recompile is the loosest, and
1731 // allows the compiled code to stay around until enough traps are seen,
1732 // and until the compiler gets around to recompiling the trapping method.
1733 //
1734 // The other actions cause immediate removal of the present code.
1735
Vladimir Ivanov90a42c22015-06-11 14:19:40 +03001736 // Traps caused by injected profile shouldn't pollute trap counts.
1737 bool injected_profile_trap = trap_method->has_injected_profile() &&
1738 (reason == Reason_intrinsic || reason == Reason_unreached);
1739
1740 bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;
J. Duke81537792007-12-01 00:00:00 +00001741 bool make_not_entrant = false;
1742 bool make_not_compilable = false;
Igor Veresov2c66a6c2010-09-03 17:51:07 -07001743 bool reprofile = false;
J. Duke81537792007-12-01 00:00:00 +00001744 switch (action) {
1745 case Action_none:
1746 // Keep the old code.
1747 update_trap_state = false;
1748 break;
1749 case Action_maybe_recompile:
1750 // Do not need to invalidate the present code, but we can
1751 // initiate another
1752 // Start compiler without (necessarily) invalidating the nmethod.
1753 // The system will tolerate the old code, but new code should be
1754 // generated when possible.
1755 break;
1756 case Action_reinterpret:
1757 // Go back into the interpreter for a while, and then consider
1758 // recompiling form scratch.
1759 make_not_entrant = true;
1760 // Reset invocation counter for outer most method.
1761 // This will allow the interpreter to exercise the bytecodes
1762 // for a while before recompiling.
1763 // By contrast, Action_make_not_entrant is immediate.
1764 //
1765 // Note that the compiler will track null_check, null_assert,
1766 // range_check, and class_check events and log them as if they
1767 // had been traps taken from compiled code. This will update
1768 // the MDO trap history so that the next compilation will
1769 // properly detect hot trap sites.
Igor Veresov2c66a6c2010-09-03 17:51:07 -07001770 reprofile = true;
J. Duke81537792007-12-01 00:00:00 +00001771 break;
1772 case Action_make_not_entrant:
1773 // Request immediate recompilation, and get rid of the old code.
1774 // Make them not entrant, so next time they are called they get
1775 // recompiled. Unloaded classes are loaded now so recompile before next
1776 // time they are called. Same for uninitialized. The interpreter will
1777 // link the missing class, if any.
1778 make_not_entrant = true;
1779 break;
1780 case Action_make_not_compilable:
1781 // Give up on compiling this method at all.
1782 make_not_entrant = true;
1783 make_not_compilable = true;
1784 break;
1785 default:
1786 ShouldNotReachHere();
1787 }
1788
1789 // Setting +ProfileTraps fixes the following, on all platforms:
1790 // 4852688: ProfileInterpreter is off by default for ia64. The result is
1791 // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001792 // recompile relies on a MethodData* to record heroic opt failures.
J. Duke81537792007-12-01 00:00:00 +00001793
1794 // Whether the interpreter is producing MDO data or not, we also need
1795 // to use the MDO to detect hot deoptimization points and control
1796 // aggressive optimization.
Vladimir Kozlov0c27c552010-02-01 16:49:49 -08001797 bool inc_recompile_count = false;
1798 ProfileData* pdata = NULL;
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001799 if (ProfileTraps && update_trap_state && trap_mdo != NULL) {
Christian Thalinger16526e02015-10-08 12:49:30 -10001800 assert(trap_mdo == get_method_data(thread, profiled_method, false), "sanity");
J. Duke81537792007-12-01 00:00:00 +00001801 uint this_trap_count = 0;
1802 bool maybe_prior_trap = false;
1803 bool maybe_prior_recompile = false;
Christian Thalinger16526e02015-10-08 12:49:30 -10001804 pdata = query_update_method_data(trap_mdo, trap_bci, reason, true,
1805#if INCLUDE_JVMCI
1806 nm->is_compiled_by_jvmci() && nm->is_osr_method(),
1807#endif
Roland Westrelin493557f2014-02-25 18:16:24 +01001808 nm->method(),
J. Duke81537792007-12-01 00:00:00 +00001809 //outputs:
1810 this_trap_count,
1811 maybe_prior_trap,
1812 maybe_prior_recompile);
1813 // Because the interpreter also counts null, div0, range, and class
1814 // checks, these traps from compiled code are double-counted.
1815 // This is harmless; it just means that the PerXTrapLimit values
1816 // are in effect a little smaller than they look.
1817
1818 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
1819 if (per_bc_reason != Reason_none) {
1820 // Now take action based on the partially known per-BCI history.
1821 if (maybe_prior_trap
1822 && this_trap_count >= (uint)PerBytecodeTrapLimit) {
1823 // If there are too many traps at this BCI, force a recompile.
1824 // This will allow the compiler to see the limit overflow, and
1825 // take corrective action, if possible. The compiler generally
1826 // does not use the exact PerBytecodeTrapLimit value, but instead
1827 // changes its tactics if it sees any traps at all. This provides
1828 // a little hysteresis, delaying a recompile until a trap happens
1829 // several times.
1830 //
1831 // Actually, since there is only one bit of counter per BCI,
1832 // the possible per-BCI counts are {0,1,(per-method count)}.
1833 // This produces accurate results if in fact there is only
1834 // one hot trap site, but begins to get fuzzy if there are
1835 // many sites. For example, if there are ten sites each
1836 // trapping two or more times, they each get the blame for
1837 // all of their traps.
1838 make_not_entrant = true;
1839 }
1840
1841 // Detect repeated recompilation at the same BCI, and enforce a limit.
1842 if (make_not_entrant && maybe_prior_recompile) {
1843 // More than one recompile at this point.
Vladimir Kozlov0c27c552010-02-01 16:49:49 -08001844 inc_recompile_count = maybe_prior_trap;
J. Duke81537792007-12-01 00:00:00 +00001845 }
1846 } else {
1847 // For reasons which are not recorded per-bytecode, we simply
1848 // force recompiles unconditionally.
1849 // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
1850 make_not_entrant = true;
1851 }
1852
1853 // Go back to the compiler if there are too many traps in this method.
Roland Westrelin493557f2014-02-25 18:16:24 +01001854 if (this_trap_count >= per_method_trap_limit(reason)) {
J. Duke81537792007-12-01 00:00:00 +00001855 // If there are too many traps in this method, force a recompile.
1856 // This will allow the compiler to see the limit overflow, and
1857 // take corrective action, if possible.
1858 // (This condition is an unlikely backstop only, because the
1859 // PerBytecodeTrapLimit is more likely to take effect first,
1860 // if it is applicable.)
1861 make_not_entrant = true;
1862 }
1863
1864 // Here's more hysteresis: If there has been a recompile at
1865 // this trap point already, run the method in the interpreter
1866 // for a while to exercise it more thoroughly.
1867 if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
Igor Veresov2c66a6c2010-09-03 17:51:07 -07001868 reprofile = true;
J. Duke81537792007-12-01 00:00:00 +00001869 }
Vladimir Kozlov0c27c552010-02-01 16:49:49 -08001870 }
1871
1872 // Take requested actions on the method:
1873
1874 // Recompile
1875 if (make_not_entrant) {
1876 if (!nm->make_not_entrant()) {
1877 return; // the call did not change nmethod's state
1878 }
1879
1880 if (pdata != NULL) {
J. Duke81537792007-12-01 00:00:00 +00001881 // Record the recompilation event, if any.
1882 int tstate0 = pdata->trap_state();
1883 int tstate1 = trap_state_set_recompiled(tstate0, true);
1884 if (tstate1 != tstate0)
1885 pdata->set_trap_state(tstate1);
1886 }
Vladimir Kozlov97a51c52014-03-20 17:49:27 -07001887
1888#if INCLUDE_RTM_OPT
1889 // Restart collecting RTM locking abort statistic if the method
1890 // is recompiled for a reason other than RTM state change.
1891 // Assume that in new recompiled code the statistic could be different,
1892 // for example, due to different inlining.
1893 if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&
1894 UseRTMDeopt && (nm->rtm_state() != ProfileRTM)) {
1895 trap_mdo->atomic_set_rtm_state(ProfileRTM);
1896 }
1897#endif
Igor Veresov54db2c22014-05-13 11:32:10 -07001898 // For code aging we count traps separately here, using make_not_entrant()
1899 // as a guard against simultaneous deopts in multiple threads.
1900 if (reason == Reason_tenured && trap_mdo != NULL) {
1901 trap_mdo->inc_tenure_traps();
1902 }
J. Duke81537792007-12-01 00:00:00 +00001903 }
1904
Vladimir Kozlov0c27c552010-02-01 16:49:49 -08001905 if (inc_recompile_count) {
1906 trap_mdo->inc_overflow_recompile_count();
1907 if ((uint)trap_mdo->overflow_recompile_count() >
1908 (uint)PerBytecodeRecompilationCutoff) {
1909 // Give up on the method containing the bad BCI.
1910 if (trap_method() == nm->method()) {
1911 make_not_compilable = true;
1912 } else {
Igor Ignatyev014d9482013-02-05 08:25:51 -08001913 trap_method->set_not_compilable(CompLevel_full_optimization, true, "overflow_recompile_count > PerBytecodeRecompilationCutoff");
Vladimir Kozlov0c27c552010-02-01 16:49:49 -08001914 // But give grace to the enclosing nm->method().
1915 }
1916 }
1917 }
J. Duke81537792007-12-01 00:00:00 +00001918
Igor Veresov2c66a6c2010-09-03 17:51:07 -07001919 // Reprofile
1920 if (reprofile) {
1921 CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method());
J. Duke81537792007-12-01 00:00:00 +00001922 }
1923
J. Duke81537792007-12-01 00:00:00 +00001924 // Give up compiling
Igor Veresov2c66a6c2010-09-03 17:51:07 -07001925 if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
J. Duke81537792007-12-01 00:00:00 +00001926 assert(make_not_entrant, "consistent");
Igor Veresov2c66a6c2010-09-03 17:51:07 -07001927 nm->method()->set_not_compilable(CompLevel_full_optimization);
J. Duke81537792007-12-01 00:00:00 +00001928 }
1929
1930 } // Free marked resources
1931
1932}
1933JRT_END
1934
J. Duke81537792007-12-01 00:00:00 +00001935ProfileData*
Jon Masamitsu5c58d272012-09-01 13:25:18 -04001936Deoptimization::query_update_method_data(MethodData* trap_mdo,
J. Duke81537792007-12-01 00:00:00 +00001937 int trap_bci,
1938 Deoptimization::DeoptReason reason,
Christian Thalinger16526e02015-10-08 12:49:30 -10001939 bool update_total_trap_count,
1940#if INCLUDE_JVMCI
1941 bool is_osr,
1942#endif
Roland Westrelin493557f2014-02-25 18:16:24 +01001943 Method* compiled_method,
J. Duke81537792007-12-01 00:00:00 +00001944 //outputs:
1945 uint& ret_this_trap_count,
1946 bool& ret_maybe_prior_trap,
1947 bool& ret_maybe_prior_recompile) {
Christian Thalinger16526e02015-10-08 12:49:30 -10001948 bool maybe_prior_trap = false;
1949 bool maybe_prior_recompile = false;
1950 uint this_trap_count = 0;
1951 if (update_total_trap_count) {
1952 uint idx = reason;
1953#if INCLUDE_JVMCI
1954 if (is_osr) {
1955 idx += Reason_LIMIT;
1956 }
1957#endif
1958 uint prior_trap_count = trap_mdo->trap_count(idx);
1959 this_trap_count = trap_mdo->inc_trap_count(idx);
J. Duke81537792007-12-01 00:00:00 +00001960
Christian Thalinger16526e02015-10-08 12:49:30 -10001961 // If the runtime cannot find a place to store trap history,
1962 // it is estimated based on the general condition of the method.
1963 // If the method has ever been recompiled, or has ever incurred
1964 // a trap with the present reason , then this BCI is assumed
1965 // (pessimistically) to be the culprit.
1966 maybe_prior_trap = (prior_trap_count != 0);
1967 maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
1968 }
J. Duke81537792007-12-01 00:00:00 +00001969 ProfileData* pdata = NULL;
1970
1971
1972 // For reasons which are recorded per bytecode, we check per-BCI data.
1973 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
Christian Thalinger16526e02015-10-08 12:49:30 -10001974 assert(per_bc_reason != Reason_none || update_total_trap_count, "must be");
J. Duke81537792007-12-01 00:00:00 +00001975 if (per_bc_reason != Reason_none) {
1976 // Find the profile data for this BCI. If there isn't one,
1977 // try to allocate one from the MDO's set of spares.
1978 // This will let us detect a repeated trap at this point.
Roland Westrelin493557f2014-02-25 18:16:24 +01001979 pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);
J. Duke81537792007-12-01 00:00:00 +00001980
1981 if (pdata != NULL) {
Roland Westrelin493557f2014-02-25 18:16:24 +01001982 if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
1983 if (LogCompilation && xtty != NULL) {
1984 ttyLocker ttyl;
1985 // no more room for speculative traps in this MDO
1986 xtty->elem("speculative_traps_oom");
1987 }
1988 }
J. Duke81537792007-12-01 00:00:00 +00001989 // Query the trap state of this profile datum.
1990 int tstate0 = pdata->trap_state();
1991 if (!trap_state_has_reason(tstate0, per_bc_reason))
1992 maybe_prior_trap = false;
1993 if (!trap_state_is_recompiled(tstate0))
1994 maybe_prior_recompile = false;
1995
1996 // Update the trap state of this profile datum.
1997 int tstate1 = tstate0;
1998 // Record the reason.
1999 tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
2000 // Store the updated state on the MDO, for next time.
2001 if (tstate1 != tstate0)
2002 pdata->set_trap_state(tstate1);
2003 } else {
Vladimir Kozlov0c27c552010-02-01 16:49:49 -08002004 if (LogCompilation && xtty != NULL) {
2005 ttyLocker ttyl;
J. Duke81537792007-12-01 00:00:00 +00002006 // Missing MDP? Leave a small complaint in the log.
2007 xtty->elem("missing_mdp bci='%d'", trap_bci);
Vladimir Kozlov0c27c552010-02-01 16:49:49 -08002008 }
J. Duke81537792007-12-01 00:00:00 +00002009 }
2010 }
2011
2012 // Return results:
2013 ret_this_trap_count = this_trap_count;
2014 ret_maybe_prior_trap = maybe_prior_trap;
2015 ret_maybe_prior_recompile = maybe_prior_recompile;
2016 return pdata;
2017}
2018
2019void
Jon Masamitsu5c58d272012-09-01 13:25:18 -04002020Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
J. Duke81537792007-12-01 00:00:00 +00002021 ResourceMark rm;
2022 // Ignored outputs:
2023 uint ignore_this_trap_count;
2024 bool ignore_maybe_prior_trap;
2025 bool ignore_maybe_prior_recompile;
Roland Westrelin493557f2014-02-25 18:16:24 +01002026 assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
Christian Thalinger16526e02015-10-08 12:49:30 -10002027 // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts
2028 bool update_total_counts = JVMCI_ONLY(false) NOT_JVMCI(true);
J. Duke81537792007-12-01 00:00:00 +00002029 query_update_method_data(trap_mdo, trap_bci,
2030 (DeoptReason)reason,
Christian Thalinger16526e02015-10-08 12:49:30 -10002031 update_total_counts,
2032#if INCLUDE_JVMCI
2033 false,
2034#endif
Roland Westrelin493557f2014-02-25 18:16:24 +01002035 NULL,
J. Duke81537792007-12-01 00:00:00 +00002036 ignore_this_trap_count,
2037 ignore_maybe_prior_trap,
2038 ignore_maybe_prior_recompile);
2039}
2040
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -10002041Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request, jint exec_mode) {
Christian Thalinger16526e02015-10-08 12:49:30 -10002042 if (TraceDeoptimization) {
2043 tty->print("Uncommon trap ");
2044 }
J. Duke81537792007-12-01 00:00:00 +00002045 // Still in Java no safepoints
2046 {
2047 // This enters VM and may safepoint
2048 uncommon_trap_inner(thread, trap_request);
2049 }
Gilles Duboscqc4ce43c2015-11-11 14:40:38 -10002050 return fetch_unroll_info_helper(thread, exec_mode);
J. Duke81537792007-12-01 00:00:00 +00002051}
2052
2053// Local derived constants.
2054// Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2055const int DS_REASON_MASK = DataLayout::trap_mask >> 1;
2056const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2057
2058//---------------------------trap_state_reason---------------------------------
2059Deoptimization::DeoptReason
2060Deoptimization::trap_state_reason(int trap_state) {
2061 // This assert provides the link between the width of DataLayout::trap_bits
2062 // and the encoding of "recorded" reasons. It ensures there are enough
2063 // bits to store all needed reasons in the per-BCI MDO profile.
2064 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2065 int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2066 trap_state -= recompile_bit;
2067 if (trap_state == DS_REASON_MASK) {
2068 return Reason_many;
2069 } else {
2070 assert((int)Reason_none == 0, "state=0 => Reason_none");
2071 return (DeoptReason)trap_state;
2072 }
2073}
2074//-------------------------trap_state_has_reason-------------------------------
2075int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2076 assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
2077 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2078 int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2079 trap_state -= recompile_bit;
2080 if (trap_state == DS_REASON_MASK) {
2081 return -1; // true, unspecifically (bottom of state lattice)
2082 } else if (trap_state == reason) {
2083 return 1; // true, definitely
2084 } else if (trap_state == 0) {
2085 return 0; // false, definitely (top of state lattice)
2086 } else {
2087 return 0; // false, definitely
2088 }
2089}
2090//-------------------------trap_state_add_reason-------------------------------
2091int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
2092 assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
2093 int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2094 trap_state -= recompile_bit;
2095 if (trap_state == DS_REASON_MASK) {
2096 return trap_state + recompile_bit; // already at state lattice bottom
2097 } else if (trap_state == reason) {
2098 return trap_state + recompile_bit; // the condition is already true
2099 } else if (trap_state == 0) {
2100 return reason + recompile_bit; // no condition has yet been true
2101 } else {
2102 return DS_REASON_MASK + recompile_bit; // fall to state lattice bottom
2103 }
2104}
2105//-----------------------trap_state_is_recompiled------------------------------
2106bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2107 return (trap_state & DS_RECOMPILE_BIT) != 0;
2108}
2109//-----------------------trap_state_set_recompiled-----------------------------
2110int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
2111 if (z) return trap_state | DS_RECOMPILE_BIT;
2112 else return trap_state & ~DS_RECOMPILE_BIT;
2113}
2114//---------------------------format_trap_state---------------------------------
Vladimir Ivanov13d322d2013-09-13 04:16:54 -07002115// This is used for debugging and diagnostics, including LogFile output.
J. Duke81537792007-12-01 00:00:00 +00002116const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2117 int trap_state) {
Goetz Lindenmaier3b8c97f2015-10-26 16:21:37 +01002118 assert(buflen > 0, "sanity");
J. Duke81537792007-12-01 00:00:00 +00002119 DeoptReason reason = trap_state_reason(trap_state);
2120 bool recomp_flag = trap_state_is_recompiled(trap_state);
2121 // Re-encode the state from its decoded components.
2122 int decoded_state = 0;
2123 if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
2124 decoded_state = trap_state_add_reason(decoded_state, reason);
2125 if (recomp_flag)
2126 decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
2127 // If the state re-encodes properly, format it symbolically.
2128 // Because this routine is used for debugging and diagnostics,
2129 // be robust even if the state is a strange value.
2130 size_t len;
2131 if (decoded_state != trap_state) {
2132 // Random buggy state that doesn't decode??
2133 len = jio_snprintf(buf, buflen, "#%d", trap_state);
2134 } else {
2135 len = jio_snprintf(buf, buflen, "%s%s",
2136 trap_reason_name(reason),
2137 recomp_flag ? " recompiled" : "");
2138 }
J. Duke81537792007-12-01 00:00:00 +00002139 return buf;
2140}
2141
2142
2143//--------------------------------statics--------------------------------------
Igor Veresova2eea472014-05-15 10:37:52 -07002144const char* Deoptimization::_trap_reason_name[] = {
J. Duke81537792007-12-01 00:00:00 +00002145 // Note: Keep this in sync. with enum DeoptReason.
2146 "none",
2147 "null_check",
Christian Thalinger16526e02015-10-08 12:49:30 -10002148 "null_assert" JVMCI_ONLY("_or_unreached0"),
J. Duke81537792007-12-01 00:00:00 +00002149 "range_check",
2150 "class_check",
2151 "array_check",
Christian Thalinger16526e02015-10-08 12:49:30 -10002152 "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),
2153 "bimorphic" JVMCI_ONLY("_or_optimized_type_check"),
J. Duke81537792007-12-01 00:00:00 +00002154 "unloaded",
2155 "uninitialized",
2156 "unreached",
2157 "unhandled",
2158 "constraint",
2159 "div0_check",
Changpeng Fang815db4f2010-01-12 14:37:35 -08002160 "age",
Vladimir Kozlov1ac79542011-05-04 13:12:42 -07002161 "predicate",
Roland Westrelin493557f2014-02-25 18:16:24 +01002162 "loop_limit_check",
Vladimir Kozlov97a51c52014-03-20 17:49:27 -07002163 "speculate_class_check",
Roland Westrelinfa3b0a82014-03-31 09:08:53 +02002164 "speculate_null_check",
Igor Veresova2eea472014-05-15 10:37:52 -07002165 "rtm_state_change",
Rickard Bäckman8bd4b562014-05-22 13:42:44 +02002166 "unstable_if",
Roland Westrelin71e31ee2015-03-17 10:06:31 +01002167 "unstable_fused_if",
Christian Thalinger16526e02015-10-08 12:49:30 -10002168#if INCLUDE_JVMCI
2169 "aliasing",
2170 "transfer_to_interpreter",
2171 "not_compiled_exception_handler",
2172 "unresolved",
2173 "jsr_mismatch",
2174#endif
Igor Veresova2eea472014-05-15 10:37:52 -07002175 "tenured"
J. Duke81537792007-12-01 00:00:00 +00002176};
Igor Veresova2eea472014-05-15 10:37:52 -07002177const char* Deoptimization::_trap_action_name[] = {
J. Duke81537792007-12-01 00:00:00 +00002178 // Note: Keep this in sync. with enum DeoptAction.
2179 "none",
2180 "maybe_recompile",
2181 "reinterpret",
2182 "make_not_entrant",
2183 "make_not_compilable"
2184};
2185
2186const char* Deoptimization::trap_reason_name(int reason) {
Igor Veresova2eea472014-05-15 10:37:52 -07002187 // Check that every reason has a name
2188 STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);
2189
J. Duke81537792007-12-01 00:00:00 +00002190 if (reason == Reason_many) return "many";
2191 if ((uint)reason < Reason_LIMIT)
2192 return _trap_reason_name[reason];
2193 static char buf[20];
2194 sprintf(buf, "reason%d", reason);
2195 return buf;
2196}
2197const char* Deoptimization::trap_action_name(int action) {
Igor Veresova2eea472014-05-15 10:37:52 -07002198 // Check that every action has a name
2199 STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);
2200
J. Duke81537792007-12-01 00:00:00 +00002201 if ((uint)action < Action_LIMIT)
2202 return _trap_action_name[action];
2203 static char buf[20];
2204 sprintf(buf, "action%d", action);
2205 return buf;
2206}
2207
Vladimir Ivanov13d322d2013-09-13 04:16:54 -07002208// This is used for debugging and diagnostics, including LogFile output.
J. Duke81537792007-12-01 00:00:00 +00002209const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
2210 int trap_request) {
2211 jint unloaded_class_index = trap_request_index(trap_request);
2212 const char* reason = trap_reason_name(trap_request_reason(trap_request));
2213 const char* action = trap_action_name(trap_request_action(trap_request));
Christian Thalinger16526e02015-10-08 12:49:30 -10002214#if INCLUDE_JVMCI
2215 int debug_id = trap_request_debug_id(trap_request);
2216#endif
J. Duke81537792007-12-01 00:00:00 +00002217 size_t len;
2218 if (unloaded_class_index < 0) {
Christian Thalinger16526e02015-10-08 12:49:30 -10002219 len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),
2220 reason, action
2221#if INCLUDE_JVMCI
2222 ,debug_id
2223#endif
2224 );
J. Duke81537792007-12-01 00:00:00 +00002225 } else {
Christian Thalinger16526e02015-10-08 12:49:30 -10002226 len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),
2227 reason, action, unloaded_class_index
2228#if INCLUDE_JVMCI
2229 ,debug_id
2230#endif
2231 );
J. Duke81537792007-12-01 00:00:00 +00002232 }
J. Duke81537792007-12-01 00:00:00 +00002233 return buf;
2234}
2235
2236juint Deoptimization::_deoptimization_hist
2237 [Deoptimization::Reason_LIMIT]
2238 [1 + Deoptimization::Action_LIMIT]
2239 [Deoptimization::BC_CASE_LIMIT]
2240 = {0};
2241
2242enum {
2243 LSB_BITS = 8,
2244 LSB_MASK = right_n_bits(LSB_BITS)
2245};
2246
2247void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2248 Bytecodes::Code bc) {
2249 assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2250 assert(action >= 0 && action < Action_LIMIT, "oob");
2251 _deoptimization_hist[Reason_none][0][0] += 1; // total
2252 _deoptimization_hist[reason][0][0] += 1; // per-reason total
2253 juint* cases = _deoptimization_hist[reason][1+action];
2254 juint* bc_counter_addr = NULL;
2255 juint bc_counter = 0;
2256 // Look for an unused counter, or an exact match to this BC.
2257 if (bc != Bytecodes::_illegal) {
2258 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2259 juint* counter_addr = &cases[bc_case];
2260 juint counter = *counter_addr;
2261 if ((counter == 0 && bc_counter_addr == NULL)
2262 || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
2263 // this counter is either free or is already devoted to this BC
2264 bc_counter_addr = counter_addr;
2265 bc_counter = counter | bc;
2266 }
2267 }
2268 }
2269 if (bc_counter_addr == NULL) {
2270 // Overflow, or no given bytecode.
2271 bc_counter_addr = &cases[BC_CASE_LIMIT-1];
2272 bc_counter = (*bc_counter_addr & ~LSB_MASK); // clear LSB
2273 }
2274 *bc_counter_addr = bc_counter + (1 << LSB_BITS);
2275}
2276
2277jint Deoptimization::total_deoptimization_count() {
2278 return _deoptimization_hist[Reason_none][0][0];
2279}
2280
2281jint Deoptimization::deoptimization_count(DeoptReason reason) {
2282 assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2283 return _deoptimization_hist[reason][0][0];
2284}
2285
2286void Deoptimization::print_statistics() {
2287 juint total = total_deoptimization_count();
2288 juint account = total;
2289 if (total != 0) {
2290 ttyLocker ttyl;
2291 if (xtty != NULL) xtty->head("statistics type='deoptimization'");
2292 tty->print_cr("Deoptimization traps recorded:");
2293 #define PRINT_STAT_LINE(name, r) \
2294 tty->print_cr(" %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
2295 PRINT_STAT_LINE("total", total);
2296 // For each non-zero entry in the histogram, print the reason,
2297 // the action, and (if specifically known) the type of bytecode.
2298 for (int reason = 0; reason < Reason_LIMIT; reason++) {
2299 for (int action = 0; action < Action_LIMIT; action++) {
2300 juint* cases = _deoptimization_hist[reason][1+action];
2301 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2302 juint counter = cases[bc_case];
2303 if (counter != 0) {
2304 char name[1*K];
2305 Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
2306 if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
2307 bc = Bytecodes::_illegal;
2308 sprintf(name, "%s/%s/%s",
2309 trap_reason_name(reason),
2310 trap_action_name(action),
2311 Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
2312 juint r = counter >> LSB_BITS;
2313 tty->print_cr(" %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
2314 account -= r;
2315 }
2316 }
2317 }
2318 }
2319 if (account != 0) {
2320 PRINT_STAT_LINE("unaccounted", account);
2321 }
2322 #undef PRINT_STAT_LINE
2323 if (xtty != NULL) xtty->tail("statistics");
2324 }
2325}
Christian Thalinger16526e02015-10-08 12:49:30 -10002326#else // COMPILER2 || SHARK || INCLUDE_JVMCI
J. Duke81537792007-12-01 00:00:00 +00002327
2328
2329// Stubs for C1 only system.
2330bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2331 return false;
2332}
2333
2334const char* Deoptimization::trap_reason_name(int reason) {
2335 return "unknown";
2336}
2337
2338void Deoptimization::print_statistics() {
2339 // no output
2340}
2341
2342void
Jon Masamitsu5c58d272012-09-01 13:25:18 -04002343Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
J. Duke81537792007-12-01 00:00:00 +00002344 // no udpate
2345}
2346
2347int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2348 return 0;
2349}
2350
2351void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2352 Bytecodes::Code bc) {
2353 // no update
2354}
2355
2356const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2357 int trap_state) {
2358 jio_snprintf(buf, buflen, "#%d", trap_state);
2359 return buf;
2360}
2361
Christian Thalinger16526e02015-10-08 12:49:30 -10002362#endif // COMPILER2 || SHARK || INCLUDE_JVMCI