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