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