1 2 3 /* 4 * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. 5 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 6 * 7 * This code is free software; you can redistribute it and/or modify it 8 * under the terms of the GNU General Public License version 2 only, as 9 * published by the Free Software Foundation. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 * 25 */ 26 27 #include "precompiled.hpp" 28 #include "jvm.h" 29 #include "classfile/javaClasses.inline.hpp" 30 #include "classfile/symbolTable.hpp" 31 #include "classfile/systemDictionary.hpp" 32 #include "code/codeCache.hpp" 33 #include "code/debugInfoRec.hpp" 34 #include "code/nmethod.hpp" 35 #include "code/pcDesc.hpp" 36 #include "code/scopeDesc.hpp" 37 #include "compiler/compilationPolicy.hpp" 38 #include "interpreter/bytecode.hpp" 39 #include "interpreter/interpreter.hpp" 40 #include "interpreter/oopMapCache.hpp" 41 #include "memory/allocation.inline.hpp" 42 #include "memory/oopFactory.hpp" 43 #include "memory/resourceArea.hpp" 44 #include "memory/universe.hpp" 45 #include "oops/constantPool.hpp" 46 #include "oops/method.hpp" 47 #include "oops/objArrayKlass.hpp" 48 #include "oops/objArrayOop.inline.hpp" 49 #include "oops/oop.inline.hpp" 50 #include "oops/fieldStreams.inline.hpp" 51 #include "oops/typeArrayOop.inline.hpp" 52 #include "oops/verifyOopClosure.hpp" 53 #include "prims/jvmtiThreadState.hpp" 54 #include "runtime/atomic.hpp" 55 #include "runtime/biasedLocking.hpp" 56 #include "runtime/deoptimization.hpp" 57 #include "runtime/fieldDescriptor.hpp" 58 #include "runtime/fieldDescriptor.inline.hpp" 59 #include "runtime/frame.inline.hpp" 60 #include "runtime/handles.inline.hpp" 61 #include "runtime/interfaceSupport.inline.hpp" 62 #include "runtime/jniHandles.inline.hpp" 63 #include "runtime/safepointVerifiers.hpp" 64 #include "runtime/sharedRuntime.hpp" 65 #include "runtime/signature.hpp" 66 #include "runtime/stubRoutines.hpp" 67 #include "runtime/thread.hpp" 68 #include "runtime/threadSMR.hpp" 69 #include "runtime/vframe.hpp" 70 #include "runtime/vframeArray.hpp" 71 #include "runtime/vframe_hp.hpp" 72 #include "utilities/events.hpp" 73 #include "utilities/macros.hpp" 74 #include "utilities/preserveException.hpp" 75 #include "utilities/xmlstream.hpp" 76 #if INCLUDE_JFR 77 #include "jfr/jfrEvents.hpp" 78 #include "jfr/metadata/jfrSerializer.hpp" 79 #endif 80 81 bool DeoptimizationMarker::_is_active = false; 82 83 Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame, 84 int caller_adjustment, 85 int caller_actual_parameters, 86 int number_of_frames, 87 intptr_t* frame_sizes, 88 address* frame_pcs, 89 BasicType return_type, 90 int exec_mode) { 91 _size_of_deoptimized_frame = size_of_deoptimized_frame; 92 _caller_adjustment = caller_adjustment; 93 _caller_actual_parameters = caller_actual_parameters; 94 _number_of_frames = number_of_frames; 95 _frame_sizes = frame_sizes; 96 _frame_pcs = frame_pcs; 97 _register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler); 98 _return_type = return_type; 99 _initial_info = 0; 100 // PD (x86 only) 101 _counter_temp = 0; 102 _unpack_kind = exec_mode; 103 _sender_sp_temp = 0; 104 105 _total_frame_sizes = size_of_frames(); 106 assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode"); 107 } 108 109 110 Deoptimization::UnrollBlock::~UnrollBlock() { 111 FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes); 112 FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs); 113 FREE_C_HEAP_ARRAY(intptr_t, _register_block); 114 } 115 116 117 intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const { 118 assert(register_number < RegisterMap::reg_count, "checking register number"); 119 return &_register_block[register_number * 2]; 120 } 121 122 123 124 int Deoptimization::UnrollBlock::size_of_frames() const { 125 // Acount first for the adjustment of the initial frame 126 int result = _caller_adjustment; 127 for (int index = 0; index < number_of_frames(); index++) { 128 result += frame_sizes()[index]; 129 } 130 return result; 131 } 132 133 134 void Deoptimization::UnrollBlock::print() { 135 ttyLocker ttyl; 136 tty->print_cr("UnrollBlock"); 137 tty->print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame); 138 tty->print( " frame_sizes: "); 139 for (int index = 0; index < number_of_frames(); index++) { 140 tty->print(INTX_FORMAT " ", frame_sizes()[index]); 141 } 142 tty->cr(); 143 } 144 145 146 // In order to make fetch_unroll_info work properly with escape 147 // analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and 148 // ResetNoHandleMark and HandleMark were removed from it. The actual reallocation 149 // of previously eliminated objects occurs in realloc_objects, which is 150 // called from the method fetch_unroll_info_helper below. 151 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread, int exec_mode)) 152 // It is actually ok to allocate handles in a leaf method. It causes no safepoints, 153 // but makes the entry a little slower. There is however a little dance we have to 154 // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro 155 156 // fetch_unroll_info() is called at the beginning of the deoptimization 157 // handler. Note this fact before we start generating temporary frames 158 // that can confuse an asynchronous stack walker. This counter is 159 // decremented at the end of unpack_frames(). 160 if (TraceDeoptimization) { 161 tty->print_cr("Deoptimizing thread " INTPTR_FORMAT, p2i(thread)); 162 } 163 thread->inc_in_deopt_handler(); 164 165 return fetch_unroll_info_helper(thread, exec_mode); 166 JRT_END 167 168 #if COMPILER2_OR_JVMCI 169 static bool eliminate_allocations(JavaThread* thread, int exec_mode, CompiledMethod* compiled_method, 170 frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk) { 171 bool realloc_failures = false; 172 assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames"); 173 174 GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects(); 175 176 // The flag return_oop() indicates call sites which return oop 177 // in compiled code. Such sites include java method calls, 178 // runtime calls (for example, used to allocate new objects/arrays 179 // on slow code path) and any other calls generated in compiled code. 180 // It is not guaranteed that we can get such information here only 181 // by analyzing bytecode in deoptimized frames. This is why this flag 182 // is set during method compilation (see Compile::Process_OopMap_Node()). 183 // If the previous frame was popped or if we are dispatching an exception, 184 // we don't have an oop result. 185 bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt); 186 Handle return_value; 187 if (save_oop_result) { 188 // Reallocation may trigger GC. If deoptimization happened on return from 189 // call which returns oop we need to save it since it is not in oopmap. 190 oop result = deoptee.saved_oop_result(&map); 191 assert(oopDesc::is_oop_or_null(result), "must be oop"); 192 return_value = Handle(thread, result); 193 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer"); 194 if (TraceDeoptimization) { 195 ttyLocker ttyl; 196 tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread)); 197 } 198 } 199 if (objects != NULL) { 200 JRT_BLOCK 201 realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD); 202 JRT_END 203 bool skip_internal = (compiled_method != NULL) && !compiled_method->is_compiled_by_jvmci(); 204 Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal); 205 #ifndef PRODUCT 206 if (TraceDeoptimization) { 207 ttyLocker ttyl; 208 tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(thread)); 209 Deoptimization::print_objects(objects, realloc_failures); 210 } 211 #endif 212 } 213 if (save_oop_result) { 214 // Restore result. 215 deoptee.set_saved_oop_result(&map, return_value()); 216 } 217 return realloc_failures; 218 } 219 220 static void eliminate_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) { 221 #ifndef PRODUCT 222 bool first = true; 223 #endif 224 for (int i = 0; i < chunk->length(); i++) { 225 compiledVFrame* cvf = chunk->at(i); 226 assert (cvf->scope() != NULL,"expect only compiled java frames"); 227 GrowableArray<MonitorInfo*>* monitors = cvf->monitors(); 228 if (monitors->is_nonempty()) { 229 Deoptimization::relock_objects(monitors, thread, realloc_failures); 230 #ifndef PRODUCT 231 if (PrintDeoptimizationDetails) { 232 ttyLocker ttyl; 233 for (int j = 0; j < monitors->length(); j++) { 234 MonitorInfo* mi = monitors->at(j); 235 if (mi->eliminated()) { 236 if (first) { 237 first = false; 238 tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread)); 239 } 240 if (mi->owner_is_scalar_replaced()) { 241 Klass* k = java_lang_Class::as_Klass(mi->owner_klass()); 242 tty->print_cr(" failed reallocation for klass %s", k->external_name()); 243 } else { 244 tty->print_cr(" object <" INTPTR_FORMAT "> locked", p2i(mi->owner())); 245 } 246 } 247 } 248 } 249 #endif // !PRODUCT 250 } 251 } 252 } 253 #endif // COMPILER2_OR_JVMCI 254 255 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap) 256 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread, int exec_mode) { 257 258 // Note: there is a safepoint safety issue here. No matter whether we enter 259 // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once 260 // the vframeArray is created. 261 // 262 263 // Allocate our special deoptimization ResourceMark 264 DeoptResourceMark* dmark = new DeoptResourceMark(thread); 265 assert(thread->deopt_mark() == NULL, "Pending deopt!"); 266 thread->set_deopt_mark(dmark); 267 268 frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect 269 RegisterMap map(thread, true); 270 RegisterMap dummy_map(thread, false); 271 // Now get the deoptee with a valid map 272 frame deoptee = stub_frame.sender(&map); 273 // Set the deoptee nmethod 274 assert(thread->deopt_compiled_method() == NULL, "Pending deopt!"); 275 CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null(); 276 thread->set_deopt_compiled_method(cm); 277 278 if (VerifyStack) { 279 thread->validate_frame_layout(); 280 } 281 282 // Create a growable array of VFrames where each VFrame represents an inlined 283 // Java frame. This storage is allocated with the usual system arena. 284 assert(deoptee.is_compiled_frame(), "Wrong frame type"); 285 GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10); 286 vframe* vf = vframe::new_vframe(&deoptee, &map, thread); 287 while (!vf->is_top()) { 288 assert(vf->is_compiled_frame(), "Wrong frame type"); 289 chunk->push(compiledVFrame::cast(vf)); 290 vf = vf->sender(); 291 } 292 assert(vf->is_compiled_frame(), "Wrong frame type"); 293 chunk->push(compiledVFrame::cast(vf)); 294 295 bool realloc_failures = false; 296 297 #if COMPILER2_OR_JVMCI 298 #if INCLUDE_JVMCI 299 bool jvmci_enabled = true; 300 #else 301 bool jvmci_enabled = false; 302 #endif 303 304 // Reallocate the non-escaping objects and restore their fields. Then 305 // relock objects if synchronization on them was eliminated. 306 if (jvmci_enabled COMPILER2_PRESENT( || (DoEscapeAnalysis && EliminateAllocations) )) { 307 realloc_failures = eliminate_allocations(thread, exec_mode, cm, deoptee, map, chunk); 308 } 309 #endif // COMPILER2_OR_JVMCI 310 311 // Revoke biases, done with in java state. 312 // No safepoints allowed after this 313 revoke_from_deopt_handler(thread, deoptee, &map); 314 315 // Ensure that no safepoint is taken after pointers have been stored 316 // in fields of rematerialized objects. If a safepoint occurs from here on 317 // out the java state residing in the vframeArray will be missed. 318 // Locks may be rebaised in a safepoint. 319 NoSafepointVerifier no_safepoint; 320 321 #if COMPILER2_OR_JVMCI 322 if (jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) )) { 323 eliminate_locks(thread, chunk, realloc_failures); 324 } 325 #endif // COMPILER2_OR_JVMCI 326 327 ScopeDesc* trap_scope = chunk->at(0)->scope(); 328 Handle exceptionObject; 329 if (trap_scope->rethrow_exception()) { 330 if (PrintDeoptimizationDetails) { 331 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()); 332 } 333 GrowableArray<ScopeValue*>* expressions = trap_scope->expressions(); 334 guarantee(expressions != NULL && expressions->length() > 0, "must have exception to throw"); 335 ScopeValue* topOfStack = expressions->top(); 336 exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj(); 337 guarantee(exceptionObject() != NULL, "exception oop can not be null"); 338 } 339 340 vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures); 341 #if COMPILER2_OR_JVMCI 342 if (realloc_failures) { 343 pop_frames_failed_reallocs(thread, array); 344 } 345 #endif 346 347 assert(thread->vframe_array_head() == NULL, "Pending deopt!"); 348 thread->set_vframe_array_head(array); 349 350 // Now that the vframeArray has been created if we have any deferred local writes 351 // added by jvmti then we can free up that structure as the data is now in the 352 // vframeArray 353 354 if (thread->deferred_locals() != NULL) { 355 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals(); 356 int i = 0; 357 do { 358 // Because of inlining we could have multiple vframes for a single frame 359 // and several of the vframes could have deferred writes. Find them all. 360 if (list->at(i)->id() == array->original().id()) { 361 jvmtiDeferredLocalVariableSet* dlv = list->at(i); 362 list->remove_at(i); 363 // individual jvmtiDeferredLocalVariableSet are CHeapObj's 364 delete dlv; 365 } else { 366 i++; 367 } 368 } while ( i < list->length() ); 369 if (list->length() == 0) { 370 thread->set_deferred_locals(NULL); 371 // free the list and elements back to C heap. 372 delete list; 373 } 374 375 } 376 377 // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info. 378 CodeBlob* cb = stub_frame.cb(); 379 // Verify we have the right vframeArray 380 assert(cb->frame_size() >= 0, "Unexpected frame size"); 381 intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size(); 382 383 // If the deopt call site is a MethodHandle invoke call site we have 384 // to adjust the unpack_sp. 385 nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null(); 386 if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc())) 387 unpack_sp = deoptee.unextended_sp(); 388 389 #ifdef ASSERT 390 assert(cb->is_deoptimization_stub() || 391 cb->is_uncommon_trap_stub() || 392 strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 || 393 strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0, 394 "unexpected code blob: %s", cb->name()); 395 #endif 396 397 // This is a guarantee instead of an assert because if vframe doesn't match 398 // we will unpack the wrong deoptimized frame and wind up in strange places 399 // where it will be very difficult to figure out what went wrong. Better 400 // to die an early death here than some very obscure death later when the 401 // trail is cold. 402 // Note: on ia64 this guarantee can be fooled by frames with no memory stack 403 // in that it will fail to detect a problem when there is one. This needs 404 // more work in tiger timeframe. 405 guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack"); 406 407 int number_of_frames = array->frames(); 408 409 // Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost 410 // virtual activation, which is the reverse of the elements in the vframes array. 411 intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler); 412 // +1 because we always have an interpreter return address for the final slot. 413 address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler); 414 int popframe_extra_args = 0; 415 // Create an interpreter return address for the stub to use as its return 416 // address so the skeletal frames are perfectly walkable 417 frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0); 418 419 // PopFrame requires that the preserved incoming arguments from the recently-popped topmost 420 // activation be put back on the expression stack of the caller for reexecution 421 if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) { 422 popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words()); 423 } 424 425 // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized 426 // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather 427 // than simply use array->sender.pc(). This requires us to walk the current set of frames 428 // 429 frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame 430 deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller 431 432 // It's possible that the number of parameters at the call site is 433 // different than number of arguments in the callee when method 434 // handles are used. If the caller is interpreted get the real 435 // value so that the proper amount of space can be added to it's 436 // frame. 437 bool caller_was_method_handle = false; 438 if (deopt_sender.is_interpreted_frame()) { 439 methodHandle method(thread, deopt_sender.interpreter_frame_method()); 440 Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci()); 441 if (cur.is_invokedynamic() || cur.is_invokehandle()) { 442 // Method handle invokes may involve fairly arbitrary chains of 443 // calls so it's impossible to know how much actual space the 444 // caller has for locals. 445 caller_was_method_handle = true; 446 } 447 } 448 449 // 450 // frame_sizes/frame_pcs[0] oldest frame (int or c2i) 451 // frame_sizes/frame_pcs[1] next oldest frame (int) 452 // frame_sizes/frame_pcs[n] youngest frame (int) 453 // 454 // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame 455 // owns the space for the return address to it's caller). Confusing ain't it. 456 // 457 // The vframe array can address vframes with indices running from 458 // 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame. 459 // When we create the skeletal frames we need the oldest frame to be in the zero slot 460 // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk. 461 // so things look a little strange in this loop. 462 // 463 int callee_parameters = 0; 464 int callee_locals = 0; 465 for (int index = 0; index < array->frames(); index++ ) { 466 // frame[number_of_frames - 1 ] = on_stack_size(youngest) 467 // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest)) 468 // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest))) 469 frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters, 470 callee_locals, 471 index == 0, 472 popframe_extra_args); 473 // This pc doesn't have to be perfect just good enough to identify the frame 474 // as interpreted so the skeleton frame will be walkable 475 // The correct pc will be set when the skeleton frame is completely filled out 476 // The final pc we store in the loop is wrong and will be overwritten below 477 frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset; 478 479 callee_parameters = array->element(index)->method()->size_of_parameters(); 480 callee_locals = array->element(index)->method()->max_locals(); 481 popframe_extra_args = 0; 482 } 483 484 // Compute whether the root vframe returns a float or double value. 485 BasicType return_type; 486 { 487 methodHandle method(thread, array->element(0)->method()); 488 Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci()); 489 return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL; 490 } 491 492 // Compute information for handling adapters and adjusting the frame size of the caller. 493 int caller_adjustment = 0; 494 495 // Compute the amount the oldest interpreter frame will have to adjust 496 // its caller's stack by. If the caller is a compiled frame then 497 // we pretend that the callee has no parameters so that the 498 // extension counts for the full amount of locals and not just 499 // locals-parms. This is because without a c2i adapter the parm 500 // area as created by the compiled frame will not be usable by 501 // the interpreter. (Depending on the calling convention there 502 // may not even be enough space). 503 504 // QQQ I'd rather see this pushed down into last_frame_adjust 505 // and have it take the sender (aka caller). 506 507 if (deopt_sender.is_compiled_frame() || caller_was_method_handle) { 508 caller_adjustment = last_frame_adjust(0, callee_locals); 509 } else if (callee_locals > callee_parameters) { 510 // The caller frame may need extending to accommodate 511 // non-parameter locals of the first unpacked interpreted frame. 512 // Compute that adjustment. 513 caller_adjustment = last_frame_adjust(callee_parameters, callee_locals); 514 } 515 516 // If the sender is deoptimized the we must retrieve the address of the handler 517 // since the frame will "magically" show the original pc before the deopt 518 // and we'd undo the deopt. 519 520 frame_pcs[0] = deopt_sender.raw_pc(); 521 522 assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc"); 523 524 #if INCLUDE_JVMCI 525 if (exceptionObject() != NULL) { 526 thread->set_exception_oop(exceptionObject()); 527 exec_mode = Unpack_exception; 528 } 529 #endif 530 531 if (thread->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) { 532 assert(thread->has_pending_exception(), "should have thrown OOME"); 533 thread->set_exception_oop(thread->pending_exception()); 534 thread->clear_pending_exception(); 535 exec_mode = Unpack_exception; 536 } 537 538 #if INCLUDE_JVMCI 539 if (thread->frames_to_pop_failed_realloc() > 0) { 540 thread->set_pending_monitorenter(false); 541 } 542 #endif 543 544 UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord, 545 caller_adjustment * BytesPerWord, 546 caller_was_method_handle ? 0 : callee_parameters, 547 number_of_frames, 548 frame_sizes, 549 frame_pcs, 550 return_type, 551 exec_mode); 552 // On some platforms, we need a way to pass some platform dependent 553 // information to the unpacking code so the skeletal frames come out 554 // correct (initial fp value, unextended sp, ...) 555 info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info()); 556 557 if (array->frames() > 1) { 558 if (VerifyStack && TraceDeoptimization) { 559 ttyLocker ttyl; 560 tty->print_cr("Deoptimizing method containing inlining"); 561 } 562 } 563 564 array->set_unroll_block(info); 565 return info; 566 } 567 568 // Called to cleanup deoptimization data structures in normal case 569 // after unpacking to stack and when stack overflow error occurs 570 void Deoptimization::cleanup_deopt_info(JavaThread *thread, 571 vframeArray *array) { 572 573 // Get array if coming from exception 574 if (array == NULL) { 575 array = thread->vframe_array_head(); 576 } 577 thread->set_vframe_array_head(NULL); 578 579 // Free the previous UnrollBlock 580 vframeArray* old_array = thread->vframe_array_last(); 581 thread->set_vframe_array_last(array); 582 583 if (old_array != NULL) { 584 UnrollBlock* old_info = old_array->unroll_block(); 585 old_array->set_unroll_block(NULL); 586 delete old_info; 587 delete old_array; 588 } 589 590 // Deallocate any resource creating in this routine and any ResourceObjs allocated 591 // inside the vframeArray (StackValueCollections) 592 593 delete thread->deopt_mark(); 594 thread->set_deopt_mark(NULL); 595 thread->set_deopt_compiled_method(NULL); 596 597 598 if (JvmtiExport::can_pop_frame()) { 599 #ifndef CC_INTERP 600 // Regardless of whether we entered this routine with the pending 601 // popframe condition bit set, we should always clear it now 602 thread->clear_popframe_condition(); 603 #else 604 // C++ interpreter will clear has_pending_popframe when it enters 605 // with method_resume. For deopt_resume2 we clear it now. 606 if (thread->popframe_forcing_deopt_reexecution()) 607 thread->clear_popframe_condition(); 608 #endif /* CC_INTERP */ 609 } 610 611 // unpack_frames() is called at the end of the deoptimization handler 612 // and (in C2) at the end of the uncommon trap handler. Note this fact 613 // so that an asynchronous stack walker can work again. This counter is 614 // incremented at the beginning of fetch_unroll_info() and (in C2) at 615 // the beginning of uncommon_trap(). 616 thread->dec_in_deopt_handler(); 617 } 618 619 // Moved from cpu directories because none of the cpus has callee save values. 620 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp. 621 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) { 622 623 // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in 624 // the days we had adapter frames. When we deoptimize a situation where a 625 // compiled caller calls a compiled caller will have registers it expects 626 // to survive the call to the callee. If we deoptimize the callee the only 627 // way we can restore these registers is to have the oldest interpreter 628 // frame that we create restore these values. That is what this routine 629 // will accomplish. 630 631 // At the moment we have modified c2 to not have any callee save registers 632 // so this problem does not exist and this routine is just a place holder. 633 634 assert(f->is_interpreted_frame(), "must be interpreted"); 635 } 636 637 // Return BasicType of value being returned 638 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)) 639 640 // We are already active in the special DeoptResourceMark any ResourceObj's we 641 // allocate will be freed at the end of the routine. 642 643 // It is actually ok to allocate handles in a leaf method. It causes no safepoints, 644 // but makes the entry a little slower. There is however a little dance we have to 645 // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro 646 ResetNoHandleMark rnhm; // No-op in release/product versions 647 HandleMark hm; 648 649 frame stub_frame = thread->last_frame(); 650 651 // Since the frame to unpack is the top frame of this thread, the vframe_array_head 652 // must point to the vframeArray for the unpack frame. 653 vframeArray* array = thread->vframe_array_head(); 654 655 #ifndef PRODUCT 656 if (TraceDeoptimization) { 657 ttyLocker ttyl; 658 tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", 659 p2i(thread), p2i(array), exec_mode); 660 } 661 #endif 662 Events::log_deopt_message(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d", 663 p2i(stub_frame.pc()), p2i(stub_frame.sp()), exec_mode); 664 665 UnrollBlock* info = array->unroll_block(); 666 667 // We set the last_Java frame. But the stack isn't really parsable here. So we 668 // clear it to make sure JFR understands not to try and walk stacks from events 669 // in here. 670 intptr_t* sp = thread->frame_anchor()->last_Java_sp(); 671 thread->frame_anchor()->set_last_Java_sp(NULL); 672 673 // Unpack the interpreter frames and any adapter frame (c2 only) we might create. 674 array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters()); 675 676 thread->frame_anchor()->set_last_Java_sp(sp); 677 678 BasicType bt = info->return_type(); 679 680 // If we have an exception pending, claim that the return type is an oop 681 // so the deopt_blob does not overwrite the exception_oop. 682 683 if (exec_mode == Unpack_exception) 684 bt = T_OBJECT; 685 686 // Cleanup thread deopt data 687 cleanup_deopt_info(thread, array); 688 689 #ifndef PRODUCT 690 if (VerifyStack) { 691 ResourceMark res_mark; 692 // Clear pending exception to not break verification code (restored afterwards) 693 PRESERVE_EXCEPTION_MARK; 694 695 thread->validate_frame_layout(); 696 697 // Verify that the just-unpacked frames match the interpreter's 698 // notions of expression stack and locals 699 vframeArray* cur_array = thread->vframe_array_last(); 700 RegisterMap rm(thread, false); 701 rm.set_include_argument_oops(false); 702 bool is_top_frame = true; 703 int callee_size_of_parameters = 0; 704 int callee_max_locals = 0; 705 for (int i = 0; i < cur_array->frames(); i++) { 706 vframeArrayElement* el = cur_array->element(i); 707 frame* iframe = el->iframe(); 708 guarantee(iframe->is_interpreted_frame(), "Wrong frame type"); 709 710 // Get the oop map for this bci 711 InterpreterOopMap mask; 712 int cur_invoke_parameter_size = 0; 713 bool try_next_mask = false; 714 int next_mask_expression_stack_size = -1; 715 int top_frame_expression_stack_adjustment = 0; 716 methodHandle mh(thread, iframe->interpreter_frame_method()); 717 OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask); 718 BytecodeStream str(mh, iframe->interpreter_frame_bci()); 719 int max_bci = mh->code_size(); 720 // Get to the next bytecode if possible 721 assert(str.bci() < max_bci, "bci in interpreter frame out of bounds"); 722 // Check to see if we can grab the number of outgoing arguments 723 // at an uncommon trap for an invoke (where the compiler 724 // generates debug info before the invoke has executed) 725 Bytecodes::Code cur_code = str.next(); 726 if (Bytecodes::is_invoke(cur_code)) { 727 Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci()); 728 cur_invoke_parameter_size = invoke.size_of_parameters(); 729 if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) { 730 callee_size_of_parameters++; 731 } 732 } 733 if (str.bci() < max_bci) { 734 Bytecodes::Code next_code = str.next(); 735 if (next_code >= 0) { 736 // The interpreter oop map generator reports results before 737 // the current bytecode has executed except in the case of 738 // calls. It seems to be hard to tell whether the compiler 739 // has emitted debug information matching the "state before" 740 // a given bytecode or the state after, so we try both 741 if (!Bytecodes::is_invoke(cur_code) && cur_code != Bytecodes::_athrow) { 742 // Get expression stack size for the next bytecode 743 InterpreterOopMap next_mask; 744 OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask); 745 next_mask_expression_stack_size = next_mask.expression_stack_size(); 746 if (Bytecodes::is_invoke(next_code)) { 747 Bytecode_invoke invoke(mh, str.bci()); 748 next_mask_expression_stack_size += invoke.size_of_parameters(); 749 } 750 // Need to subtract off the size of the result type of 751 // the bytecode because this is not described in the 752 // debug info but returned to the interpreter in the TOS 753 // caching register 754 BasicType bytecode_result_type = Bytecodes::result_type(cur_code); 755 if (bytecode_result_type != T_ILLEGAL) { 756 top_frame_expression_stack_adjustment = type2size[bytecode_result_type]; 757 } 758 assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive"); 759 try_next_mask = true; 760 } 761 } 762 } 763 764 // Verify stack depth and oops in frame 765 // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc) 766 if (!( 767 /* SPARC */ 768 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) || 769 /* x86 */ 770 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) || 771 (try_next_mask && 772 (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size - 773 top_frame_expression_stack_adjustment))) || 774 (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) || 775 (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) && 776 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size)) 777 )) { 778 { 779 ttyLocker ttyl; 780 781 // Print out some information that will help us debug the problem 782 tty->print_cr("Wrong number of expression stack elements during deoptimization"); 783 tty->print_cr(" Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1); 784 tty->print_cr(" Fabricated interpreter frame had %d expression stack elements", 785 iframe->interpreter_frame_expression_stack_size()); 786 tty->print_cr(" Interpreter oop map had %d expression stack elements", mask.expression_stack_size()); 787 tty->print_cr(" try_next_mask = %d", try_next_mask); 788 tty->print_cr(" next_mask_expression_stack_size = %d", next_mask_expression_stack_size); 789 tty->print_cr(" callee_size_of_parameters = %d", callee_size_of_parameters); 790 tty->print_cr(" callee_max_locals = %d", callee_max_locals); 791 tty->print_cr(" top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment); 792 tty->print_cr(" exec_mode = %d", exec_mode); 793 tty->print_cr(" cur_invoke_parameter_size = %d", cur_invoke_parameter_size); 794 tty->print_cr(" Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id()); 795 tty->print_cr(" Interpreted frames:"); 796 for (int k = 0; k < cur_array->frames(); k++) { 797 vframeArrayElement* el = cur_array->element(k); 798 tty->print_cr(" %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci()); 799 } 800 cur_array->print_on_2(tty); 801 } // release tty lock before calling guarantee 802 guarantee(false, "wrong number of expression stack elements during deopt"); 803 } 804 VerifyOopClosure verify; 805 iframe->oops_interpreted_do(&verify, &rm, false); 806 callee_size_of_parameters = mh->size_of_parameters(); 807 callee_max_locals = mh->max_locals(); 808 is_top_frame = false; 809 } 810 } 811 #endif /* !PRODUCT */ 812 813 return bt; 814 JRT_END 815 816 class DeoptimizeMarkedClosure : public HandshakeClosure { 817 public: 818 DeoptimizeMarkedClosure() : HandshakeClosure("Deoptimize") {} 819 void do_thread(Thread* thread) { 820 JavaThread* jt = (JavaThread*)thread; 821 jt->deoptimize_marked_methods(); 822 } 823 }; 824 825 void Deoptimization::deoptimize_all_marked(nmethod* nmethod_only) { 826 ResourceMark rm; 827 DeoptimizationMarker dm; 828 829 // Make the dependent methods not entrant 830 if (nmethod_only != NULL) { 831 nmethod_only->mark_for_deoptimization(); 832 nmethod_only->make_not_entrant(); 833 } else { 834 MutexLocker mu(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, Mutex::_no_safepoint_check_flag); 835 CodeCache::make_marked_nmethods_not_entrant(); 836 } 837 838 DeoptimizeMarkedClosure deopt; 839 if (SafepointSynchronize::is_at_safepoint()) { 840 Threads::java_threads_do(&deopt); 841 } else { 842 Handshake::execute(&deopt); 843 } 844 } 845 846 Deoptimization::DeoptAction Deoptimization::_unloaded_action 847 = Deoptimization::Action_reinterpret; 848 849 850 851 #if INCLUDE_JVMCI || INCLUDE_AOT 852 template<typename CacheType> 853 class BoxCacheBase : public CHeapObj<mtCompiler> { 854 protected: 855 static InstanceKlass* find_cache_klass(Symbol* klass_name, TRAPS) { 856 ResourceMark rm; 857 char* klass_name_str = klass_name->as_C_string(); 858 Klass* k = SystemDictionary::find(klass_name, Handle(), Handle(), THREAD); 859 guarantee(k != NULL, "%s must be loaded", klass_name_str); 860 InstanceKlass* ik = InstanceKlass::cast(k); 861 guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str); 862 CacheType::compute_offsets(ik); 863 return ik; 864 } 865 }; 866 867 template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache : public BoxCacheBase<CacheType> { 868 PrimitiveType _low; 869 PrimitiveType _high; 870 jobject _cache; 871 protected: 872 static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton; 873 BoxCache(Thread* thread) { 874 InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(CacheType::symbol(), thread); 875 objArrayOop cache = CacheType::cache(ik); 876 assert(cache->length() > 0, "Empty cache"); 877 _low = BoxType::value(cache->obj_at(0)); 878 _high = _low + cache->length() - 1; 879 _cache = JNIHandles::make_global(Handle(thread, cache)); 880 } 881 ~BoxCache() { 882 JNIHandles::destroy_global(_cache); 883 } 884 public: 885 static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) { 886 if (_singleton == NULL) { 887 BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread); 888 if (!Atomic::replace_if_null(&_singleton, s)) { 889 delete s; 890 } 891 } 892 return _singleton; 893 } 894 oop lookup(PrimitiveType value) { 895 if (_low <= value && value <= _high) { 896 int offset = value - _low; 897 return objArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset); 898 } 899 return NULL; 900 } 901 oop lookup_raw(intptr_t raw_value) { 902 // Have to cast to avoid little/big-endian problems. 903 if (sizeof(PrimitiveType) > sizeof(jint)) { 904 jlong value = (jlong)raw_value; 905 return lookup(value); 906 } 907 PrimitiveType value = (PrimitiveType)*((jint*)&raw_value); 908 return lookup(value); 909 } 910 }; 911 912 typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache; 913 typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache; 914 typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache; 915 typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache; 916 typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache; 917 918 template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = NULL; 919 template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = NULL; 920 template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = NULL; 921 template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = NULL; 922 template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = NULL; 923 924 class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> { 925 jobject _true_cache; 926 jobject _false_cache; 927 protected: 928 static BooleanBoxCache *_singleton; 929 BooleanBoxCache(Thread *thread) { 930 InstanceKlass* ik = find_cache_klass(java_lang_Boolean::symbol(), thread); 931 _true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik))); 932 _false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik))); 933 } 934 ~BooleanBoxCache() { 935 JNIHandles::destroy_global(_true_cache); 936 JNIHandles::destroy_global(_false_cache); 937 } 938 public: 939 static BooleanBoxCache* singleton(Thread* thread) { 940 if (_singleton == NULL) { 941 BooleanBoxCache* s = new BooleanBoxCache(thread); 942 if (!Atomic::replace_if_null(&_singleton, s)) { 943 delete s; 944 } 945 } 946 return _singleton; 947 } 948 oop lookup_raw(intptr_t raw_value) { 949 // Have to cast to avoid little/big-endian problems. 950 jboolean value = (jboolean)*((jint*)&raw_value); 951 return lookup(value); 952 } 953 oop lookup(jboolean value) { 954 if (value != 0) { 955 return JNIHandles::resolve_non_null(_true_cache); 956 } 957 return JNIHandles::resolve_non_null(_false_cache); 958 } 959 }; 960 961 BooleanBoxCache* BooleanBoxCache::_singleton = NULL; 962 963 oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, TRAPS) { 964 Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()()); 965 BasicType box_type = SystemDictionary::box_klass_type(k); 966 if (box_type != T_OBJECT) { 967 StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0)); 968 switch(box_type) { 969 case T_INT: return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 970 case T_CHAR: return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 971 case T_SHORT: return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 972 case T_BYTE: return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 973 case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 974 case T_LONG: return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 975 default:; 976 } 977 } 978 return NULL; 979 } 980 #endif // INCLUDE_JVMCI || INCLUDE_AOT 981 982 #if COMPILER2_OR_JVMCI 983 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) { 984 Handle pending_exception(THREAD, thread->pending_exception()); 985 const char* exception_file = thread->exception_file(); 986 int exception_line = thread->exception_line(); 987 thread->clear_pending_exception(); 988 989 bool failures = false; 990 991 for (int i = 0; i < objects->length(); i++) { 992 assert(objects->at(i)->is_object(), "invalid debug information"); 993 ObjectValue* sv = (ObjectValue*) objects->at(i); 994 995 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()); 996 oop obj = NULL; 997 998 if (k->is_instance_klass()) { 999 #if INCLUDE_JVMCI || INCLUDE_AOT 1000 CompiledMethod* cm = fr->cb()->as_compiled_method_or_null(); 1001 if (cm->is_compiled_by_jvmci() && sv->is_auto_box()) { 1002 AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv; 1003 obj = get_cached_box(abv, fr, reg_map, THREAD); 1004 if (obj != NULL) { 1005 // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it. 1006 abv->set_cached(true); 1007 } 1008 } 1009 #endif // INCLUDE_JVMCI || INCLUDE_AOT 1010 InstanceKlass* ik = InstanceKlass::cast(k); 1011 if (obj == NULL) { 1012 obj = ik->allocate_instance(THREAD); 1013 } 1014 } else if (k->is_typeArray_klass()) { 1015 TypeArrayKlass* ak = TypeArrayKlass::cast(k); 1016 assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length"); 1017 int len = sv->field_size() / type2size[ak->element_type()]; 1018 obj = ak->allocate(len, THREAD); 1019 } else if (k->is_objArray_klass()) { 1020 ObjArrayKlass* ak = ObjArrayKlass::cast(k); 1021 obj = ak->allocate(sv->field_size(), THREAD); 1022 } 1023 1024 if (obj == NULL) { 1025 failures = true; 1026 } 1027 1028 assert(sv->value().is_null(), "redundant reallocation"); 1029 assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception"); 1030 CLEAR_PENDING_EXCEPTION; 1031 sv->set_value(obj); 1032 } 1033 1034 if (failures) { 1035 THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures); 1036 } else if (pending_exception.not_null()) { 1037 thread->set_pending_exception(pending_exception(), exception_file, exception_line); 1038 } 1039 1040 return failures; 1041 } 1042 1043 #if INCLUDE_JVMCI 1044 /** 1045 * For primitive types whose kind gets "erased" at runtime (shorts become stack ints), 1046 * we need to somehow be able to recover the actual kind to be able to write the correct 1047 * amount of bytes. 1048 * For that purpose, this method assumes that, for an entry spanning n bytes at index i, 1049 * the entries at index n + 1 to n + i are 'markers'. 1050 * For example, if we were writing a short at index 4 of a byte array of size 8, the 1051 * expected form of the array would be: 1052 * 1053 * {b0, b1, b2, b3, INT, marker, b6, b7} 1054 * 1055 * Thus, in order to get back the size of the entry, we simply need to count the number 1056 * of marked entries 1057 * 1058 * @param virtualArray the virtualized byte array 1059 * @param i index of the virtual entry we are recovering 1060 * @return The number of bytes the entry spans 1061 */ 1062 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) { 1063 int index = i; 1064 while (++index < virtualArray->field_size() && 1065 virtualArray->field_at(index)->is_marker()) {} 1066 return index - i; 1067 } 1068 1069 /** 1070 * If there was a guarantee for byte array to always start aligned to a long, we could 1071 * do a simple check on the parity of the index. Unfortunately, that is not always the 1072 * case. Thus, we check alignment of the actual address we are writing to. 1073 * In the unlikely case index 0 is 5-aligned for example, it would then be possible to 1074 * write a long to index 3. 1075 */ 1076 static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) { 1077 jbyte* res = obj->byte_at_addr(index); 1078 assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write"); 1079 return res; 1080 } 1081 1082 static void byte_array_put(typeArrayOop obj, intptr_t val, int index, int byte_count) { 1083 switch (byte_count) { 1084 case 1: 1085 obj->byte_at_put(index, (jbyte) *((jint *) &val)); 1086 break; 1087 case 2: 1088 *((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) *((jint *) &val); 1089 break; 1090 case 4: 1091 *((jint *) check_alignment_get_addr(obj, index, 4)) = (jint) *((jint *) &val); 1092 break; 1093 case 8: 1094 *((jlong *) check_alignment_get_addr(obj, index, 8)) = (jlong) *((jlong *) &val); 1095 break; 1096 default: 1097 ShouldNotReachHere(); 1098 } 1099 } 1100 #endif // INCLUDE_JVMCI 1101 1102 1103 // restore elements of an eliminated type array 1104 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) { 1105 int index = 0; 1106 intptr_t val; 1107 1108 for (int i = 0; i < sv->field_size(); i++) { 1109 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i)); 1110 switch(type) { 1111 case T_LONG: case T_DOUBLE: { 1112 assert(value->type() == T_INT, "Agreement."); 1113 StackValue* low = 1114 StackValue::create_stack_value(fr, reg_map, sv->field_at(++i)); 1115 #ifdef _LP64 1116 jlong res = (jlong)low->get_int(); 1117 #else 1118 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); 1119 #endif 1120 obj->long_at_put(index, res); 1121 break; 1122 } 1123 1124 // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem. 1125 case T_INT: case T_FLOAT: { // 4 bytes. 1126 assert(value->type() == T_INT, "Agreement."); 1127 bool big_value = false; 1128 if (i + 1 < sv->field_size() && type == T_INT) { 1129 if (sv->field_at(i)->is_location()) { 1130 Location::Type type = ((LocationValue*) sv->field_at(i))->location().type(); 1131 if (type == Location::dbl || type == Location::lng) { 1132 big_value = true; 1133 } 1134 } else if (sv->field_at(i)->is_constant_int()) { 1135 ScopeValue* next_scope_field = sv->field_at(i + 1); 1136 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) { 1137 big_value = true; 1138 } 1139 } 1140 } 1141 1142 if (big_value) { 1143 StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i)); 1144 #ifdef _LP64 1145 jlong res = (jlong)low->get_int(); 1146 #else 1147 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); 1148 #endif 1149 obj->int_at_put(index, (jint)*((jint*)&res)); 1150 obj->int_at_put(++index, (jint)*(((jint*)&res) + 1)); 1151 } else { 1152 val = value->get_int(); 1153 obj->int_at_put(index, (jint)*((jint*)&val)); 1154 } 1155 break; 1156 } 1157 1158 case T_SHORT: 1159 assert(value->type() == T_INT, "Agreement."); 1160 val = value->get_int(); 1161 obj->short_at_put(index, (jshort)*((jint*)&val)); 1162 break; 1163 1164 case T_CHAR: 1165 assert(value->type() == T_INT, "Agreement."); 1166 val = value->get_int(); 1167 obj->char_at_put(index, (jchar)*((jint*)&val)); 1168 break; 1169 1170 case T_BYTE: { 1171 assert(value->type() == T_INT, "Agreement."); 1172 // The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'. 1173 val = value->get_int(); 1174 #if INCLUDE_JVMCI 1175 int byte_count = count_number_of_bytes_for_entry(sv, i); 1176 byte_array_put(obj, val, index, byte_count); 1177 // According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip. 1178 i += byte_count - 1; // Balance the loop counter. 1179 index += byte_count; 1180 // index has been updated so continue at top of loop 1181 continue; 1182 #else 1183 obj->byte_at_put(index, (jbyte)*((jint*)&val)); 1184 break; 1185 #endif // INCLUDE_JVMCI 1186 } 1187 1188 case T_BOOLEAN: { 1189 assert(value->type() == T_INT, "Agreement."); 1190 val = value->get_int(); 1191 obj->bool_at_put(index, (jboolean)*((jint*)&val)); 1192 break; 1193 } 1194 1195 default: 1196 ShouldNotReachHere(); 1197 } 1198 index++; 1199 } 1200 } 1201 1202 // restore fields of an eliminated object array 1203 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) { 1204 for (int i = 0; i < sv->field_size(); i++) { 1205 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i)); 1206 assert(value->type() == T_OBJECT, "object element expected"); 1207 obj->obj_at_put(i, value->get_obj()()); 1208 } 1209 } 1210 1211 class ReassignedField { 1212 public: 1213 int _offset; 1214 BasicType _type; 1215 public: 1216 ReassignedField() { 1217 _offset = 0; 1218 _type = T_ILLEGAL; 1219 } 1220 }; 1221 1222 int compare(ReassignedField* left, ReassignedField* right) { 1223 return left->_offset - right->_offset; 1224 } 1225 1226 // Restore fields of an eliminated instance object using the same field order 1227 // returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true) 1228 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) { 1229 GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>(); 1230 InstanceKlass* ik = klass; 1231 while (ik != NULL) { 1232 for (AllFieldStream fs(ik); !fs.done(); fs.next()) { 1233 if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) { 1234 ReassignedField field; 1235 field._offset = fs.offset(); 1236 field._type = Signature::basic_type(fs.signature()); 1237 fields->append(field); 1238 } 1239 } 1240 ik = ik->superklass(); 1241 } 1242 fields->sort(compare); 1243 for (int i = 0; i < fields->length(); i++) { 1244 intptr_t val; 1245 ScopeValue* scope_field = sv->field_at(svIndex); 1246 StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field); 1247 int offset = fields->at(i)._offset; 1248 BasicType type = fields->at(i)._type; 1249 switch (type) { 1250 case T_OBJECT: case T_ARRAY: 1251 assert(value->type() == T_OBJECT, "Agreement."); 1252 obj->obj_field_put(offset, value->get_obj()()); 1253 break; 1254 1255 // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem. 1256 case T_INT: case T_FLOAT: { // 4 bytes. 1257 assert(value->type() == T_INT, "Agreement."); 1258 bool big_value = false; 1259 if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) { 1260 if (scope_field->is_location()) { 1261 Location::Type type = ((LocationValue*) scope_field)->location().type(); 1262 if (type == Location::dbl || type == Location::lng) { 1263 big_value = true; 1264 } 1265 } 1266 if (scope_field->is_constant_int()) { 1267 ScopeValue* next_scope_field = sv->field_at(svIndex + 1); 1268 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) { 1269 big_value = true; 1270 } 1271 } 1272 } 1273 1274 if (big_value) { 1275 i++; 1276 assert(i < fields->length(), "second T_INT field needed"); 1277 assert(fields->at(i)._type == T_INT, "T_INT field needed"); 1278 } else { 1279 val = value->get_int(); 1280 obj->int_field_put(offset, (jint)*((jint*)&val)); 1281 break; 1282 } 1283 } 1284 /* no break */ 1285 1286 case T_LONG: case T_DOUBLE: { 1287 assert(value->type() == T_INT, "Agreement."); 1288 StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex)); 1289 #ifdef _LP64 1290 jlong res = (jlong)low->get_int(); 1291 #else 1292 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); 1293 #endif 1294 obj->long_field_put(offset, res); 1295 break; 1296 } 1297 1298 case T_SHORT: 1299 assert(value->type() == T_INT, "Agreement."); 1300 val = value->get_int(); 1301 obj->short_field_put(offset, (jshort)*((jint*)&val)); 1302 break; 1303 1304 case T_CHAR: 1305 assert(value->type() == T_INT, "Agreement."); 1306 val = value->get_int(); 1307 obj->char_field_put(offset, (jchar)*((jint*)&val)); 1308 break; 1309 1310 case T_BYTE: 1311 assert(value->type() == T_INT, "Agreement."); 1312 val = value->get_int(); 1313 obj->byte_field_put(offset, (jbyte)*((jint*)&val)); 1314 break; 1315 1316 case T_BOOLEAN: 1317 assert(value->type() == T_INT, "Agreement."); 1318 val = value->get_int(); 1319 obj->bool_field_put(offset, (jboolean)*((jint*)&val)); 1320 break; 1321 1322 default: 1323 ShouldNotReachHere(); 1324 } 1325 svIndex++; 1326 } 1327 return svIndex; 1328 } 1329 1330 // restore fields of all eliminated objects and arrays 1331 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) { 1332 for (int i = 0; i < objects->length(); i++) { 1333 ObjectValue* sv = (ObjectValue*) objects->at(i); 1334 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()); 1335 Handle obj = sv->value(); 1336 assert(obj.not_null() || realloc_failures, "reallocation was missed"); 1337 if (PrintDeoptimizationDetails) { 1338 tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string()); 1339 } 1340 if (obj.is_null()) { 1341 continue; 1342 } 1343 #if INCLUDE_JVMCI || INCLUDE_AOT 1344 // Don't reassign fields of boxes that came from a cache. Caches may be in CDS. 1345 if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) { 1346 continue; 1347 } 1348 #endif // INCLUDE_JVMCI || INCLUDE_AOT 1349 if (k->is_instance_klass()) { 1350 InstanceKlass* ik = InstanceKlass::cast(k); 1351 reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal); 1352 } else if (k->is_typeArray_klass()) { 1353 TypeArrayKlass* ak = TypeArrayKlass::cast(k); 1354 reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type()); 1355 } else if (k->is_objArray_klass()) { 1356 reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj()); 1357 } 1358 } 1359 } 1360 1361 1362 // relock objects for which synchronization was eliminated 1363 void Deoptimization::relock_objects(GrowableArray<MonitorInfo*>* monitors, JavaThread* thread, bool realloc_failures) { 1364 for (int i = 0; i < monitors->length(); i++) { 1365 MonitorInfo* mon_info = monitors->at(i); 1366 if (mon_info->eliminated()) { 1367 assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed"); 1368 if (!mon_info->owner_is_scalar_replaced()) { 1369 Handle obj(thread, mon_info->owner()); 1370 markWord mark = obj->mark(); 1371 if (UseBiasedLocking && mark.has_bias_pattern()) { 1372 // New allocated objects may have the mark set to anonymously biased. 1373 // Also the deoptimized method may called methods with synchronization 1374 // where the thread-local object is bias locked to the current thread. 1375 assert(mark.is_biased_anonymously() || 1376 mark.biased_locker() == thread, "should be locked to current thread"); 1377 // Reset mark word to unbiased prototype. 1378 markWord unbiased_prototype = markWord::prototype().set_age(mark.age()); 1379 obj->set_mark(unbiased_prototype); 1380 } 1381 BasicLock* lock = mon_info->lock(); 1382 ObjectSynchronizer::enter(obj, lock, thread); 1383 assert(mon_info->owner()->is_locked(), "object must be locked now"); 1384 } 1385 } 1386 } 1387 } 1388 1389 1390 #ifndef PRODUCT 1391 // print information about reallocated objects 1392 void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) { 1393 fieldDescriptor fd; 1394 1395 for (int i = 0; i < objects->length(); i++) { 1396 ObjectValue* sv = (ObjectValue*) objects->at(i); 1397 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()); 1398 Handle obj = sv->value(); 1399 1400 tty->print(" object <" INTPTR_FORMAT "> of type ", p2i(sv->value()())); 1401 k->print_value(); 1402 assert(obj.not_null() || realloc_failures, "reallocation was missed"); 1403 if (obj.is_null()) { 1404 tty->print(" allocation failed"); 1405 } else { 1406 tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize); 1407 } 1408 tty->cr(); 1409 1410 if (Verbose && !obj.is_null()) { 1411 k->oop_print_on(obj(), tty); 1412 } 1413 } 1414 } 1415 #endif 1416 #endif // COMPILER2_OR_JVMCI 1417 1418 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) { 1419 Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp())); 1420 1421 #ifndef PRODUCT 1422 if (PrintDeoptimizationDetails) { 1423 ttyLocker ttyl; 1424 tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", p2i(thread)); 1425 fr.print_on(tty); 1426 tty->print_cr(" Virtual frames (innermost first):"); 1427 for (int index = 0; index < chunk->length(); index++) { 1428 compiledVFrame* vf = chunk->at(index); 1429 tty->print(" %2d - ", index); 1430 vf->print_value(); 1431 int bci = chunk->at(index)->raw_bci(); 1432 const char* code_name; 1433 if (bci == SynchronizationEntryBCI) { 1434 code_name = "sync entry"; 1435 } else { 1436 Bytecodes::Code code = vf->method()->code_at(bci); 1437 code_name = Bytecodes::name(code); 1438 } 1439 tty->print(" - %s", code_name); 1440 tty->print_cr(" @ bci %d ", bci); 1441 if (Verbose) { 1442 vf->print(); 1443 tty->cr(); 1444 } 1445 } 1446 } 1447 #endif 1448 1449 // Register map for next frame (used for stack crawl). We capture 1450 // the state of the deopt'ing frame's caller. Thus if we need to 1451 // stuff a C2I adapter we can properly fill in the callee-save 1452 // register locations. 1453 frame caller = fr.sender(reg_map); 1454 int frame_size = caller.sp() - fr.sp(); 1455 1456 frame sender = caller; 1457 1458 // Since the Java thread being deoptimized will eventually adjust it's own stack, 1459 // the vframeArray containing the unpacking information is allocated in the C heap. 1460 // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames(). 1461 vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures); 1462 1463 // Compare the vframeArray to the collected vframes 1464 assert(array->structural_compare(thread, chunk), "just checking"); 1465 1466 #ifndef PRODUCT 1467 if (PrintDeoptimizationDetails) { 1468 ttyLocker ttyl; 1469 tty->print_cr(" Created vframeArray " INTPTR_FORMAT, p2i(array)); 1470 } 1471 #endif // PRODUCT 1472 1473 return array; 1474 } 1475 1476 #if COMPILER2_OR_JVMCI 1477 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) { 1478 // Reallocation of some scalar replaced objects failed. Record 1479 // that we need to pop all the interpreter frames for the 1480 // deoptimized compiled frame. 1481 assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?"); 1482 thread->set_frames_to_pop_failed_realloc(array->frames()); 1483 // Unlock all monitors here otherwise the interpreter will see a 1484 // mix of locked and unlocked monitors (because of failed 1485 // reallocations of synchronized objects) and be confused. 1486 for (int i = 0; i < array->frames(); i++) { 1487 MonitorChunk* monitors = array->element(i)->monitors(); 1488 if (monitors != NULL) { 1489 for (int j = 0; j < monitors->number_of_monitors(); j++) { 1490 BasicObjectLock* src = monitors->at(j); 1491 if (src->obj() != NULL) { 1492 ObjectSynchronizer::exit(src->obj(), src->lock(), thread); 1493 } 1494 } 1495 array->element(i)->free_monitors(thread); 1496 #ifdef ASSERT 1497 array->element(i)->set_removed_monitors(); 1498 #endif 1499 } 1500 } 1501 } 1502 #endif 1503 1504 static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke) { 1505 GrowableArray<MonitorInfo*>* monitors = cvf->monitors(); 1506 Thread* thread = Thread::current(); 1507 for (int i = 0; i < monitors->length(); i++) { 1508 MonitorInfo* mon_info = monitors->at(i); 1509 if (!mon_info->eliminated() && mon_info->owner() != NULL) { 1510 objects_to_revoke->append(Handle(thread, mon_info->owner())); 1511 } 1512 } 1513 } 1514 1515 static void get_monitors_from_stack(GrowableArray<Handle>* objects_to_revoke, JavaThread* thread, frame fr, RegisterMap* map) { 1516 // Unfortunately we don't have a RegisterMap available in most of 1517 // the places we want to call this routine so we need to walk the 1518 // stack again to update the register map. 1519 if (map == NULL || !map->update_map()) { 1520 StackFrameStream sfs(thread, true); 1521 bool found = false; 1522 while (!found && !sfs.is_done()) { 1523 frame* cur = sfs.current(); 1524 sfs.next(); 1525 found = cur->id() == fr.id(); 1526 } 1527 assert(found, "frame to be deoptimized not found on target thread's stack"); 1528 map = sfs.register_map(); 1529 } 1530 1531 vframe* vf = vframe::new_vframe(&fr, map, thread); 1532 compiledVFrame* cvf = compiledVFrame::cast(vf); 1533 // Revoke monitors' biases in all scopes 1534 while (!cvf->is_top()) { 1535 collect_monitors(cvf, objects_to_revoke); 1536 cvf = compiledVFrame::cast(cvf->sender()); 1537 } 1538 collect_monitors(cvf, objects_to_revoke); 1539 } 1540 1541 void Deoptimization::revoke_from_deopt_handler(JavaThread* thread, frame fr, RegisterMap* map) { 1542 if (!UseBiasedLocking) { 1543 return; 1544 } 1545 GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>(); 1546 get_monitors_from_stack(objects_to_revoke, thread, fr, map); 1547 1548 int len = objects_to_revoke->length(); 1549 for (int i = 0; i < len; i++) { 1550 oop obj = (objects_to_revoke->at(i))(); 1551 BiasedLocking::revoke_own_lock(objects_to_revoke->at(i), thread); 1552 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 1553 } 1554 } 1555 1556 1557 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) { 1558 assert(fr.can_be_deoptimized(), "checking frame type"); 1559 1560 gather_statistics(reason, Action_none, Bytecodes::_illegal); 1561 1562 if (LogCompilation && xtty != NULL) { 1563 CompiledMethod* cm = fr.cb()->as_compiled_method_or_null(); 1564 assert(cm != NULL, "only compiled methods can deopt"); 1565 1566 ttyLocker ttyl; 1567 xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc())); 1568 cm->log_identity(xtty); 1569 xtty->end_head(); 1570 for (ScopeDesc* sd = cm->scope_desc_at(fr.pc()); ; sd = sd->sender()) { 1571 xtty->begin_elem("jvms bci='%d'", sd->bci()); 1572 xtty->method(sd->method()); 1573 xtty->end_elem(); 1574 if (sd->is_top()) break; 1575 } 1576 xtty->tail("deoptimized"); 1577 } 1578 1579 // Patch the compiled method so that when execution returns to it we will 1580 // deopt the execution state and return to the interpreter. 1581 fr.deoptimize(thread); 1582 } 1583 1584 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) { 1585 // Deoptimize only if the frame comes from compile code. 1586 // Do not deoptimize the frame which is already patched 1587 // during the execution of the loops below. 1588 if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) { 1589 return; 1590 } 1591 ResourceMark rm; 1592 DeoptimizationMarker dm; 1593 deoptimize_single_frame(thread, fr, reason); 1594 } 1595 1596 #if INCLUDE_JVMCI 1597 address Deoptimization::deoptimize_for_missing_exception_handler(CompiledMethod* cm) { 1598 // there is no exception handler for this pc => deoptimize 1599 cm->make_not_entrant(); 1600 1601 // Use Deoptimization::deoptimize for all of its side-effects: 1602 // gathering traps statistics, logging... 1603 // it also patches the return pc but we do not care about that 1604 // since we return a continuation to the deopt_blob below. 1605 JavaThread* thread = JavaThread::current(); 1606 RegisterMap reg_map(thread, false); 1607 frame runtime_frame = thread->last_frame(); 1608 frame caller_frame = runtime_frame.sender(®_map); 1609 assert(caller_frame.cb()->as_compiled_method_or_null() == cm, "expect top frame compiled method"); 1610 Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler); 1611 1612 MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, cm->method()), true); 1613 if (trap_mdo != NULL) { 1614 trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler); 1615 } 1616 1617 return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls(); 1618 } 1619 #endif 1620 1621 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) { 1622 assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(), 1623 "can only deoptimize other thread at a safepoint"); 1624 // Compute frame and register map based on thread and sp. 1625 RegisterMap reg_map(thread, false); 1626 frame fr = thread->last_frame(); 1627 while (fr.id() != id) { 1628 fr = fr.sender(®_map); 1629 } 1630 deoptimize(thread, fr, reason); 1631 } 1632 1633 1634 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) { 1635 if (thread == Thread::current()) { 1636 Deoptimization::deoptimize_frame_internal(thread, id, reason); 1637 } else { 1638 VM_DeoptimizeFrame deopt(thread, id, reason); 1639 VMThread::execute(&deopt); 1640 } 1641 } 1642 1643 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) { 1644 deoptimize_frame(thread, id, Reason_constraint); 1645 } 1646 1647 // JVMTI PopFrame support 1648 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address)) 1649 { 1650 thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address); 1651 } 1652 JRT_END 1653 1654 MethodData* 1655 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m, 1656 bool create_if_missing) { 1657 Thread* THREAD = thread; 1658 MethodData* mdo = m()->method_data(); 1659 if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) { 1660 // Build an MDO. Ignore errors like OutOfMemory; 1661 // that simply means we won't have an MDO to update. 1662 Method::build_interpreter_method_data(m, THREAD); 1663 if (HAS_PENDING_EXCEPTION) { 1664 assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here"); 1665 CLEAR_PENDING_EXCEPTION; 1666 } 1667 mdo = m()->method_data(); 1668 } 1669 return mdo; 1670 } 1671 1672 #if COMPILER2_OR_JVMCI 1673 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) { 1674 // In case of an unresolved klass entry, load the class. 1675 // This path is exercised from case _ldc in Parse::do_one_bytecode, 1676 // and probably nowhere else. 1677 // Even that case would benefit from simply re-interpreting the 1678 // bytecode, without paying special attention to the class index. 1679 // So this whole "class index" feature should probably be removed. 1680 1681 if (constant_pool->tag_at(index).is_unresolved_klass()) { 1682 Klass* tk = constant_pool->klass_at_ignore_error(index, CHECK); 1683 return; 1684 } 1685 1686 assert(!constant_pool->tag_at(index).is_symbol(), 1687 "no symbolic names here, please"); 1688 } 1689 1690 1691 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index) { 1692 EXCEPTION_MARK; 1693 load_class_by_index(constant_pool, index, THREAD); 1694 if (HAS_PENDING_EXCEPTION) { 1695 // Exception happened during classloading. We ignore the exception here, since it 1696 // is going to be rethrown since the current activation is going to be deoptimized and 1697 // the interpreter will re-execute the bytecode. 1698 CLEAR_PENDING_EXCEPTION; 1699 // Class loading called java code which may have caused a stack 1700 // overflow. If the exception was thrown right before the return 1701 // to the runtime the stack is no longer guarded. Reguard the 1702 // stack otherwise if we return to the uncommon trap blob and the 1703 // stack bang causes a stack overflow we crash. 1704 assert(THREAD->is_Java_thread(), "only a java thread can be here"); 1705 JavaThread* thread = (JavaThread*)THREAD; 1706 bool guard_pages_enabled = thread->stack_guards_enabled(); 1707 if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack(); 1708 assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash"); 1709 } 1710 } 1711 1712 #if INCLUDE_JFR 1713 1714 class DeoptReasonSerializer : public JfrSerializer { 1715 public: 1716 void serialize(JfrCheckpointWriter& writer) { 1717 writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1) 1718 for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) { 1719 writer.write_key((u8)i); 1720 writer.write(Deoptimization::trap_reason_name(i)); 1721 } 1722 } 1723 }; 1724 1725 class DeoptActionSerializer : public JfrSerializer { 1726 public: 1727 void serialize(JfrCheckpointWriter& writer) { 1728 static const u4 nof_actions = Deoptimization::Action_LIMIT; 1729 writer.write_count(nof_actions); 1730 for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) { 1731 writer.write_key(i); 1732 writer.write(Deoptimization::trap_action_name((int)i)); 1733 } 1734 } 1735 }; 1736 1737 static void register_serializers() { 1738 static int critical_section = 0; 1739 if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) { 1740 return; 1741 } 1742 JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer()); 1743 JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer()); 1744 } 1745 1746 static void post_deoptimization_event(CompiledMethod* nm, 1747 const Method* method, 1748 int trap_bci, 1749 int instruction, 1750 Deoptimization::DeoptReason reason, 1751 Deoptimization::DeoptAction action) { 1752 assert(nm != NULL, "invariant"); 1753 assert(method != NULL, "invariant"); 1754 if (EventDeoptimization::is_enabled()) { 1755 static bool serializers_registered = false; 1756 if (!serializers_registered) { 1757 register_serializers(); 1758 serializers_registered = true; 1759 } 1760 EventDeoptimization event; 1761 event.set_compileId(nm->compile_id()); 1762 event.set_compiler(nm->compiler_type()); 1763 event.set_method(method); 1764 event.set_lineNumber(method->line_number_from_bci(trap_bci)); 1765 event.set_bci(trap_bci); 1766 event.set_instruction(instruction); 1767 event.set_reason(reason); 1768 event.set_action(action); 1769 event.commit(); 1770 } 1771 } 1772 1773 #endif // INCLUDE_JFR 1774 1775 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) { 1776 HandleMark hm; 1777 1778 // uncommon_trap() is called at the beginning of the uncommon trap 1779 // handler. Note this fact before we start generating temporary frames 1780 // that can confuse an asynchronous stack walker. This counter is 1781 // decremented at the end of unpack_frames(). 1782 thread->inc_in_deopt_handler(); 1783 1784 // We need to update the map if we have biased locking. 1785 #if INCLUDE_JVMCI 1786 // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid 1787 RegisterMap reg_map(thread, true); 1788 #else 1789 RegisterMap reg_map(thread, UseBiasedLocking); 1790 #endif 1791 frame stub_frame = thread->last_frame(); 1792 frame fr = stub_frame.sender(®_map); 1793 // Make sure the calling nmethod is not getting deoptimized and removed 1794 // before we are done with it. 1795 nmethodLocker nl(fr.pc()); 1796 1797 // Log a message 1798 Events::log_deopt_message(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT, 1799 trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin()); 1800 1801 { 1802 ResourceMark rm; 1803 1804 DeoptReason reason = trap_request_reason(trap_request); 1805 DeoptAction action = trap_request_action(trap_request); 1806 #if INCLUDE_JVMCI 1807 int debug_id = trap_request_debug_id(trap_request); 1808 #endif 1809 jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1 1810 1811 vframe* vf = vframe::new_vframe(&fr, ®_map, thread); 1812 compiledVFrame* cvf = compiledVFrame::cast(vf); 1813 1814 CompiledMethod* nm = cvf->code(); 1815 1816 ScopeDesc* trap_scope = cvf->scope(); 1817 1818 if (TraceDeoptimization) { 1819 ttyLocker ttyl; 1820 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() 1821 #if INCLUDE_JVMCI 1822 , debug_id 1823 #endif 1824 ); 1825 } 1826 1827 methodHandle trap_method(THREAD, trap_scope->method()); 1828 int trap_bci = trap_scope->bci(); 1829 #if INCLUDE_JVMCI 1830 jlong speculation = thread->pending_failed_speculation(); 1831 if (nm->is_compiled_by_jvmci() && nm->is_nmethod()) { // Exclude AOTed methods 1832 nm->as_nmethod()->update_speculation(thread); 1833 } else { 1834 assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers"); 1835 } 1836 1837 if (trap_bci == SynchronizationEntryBCI) { 1838 trap_bci = 0; 1839 thread->set_pending_monitorenter(true); 1840 } 1841 1842 if (reason == Deoptimization::Reason_transfer_to_interpreter) { 1843 thread->set_pending_transfer_to_interpreter(true); 1844 } 1845 #endif 1846 1847 Bytecodes::Code trap_bc = trap_method->java_code_at(trap_bci); 1848 // Record this event in the histogram. 1849 gather_statistics(reason, action, trap_bc); 1850 1851 // Ensure that we can record deopt. history: 1852 // Need MDO to record RTM code generation state. 1853 bool create_if_missing = ProfileTraps || UseCodeAging RTM_OPT_ONLY( || UseRTMLocking ); 1854 1855 methodHandle profiled_method; 1856 #if INCLUDE_JVMCI 1857 if (nm->is_compiled_by_jvmci()) { 1858 profiled_method = methodHandle(THREAD, nm->method()); 1859 } else { 1860 profiled_method = trap_method; 1861 } 1862 #else 1863 profiled_method = trap_method; 1864 #endif 1865 1866 MethodData* trap_mdo = 1867 get_method_data(thread, profiled_method, create_if_missing); 1868 1869 JFR_ONLY(post_deoptimization_event(nm, trap_method(), trap_bci, trap_bc, reason, action);) 1870 1871 // Log a message 1872 Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s", 1873 trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()), 1874 trap_method->name_and_sig_as_C_string(), trap_bci, nm->compiler_name()); 1875 1876 // Print a bunch of diagnostics, if requested. 1877 if (TraceDeoptimization || LogCompilation) { 1878 ResourceMark rm; 1879 ttyLocker ttyl; 1880 char buf[100]; 1881 if (xtty != NULL) { 1882 xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s", 1883 os::current_thread_id(), 1884 format_trap_request(buf, sizeof(buf), trap_request)); 1885 #if INCLUDE_JVMCI 1886 if (speculation != 0) { 1887 xtty->print(" speculation='" JLONG_FORMAT "'", speculation); 1888 } 1889 #endif 1890 nm->log_identity(xtty); 1891 } 1892 Symbol* class_name = NULL; 1893 bool unresolved = false; 1894 if (unloaded_class_index >= 0) { 1895 constantPoolHandle constants (THREAD, trap_method->constants()); 1896 if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) { 1897 class_name = constants->klass_name_at(unloaded_class_index); 1898 unresolved = true; 1899 if (xtty != NULL) 1900 xtty->print(" unresolved='1'"); 1901 } else if (constants->tag_at(unloaded_class_index).is_symbol()) { 1902 class_name = constants->symbol_at(unloaded_class_index); 1903 } 1904 if (xtty != NULL) 1905 xtty->name(class_name); 1906 } 1907 if (xtty != NULL && trap_mdo != NULL && (int)reason < (int)MethodData::_trap_hist_limit) { 1908 // Dump the relevant MDO state. 1909 // This is the deopt count for the current reason, any previous 1910 // reasons or recompiles seen at this point. 1911 int dcnt = trap_mdo->trap_count(reason); 1912 if (dcnt != 0) 1913 xtty->print(" count='%d'", dcnt); 1914 ProfileData* pdata = trap_mdo->bci_to_data(trap_bci); 1915 int dos = (pdata == NULL)? 0: pdata->trap_state(); 1916 if (dos != 0) { 1917 xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos)); 1918 if (trap_state_is_recompiled(dos)) { 1919 int recnt2 = trap_mdo->overflow_recompile_count(); 1920 if (recnt2 != 0) 1921 xtty->print(" recompiles2='%d'", recnt2); 1922 } 1923 } 1924 } 1925 if (xtty != NULL) { 1926 xtty->stamp(); 1927 xtty->end_head(); 1928 } 1929 if (TraceDeoptimization) { // make noise on the tty 1930 tty->print("Uncommon trap occurred in"); 1931 nm->method()->print_short_name(tty); 1932 tty->print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id()); 1933 #if INCLUDE_JVMCI 1934 if (nm->is_nmethod()) { 1935 const char* installed_code_name = nm->as_nmethod()->jvmci_name(); 1936 if (installed_code_name != NULL) { 1937 tty->print(" (JVMCI: installed code name=%s) ", installed_code_name); 1938 } 1939 } 1940 #endif 1941 tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"), 1942 p2i(fr.pc()), 1943 os::current_thread_id(), 1944 trap_reason_name(reason), 1945 trap_action_name(action), 1946 unloaded_class_index 1947 #if INCLUDE_JVMCI 1948 , debug_id 1949 #endif 1950 ); 1951 if (class_name != NULL) { 1952 tty->print(unresolved ? " unresolved class: " : " symbol: "); 1953 class_name->print_symbol_on(tty); 1954 } 1955 tty->cr(); 1956 } 1957 if (xtty != NULL) { 1958 // Log the precise location of the trap. 1959 for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) { 1960 xtty->begin_elem("jvms bci='%d'", sd->bci()); 1961 xtty->method(sd->method()); 1962 xtty->end_elem(); 1963 if (sd->is_top()) break; 1964 } 1965 xtty->tail("uncommon_trap"); 1966 } 1967 } 1968 // (End diagnostic printout.) 1969 1970 // Load class if necessary 1971 if (unloaded_class_index >= 0) { 1972 constantPoolHandle constants(THREAD, trap_method->constants()); 1973 load_class_by_index(constants, unloaded_class_index); 1974 } 1975 1976 // Flush the nmethod if necessary and desirable. 1977 // 1978 // We need to avoid situations where we are re-flushing the nmethod 1979 // because of a hot deoptimization site. Repeated flushes at the same 1980 // point need to be detected by the compiler and avoided. If the compiler 1981 // cannot avoid them (or has a bug and "refuses" to avoid them), this 1982 // module must take measures to avoid an infinite cycle of recompilation 1983 // and deoptimization. There are several such measures: 1984 // 1985 // 1. If a recompilation is ordered a second time at some site X 1986 // and for the same reason R, the action is adjusted to 'reinterpret', 1987 // to give the interpreter time to exercise the method more thoroughly. 1988 // If this happens, the method's overflow_recompile_count is incremented. 1989 // 1990 // 2. If the compiler fails to reduce the deoptimization rate, then 1991 // the method's overflow_recompile_count will begin to exceed the set 1992 // limit PerBytecodeRecompilationCutoff. If this happens, the action 1993 // is adjusted to 'make_not_compilable', and the method is abandoned 1994 // to the interpreter. This is a performance hit for hot methods, 1995 // but is better than a disastrous infinite cycle of recompilations. 1996 // (Actually, only the method containing the site X is abandoned.) 1997 // 1998 // 3. In parallel with the previous measures, if the total number of 1999 // recompilations of a method exceeds the much larger set limit 2000 // PerMethodRecompilationCutoff, the method is abandoned. 2001 // This should only happen if the method is very large and has 2002 // many "lukewarm" deoptimizations. The code which enforces this 2003 // limit is elsewhere (class nmethod, class Method). 2004 // 2005 // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance 2006 // to recompile at each bytecode independently of the per-BCI cutoff. 2007 // 2008 // The decision to update code is up to the compiler, and is encoded 2009 // in the Action_xxx code. If the compiler requests Action_none 2010 // no trap state is changed, no compiled code is changed, and the 2011 // computation suffers along in the interpreter. 2012 // 2013 // The other action codes specify various tactics for decompilation 2014 // and recompilation. Action_maybe_recompile is the loosest, and 2015 // allows the compiled code to stay around until enough traps are seen, 2016 // and until the compiler gets around to recompiling the trapping method. 2017 // 2018 // The other actions cause immediate removal of the present code. 2019 2020 // Traps caused by injected profile shouldn't pollute trap counts. 2021 bool injected_profile_trap = trap_method->has_injected_profile() && 2022 (reason == Reason_intrinsic || reason == Reason_unreached); 2023 2024 bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap; 2025 bool make_not_entrant = false; 2026 bool make_not_compilable = false; 2027 bool reprofile = false; 2028 switch (action) { 2029 case Action_none: 2030 // Keep the old code. 2031 update_trap_state = false; 2032 break; 2033 case Action_maybe_recompile: 2034 // Do not need to invalidate the present code, but we can 2035 // initiate another 2036 // Start compiler without (necessarily) invalidating the nmethod. 2037 // The system will tolerate the old code, but new code should be 2038 // generated when possible. 2039 break; 2040 case Action_reinterpret: 2041 // Go back into the interpreter for a while, and then consider 2042 // recompiling form scratch. 2043 make_not_entrant = true; 2044 // Reset invocation counter for outer most method. 2045 // This will allow the interpreter to exercise the bytecodes 2046 // for a while before recompiling. 2047 // By contrast, Action_make_not_entrant is immediate. 2048 // 2049 // Note that the compiler will track null_check, null_assert, 2050 // range_check, and class_check events and log them as if they 2051 // had been traps taken from compiled code. This will update 2052 // the MDO trap history so that the next compilation will 2053 // properly detect hot trap sites. 2054 reprofile = true; 2055 break; 2056 case Action_make_not_entrant: 2057 // Request immediate recompilation, and get rid of the old code. 2058 // Make them not entrant, so next time they are called they get 2059 // recompiled. Unloaded classes are loaded now so recompile before next 2060 // time they are called. Same for uninitialized. The interpreter will 2061 // link the missing class, if any. 2062 make_not_entrant = true; 2063 break; 2064 case Action_make_not_compilable: 2065 // Give up on compiling this method at all. 2066 make_not_entrant = true; 2067 make_not_compilable = true; 2068 break; 2069 default: 2070 ShouldNotReachHere(); 2071 } 2072 2073 // Setting +ProfileTraps fixes the following, on all platforms: 2074 // 4852688: ProfileInterpreter is off by default for ia64. The result is 2075 // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the 2076 // recompile relies on a MethodData* to record heroic opt failures. 2077 2078 // Whether the interpreter is producing MDO data or not, we also need 2079 // to use the MDO to detect hot deoptimization points and control 2080 // aggressive optimization. 2081 bool inc_recompile_count = false; 2082 ProfileData* pdata = NULL; 2083 if (ProfileTraps && !is_client_compilation_mode_vm() && update_trap_state && trap_mdo != NULL) { 2084 assert(trap_mdo == get_method_data(thread, profiled_method, false), "sanity"); 2085 uint this_trap_count = 0; 2086 bool maybe_prior_trap = false; 2087 bool maybe_prior_recompile = false; 2088 pdata = query_update_method_data(trap_mdo, trap_bci, reason, true, 2089 #if INCLUDE_JVMCI 2090 nm->is_compiled_by_jvmci() && nm->is_osr_method(), 2091 #endif 2092 nm->method(), 2093 //outputs: 2094 this_trap_count, 2095 maybe_prior_trap, 2096 maybe_prior_recompile); 2097 // Because the interpreter also counts null, div0, range, and class 2098 // checks, these traps from compiled code are double-counted. 2099 // This is harmless; it just means that the PerXTrapLimit values 2100 // are in effect a little smaller than they look. 2101 2102 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason); 2103 if (per_bc_reason != Reason_none) { 2104 // Now take action based on the partially known per-BCI history. 2105 if (maybe_prior_trap 2106 && this_trap_count >= (uint)PerBytecodeTrapLimit) { 2107 // If there are too many traps at this BCI, force a recompile. 2108 // This will allow the compiler to see the limit overflow, and 2109 // take corrective action, if possible. The compiler generally 2110 // does not use the exact PerBytecodeTrapLimit value, but instead 2111 // changes its tactics if it sees any traps at all. This provides 2112 // a little hysteresis, delaying a recompile until a trap happens 2113 // several times. 2114 // 2115 // Actually, since there is only one bit of counter per BCI, 2116 // the possible per-BCI counts are {0,1,(per-method count)}. 2117 // This produces accurate results if in fact there is only 2118 // one hot trap site, but begins to get fuzzy if there are 2119 // many sites. For example, if there are ten sites each 2120 // trapping two or more times, they each get the blame for 2121 // all of their traps. 2122 make_not_entrant = true; 2123 } 2124 2125 // Detect repeated recompilation at the same BCI, and enforce a limit. 2126 if (make_not_entrant && maybe_prior_recompile) { 2127 // More than one recompile at this point. 2128 inc_recompile_count = maybe_prior_trap; 2129 } 2130 } else { 2131 // For reasons which are not recorded per-bytecode, we simply 2132 // force recompiles unconditionally. 2133 // (Note that PerMethodRecompilationCutoff is enforced elsewhere.) 2134 make_not_entrant = true; 2135 } 2136 2137 // Go back to the compiler if there are too many traps in this method. 2138 if (this_trap_count >= per_method_trap_limit(reason)) { 2139 // If there are too many traps in this method, force a recompile. 2140 // This will allow the compiler to see the limit overflow, and 2141 // take corrective action, if possible. 2142 // (This condition is an unlikely backstop only, because the 2143 // PerBytecodeTrapLimit is more likely to take effect first, 2144 // if it is applicable.) 2145 make_not_entrant = true; 2146 } 2147 2148 // Here's more hysteresis: If there has been a recompile at 2149 // this trap point already, run the method in the interpreter 2150 // for a while to exercise it more thoroughly. 2151 if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) { 2152 reprofile = true; 2153 } 2154 } 2155 2156 // Take requested actions on the method: 2157 2158 // Recompile 2159 if (make_not_entrant) { 2160 if (!nm->make_not_entrant()) { 2161 return; // the call did not change nmethod's state 2162 } 2163 2164 if (pdata != NULL) { 2165 // Record the recompilation event, if any. 2166 int tstate0 = pdata->trap_state(); 2167 int tstate1 = trap_state_set_recompiled(tstate0, true); 2168 if (tstate1 != tstate0) 2169 pdata->set_trap_state(tstate1); 2170 } 2171 2172 #if INCLUDE_RTM_OPT 2173 // Restart collecting RTM locking abort statistic if the method 2174 // is recompiled for a reason other than RTM state change. 2175 // Assume that in new recompiled code the statistic could be different, 2176 // for example, due to different inlining. 2177 if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) && 2178 UseRTMDeopt && (nm->as_nmethod()->rtm_state() != ProfileRTM)) { 2179 trap_mdo->atomic_set_rtm_state(ProfileRTM); 2180 } 2181 #endif 2182 // For code aging we count traps separately here, using make_not_entrant() 2183 // as a guard against simultaneous deopts in multiple threads. 2184 if (reason == Reason_tenured && trap_mdo != NULL) { 2185 trap_mdo->inc_tenure_traps(); 2186 } 2187 } 2188 2189 if (inc_recompile_count) { 2190 trap_mdo->inc_overflow_recompile_count(); 2191 if ((uint)trap_mdo->overflow_recompile_count() > 2192 (uint)PerBytecodeRecompilationCutoff) { 2193 // Give up on the method containing the bad BCI. 2194 if (trap_method() == nm->method()) { 2195 make_not_compilable = true; 2196 } else { 2197 trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization); 2198 // But give grace to the enclosing nm->method(). 2199 } 2200 } 2201 } 2202 2203 // Reprofile 2204 if (reprofile) { 2205 CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method()); 2206 } 2207 2208 // Give up compiling 2209 if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) { 2210 assert(make_not_entrant, "consistent"); 2211 nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization); 2212 } 2213 2214 } // Free marked resources 2215 2216 } 2217 JRT_END 2218 2219 ProfileData* 2220 Deoptimization::query_update_method_data(MethodData* trap_mdo, 2221 int trap_bci, 2222 Deoptimization::DeoptReason reason, 2223 bool update_total_trap_count, 2224 #if INCLUDE_JVMCI 2225 bool is_osr, 2226 #endif 2227 Method* compiled_method, 2228 //outputs: 2229 uint& ret_this_trap_count, 2230 bool& ret_maybe_prior_trap, 2231 bool& ret_maybe_prior_recompile) { 2232 bool maybe_prior_trap = false; 2233 bool maybe_prior_recompile = false; 2234 uint this_trap_count = 0; 2235 if (update_total_trap_count) { 2236 uint idx = reason; 2237 #if INCLUDE_JVMCI 2238 if (is_osr) { 2239 idx += Reason_LIMIT; 2240 } 2241 #endif 2242 uint prior_trap_count = trap_mdo->trap_count(idx); 2243 this_trap_count = trap_mdo->inc_trap_count(idx); 2244 2245 // If the runtime cannot find a place to store trap history, 2246 // it is estimated based on the general condition of the method. 2247 // If the method has ever been recompiled, or has ever incurred 2248 // a trap with the present reason , then this BCI is assumed 2249 // (pessimistically) to be the culprit. 2250 maybe_prior_trap = (prior_trap_count != 0); 2251 maybe_prior_recompile = (trap_mdo->decompile_count() != 0); 2252 } 2253 ProfileData* pdata = NULL; 2254 2255 2256 // For reasons which are recorded per bytecode, we check per-BCI data. 2257 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason); 2258 assert(per_bc_reason != Reason_none || update_total_trap_count, "must be"); 2259 if (per_bc_reason != Reason_none) { 2260 // Find the profile data for this BCI. If there isn't one, 2261 // try to allocate one from the MDO's set of spares. 2262 // This will let us detect a repeated trap at this point. 2263 pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL); 2264 2265 if (pdata != NULL) { 2266 if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) { 2267 if (LogCompilation && xtty != NULL) { 2268 ttyLocker ttyl; 2269 // no more room for speculative traps in this MDO 2270 xtty->elem("speculative_traps_oom"); 2271 } 2272 } 2273 // Query the trap state of this profile datum. 2274 int tstate0 = pdata->trap_state(); 2275 if (!trap_state_has_reason(tstate0, per_bc_reason)) 2276 maybe_prior_trap = false; 2277 if (!trap_state_is_recompiled(tstate0)) 2278 maybe_prior_recompile = false; 2279 2280 // Update the trap state of this profile datum. 2281 int tstate1 = tstate0; 2282 // Record the reason. 2283 tstate1 = trap_state_add_reason(tstate1, per_bc_reason); 2284 // Store the updated state on the MDO, for next time. 2285 if (tstate1 != tstate0) 2286 pdata->set_trap_state(tstate1); 2287 } else { 2288 if (LogCompilation && xtty != NULL) { 2289 ttyLocker ttyl; 2290 // Missing MDP? Leave a small complaint in the log. 2291 xtty->elem("missing_mdp bci='%d'", trap_bci); 2292 } 2293 } 2294 } 2295 2296 // Return results: 2297 ret_this_trap_count = this_trap_count; 2298 ret_maybe_prior_trap = maybe_prior_trap; 2299 ret_maybe_prior_recompile = maybe_prior_recompile; 2300 return pdata; 2301 } 2302 2303 void 2304 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) { 2305 ResourceMark rm; 2306 // Ignored outputs: 2307 uint ignore_this_trap_count; 2308 bool ignore_maybe_prior_trap; 2309 bool ignore_maybe_prior_recompile; 2310 assert(!reason_is_speculate(reason), "reason speculate only used by compiler"); 2311 // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts 2312 bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler); 2313 query_update_method_data(trap_mdo, trap_bci, 2314 (DeoptReason)reason, 2315 update_total_counts, 2316 #if INCLUDE_JVMCI 2317 false, 2318 #endif 2319 NULL, 2320 ignore_this_trap_count, 2321 ignore_maybe_prior_trap, 2322 ignore_maybe_prior_recompile); 2323 } 2324 2325 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request, jint exec_mode) { 2326 if (TraceDeoptimization) { 2327 tty->print("Uncommon trap "); 2328 } 2329 // Still in Java no safepoints 2330 { 2331 // This enters VM and may safepoint 2332 uncommon_trap_inner(thread, trap_request); 2333 } 2334 return fetch_unroll_info_helper(thread, exec_mode); 2335 } 2336 2337 // Local derived constants. 2338 // Further breakdown of DataLayout::trap_state, as promised by DataLayout. 2339 const int DS_REASON_MASK = ((uint)DataLayout::trap_mask) >> 1; 2340 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK; 2341 2342 //---------------------------trap_state_reason--------------------------------- 2343 Deoptimization::DeoptReason 2344 Deoptimization::trap_state_reason(int trap_state) { 2345 // This assert provides the link between the width of DataLayout::trap_bits 2346 // and the encoding of "recorded" reasons. It ensures there are enough 2347 // bits to store all needed reasons in the per-BCI MDO profile. 2348 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits"); 2349 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 2350 trap_state -= recompile_bit; 2351 if (trap_state == DS_REASON_MASK) { 2352 return Reason_many; 2353 } else { 2354 assert((int)Reason_none == 0, "state=0 => Reason_none"); 2355 return (DeoptReason)trap_state; 2356 } 2357 } 2358 //-------------------------trap_state_has_reason------------------------------- 2359 int Deoptimization::trap_state_has_reason(int trap_state, int reason) { 2360 assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason"); 2361 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits"); 2362 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 2363 trap_state -= recompile_bit; 2364 if (trap_state == DS_REASON_MASK) { 2365 return -1; // true, unspecifically (bottom of state lattice) 2366 } else if (trap_state == reason) { 2367 return 1; // true, definitely 2368 } else if (trap_state == 0) { 2369 return 0; // false, definitely (top of state lattice) 2370 } else { 2371 return 0; // false, definitely 2372 } 2373 } 2374 //-------------------------trap_state_add_reason------------------------------- 2375 int Deoptimization::trap_state_add_reason(int trap_state, int reason) { 2376 assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason"); 2377 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 2378 trap_state -= recompile_bit; 2379 if (trap_state == DS_REASON_MASK) { 2380 return trap_state + recompile_bit; // already at state lattice bottom 2381 } else if (trap_state == reason) { 2382 return trap_state + recompile_bit; // the condition is already true 2383 } else if (trap_state == 0) { 2384 return reason + recompile_bit; // no condition has yet been true 2385 } else { 2386 return DS_REASON_MASK + recompile_bit; // fall to state lattice bottom 2387 } 2388 } 2389 //-----------------------trap_state_is_recompiled------------------------------ 2390 bool Deoptimization::trap_state_is_recompiled(int trap_state) { 2391 return (trap_state & DS_RECOMPILE_BIT) != 0; 2392 } 2393 //-----------------------trap_state_set_recompiled----------------------------- 2394 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) { 2395 if (z) return trap_state | DS_RECOMPILE_BIT; 2396 else return trap_state & ~DS_RECOMPILE_BIT; 2397 } 2398 //---------------------------format_trap_state--------------------------------- 2399 // This is used for debugging and diagnostics, including LogFile output. 2400 const char* Deoptimization::format_trap_state(char* buf, size_t buflen, 2401 int trap_state) { 2402 assert(buflen > 0, "sanity"); 2403 DeoptReason reason = trap_state_reason(trap_state); 2404 bool recomp_flag = trap_state_is_recompiled(trap_state); 2405 // Re-encode the state from its decoded components. 2406 int decoded_state = 0; 2407 if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many) 2408 decoded_state = trap_state_add_reason(decoded_state, reason); 2409 if (recomp_flag) 2410 decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag); 2411 // If the state re-encodes properly, format it symbolically. 2412 // Because this routine is used for debugging and diagnostics, 2413 // be robust even if the state is a strange value. 2414 size_t len; 2415 if (decoded_state != trap_state) { 2416 // Random buggy state that doesn't decode?? 2417 len = jio_snprintf(buf, buflen, "#%d", trap_state); 2418 } else { 2419 len = jio_snprintf(buf, buflen, "%s%s", 2420 trap_reason_name(reason), 2421 recomp_flag ? " recompiled" : ""); 2422 } 2423 return buf; 2424 } 2425 2426 2427 //--------------------------------statics-------------------------------------- 2428 const char* Deoptimization::_trap_reason_name[] = { 2429 // Note: Keep this in sync. with enum DeoptReason. 2430 "none", 2431 "null_check", 2432 "null_assert" JVMCI_ONLY("_or_unreached0"), 2433 "range_check", 2434 "class_check", 2435 "array_check", 2436 "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"), 2437 "bimorphic" JVMCI_ONLY("_or_optimized_type_check"), 2438 "profile_predicate", 2439 "unloaded", 2440 "uninitialized", 2441 "initialized", 2442 "unreached", 2443 "unhandled", 2444 "constraint", 2445 "div0_check", 2446 "age", 2447 "predicate", 2448 "loop_limit_check", 2449 "speculate_class_check", 2450 "speculate_null_check", 2451 "speculate_null_assert", 2452 "rtm_state_change", 2453 "unstable_if", 2454 "unstable_fused_if", 2455 #if INCLUDE_JVMCI 2456 "aliasing", 2457 "transfer_to_interpreter", 2458 "not_compiled_exception_handler", 2459 "unresolved", 2460 "jsr_mismatch", 2461 #endif 2462 "tenured" 2463 }; 2464 const char* Deoptimization::_trap_action_name[] = { 2465 // Note: Keep this in sync. with enum DeoptAction. 2466 "none", 2467 "maybe_recompile", 2468 "reinterpret", 2469 "make_not_entrant", 2470 "make_not_compilable" 2471 }; 2472 2473 const char* Deoptimization::trap_reason_name(int reason) { 2474 // Check that every reason has a name 2475 STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT); 2476 2477 if (reason == Reason_many) return "many"; 2478 if ((uint)reason < Reason_LIMIT) 2479 return _trap_reason_name[reason]; 2480 static char buf[20]; 2481 sprintf(buf, "reason%d", reason); 2482 return buf; 2483 } 2484 const char* Deoptimization::trap_action_name(int action) { 2485 // Check that every action has a name 2486 STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT); 2487 2488 if ((uint)action < Action_LIMIT) 2489 return _trap_action_name[action]; 2490 static char buf[20]; 2491 sprintf(buf, "action%d", action); 2492 return buf; 2493 } 2494 2495 // This is used for debugging and diagnostics, including LogFile output. 2496 const char* Deoptimization::format_trap_request(char* buf, size_t buflen, 2497 int trap_request) { 2498 jint unloaded_class_index = trap_request_index(trap_request); 2499 const char* reason = trap_reason_name(trap_request_reason(trap_request)); 2500 const char* action = trap_action_name(trap_request_action(trap_request)); 2501 #if INCLUDE_JVMCI 2502 int debug_id = trap_request_debug_id(trap_request); 2503 #endif 2504 size_t len; 2505 if (unloaded_class_index < 0) { 2506 len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"), 2507 reason, action 2508 #if INCLUDE_JVMCI 2509 ,debug_id 2510 #endif 2511 ); 2512 } else { 2513 len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"), 2514 reason, action, unloaded_class_index 2515 #if INCLUDE_JVMCI 2516 ,debug_id 2517 #endif 2518 ); 2519 } 2520 return buf; 2521 } 2522 2523 juint Deoptimization::_deoptimization_hist 2524 [Deoptimization::Reason_LIMIT] 2525 [1 + Deoptimization::Action_LIMIT] 2526 [Deoptimization::BC_CASE_LIMIT] 2527 = {0}; 2528 2529 enum { 2530 LSB_BITS = 8, 2531 LSB_MASK = right_n_bits(LSB_BITS) 2532 }; 2533 2534 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action, 2535 Bytecodes::Code bc) { 2536 assert(reason >= 0 && reason < Reason_LIMIT, "oob"); 2537 assert(action >= 0 && action < Action_LIMIT, "oob"); 2538 _deoptimization_hist[Reason_none][0][0] += 1; // total 2539 _deoptimization_hist[reason][0][0] += 1; // per-reason total 2540 juint* cases = _deoptimization_hist[reason][1+action]; 2541 juint* bc_counter_addr = NULL; 2542 juint bc_counter = 0; 2543 // Look for an unused counter, or an exact match to this BC. 2544 if (bc != Bytecodes::_illegal) { 2545 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) { 2546 juint* counter_addr = &cases[bc_case]; 2547 juint counter = *counter_addr; 2548 if ((counter == 0 && bc_counter_addr == NULL) 2549 || (Bytecodes::Code)(counter & LSB_MASK) == bc) { 2550 // this counter is either free or is already devoted to this BC 2551 bc_counter_addr = counter_addr; 2552 bc_counter = counter | bc; 2553 } 2554 } 2555 } 2556 if (bc_counter_addr == NULL) { 2557 // Overflow, or no given bytecode. 2558 bc_counter_addr = &cases[BC_CASE_LIMIT-1]; 2559 bc_counter = (*bc_counter_addr & ~LSB_MASK); // clear LSB 2560 } 2561 *bc_counter_addr = bc_counter + (1 << LSB_BITS); 2562 } 2563 2564 jint Deoptimization::total_deoptimization_count() { 2565 return _deoptimization_hist[Reason_none][0][0]; 2566 } 2567 2568 void Deoptimization::print_statistics() { 2569 juint total = total_deoptimization_count(); 2570 juint account = total; 2571 if (total != 0) { 2572 ttyLocker ttyl; 2573 if (xtty != NULL) xtty->head("statistics type='deoptimization'"); 2574 tty->print_cr("Deoptimization traps recorded:"); 2575 #define PRINT_STAT_LINE(name, r) \ 2576 tty->print_cr(" %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name); 2577 PRINT_STAT_LINE("total", total); 2578 // For each non-zero entry in the histogram, print the reason, 2579 // the action, and (if specifically known) the type of bytecode. 2580 for (int reason = 0; reason < Reason_LIMIT; reason++) { 2581 for (int action = 0; action < Action_LIMIT; action++) { 2582 juint* cases = _deoptimization_hist[reason][1+action]; 2583 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) { 2584 juint counter = cases[bc_case]; 2585 if (counter != 0) { 2586 char name[1*K]; 2587 Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK); 2588 if (bc_case == BC_CASE_LIMIT && (int)bc == 0) 2589 bc = Bytecodes::_illegal; 2590 sprintf(name, "%s/%s/%s", 2591 trap_reason_name(reason), 2592 trap_action_name(action), 2593 Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other"); 2594 juint r = counter >> LSB_BITS; 2595 tty->print_cr(" %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total); 2596 account -= r; 2597 } 2598 } 2599 } 2600 } 2601 if (account != 0) { 2602 PRINT_STAT_LINE("unaccounted", account); 2603 } 2604 #undef PRINT_STAT_LINE 2605 if (xtty != NULL) xtty->tail("statistics"); 2606 } 2607 } 2608 #else // COMPILER2_OR_JVMCI 2609 2610 2611 // Stubs for C1 only system. 2612 bool Deoptimization::trap_state_is_recompiled(int trap_state) { 2613 return false; 2614 } 2615 2616 const char* Deoptimization::trap_reason_name(int reason) { 2617 return "unknown"; 2618 } 2619 2620 void Deoptimization::print_statistics() { 2621 // no output 2622 } 2623 2624 void 2625 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) { 2626 // no udpate 2627 } 2628 2629 int Deoptimization::trap_state_has_reason(int trap_state, int reason) { 2630 return 0; 2631 } 2632 2633 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action, 2634 Bytecodes::Code bc) { 2635 // no update 2636 } 2637 2638 const char* Deoptimization::format_trap_state(char* buf, size_t buflen, 2639 int trap_state) { 2640 jio_snprintf(buf, buflen, "#%d", trap_state); 2641 return buf; 2642 } 2643 2644 #endif // COMPILER2_OR_JVMCI