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