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