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