1 /* 2 * Copyright (c) 1999, 2023, 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/javaClasses.inline.hpp" 27 #include "classfile/symbolTable.hpp" 28 #include "classfile/vmClasses.hpp" 29 #include "classfile/vmSymbols.hpp" 30 #include "code/codeCache.hpp" 31 #include "code/codeHeapState.hpp" 32 #include "code/dependencyContext.hpp" 33 #include "compiler/compilationLog.hpp" 34 #include "compiler/compilationPolicy.hpp" 35 #include "compiler/compileBroker.hpp" 36 #include "compiler/compileLog.hpp" 37 #include "compiler/compilerEvent.hpp" 38 #include "compiler/compilerOracle.hpp" 39 #include "compiler/directivesParser.hpp" 40 #include "interpreter/linkResolver.hpp" 41 #include "jvm.h" 42 #include "jfr/jfrEvents.hpp" 43 #include "logging/log.hpp" 44 #include "logging/logStream.hpp" 45 #include "memory/allocation.inline.hpp" 46 #include "memory/resourceArea.hpp" 47 #include "memory/universe.hpp" 48 #include "oops/methodData.hpp" 49 #include "oops/method.inline.hpp" 50 #include "oops/oop.inline.hpp" 51 #include "prims/jvmtiExport.hpp" 52 #include "prims/nativeLookup.hpp" 53 #include "prims/whitebox.hpp" 54 #include "runtime/atomic.hpp" 55 #include "runtime/escapeBarrier.hpp" 56 #include "runtime/globals_extension.hpp" 57 #include "runtime/handles.inline.hpp" 58 #include "runtime/init.hpp" 59 #include "runtime/interfaceSupport.inline.hpp" 60 #include "runtime/java.hpp" 61 #include "runtime/javaCalls.hpp" 62 #include "runtime/jniHandles.inline.hpp" 63 #include "runtime/os.hpp" 64 #include "runtime/perfData.hpp" 65 #include "runtime/safepointVerifiers.hpp" 66 #include "runtime/sharedRuntime.hpp" 67 #include "runtime/threads.hpp" 68 #include "runtime/threadSMR.hpp" 69 #include "runtime/timerTrace.hpp" 70 #include "runtime/vframe.inline.hpp" 71 #include "utilities/debug.hpp" 72 #include "utilities/dtrace.hpp" 73 #include "utilities/events.hpp" 74 #include "utilities/formatBuffer.hpp" 75 #include "utilities/macros.hpp" 76 #ifdef COMPILER1 77 #include "c1/c1_Compiler.hpp" 78 #endif 79 #ifdef COMPILER2 80 #include "opto/c2compiler.hpp" 81 #endif 82 #if INCLUDE_JVMCI 83 #include "jvmci/jvmciEnv.hpp" 84 #include "jvmci/jvmciRuntime.hpp" 85 #endif 86 87 #ifdef DTRACE_ENABLED 88 89 // Only bother with this argument setup if dtrace is available 90 91 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) \ 92 { \ 93 Symbol* klass_name = (method)->klass_name(); \ 94 Symbol* name = (method)->name(); \ 95 Symbol* signature = (method)->signature(); \ 96 HOTSPOT_METHOD_COMPILE_BEGIN( \ 97 (char *) comp_name, strlen(comp_name), \ 98 (char *) klass_name->bytes(), klass_name->utf8_length(), \ 99 (char *) name->bytes(), name->utf8_length(), \ 100 (char *) signature->bytes(), signature->utf8_length()); \ 101 } 102 103 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success) \ 104 { \ 105 Symbol* klass_name = (method)->klass_name(); \ 106 Symbol* name = (method)->name(); \ 107 Symbol* signature = (method)->signature(); \ 108 HOTSPOT_METHOD_COMPILE_END( \ 109 (char *) comp_name, strlen(comp_name), \ 110 (char *) klass_name->bytes(), klass_name->utf8_length(), \ 111 (char *) name->bytes(), name->utf8_length(), \ 112 (char *) signature->bytes(), signature->utf8_length(), (success)); \ 113 } 114 115 #else // ndef DTRACE_ENABLED 116 117 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) 118 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success) 119 120 #endif // ndef DTRACE_ENABLED 121 122 bool CompileBroker::_initialized = false; 123 volatile bool CompileBroker::_should_block = false; 124 volatile int CompileBroker::_print_compilation_warning = 0; 125 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation; 126 127 // The installed compiler(s) 128 AbstractCompiler* CompileBroker::_compilers[2]; 129 130 // The maximum numbers of compiler threads to be determined during startup. 131 int CompileBroker::_c1_count = 0; 132 int CompileBroker::_c2_count = 0; 133 134 // An array of compiler names as Java String objects 135 jobject* CompileBroker::_compiler1_objects = nullptr; 136 jobject* CompileBroker::_compiler2_objects = nullptr; 137 138 CompileLog** CompileBroker::_compiler1_logs = nullptr; 139 CompileLog** CompileBroker::_compiler2_logs = nullptr; 140 141 // These counters are used to assign an unique ID to each compilation. 142 volatile jint CompileBroker::_compilation_id = 0; 143 volatile jint CompileBroker::_osr_compilation_id = 0; 144 volatile jint CompileBroker::_native_compilation_id = 0; 145 146 // Performance counters 147 PerfCounter* CompileBroker::_perf_total_compilation = nullptr; 148 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr; 149 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr; 150 151 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr; 152 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr; 153 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr; 154 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr; 155 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr; 156 157 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr; 158 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr; 159 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr; 160 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr; 161 162 PerfStringVariable* CompileBroker::_perf_last_method = nullptr; 163 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr; 164 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr; 165 PerfVariable* CompileBroker::_perf_last_compile_type = nullptr; 166 PerfVariable* CompileBroker::_perf_last_compile_size = nullptr; 167 PerfVariable* CompileBroker::_perf_last_failed_type = nullptr; 168 PerfVariable* CompileBroker::_perf_last_invalidated_type = nullptr; 169 170 // Timers and counters for generating statistics 171 elapsedTimer CompileBroker::_t_total_compilation; 172 elapsedTimer CompileBroker::_t_osr_compilation; 173 elapsedTimer CompileBroker::_t_standard_compilation; 174 elapsedTimer CompileBroker::_t_invalidated_compilation; 175 elapsedTimer CompileBroker::_t_bailedout_compilation; 176 177 uint CompileBroker::_total_bailout_count = 0; 178 uint CompileBroker::_total_invalidated_count = 0; 179 uint CompileBroker::_total_compile_count = 0; 180 uint CompileBroker::_total_osr_compile_count = 0; 181 uint CompileBroker::_total_standard_compile_count = 0; 182 uint CompileBroker::_total_compiler_stopped_count = 0; 183 uint CompileBroker::_total_compiler_restarted_count = 0; 184 185 uint CompileBroker::_sum_osr_bytes_compiled = 0; 186 uint CompileBroker::_sum_standard_bytes_compiled = 0; 187 uint CompileBroker::_sum_nmethod_size = 0; 188 uint CompileBroker::_sum_nmethod_code_size = 0; 189 190 jlong CompileBroker::_peak_compilation_time = 0; 191 192 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization]; 193 194 CompileQueue* CompileBroker::_c2_compile_queue = nullptr; 195 CompileQueue* CompileBroker::_c1_compile_queue = nullptr; 196 197 bool compileBroker_init() { 198 if (LogEvents) { 199 CompilationLog::init(); 200 } 201 202 // init directives stack, adding default directive 203 DirectivesStack::init(); 204 205 if (DirectivesParser::has_file()) { 206 return DirectivesParser::parse_from_flag(); 207 } else if (CompilerDirectivesPrint) { 208 // Print default directive even when no other was added 209 DirectivesStack::print(tty); 210 } 211 212 return true; 213 } 214 215 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) { 216 CompilerThread* thread = CompilerThread::current(); 217 thread->set_task(task); 218 CompileLog* log = thread->log(); 219 if (log != nullptr && !task->is_unloaded()) task->log_task_start(log); 220 } 221 222 CompileTaskWrapper::~CompileTaskWrapper() { 223 CompilerThread* thread = CompilerThread::current(); 224 CompileTask* task = thread->task(); 225 CompileLog* log = thread->log(); 226 if (log != nullptr && !task->is_unloaded()) task->log_task_done(log); 227 thread->set_task(nullptr); 228 thread->set_env(nullptr); 229 if (task->is_blocking()) { 230 bool free_task = false; 231 { 232 MutexLocker notifier(thread, task->lock()); 233 task->mark_complete(); 234 #if INCLUDE_JVMCI 235 if (CompileBroker::compiler(task->comp_level())->is_jvmci()) { 236 if (!task->has_waiter()) { 237 // The waiting thread timed out and thus did not free the task. 238 free_task = true; 239 } 240 task->set_blocking_jvmci_compile_state(nullptr); 241 } 242 #endif 243 if (!free_task) { 244 // Notify the waiting thread that the compilation has completed 245 // so that it can free the task. 246 task->lock()->notify_all(); 247 } 248 } 249 if (free_task) { 250 // The task can only be freed once the task lock is released. 251 CompileTask::free(task); 252 } 253 } else { 254 task->mark_complete(); 255 256 // By convention, the compiling thread is responsible for 257 // recycling a non-blocking CompileTask. 258 CompileTask::free(task); 259 } 260 } 261 262 /** 263 * Check if a CompilerThread can be removed and update count if requested. 264 */ 265 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) { 266 assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here"); 267 if (!ReduceNumberOfCompilerThreads) return false; 268 269 AbstractCompiler *compiler = ct->compiler(); 270 int compiler_count = compiler->num_compiler_threads(); 271 bool c1 = compiler->is_c1(); 272 273 // Keep at least 1 compiler thread of each type. 274 if (compiler_count < 2) return false; 275 276 // Keep thread alive for at least some time. 277 if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false; 278 279 #if INCLUDE_JVMCI 280 if (compiler->is_jvmci()) { 281 // Handles for JVMCI thread objects may get released concurrently. 282 if (do_it) { 283 assert(CompileThread_lock->owner() == ct, "must be holding lock"); 284 } else { 285 // Skip check if it's the last thread and let caller check again. 286 return true; 287 } 288 } 289 #endif 290 291 // We only allow the last compiler thread of each type to get removed. 292 jobject last_compiler = c1 ? compiler1_object(compiler_count - 1) 293 : compiler2_object(compiler_count - 1); 294 if (ct->threadObj() == JNIHandles::resolve_non_null(last_compiler)) { 295 if (do_it) { 296 assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent. 297 compiler->set_num_compiler_threads(compiler_count - 1); 298 #if INCLUDE_JVMCI 299 if (compiler->is_jvmci()) { 300 // Old j.l.Thread object can die when no longer referenced elsewhere. 301 JNIHandles::destroy_global(compiler2_object(compiler_count - 1)); 302 _compiler2_objects[compiler_count - 1] = nullptr; 303 } 304 #endif 305 } 306 return true; 307 } 308 return false; 309 } 310 311 /** 312 * Add a CompileTask to a CompileQueue. 313 */ 314 void CompileQueue::add(CompileTask* task) { 315 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock"); 316 317 task->set_next(nullptr); 318 task->set_prev(nullptr); 319 320 if (_last == nullptr) { 321 // The compile queue is empty. 322 assert(_first == nullptr, "queue is empty"); 323 _first = task; 324 _last = task; 325 } else { 326 // Append the task to the queue. 327 assert(_last->next() == nullptr, "not last"); 328 _last->set_next(task); 329 task->set_prev(_last); 330 _last = task; 331 } 332 ++_size; 333 334 // Mark the method as being in the compile queue. 335 task->method()->set_queued_for_compilation(); 336 337 if (CIPrintCompileQueue) { 338 print_tty(); 339 } 340 341 if (LogCompilation && xtty != nullptr) { 342 task->log_task_queued(); 343 } 344 345 // Notify CompilerThreads that a task is available. 346 MethodCompileQueue_lock->notify_all(); 347 } 348 349 /** 350 * Empties compilation queue by putting all compilation tasks onto 351 * a freelist. Furthermore, the method wakes up all threads that are 352 * waiting on a compilation task to finish. This can happen if background 353 * compilation is disabled. 354 */ 355 void CompileQueue::free_all() { 356 MutexLocker mu(MethodCompileQueue_lock); 357 CompileTask* next = _first; 358 359 // Iterate over all tasks in the compile queue 360 while (next != nullptr) { 361 CompileTask* current = next; 362 next = current->next(); 363 { 364 // Wake up thread that blocks on the compile task. 365 MutexLocker ct_lock(current->lock()); 366 current->lock()->notify(); 367 } 368 // Put the task back on the freelist. 369 CompileTask::free(current); 370 } 371 _first = nullptr; 372 _last = nullptr; 373 374 // Wake up all threads that block on the queue. 375 MethodCompileQueue_lock->notify_all(); 376 } 377 378 /** 379 * Get the next CompileTask from a CompileQueue 380 */ 381 CompileTask* CompileQueue::get(CompilerThread* thread) { 382 // save methods from RedefineClasses across safepoint 383 // across MethodCompileQueue_lock below. 384 methodHandle save_method; 385 methodHandle save_hot_method; 386 387 MonitorLocker locker(MethodCompileQueue_lock); 388 // If _first is null we have no more compile jobs. There are two reasons for 389 // having no compile jobs: First, we compiled everything we wanted. Second, 390 // we ran out of code cache so compilation has been disabled. In the latter 391 // case we perform code cache sweeps to free memory such that we can re-enable 392 // compilation. 393 while (_first == nullptr) { 394 // Exit loop if compilation is disabled forever 395 if (CompileBroker::is_compilation_disabled_forever()) { 396 return nullptr; 397 } 398 399 AbstractCompiler* compiler = thread->compiler(); 400 guarantee(compiler != nullptr, "Compiler object must exist"); 401 compiler->on_empty_queue(this, thread); 402 if (_first != nullptr) { 403 // The call to on_empty_queue may have temporarily unlocked the MCQ lock 404 // so check again whether any tasks were added to the queue. 405 break; 406 } 407 408 // If there are no compilation tasks and we can compile new jobs 409 // (i.e., there is enough free space in the code cache) there is 410 // no need to invoke the GC. 411 // We need a timed wait here, since compiler threads can exit if compilation 412 // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads 413 // is not critical and we do not want idle compiler threads to wake up too often. 414 locker.wait(5*1000); 415 416 if (UseDynamicNumberOfCompilerThreads && _first == nullptr) { 417 // Still nothing to compile. Give caller a chance to stop this thread. 418 if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr; 419 } 420 } 421 422 if (CompileBroker::is_compilation_disabled_forever()) { 423 return nullptr; 424 } 425 426 CompileTask* task; 427 { 428 NoSafepointVerifier nsv; 429 task = CompilationPolicy::select_task(this); 430 if (task != nullptr) { 431 task = task->select_for_compilation(); 432 } 433 } 434 435 if (task != nullptr) { 436 // Save method pointers across unlock safepoint. The task is removed from 437 // the compilation queue, which is walked during RedefineClasses. 438 Thread* thread = Thread::current(); 439 save_method = methodHandle(thread, task->method()); 440 save_hot_method = methodHandle(thread, task->hot_method()); 441 442 remove(task); 443 } 444 purge_stale_tasks(); // may temporarily release MCQ lock 445 return task; 446 } 447 448 // Clean & deallocate stale compile tasks. 449 // Temporarily releases MethodCompileQueue lock. 450 void CompileQueue::purge_stale_tasks() { 451 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock"); 452 if (_first_stale != nullptr) { 453 // Stale tasks are purged when MCQ lock is released, 454 // but _first_stale updates are protected by MCQ lock. 455 // Once task processing starts and MCQ lock is released, 456 // other compiler threads can reuse _first_stale. 457 CompileTask* head = _first_stale; 458 _first_stale = nullptr; 459 { 460 MutexUnlocker ul(MethodCompileQueue_lock); 461 for (CompileTask* task = head; task != nullptr; ) { 462 CompileTask* next_task = task->next(); 463 CompileTaskWrapper ctw(task); // Frees the task 464 task->set_failure_reason("stale task"); 465 task = next_task; 466 } 467 } 468 } 469 } 470 471 void CompileQueue::remove(CompileTask* task) { 472 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock"); 473 if (task->prev() != nullptr) { 474 task->prev()->set_next(task->next()); 475 } else { 476 // max is the first element 477 assert(task == _first, "Sanity"); 478 _first = task->next(); 479 } 480 481 if (task->next() != nullptr) { 482 task->next()->set_prev(task->prev()); 483 } else { 484 // max is the last element 485 assert(task == _last, "Sanity"); 486 _last = task->prev(); 487 } 488 --_size; 489 } 490 491 void CompileQueue::remove_and_mark_stale(CompileTask* task) { 492 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock"); 493 remove(task); 494 495 // Enqueue the task for reclamation (should be done outside MCQ lock) 496 task->set_next(_first_stale); 497 task->set_prev(nullptr); 498 _first_stale = task; 499 } 500 501 // methods in the compile queue need to be marked as used on the stack 502 // so that they don't get reclaimed by Redefine Classes 503 void CompileQueue::mark_on_stack() { 504 CompileTask* task = _first; 505 while (task != nullptr) { 506 task->mark_on_stack(); 507 task = task->next(); 508 } 509 } 510 511 512 CompileQueue* CompileBroker::compile_queue(int comp_level) { 513 if (is_c2_compile(comp_level)) return _c2_compile_queue; 514 if (is_c1_compile(comp_level)) return _c1_compile_queue; 515 return nullptr; 516 } 517 518 void CompileBroker::print_compile_queues(outputStream* st) { 519 st->print_cr("Current compiles: "); 520 521 char buf[2000]; 522 int buflen = sizeof(buf); 523 Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true); 524 525 st->cr(); 526 if (_c1_compile_queue != nullptr) { 527 _c1_compile_queue->print(st); 528 } 529 if (_c2_compile_queue != nullptr) { 530 _c2_compile_queue->print(st); 531 } 532 } 533 534 void CompileQueue::print(outputStream* st) { 535 assert_locked_or_safepoint(MethodCompileQueue_lock); 536 st->print_cr("%s:", name()); 537 CompileTask* task = _first; 538 if (task == nullptr) { 539 st->print_cr("Empty"); 540 } else { 541 while (task != nullptr) { 542 task->print(st, nullptr, true, true); 543 task = task->next(); 544 } 545 } 546 st->cr(); 547 } 548 549 void CompileQueue::print_tty() { 550 stringStream ss; 551 // Dump the compile queue into a buffer before locking the tty 552 print(&ss); 553 { 554 ttyLocker ttyl; 555 tty->print("%s", ss.freeze()); 556 } 557 } 558 559 CompilerCounters::CompilerCounters() { 560 _current_method[0] = '\0'; 561 _compile_type = CompileBroker::no_compile; 562 } 563 564 #if INCLUDE_JFR && COMPILER2_OR_JVMCI 565 // It appends new compiler phase names to growable array phase_names(a new CompilerPhaseType mapping 566 // in compiler/compilerEvent.cpp) and registers it with its serializer. 567 // 568 // c2 uses explicit CompilerPhaseType idToPhase mapping in opto/phasetype.hpp, 569 // so if c2 is used, it should be always registered first. 570 // This function is called during vm initialization. 571 void register_jfr_phasetype_serializer(CompilerType compiler_type) { 572 ResourceMark rm; 573 static bool first_registration = true; 574 if (compiler_type == compiler_jvmci) { 575 CompilerEvent::PhaseEvent::get_phase_id("NOT_A_PHASE_NAME", false, false, false); 576 first_registration = false; 577 #ifdef COMPILER2 578 } else if (compiler_type == compiler_c2) { 579 assert(first_registration, "invariant"); // c2 must be registered first. 580 for (int i = 0; i < PHASE_NUM_TYPES; i++) { 581 const char* phase_name = CompilerPhaseTypeHelper::to_description((CompilerPhaseType) i); 582 CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false); 583 } 584 first_registration = false; 585 #endif // COMPILER2 586 } 587 } 588 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI 589 590 // ------------------------------------------------------------------ 591 // CompileBroker::compilation_init 592 // 593 // Initialize the Compilation object 594 void CompileBroker::compilation_init_phase1(JavaThread* THREAD) { 595 // No need to initialize compilation system if we do not use it. 596 if (!UseCompiler) { 597 return; 598 } 599 // Set the interface to the current compiler(s). 600 _c1_count = CompilationPolicy::c1_count(); 601 _c2_count = CompilationPolicy::c2_count(); 602 603 #if INCLUDE_JVMCI 604 if (EnableJVMCI) { 605 // This is creating a JVMCICompiler singleton. 606 JVMCICompiler* jvmci = new JVMCICompiler(); 607 608 if (UseJVMCICompiler) { 609 _compilers[1] = jvmci; 610 if (FLAG_IS_DEFAULT(JVMCIThreads)) { 611 if (BootstrapJVMCI) { 612 // JVMCI will bootstrap so give it more threads 613 _c2_count = MIN2(32, os::active_processor_count()); 614 } 615 } else { 616 _c2_count = JVMCIThreads; 617 } 618 if (FLAG_IS_DEFAULT(JVMCIHostThreads)) { 619 } else { 620 #ifdef COMPILER1 621 _c1_count = JVMCIHostThreads; 622 #endif // COMPILER1 623 } 624 } 625 } 626 #endif // INCLUDE_JVMCI 627 628 #ifdef COMPILER1 629 if (_c1_count > 0) { 630 _compilers[0] = new Compiler(); 631 } 632 #endif // COMPILER1 633 634 #ifdef COMPILER2 635 if (true JVMCI_ONLY( && !UseJVMCICompiler)) { 636 if (_c2_count > 0) { 637 _compilers[1] = new C2Compiler(); 638 // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit. 639 // idToPhase mapping for c2 is in opto/phasetype.hpp 640 JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);) 641 } 642 } 643 #endif // COMPILER2 644 645 #if INCLUDE_JVMCI 646 // Register after c2 registration. 647 // JVMCI CompilerPhaseType idToPhase mapping is dynamic. 648 if (EnableJVMCI) { 649 JFR_ONLY(register_jfr_phasetype_serializer(compiler_jvmci);) 650 } 651 #endif // INCLUDE_JVMCI 652 653 // Start the compiler thread(s) 654 init_compiler_threads(); 655 // totalTime performance counter is always created as it is required 656 // by the implementation of java.lang.management.CompilationMXBean. 657 { 658 // Ensure OOM leads to vm_exit_during_initialization. 659 EXCEPTION_MARK; 660 _perf_total_compilation = 661 PerfDataManager::create_counter(JAVA_CI, "totalTime", 662 PerfData::U_Ticks, CHECK); 663 } 664 665 if (UsePerfData) { 666 667 EXCEPTION_MARK; 668 669 // create the jvmstat performance counters 670 _perf_osr_compilation = 671 PerfDataManager::create_counter(SUN_CI, "osrTime", 672 PerfData::U_Ticks, CHECK); 673 674 _perf_standard_compilation = 675 PerfDataManager::create_counter(SUN_CI, "standardTime", 676 PerfData::U_Ticks, CHECK); 677 678 _perf_total_bailout_count = 679 PerfDataManager::create_counter(SUN_CI, "totalBailouts", 680 PerfData::U_Events, CHECK); 681 682 _perf_total_invalidated_count = 683 PerfDataManager::create_counter(SUN_CI, "totalInvalidates", 684 PerfData::U_Events, CHECK); 685 686 _perf_total_compile_count = 687 PerfDataManager::create_counter(SUN_CI, "totalCompiles", 688 PerfData::U_Events, CHECK); 689 _perf_total_osr_compile_count = 690 PerfDataManager::create_counter(SUN_CI, "osrCompiles", 691 PerfData::U_Events, CHECK); 692 693 _perf_total_standard_compile_count = 694 PerfDataManager::create_counter(SUN_CI, "standardCompiles", 695 PerfData::U_Events, CHECK); 696 697 _perf_sum_osr_bytes_compiled = 698 PerfDataManager::create_counter(SUN_CI, "osrBytes", 699 PerfData::U_Bytes, CHECK); 700 701 _perf_sum_standard_bytes_compiled = 702 PerfDataManager::create_counter(SUN_CI, "standardBytes", 703 PerfData::U_Bytes, CHECK); 704 705 _perf_sum_nmethod_size = 706 PerfDataManager::create_counter(SUN_CI, "nmethodSize", 707 PerfData::U_Bytes, CHECK); 708 709 _perf_sum_nmethod_code_size = 710 PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize", 711 PerfData::U_Bytes, CHECK); 712 713 _perf_last_method = 714 PerfDataManager::create_string_variable(SUN_CI, "lastMethod", 715 CompilerCounters::cmname_buffer_length, 716 "", CHECK); 717 718 _perf_last_failed_method = 719 PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod", 720 CompilerCounters::cmname_buffer_length, 721 "", CHECK); 722 723 _perf_last_invalidated_method = 724 PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod", 725 CompilerCounters::cmname_buffer_length, 726 "", CHECK); 727 728 _perf_last_compile_type = 729 PerfDataManager::create_variable(SUN_CI, "lastType", 730 PerfData::U_None, 731 (jlong)CompileBroker::no_compile, 732 CHECK); 733 734 _perf_last_compile_size = 735 PerfDataManager::create_variable(SUN_CI, "lastSize", 736 PerfData::U_Bytes, 737 (jlong)CompileBroker::no_compile, 738 CHECK); 739 740 741 _perf_last_failed_type = 742 PerfDataManager::create_variable(SUN_CI, "lastFailedType", 743 PerfData::U_None, 744 (jlong)CompileBroker::no_compile, 745 CHECK); 746 747 _perf_last_invalidated_type = 748 PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType", 749 PerfData::U_None, 750 (jlong)CompileBroker::no_compile, 751 CHECK); 752 } 753 } 754 755 // Completes compiler initialization. Compilation requests submitted 756 // prior to this will be silently ignored. 757 void CompileBroker::compilation_init_phase2() { 758 _initialized = true; 759 } 760 761 Handle CompileBroker::create_thread_oop(const char* name, TRAPS) { 762 Handle thread_oop = JavaThread::create_system_thread_object(name, CHECK_NH); 763 return thread_oop; 764 } 765 766 #if defined(ASSERT) && COMPILER2_OR_JVMCI 767 // Stress testing. Dedicated threads revert optimizations based on escape analysis concurrently to 768 // the running java application. Configured with vm options DeoptimizeObjectsALot*. 769 class DeoptimizeObjectsALotThread : public JavaThread { 770 771 static void deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS); 772 void deoptimize_objects_alot_loop_single(); 773 void deoptimize_objects_alot_loop_all(); 774 775 public: 776 DeoptimizeObjectsALotThread() : JavaThread(&deopt_objs_alot_thread_entry) { } 777 778 bool is_hidden_from_external_view() const { return true; } 779 }; 780 781 // Entry for DeoptimizeObjectsALotThread. The threads are started in 782 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled 783 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) { 784 DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread); 785 bool enter_single_loop; 786 { 787 MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag); 788 static int single_thread_count = 0; 789 enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle; 790 } 791 if (enter_single_loop) { 792 dt->deoptimize_objects_alot_loop_single(); 793 } else { 794 dt->deoptimize_objects_alot_loop_all(); 795 } 796 } 797 798 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each 799 // barrier targets a single thread which is selected round robin. 800 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_single() { 801 HandleMark hm(this); 802 while (true) { 803 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *deoptee_thread = jtiwh.next(); ) { 804 { // Begin new scope for escape barrier 805 HandleMarkCleaner hmc(this); 806 ResourceMark rm(this); 807 EscapeBarrier eb(true, this, deoptee_thread); 808 eb.deoptimize_objects(100); 809 } 810 // Now sleep after the escape barriers destructor resumed deoptee_thread. 811 sleep(DeoptimizeObjectsALotInterval); 812 } 813 } 814 } 815 816 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each 817 // barrier targets all java threads in the vm at once. 818 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_all() { 819 HandleMark hm(this); 820 while (true) { 821 { // Begin new scope for escape barrier 822 HandleMarkCleaner hmc(this); 823 ResourceMark rm(this); 824 EscapeBarrier eb(true, this); 825 eb.deoptimize_objects_all_threads(); 826 } 827 // Now sleep after the escape barriers destructor resumed the java threads. 828 sleep(DeoptimizeObjectsALotInterval); 829 } 830 } 831 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI 832 833 834 JavaThread* CompileBroker::make_thread(ThreadType type, jobject thread_handle, CompileQueue* queue, AbstractCompiler* comp, JavaThread* THREAD) { 835 JavaThread* new_thread = nullptr; 836 837 switch (type) { 838 case compiler_t: 839 assert(comp != nullptr, "Compiler instance missing."); 840 if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) { 841 CompilerCounters* counters = new CompilerCounters(); 842 new_thread = new CompilerThread(queue, counters); 843 } 844 break; 845 #if defined(ASSERT) && COMPILER2_OR_JVMCI 846 case deoptimizer_t: 847 new_thread = new DeoptimizeObjectsALotThread(); 848 break; 849 #endif // ASSERT 850 default: 851 ShouldNotReachHere(); 852 } 853 854 // At this point the new CompilerThread data-races with this startup 855 // thread (which is the main thread and NOT the VM thread). 856 // This means Java bytecodes being executed at startup can 857 // queue compile jobs which will run at whatever default priority the 858 // newly created CompilerThread runs at. 859 860 861 // At this point it may be possible that no osthread was created for the 862 // JavaThread due to lack of resources. We will handle that failure below. 863 // Also check new_thread so that static analysis is happy. 864 if (new_thread != nullptr && new_thread->osthread() != nullptr) { 865 Handle thread_oop(THREAD, JNIHandles::resolve_non_null(thread_handle)); 866 867 if (type == compiler_t) { 868 CompilerThread::cast(new_thread)->set_compiler(comp); 869 } 870 871 // Note that we cannot call os::set_priority because it expects Java 872 // priorities and we are *explicitly* using OS priorities so that it's 873 // possible to set the compiler thread priority higher than any Java 874 // thread. 875 876 int native_prio = CompilerThreadPriority; 877 if (native_prio == -1) { 878 if (UseCriticalCompilerThreadPriority) { 879 native_prio = os::java_to_os_priority[CriticalPriority]; 880 } else { 881 native_prio = os::java_to_os_priority[NearMaxPriority]; 882 } 883 } 884 os::set_native_priority(new_thread, native_prio); 885 886 // Note that this only sets the JavaThread _priority field, which by 887 // definition is limited to Java priorities and not OS priorities. 888 JavaThread::start_internal_daemon(THREAD, new_thread, thread_oop, NearMaxPriority); 889 890 } else { // osthread initialization failure 891 if (UseDynamicNumberOfCompilerThreads && type == compiler_t 892 && comp->num_compiler_threads() > 0) { 893 // The new thread is not known to Thread-SMR yet so we can just delete. 894 delete new_thread; 895 return nullptr; 896 } else { 897 vm_exit_during_initialization("java.lang.OutOfMemoryError", 898 os::native_thread_creation_failed_msg()); 899 } 900 } 901 902 os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS) 903 904 return new_thread; 905 } 906 907 static bool trace_compiler_threads() { 908 LogTarget(Debug, jit, thread) lt; 909 return TraceCompilerThreads || lt.is_enabled(); 910 } 911 912 static void print_compiler_threads(stringStream& msg) { 913 if (TraceCompilerThreads) { 914 tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string()); 915 } 916 LogTarget(Debug, jit, thread) lt; 917 if (lt.is_enabled()) { 918 LogStream ls(lt); 919 ls.print_cr("%s", msg.as_string()); 920 } 921 } 922 923 void CompileBroker::init_compiler_threads() { 924 // Ensure any exceptions lead to vm_exit_during_initialization. 925 EXCEPTION_MARK; 926 #if !defined(ZERO) 927 assert(_c2_count > 0 || _c1_count > 0, "No compilers?"); 928 #endif // !ZERO 929 // Initialize the compilation queue 930 if (_c2_count > 0) { 931 const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue"; 932 _c2_compile_queue = new CompileQueue(name); 933 _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler); 934 _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler); 935 } 936 if (_c1_count > 0) { 937 _c1_compile_queue = new CompileQueue("C1 compile queue"); 938 _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler); 939 _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler); 940 } 941 942 char name_buffer[256]; 943 944 for (int i = 0; i < _c2_count; i++) { 945 jobject thread_handle = nullptr; 946 // Create all j.l.Thread objects for C1 and C2 threads here, but only one 947 // for JVMCI compiler which can create further ones on demand. 948 JVMCI_ONLY(if (!UseJVMCICompiler || !UseDynamicNumberOfCompilerThreads || i == 0) {) 949 // Create a name for our thread. 950 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", _compilers[1]->name(), i); 951 Handle thread_oop = create_thread_oop(name_buffer, CHECK); 952 thread_handle = JNIHandles::make_global(thread_oop); 953 JVMCI_ONLY(}) 954 _compiler2_objects[i] = thread_handle; 955 _compiler2_logs[i] = nullptr; 956 957 if (!UseDynamicNumberOfCompilerThreads || i == 0) { 958 JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD); 959 assert(ct != nullptr, "should have been handled for initial thread"); 960 _compilers[1]->set_num_compiler_threads(i + 1); 961 if (trace_compiler_threads()) { 962 ResourceMark rm; 963 ThreadsListHandle tlh; // name() depends on the TLH. 964 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct)); 965 stringStream msg; 966 msg.print("Added initial compiler thread %s", ct->name()); 967 print_compiler_threads(msg); 968 } 969 } 970 } 971 972 for (int i = 0; i < _c1_count; i++) { 973 // Create a name for our thread. 974 os::snprintf_checked(name_buffer, sizeof(name_buffer), "C1 CompilerThread%d", i); 975 Handle thread_oop = create_thread_oop(name_buffer, CHECK); 976 jobject thread_handle = JNIHandles::make_global(thread_oop); 977 _compiler1_objects[i] = thread_handle; 978 _compiler1_logs[i] = nullptr; 979 980 if (!UseDynamicNumberOfCompilerThreads || i == 0) { 981 JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD); 982 assert(ct != nullptr, "should have been handled for initial thread"); 983 _compilers[0]->set_num_compiler_threads(i + 1); 984 if (trace_compiler_threads()) { 985 ResourceMark rm; 986 ThreadsListHandle tlh; // name() depends on the TLH. 987 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct)); 988 stringStream msg; 989 msg.print("Added initial compiler thread %s", ct->name()); 990 print_compiler_threads(msg); 991 } 992 } 993 } 994 995 if (UsePerfData) { 996 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK); 997 } 998 999 #if defined(ASSERT) && COMPILER2_OR_JVMCI 1000 if (DeoptimizeObjectsALot) { 1001 // Initialize and start the object deoptimizer threads 1002 const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll; 1003 for (int count = 0; count < total_count; count++) { 1004 Handle thread_oop = create_thread_oop("Deoptimize objects a lot single mode", CHECK); 1005 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop()); 1006 make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD); 1007 } 1008 } 1009 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI 1010 } 1011 1012 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) { 1013 1014 julong free_memory = os::free_memory(); 1015 // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All). 1016 size_t available_cc_np = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled), 1017 available_cc_p = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled); 1018 1019 // Only do attempt to start additional threads if the lock is free. 1020 if (!CompileThread_lock->try_lock()) return; 1021 1022 if (_c2_compile_queue != nullptr) { 1023 int old_c2_count = _compilers[1]->num_compiler_threads(); 1024 int new_c2_count = MIN4(_c2_count, 1025 _c2_compile_queue->size() / 2, 1026 (int)(free_memory / (200*M)), 1027 (int)(available_cc_np / (128*K))); 1028 1029 for (int i = old_c2_count; i < new_c2_count; i++) { 1030 #if INCLUDE_JVMCI 1031 if (UseJVMCICompiler) { 1032 // Native compiler threads as used in C1/C2 can reuse the j.l.Thread 1033 // objects as their existence is completely hidden from the rest of 1034 // the VM (and those compiler threads can't call Java code to do the 1035 // creation anyway). For JVMCI we have to create new j.l.Thread objects 1036 // as they are visible and we can see unexpected thread lifecycle 1037 // transitions if we bind them to new JavaThreads. 1038 if (!THREAD->can_call_java()) break; 1039 char name_buffer[256]; 1040 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", _compilers[1]->name(), i); 1041 Handle thread_oop; 1042 { 1043 // We have to give up the lock temporarily for the Java calls. 1044 MutexUnlocker mu(CompileThread_lock); 1045 thread_oop = create_thread_oop(name_buffer, THREAD); 1046 } 1047 if (HAS_PENDING_EXCEPTION) { 1048 if (trace_compiler_threads()) { 1049 ResourceMark rm; 1050 stringStream msg; 1051 msg.print_cr("JVMCI compiler thread creation failed:"); 1052 PENDING_EXCEPTION->print_on(&msg); 1053 print_compiler_threads(msg); 1054 } 1055 CLEAR_PENDING_EXCEPTION; 1056 break; 1057 } 1058 // Check if another thread has beaten us during the Java calls. 1059 if (_compilers[1]->num_compiler_threads() != i) break; 1060 jobject thread_handle = JNIHandles::make_global(thread_oop); 1061 assert(compiler2_object(i) == nullptr, "Old one must be released!"); 1062 _compiler2_objects[i] = thread_handle; 1063 } 1064 #endif 1065 JavaThread *ct = make_thread(compiler_t, compiler2_object(i), _c2_compile_queue, _compilers[1], THREAD); 1066 if (ct == nullptr) break; 1067 _compilers[1]->set_num_compiler_threads(i + 1); 1068 if (trace_compiler_threads()) { 1069 ResourceMark rm; 1070 ThreadsListHandle tlh; // name() depends on the TLH. 1071 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct)); 1072 stringStream msg; 1073 msg.print("Added compiler thread %s (free memory: %dMB, available non-profiled code cache: %dMB)", 1074 ct->name(), (int)(free_memory/M), (int)(available_cc_np/M)); 1075 print_compiler_threads(msg); 1076 } 1077 } 1078 } 1079 1080 if (_c1_compile_queue != nullptr) { 1081 int old_c1_count = _compilers[0]->num_compiler_threads(); 1082 int new_c1_count = MIN4(_c1_count, 1083 _c1_compile_queue->size() / 4, 1084 (int)(free_memory / (100*M)), 1085 (int)(available_cc_p / (128*K))); 1086 1087 for (int i = old_c1_count; i < new_c1_count; i++) { 1088 JavaThread *ct = make_thread(compiler_t, compiler1_object(i), _c1_compile_queue, _compilers[0], THREAD); 1089 if (ct == nullptr) break; 1090 _compilers[0]->set_num_compiler_threads(i + 1); 1091 if (trace_compiler_threads()) { 1092 ResourceMark rm; 1093 ThreadsListHandle tlh; // name() depends on the TLH. 1094 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct)); 1095 stringStream msg; 1096 msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)", 1097 ct->name(), (int)(free_memory/M), (int)(available_cc_p/M)); 1098 print_compiler_threads(msg); 1099 } 1100 } 1101 } 1102 1103 CompileThread_lock->unlock(); 1104 } 1105 1106 1107 /** 1108 * Set the methods on the stack as on_stack so that redefine classes doesn't 1109 * reclaim them. This method is executed at a safepoint. 1110 */ 1111 void CompileBroker::mark_on_stack() { 1112 assert(SafepointSynchronize::is_at_safepoint(), "sanity check"); 1113 // Since we are at a safepoint, we do not need a lock to access 1114 // the compile queues. 1115 if (_c2_compile_queue != nullptr) { 1116 _c2_compile_queue->mark_on_stack(); 1117 } 1118 if (_c1_compile_queue != nullptr) { 1119 _c1_compile_queue->mark_on_stack(); 1120 } 1121 } 1122 1123 // ------------------------------------------------------------------ 1124 // CompileBroker::compile_method 1125 // 1126 // Request compilation of a method. 1127 void CompileBroker::compile_method_base(const methodHandle& method, 1128 int osr_bci, 1129 int comp_level, 1130 const methodHandle& hot_method, 1131 int hot_count, 1132 CompileTask::CompileReason compile_reason, 1133 bool blocking, 1134 Thread* thread) { 1135 guarantee(!method->is_abstract(), "cannot compile abstract methods"); 1136 assert(method->method_holder()->is_instance_klass(), 1137 "sanity check"); 1138 assert(!method->method_holder()->is_not_initialized(), 1139 "method holder must be initialized"); 1140 assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys"); 1141 1142 if (CIPrintRequests) { 1143 tty->print("request: "); 1144 method->print_short_name(tty); 1145 if (osr_bci != InvocationEntryBci) { 1146 tty->print(" osr_bci: %d", osr_bci); 1147 } 1148 tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count); 1149 if (!hot_method.is_null()) { 1150 tty->print(" hot: "); 1151 if (hot_method() != method()) { 1152 hot_method->print_short_name(tty); 1153 } else { 1154 tty->print("yes"); 1155 } 1156 } 1157 tty->cr(); 1158 } 1159 1160 // A request has been made for compilation. Before we do any 1161 // real work, check to see if the method has been compiled 1162 // in the meantime with a definitive result. 1163 if (compilation_is_complete(method, osr_bci, comp_level)) { 1164 return; 1165 } 1166 1167 #ifndef PRODUCT 1168 if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) { 1169 if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) { 1170 // Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI. 1171 return; 1172 } 1173 } 1174 #endif 1175 1176 // If this method is already in the compile queue, then 1177 // we do not block the current thread. 1178 if (compilation_is_in_queue(method)) { 1179 // We may want to decay our counter a bit here to prevent 1180 // multiple denied requests for compilation. This is an 1181 // open compilation policy issue. Note: The other possibility, 1182 // in the case that this is a blocking compile request, is to have 1183 // all subsequent blocking requesters wait for completion of 1184 // ongoing compiles. Note that in this case we'll need a protocol 1185 // for freeing the associated compile tasks. [Or we could have 1186 // a single static monitor on which all these waiters sleep.] 1187 return; 1188 } 1189 1190 // Tiered policy requires MethodCounters to exist before adding a method to 1191 // the queue. Create if we don't have them yet. 1192 method->get_method_counters(thread); 1193 1194 // Outputs from the following MutexLocker block: 1195 CompileTask* task = nullptr; 1196 CompileQueue* queue = compile_queue(comp_level); 1197 1198 // Acquire our lock. 1199 { 1200 MutexLocker locker(thread, MethodCompileQueue_lock); 1201 1202 // Make sure the method has not slipped into the queues since 1203 // last we checked; note that those checks were "fast bail-outs". 1204 // Here we need to be more careful, see 14012000 below. 1205 if (compilation_is_in_queue(method)) { 1206 return; 1207 } 1208 1209 // We need to check again to see if the compilation has 1210 // completed. A previous compilation may have registered 1211 // some result. 1212 if (compilation_is_complete(method, osr_bci, comp_level)) { 1213 return; 1214 } 1215 1216 // We now know that this compilation is not pending, complete, 1217 // or prohibited. Assign a compile_id to this compilation 1218 // and check to see if it is in our [Start..Stop) range. 1219 int compile_id = assign_compile_id(method, osr_bci); 1220 if (compile_id == 0) { 1221 // The compilation falls outside the allowed range. 1222 return; 1223 } 1224 1225 #if INCLUDE_JVMCI 1226 if (UseJVMCICompiler && blocking) { 1227 // Don't allow blocking compiles for requests triggered by JVMCI. 1228 if (thread->is_Compiler_thread()) { 1229 blocking = false; 1230 } 1231 1232 if (!UseJVMCINativeLibrary) { 1233 // Don't allow blocking compiles if inside a class initializer or while performing class loading 1234 vframeStream vfst(JavaThread::cast(thread)); 1235 for (; !vfst.at_end(); vfst.next()) { 1236 if (vfst.method()->is_class_initializer() || 1237 (vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass()) && 1238 vfst.method()->name() == vmSymbols::loadClass_name())) { 1239 blocking = false; 1240 break; 1241 } 1242 } 1243 } 1244 1245 // Don't allow blocking compilation requests to JVMCI 1246 // if JVMCI itself is not yet initialized 1247 if (!JVMCI::is_compiler_initialized() && compiler(comp_level)->is_jvmci()) { 1248 blocking = false; 1249 } 1250 1251 // Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown 1252 // to avoid deadlock between compiler thread(s) and threads run at shutdown 1253 // such as the DestroyJavaVM thread. 1254 if (JVMCI::in_shutdown()) { 1255 blocking = false; 1256 } 1257 } 1258 #endif // INCLUDE_JVMCI 1259 1260 // We will enter the compilation in the queue. 1261 // 14012000: Note that this sets the queued_for_compile bits in 1262 // the target method. We can now reason that a method cannot be 1263 // queued for compilation more than once, as follows: 1264 // Before a thread queues a task for compilation, it first acquires 1265 // the compile queue lock, then checks if the method's queued bits 1266 // are set or it has already been compiled. Thus there can not be two 1267 // instances of a compilation task for the same method on the 1268 // compilation queue. Consider now the case where the compilation 1269 // thread has already removed a task for that method from the queue 1270 // and is in the midst of compiling it. In this case, the 1271 // queued_for_compile bits must be set in the method (and these 1272 // will be visible to the current thread, since the bits were set 1273 // under protection of the compile queue lock, which we hold now. 1274 // When the compilation completes, the compiler thread first sets 1275 // the compilation result and then clears the queued_for_compile 1276 // bits. Neither of these actions are protected by a barrier (or done 1277 // under the protection of a lock), so the only guarantee we have 1278 // (on machines with TSO (Total Store Order)) is that these values 1279 // will update in that order. As a result, the only combinations of 1280 // these bits that the current thread will see are, in temporal order: 1281 // <RESULT, QUEUE> : 1282 // <0, 1> : in compile queue, but not yet compiled 1283 // <1, 1> : compiled but queue bit not cleared 1284 // <1, 0> : compiled and queue bit cleared 1285 // Because we first check the queue bits then check the result bits, 1286 // we are assured that we cannot introduce a duplicate task. 1287 // Note that if we did the tests in the reverse order (i.e. check 1288 // result then check queued bit), we could get the result bit before 1289 // the compilation completed, and the queue bit after the compilation 1290 // completed, and end up introducing a "duplicate" (redundant) task. 1291 // In that case, the compiler thread should first check if a method 1292 // has already been compiled before trying to compile it. 1293 // NOTE: in the event that there are multiple compiler threads and 1294 // there is de-optimization/recompilation, things will get hairy, 1295 // and in that case it's best to protect both the testing (here) of 1296 // these bits, and their updating (here and elsewhere) under a 1297 // common lock. 1298 task = create_compile_task(queue, 1299 compile_id, method, 1300 osr_bci, comp_level, 1301 hot_method, hot_count, compile_reason, 1302 blocking); 1303 } 1304 1305 if (blocking) { 1306 wait_for_completion(task); 1307 } 1308 } 1309 1310 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci, 1311 int comp_level, 1312 const methodHandle& hot_method, int hot_count, 1313 CompileTask::CompileReason compile_reason, 1314 TRAPS) { 1315 // Do nothing if compilebroker is not initialized or compiles are submitted on level none 1316 if (!_initialized || comp_level == CompLevel_none) { 1317 return nullptr; 1318 } 1319 1320 AbstractCompiler *comp = CompileBroker::compiler(comp_level); 1321 assert(comp != nullptr, "Ensure we have a compiler"); 1322 1323 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp); 1324 // CompileBroker::compile_method can trap and can have pending async exception. 1325 nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, directive, THREAD); 1326 DirectivesStack::release(directive); 1327 return nm; 1328 } 1329 1330 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci, 1331 int comp_level, 1332 const methodHandle& hot_method, int hot_count, 1333 CompileTask::CompileReason compile_reason, 1334 DirectiveSet* directive, 1335 TRAPS) { 1336 1337 // make sure arguments make sense 1338 assert(method->method_holder()->is_instance_klass(), "not an instance method"); 1339 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range"); 1340 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods"); 1341 assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized"); 1342 // return quickly if possible 1343 1344 // lock, make sure that the compilation 1345 // isn't prohibited in a straightforward way. 1346 AbstractCompiler* comp = CompileBroker::compiler(comp_level); 1347 if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) { 1348 return nullptr; 1349 } 1350 1351 #if INCLUDE_JVMCI 1352 if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) { 1353 return nullptr; 1354 } 1355 #endif 1356 1357 if (osr_bci == InvocationEntryBci) { 1358 // standard compilation 1359 CompiledMethod* method_code = method->code(); 1360 if (method_code != nullptr && method_code->is_nmethod()) { 1361 if (compilation_is_complete(method, osr_bci, comp_level)) { 1362 return (nmethod*) method_code; 1363 } 1364 } 1365 if (method->is_not_compilable(comp_level)) { 1366 return nullptr; 1367 } 1368 } else { 1369 // osr compilation 1370 // We accept a higher level osr method 1371 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false); 1372 if (nm != nullptr) return nm; 1373 if (method->is_not_osr_compilable(comp_level)) return nullptr; 1374 } 1375 1376 assert(!HAS_PENDING_EXCEPTION, "No exception should be present"); 1377 // some prerequisites that are compiler specific 1378 if (comp->is_c2() || comp->is_jvmci()) { 1379 method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL); 1380 // Resolve all classes seen in the signature of the method 1381 // we are compiling. 1382 Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL); 1383 } 1384 1385 // If the method is native, do the lookup in the thread requesting 1386 // the compilation. Native lookups can load code, which is not 1387 // permitted during compilation. 1388 // 1389 // Note: A native method implies non-osr compilation which is 1390 // checked with an assertion at the entry of this method. 1391 if (method->is_native() && !method->is_method_handle_intrinsic()) { 1392 address adr = NativeLookup::lookup(method, THREAD); 1393 if (HAS_PENDING_EXCEPTION) { 1394 // In case of an exception looking up the method, we just forget 1395 // about it. The interpreter will kick-in and throw the exception. 1396 method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable() 1397 CLEAR_PENDING_EXCEPTION; 1398 return nullptr; 1399 } 1400 assert(method->has_native_function(), "must have native code by now"); 1401 } 1402 1403 // RedefineClasses() has replaced this method; just return 1404 if (method->is_old()) { 1405 return nullptr; 1406 } 1407 1408 // JVMTI -- post_compile_event requires jmethod_id() that may require 1409 // a lock the compiling thread can not acquire. Prefetch it here. 1410 if (JvmtiExport::should_post_compiled_method_load()) { 1411 method->jmethod_id(); 1412 } 1413 1414 // do the compilation 1415 if (method->is_native()) { 1416 if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) { 1417 #if defined(X86) && !defined(ZERO) 1418 // The following native methods: 1419 // 1420 // java.lang.Float.intBitsToFloat 1421 // java.lang.Float.floatToRawIntBits 1422 // java.lang.Double.longBitsToDouble 1423 // java.lang.Double.doubleToRawLongBits 1424 // 1425 // are called through the interpreter even if interpreter native stubs 1426 // are not preferred (i.e., calling through adapter handlers is preferred). 1427 // The reason is that on x86_32 signaling NaNs (sNaNs) are not preserved 1428 // if the version of the methods from the native libraries is called. 1429 // As the interpreter and the C2-intrinsified version of the methods preserves 1430 // sNaNs, that would result in an inconsistent way of handling of sNaNs. 1431 if ((UseSSE >= 1 && 1432 (method->intrinsic_id() == vmIntrinsics::_intBitsToFloat || 1433 method->intrinsic_id() == vmIntrinsics::_floatToRawIntBits)) || 1434 (UseSSE >= 2 && 1435 (method->intrinsic_id() == vmIntrinsics::_longBitsToDouble || 1436 method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) { 1437 return nullptr; 1438 } 1439 #endif // X86 && !ZERO 1440 1441 // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that 1442 // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime). 1443 // 1444 // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter 1445 // in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls. 1446 AdapterHandlerLibrary::create_native_wrapper(method); 1447 } else { 1448 return nullptr; 1449 } 1450 } else { 1451 // If the compiler is shut off due to code cache getting full 1452 // fail out now so blocking compiles dont hang the java thread 1453 if (!should_compile_new_jobs()) { 1454 return nullptr; 1455 } 1456 bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles; 1457 compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, is_blocking, THREAD); 1458 } 1459 1460 // return requested nmethod 1461 // We accept a higher level osr method 1462 if (osr_bci == InvocationEntryBci) { 1463 CompiledMethod* code = method->code(); 1464 if (code == nullptr) { 1465 return (nmethod*) code; 1466 } else { 1467 return code->as_nmethod_or_null(); 1468 } 1469 } 1470 return method->lookup_osr_nmethod_for(osr_bci, comp_level, false); 1471 } 1472 1473 1474 // ------------------------------------------------------------------ 1475 // CompileBroker::compilation_is_complete 1476 // 1477 // See if compilation of this method is already complete. 1478 bool CompileBroker::compilation_is_complete(const methodHandle& method, 1479 int osr_bci, 1480 int comp_level) { 1481 bool is_osr = (osr_bci != standard_entry_bci); 1482 if (is_osr) { 1483 if (method->is_not_osr_compilable(comp_level)) { 1484 return true; 1485 } else { 1486 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true); 1487 return (result != nullptr); 1488 } 1489 } else { 1490 if (method->is_not_compilable(comp_level)) { 1491 return true; 1492 } else { 1493 CompiledMethod* result = method->code(); 1494 if (result == nullptr) return false; 1495 return comp_level == result->comp_level(); 1496 } 1497 } 1498 } 1499 1500 1501 /** 1502 * See if this compilation is already requested. 1503 * 1504 * Implementation note: there is only a single "is in queue" bit 1505 * for each method. This means that the check below is overly 1506 * conservative in the sense that an osr compilation in the queue 1507 * will block a normal compilation from entering the queue (and vice 1508 * versa). This can be remedied by a full queue search to disambiguate 1509 * cases. If it is deemed profitable, this may be done. 1510 */ 1511 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) { 1512 return method->queued_for_compilation(); 1513 } 1514 1515 // ------------------------------------------------------------------ 1516 // CompileBroker::compilation_is_prohibited 1517 // 1518 // See if this compilation is not allowed. 1519 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) { 1520 bool is_native = method->is_native(); 1521 // Some compilers may not support the compilation of natives. 1522 AbstractCompiler *comp = compiler(comp_level); 1523 if (is_native && (!CICompileNatives || comp == nullptr)) { 1524 method->set_not_compilable_quietly("native methods not supported", comp_level); 1525 return true; 1526 } 1527 1528 bool is_osr = (osr_bci != standard_entry_bci); 1529 // Some compilers may not support on stack replacement. 1530 if (is_osr && (!CICompileOSR || comp == nullptr)) { 1531 method->set_not_osr_compilable("OSR not supported", comp_level); 1532 return true; 1533 } 1534 1535 // The method may be explicitly excluded by the user. 1536 double scale; 1537 if (excluded || (CompilerOracle::has_option_value(method, CompileCommand::CompileThresholdScaling, scale) && scale == 0)) { 1538 bool quietly = CompilerOracle::be_quiet(); 1539 if (PrintCompilation && !quietly) { 1540 // This does not happen quietly... 1541 ResourceMark rm; 1542 tty->print("### Excluding %s:%s", 1543 method->is_native() ? "generation of native wrapper" : "compile", 1544 (method->is_static() ? " static" : "")); 1545 method->print_short_name(tty); 1546 tty->cr(); 1547 } 1548 method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly); 1549 } 1550 1551 return false; 1552 } 1553 1554 /** 1555 * Generate serialized IDs for compilation requests. If certain debugging flags are used 1556 * and the ID is not within the specified range, the method is not compiled and 0 is returned. 1557 * The function also allows to generate separate compilation IDs for OSR compilations. 1558 */ 1559 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) { 1560 #ifdef ASSERT 1561 bool is_osr = (osr_bci != standard_entry_bci); 1562 int id; 1563 if (method->is_native()) { 1564 assert(!is_osr, "can't be osr"); 1565 // Adapters, native wrappers and method handle intrinsics 1566 // should be generated always. 1567 return Atomic::add(CICountNative ? &_native_compilation_id : &_compilation_id, 1); 1568 } else if (CICountOSR && is_osr) { 1569 id = Atomic::add(&_osr_compilation_id, 1); 1570 if (CIStartOSR <= id && id < CIStopOSR) { 1571 return id; 1572 } 1573 } else { 1574 id = Atomic::add(&_compilation_id, 1); 1575 if (CIStart <= id && id < CIStop) { 1576 return id; 1577 } 1578 } 1579 1580 // Method was not in the appropriate compilation range. 1581 method->set_not_compilable_quietly("Not in requested compile id range"); 1582 return 0; 1583 #else 1584 // CICountOSR is a develop flag and set to 'false' by default. In a product built, 1585 // only _compilation_id is incremented. 1586 return Atomic::add(&_compilation_id, 1); 1587 #endif 1588 } 1589 1590 // ------------------------------------------------------------------ 1591 // CompileBroker::assign_compile_id_unlocked 1592 // 1593 // Public wrapper for assign_compile_id that acquires the needed locks 1594 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) { 1595 MutexLocker locker(thread, MethodCompileQueue_lock); 1596 return assign_compile_id(method, osr_bci); 1597 } 1598 1599 // ------------------------------------------------------------------ 1600 // CompileBroker::create_compile_task 1601 // 1602 // Create a CompileTask object representing the current request for 1603 // compilation. Add this task to the queue. 1604 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue, 1605 int compile_id, 1606 const methodHandle& method, 1607 int osr_bci, 1608 int comp_level, 1609 const methodHandle& hot_method, 1610 int hot_count, 1611 CompileTask::CompileReason compile_reason, 1612 bool blocking) { 1613 CompileTask* new_task = CompileTask::allocate(); 1614 new_task->initialize(compile_id, method, osr_bci, comp_level, 1615 hot_method, hot_count, compile_reason, 1616 blocking); 1617 queue->add(new_task); 1618 return new_task; 1619 } 1620 1621 #if INCLUDE_JVMCI 1622 // The number of milliseconds to wait before checking if 1623 // JVMCI compilation has made progress. 1624 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000; 1625 1626 // The number of JVMCI compilation progress checks that must fail 1627 // before unblocking a thread waiting for a blocking compilation. 1628 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10; 1629 1630 /** 1631 * Waits for a JVMCI compiler to complete a given task. This thread 1632 * waits until either the task completes or it sees no JVMCI compilation 1633 * progress for N consecutive milliseconds where N is 1634 * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE * 1635 * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS. 1636 * 1637 * @return true if this thread needs to free/recycle the task 1638 */ 1639 bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) { 1640 assert(UseJVMCICompiler, "sanity"); 1641 MonitorLocker ml(thread, task->lock()); 1642 int progress_wait_attempts = 0; 1643 jint thread_jvmci_compilation_ticks = 0; 1644 jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks(); 1645 while (!task->is_complete() && !is_compilation_disabled_forever() && 1646 ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) { 1647 JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state(); 1648 1649 bool progress; 1650 if (jvmci_compile_state != nullptr) { 1651 jint ticks = jvmci_compile_state->compilation_ticks(); 1652 progress = (ticks - thread_jvmci_compilation_ticks) != 0; 1653 JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks); 1654 thread_jvmci_compilation_ticks = ticks; 1655 } else { 1656 // Still waiting on JVMCI compiler queue. This thread may be holding a lock 1657 // that all JVMCI compiler threads are blocked on. We use the global JVMCI 1658 // compilation ticks to determine whether JVMCI compilation 1659 // is still making progress through the JVMCI compiler queue. 1660 jint ticks = jvmci->global_compilation_ticks(); 1661 progress = (ticks - global_jvmci_compilation_ticks) != 0; 1662 JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks); 1663 global_jvmci_compilation_ticks = ticks; 1664 } 1665 1666 if (!progress) { 1667 if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) { 1668 if (PrintCompilation) { 1669 task->print(tty, "wait for blocking compilation timed out"); 1670 } 1671 JVMCI_event_1("waiting on compilation %d timed out", task->compile_id()); 1672 break; 1673 } 1674 } else { 1675 progress_wait_attempts = 0; 1676 } 1677 } 1678 task->clear_waiter(); 1679 return task->is_complete(); 1680 } 1681 #endif 1682 1683 /** 1684 * Wait for the compilation task to complete. 1685 */ 1686 void CompileBroker::wait_for_completion(CompileTask* task) { 1687 if (CIPrintCompileQueue) { 1688 ttyLocker ttyl; 1689 tty->print_cr("BLOCKING FOR COMPILE"); 1690 } 1691 1692 assert(task->is_blocking(), "can only wait on blocking task"); 1693 1694 JavaThread* thread = JavaThread::current(); 1695 1696 methodHandle method(thread, task->method()); 1697 bool free_task; 1698 #if INCLUDE_JVMCI 1699 AbstractCompiler* comp = compiler(task->comp_level()); 1700 if (comp->is_jvmci() && !task->should_wait_for_compilation()) { 1701 // It may return before compilation is completed. 1702 free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread); 1703 } else 1704 #endif 1705 { 1706 MonitorLocker ml(thread, task->lock()); 1707 free_task = true; 1708 while (!task->is_complete() && !is_compilation_disabled_forever()) { 1709 ml.wait(); 1710 } 1711 } 1712 1713 if (free_task) { 1714 if (is_compilation_disabled_forever()) { 1715 CompileTask::free(task); 1716 return; 1717 } 1718 1719 // It is harmless to check this status without the lock, because 1720 // completion is a stable property (until the task object is recycled). 1721 assert(task->is_complete(), "Compilation should have completed"); 1722 1723 // By convention, the waiter is responsible for recycling a 1724 // blocking CompileTask. Since there is only one waiter ever 1725 // waiting on a CompileTask, we know that no one else will 1726 // be using this CompileTask; we can free it. 1727 CompileTask::free(task); 1728 } 1729 } 1730 1731 /** 1732 * Initialize compiler thread(s) + compiler object(s). The postcondition 1733 * of this function is that the compiler runtimes are initialized and that 1734 * compiler threads can start compiling. 1735 */ 1736 bool CompileBroker::init_compiler_runtime() { 1737 CompilerThread* thread = CompilerThread::current(); 1738 AbstractCompiler* comp = thread->compiler(); 1739 // Final sanity check - the compiler object must exist 1740 guarantee(comp != nullptr, "Compiler object must exist"); 1741 1742 { 1743 // Must switch to native to allocate ci_env 1744 ThreadToNativeFromVM ttn(thread); 1745 ciEnv ci_env((CompileTask*)nullptr); 1746 // Cache Jvmti state 1747 ci_env.cache_jvmti_state(); 1748 // Cache DTrace flags 1749 ci_env.cache_dtrace_flags(); 1750 1751 // Switch back to VM state to do compiler initialization 1752 ThreadInVMfromNative tv(thread); 1753 1754 // Perform per-thread and global initializations 1755 comp->initialize(); 1756 } 1757 1758 if (comp->is_failed()) { 1759 disable_compilation_forever(); 1760 // If compiler initialization failed, no compiler thread that is specific to a 1761 // particular compiler runtime will ever start to compile methods. 1762 shutdown_compiler_runtime(comp, thread); 1763 return false; 1764 } 1765 1766 // C1 specific check 1767 if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) { 1768 warning("Initialization of %s thread failed (no space to run compilers)", thread->name()); 1769 return false; 1770 } 1771 1772 return true; 1773 } 1774 1775 /** 1776 * If C1 and/or C2 initialization failed, we shut down all compilation. 1777 * We do this to keep things simple. This can be changed if it ever turns 1778 * out to be a problem. 1779 */ 1780 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) { 1781 // Free buffer blob, if allocated 1782 if (thread->get_buffer_blob() != nullptr) { 1783 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1784 CodeCache::free(thread->get_buffer_blob()); 1785 } 1786 1787 if (comp->should_perform_shutdown()) { 1788 // There are two reasons for shutting down the compiler 1789 // 1) compiler runtime initialization failed 1790 // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing 1791 warning("%s initialization failed. Shutting down all compilers", comp->name()); 1792 1793 // Only one thread per compiler runtime object enters here 1794 // Set state to shut down 1795 comp->set_shut_down(); 1796 1797 // Delete all queued compilation tasks to make compiler threads exit faster. 1798 if (_c1_compile_queue != nullptr) { 1799 _c1_compile_queue->free_all(); 1800 } 1801 1802 if (_c2_compile_queue != nullptr) { 1803 _c2_compile_queue->free_all(); 1804 } 1805 1806 // Set flags so that we continue execution with using interpreter only. 1807 UseCompiler = false; 1808 UseInterpreter = true; 1809 1810 // We could delete compiler runtimes also. However, there are references to 1811 // the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then 1812 // fail. This can be done later if necessary. 1813 } 1814 } 1815 1816 /** 1817 * Helper function to create new or reuse old CompileLog. 1818 */ 1819 CompileLog* CompileBroker::get_log(CompilerThread* ct) { 1820 if (!LogCompilation) return nullptr; 1821 1822 AbstractCompiler *compiler = ct->compiler(); 1823 bool c1 = compiler->is_c1(); 1824 jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects; 1825 assert(compiler_objects != nullptr, "must be initialized at this point"); 1826 CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs; 1827 assert(logs != nullptr, "must be initialized at this point"); 1828 int count = c1 ? _c1_count : _c2_count; 1829 1830 // Find Compiler number by its threadObj. 1831 oop compiler_obj = ct->threadObj(); 1832 int compiler_number = 0; 1833 bool found = false; 1834 for (; compiler_number < count; compiler_number++) { 1835 if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) { 1836 found = true; 1837 break; 1838 } 1839 } 1840 assert(found, "Compiler must exist at this point"); 1841 1842 // Determine pointer for this thread's log. 1843 CompileLog** log_ptr = &logs[compiler_number]; 1844 1845 // Return old one if it exists. 1846 CompileLog* log = *log_ptr; 1847 if (log != nullptr) { 1848 ct->init_log(log); 1849 return log; 1850 } 1851 1852 // Create a new one and remember it. 1853 init_compiler_thread_log(); 1854 log = ct->log(); 1855 *log_ptr = log; 1856 return log; 1857 } 1858 1859 // ------------------------------------------------------------------ 1860 // CompileBroker::compiler_thread_loop 1861 // 1862 // The main loop run by a CompilerThread. 1863 void CompileBroker::compiler_thread_loop() { 1864 CompilerThread* thread = CompilerThread::current(); 1865 CompileQueue* queue = thread->queue(); 1866 // For the thread that initializes the ciObjectFactory 1867 // this resource mark holds all the shared objects 1868 ResourceMark rm; 1869 1870 // First thread to get here will initialize the compiler interface 1871 1872 { 1873 ASSERT_IN_VM; 1874 MutexLocker only_one (thread, CompileThread_lock); 1875 if (!ciObjectFactory::is_initialized()) { 1876 ciObjectFactory::initialize(); 1877 } 1878 } 1879 1880 // Open a log. 1881 CompileLog* log = get_log(thread); 1882 if (log != nullptr) { 1883 log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'", 1884 thread->name(), 1885 os::current_thread_id(), 1886 os::current_process_id()); 1887 log->stamp(); 1888 log->end_elem(); 1889 } 1890 1891 // If compiler thread/runtime initialization fails, exit the compiler thread 1892 if (!init_compiler_runtime()) { 1893 return; 1894 } 1895 1896 thread->start_idle_timer(); 1897 1898 // Poll for new compilation tasks as long as the JVM runs. Compilation 1899 // should only be disabled if something went wrong while initializing the 1900 // compiler runtimes. This, in turn, should not happen. The only known case 1901 // when compiler runtime initialization fails is if there is not enough free 1902 // space in the code cache to generate the necessary stubs, etc. 1903 while (!is_compilation_disabled_forever()) { 1904 // We need this HandleMark to avoid leaking VM handles. 1905 HandleMark hm(thread); 1906 1907 CompileTask* task = queue->get(thread); 1908 if (task == nullptr) { 1909 if (UseDynamicNumberOfCompilerThreads) { 1910 // Access compiler_count under lock to enforce consistency. 1911 MutexLocker only_one(CompileThread_lock); 1912 if (can_remove(thread, true)) { 1913 if (trace_compiler_threads()) { 1914 ResourceMark rm; 1915 stringStream msg; 1916 msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time", 1917 thread->name(), thread->idle_time_millis()); 1918 print_compiler_threads(msg); 1919 } 1920 1921 // Notify compiler that the compiler thread is about to stop 1922 thread->compiler()->stopping_compiler_thread(thread); 1923 1924 // Free buffer blob, if allocated 1925 if (thread->get_buffer_blob() != nullptr) { 1926 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1927 CodeCache::free(thread->get_buffer_blob()); 1928 } 1929 return; // Stop this thread. 1930 } 1931 } 1932 } else { 1933 // Assign the task to the current thread. Mark this compilation 1934 // thread as active for the profiler. 1935 // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition 1936 // occurs after fetching the compile task off the queue. 1937 CompileTaskWrapper ctw(task); 1938 methodHandle method(thread, task->method()); 1939 1940 // Never compile a method if breakpoints are present in it 1941 if (method()->number_of_breakpoints() == 0) { 1942 // Compile the method. 1943 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) { 1944 invoke_compiler_on_method(task); 1945 thread->start_idle_timer(); 1946 } else { 1947 // After compilation is disabled, remove remaining methods from queue 1948 method->clear_queued_for_compilation(); 1949 task->set_failure_reason("compilation is disabled"); 1950 } 1951 } else { 1952 task->set_failure_reason("breakpoints are present"); 1953 } 1954 1955 if (UseDynamicNumberOfCompilerThreads) { 1956 possibly_add_compiler_threads(thread); 1957 assert(!thread->has_pending_exception(), "should have been handled"); 1958 } 1959 } 1960 } 1961 1962 // Shut down compiler runtime 1963 shutdown_compiler_runtime(thread->compiler(), thread); 1964 } 1965 1966 // ------------------------------------------------------------------ 1967 // CompileBroker::init_compiler_thread_log 1968 // 1969 // Set up state required by +LogCompilation. 1970 void CompileBroker::init_compiler_thread_log() { 1971 CompilerThread* thread = CompilerThread::current(); 1972 char file_name[4*K]; 1973 FILE* fp = nullptr; 1974 intx thread_id = os::current_thread_id(); 1975 for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) { 1976 const char* dir = (try_temp_dir ? os::get_temp_directory() : nullptr); 1977 if (dir == nullptr) { 1978 jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log", 1979 thread_id, os::current_process_id()); 1980 } else { 1981 jio_snprintf(file_name, sizeof(file_name), 1982 "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir, 1983 os::file_separator(), thread_id, os::current_process_id()); 1984 } 1985 1986 fp = os::fopen(file_name, "wt"); 1987 if (fp != nullptr) { 1988 if (LogCompilation && Verbose) { 1989 tty->print_cr("Opening compilation log %s", file_name); 1990 } 1991 CompileLog* log = new(mtCompiler) CompileLog(file_name, fp, thread_id); 1992 if (log == nullptr) { 1993 fclose(fp); 1994 return; 1995 } 1996 thread->init_log(log); 1997 1998 if (xtty != nullptr) { 1999 ttyLocker ttyl; 2000 // Record any per thread log files 2001 xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name); 2002 } 2003 return; 2004 } 2005 } 2006 warning("Cannot open log file: %s", file_name); 2007 } 2008 2009 void CompileBroker::log_metaspace_failure() { 2010 const char* message = "some methods may not be compiled because metaspace " 2011 "is out of memory"; 2012 if (CompilationLog::log() != nullptr) { 2013 CompilationLog::log()->log_metaspace_failure(message); 2014 } 2015 if (PrintCompilation) { 2016 tty->print_cr("COMPILE PROFILING SKIPPED: %s", message); 2017 } 2018 } 2019 2020 2021 // ------------------------------------------------------------------ 2022 // CompileBroker::set_should_block 2023 // 2024 // Set _should_block. 2025 // Call this from the VM, with Threads_lock held and a safepoint requested. 2026 void CompileBroker::set_should_block() { 2027 assert(Threads_lock->owner() == Thread::current(), "must have threads lock"); 2028 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already"); 2029 #ifndef PRODUCT 2030 if (PrintCompilation && (Verbose || WizardMode)) 2031 tty->print_cr("notifying compiler thread pool to block"); 2032 #endif 2033 _should_block = true; 2034 } 2035 2036 // ------------------------------------------------------------------ 2037 // CompileBroker::maybe_block 2038 // 2039 // Call this from the compiler at convenient points, to poll for _should_block. 2040 void CompileBroker::maybe_block() { 2041 if (_should_block) { 2042 #ifndef PRODUCT 2043 if (PrintCompilation && (Verbose || WizardMode)) 2044 tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current())); 2045 #endif 2046 ThreadInVMfromNative tivfn(JavaThread::current()); 2047 } 2048 } 2049 2050 // wrapper for CodeCache::print_summary() 2051 static void codecache_print(bool detailed) 2052 { 2053 stringStream s; 2054 // Dump code cache into a buffer before locking the tty, 2055 { 2056 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 2057 CodeCache::print_summary(&s, detailed); 2058 } 2059 ttyLocker ttyl; 2060 tty->print("%s", s.freeze()); 2061 } 2062 2063 // wrapper for CodeCache::print_summary() using outputStream 2064 static void codecache_print(outputStream* out, bool detailed) { 2065 stringStream s; 2066 2067 // Dump code cache into a buffer 2068 { 2069 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 2070 CodeCache::print_summary(&s, detailed); 2071 } 2072 2073 char* remaining_log = s.as_string(); 2074 while (*remaining_log != '\0') { 2075 char* eol = strchr(remaining_log, '\n'); 2076 if (eol == nullptr) { 2077 out->print_cr("%s", remaining_log); 2078 remaining_log = remaining_log + strlen(remaining_log); 2079 } else { 2080 *eol = '\0'; 2081 out->print_cr("%s", remaining_log); 2082 remaining_log = eol + 1; 2083 } 2084 } 2085 } 2086 2087 void CompileBroker::handle_compile_error(CompilerThread* thread, CompileTask* task, ciEnv* ci_env, 2088 int compilable, const char* failure_reason) { 2089 if (!AbortVMOnCompilationFailure) { 2090 return; 2091 } 2092 if (compilable == ciEnv::MethodCompilable_not_at_tier) { 2093 fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason); 2094 } 2095 if (compilable == ciEnv::MethodCompilable_never) { 2096 fatal("Never compilable: %s", failure_reason); 2097 } 2098 } 2099 2100 static void post_compilation_event(EventCompilation& event, CompileTask* task) { 2101 assert(task != nullptr, "invariant"); 2102 CompilerEvent::CompilationEvent::post(event, 2103 task->compile_id(), 2104 task->compiler()->type(), 2105 task->method(), 2106 task->comp_level(), 2107 task->is_success(), 2108 task->osr_bci() != CompileBroker::standard_entry_bci, 2109 task->nm_total_size(), 2110 task->num_inlined_bytecodes()); 2111 } 2112 2113 int DirectivesStack::_depth = 0; 2114 CompilerDirectives* DirectivesStack::_top = nullptr; 2115 CompilerDirectives* DirectivesStack::_bottom = nullptr; 2116 2117 // Acquires Compilation_lock and waits for it to be notified 2118 // as long as WhiteBox::compilation_locked is true. 2119 static void whitebox_lock_compilation() { 2120 MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag); 2121 while (WhiteBox::compilation_locked) { 2122 locker.wait(); 2123 } 2124 } 2125 2126 // ------------------------------------------------------------------ 2127 // CompileBroker::invoke_compiler_on_method 2128 // 2129 // Compile a method. 2130 // 2131 void CompileBroker::invoke_compiler_on_method(CompileTask* task) { 2132 task->print_ul(); 2133 elapsedTimer time; 2134 2135 DirectiveSet* directive = task->directive(); 2136 if (directive->PrintCompilationOption) { 2137 ResourceMark rm; 2138 task->print_tty(); 2139 } 2140 2141 CompilerThread* thread = CompilerThread::current(); 2142 ResourceMark rm(thread); 2143 2144 if (CompilationLog::log() != nullptr) { 2145 CompilationLog::log()->log_compile(thread, task); 2146 } 2147 2148 // Common flags. 2149 int compile_id = task->compile_id(); 2150 int osr_bci = task->osr_bci(); 2151 bool is_osr = (osr_bci != standard_entry_bci); 2152 bool should_log = (thread->log() != nullptr); 2153 bool should_break = false; 2154 const int task_level = task->comp_level(); 2155 AbstractCompiler* comp = task->compiler(); 2156 { 2157 // create the handle inside it's own block so it can't 2158 // accidentally be referenced once the thread transitions to 2159 // native. The NoHandleMark before the transition should catch 2160 // any cases where this occurs in the future. 2161 methodHandle method(thread, task->method()); 2162 2163 assert(!method->is_native(), "no longer compile natives"); 2164 2165 // Update compile information when using perfdata. 2166 if (UsePerfData) { 2167 update_compile_perf_data(thread, method, is_osr); 2168 } 2169 2170 DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level)); 2171 } 2172 2173 should_break = directive->BreakAtCompileOption || task->check_break_at_flags(); 2174 if (should_log && !directive->LogOption) { 2175 should_log = false; 2176 } 2177 2178 // Allocate a new set of JNI handles. 2179 JNIHandleMark jhm(thread); 2180 Method* target_handle = task->method(); 2181 int compilable = ciEnv::MethodCompilable; 2182 const char* failure_reason = nullptr; 2183 bool failure_reason_on_C_heap = false; 2184 const char* retry_message = nullptr; 2185 2186 #if INCLUDE_JVMCI 2187 if (UseJVMCICompiler && comp != nullptr && comp->is_jvmci()) { 2188 JVMCICompiler* jvmci = (JVMCICompiler*) comp; 2189 2190 TraceTime t1("compilation", &time); 2191 EventCompilation event; 2192 JVMCICompileState compile_state(task, jvmci); 2193 JVMCIRuntime *runtime = nullptr; 2194 2195 if (JVMCI::in_shutdown()) { 2196 failure_reason = "in JVMCI shutdown"; 2197 retry_message = "not retryable"; 2198 compilable = ciEnv::MethodCompilable_never; 2199 } else if (compile_state.target_method_is_old()) { 2200 // Skip redefined methods 2201 failure_reason = "redefined method"; 2202 retry_message = "not retryable"; 2203 compilable = ciEnv::MethodCompilable_never; 2204 } else { 2205 JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__); 2206 failure_reason = compile_state.failure_reason(); 2207 if (failure_reason == nullptr) { 2208 if (WhiteBoxAPI && WhiteBox::compilation_locked) { 2209 // Must switch to native to block 2210 ThreadToNativeFromVM ttn(thread); 2211 whitebox_lock_compilation(); 2212 } 2213 methodHandle method(thread, target_handle); 2214 runtime = env.runtime(); 2215 runtime->compile_method(&env, jvmci, method, osr_bci); 2216 2217 failure_reason = compile_state.failure_reason(); 2218 failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap(); 2219 if (!compile_state.retryable()) { 2220 retry_message = "not retryable"; 2221 compilable = ciEnv::MethodCompilable_not_at_tier; 2222 } 2223 if (!task->is_success()) { 2224 assert(failure_reason != nullptr, "must specify failure_reason"); 2225 } 2226 } 2227 } 2228 if (!task->is_success()) { 2229 handle_compile_error(thread, task, nullptr, compilable, failure_reason); 2230 } 2231 if (event.should_commit()) { 2232 post_compilation_event(event, task); 2233 } 2234 2235 if (runtime != nullptr) { 2236 runtime->post_compile(thread); 2237 } 2238 } else 2239 #endif // INCLUDE_JVMCI 2240 { 2241 NoHandleMark nhm; 2242 ThreadToNativeFromVM ttn(thread); 2243 2244 ciEnv ci_env(task); 2245 if (should_break) { 2246 ci_env.set_break_at_compile(true); 2247 } 2248 if (should_log) { 2249 ci_env.set_log(thread->log()); 2250 } 2251 assert(thread->env() == &ci_env, "set by ci_env"); 2252 // The thread-env() field is cleared in ~CompileTaskWrapper. 2253 2254 // Cache Jvmti state 2255 bool method_is_old = ci_env.cache_jvmti_state(); 2256 2257 // Skip redefined methods 2258 if (method_is_old) { 2259 ci_env.record_method_not_compilable("redefined method", true); 2260 } 2261 2262 // Cache DTrace flags 2263 ci_env.cache_dtrace_flags(); 2264 2265 ciMethod* target = ci_env.get_method_from_handle(target_handle); 2266 2267 TraceTime t1("compilation", &time); 2268 EventCompilation event; 2269 2270 if (comp == nullptr) { 2271 ci_env.record_method_not_compilable("no compiler"); 2272 } else if (!ci_env.failing()) { 2273 if (WhiteBoxAPI && WhiteBox::compilation_locked) { 2274 whitebox_lock_compilation(); 2275 } 2276 comp->compile_method(&ci_env, target, osr_bci, true, directive); 2277 2278 /* Repeat compilation without installing code for profiling purposes */ 2279 int repeat_compilation_count = directive->RepeatCompilationOption; 2280 while (repeat_compilation_count > 0) { 2281 ResourceMark rm(thread); 2282 task->print_ul("NO CODE INSTALLED"); 2283 comp->compile_method(&ci_env, target, osr_bci, false, directive); 2284 repeat_compilation_count--; 2285 } 2286 } 2287 2288 DirectivesStack::release(directive); 2289 2290 if (!ci_env.failing() && !task->is_success()) { 2291 assert(ci_env.failure_reason() != nullptr, "expect failure reason"); 2292 assert(false, "compiler should always document failure: %s", ci_env.failure_reason()); 2293 // The compiler elected, without comment, not to register a result. 2294 // Do not attempt further compilations of this method. 2295 ci_env.record_method_not_compilable("compile failed"); 2296 } 2297 2298 // Copy this bit to the enclosing block: 2299 compilable = ci_env.compilable(); 2300 2301 if (ci_env.failing()) { 2302 failure_reason = ci_env.failure_reason(); 2303 retry_message = ci_env.retry_message(); 2304 ci_env.report_failure(failure_reason); 2305 } 2306 2307 if (ci_env.failing()) { 2308 handle_compile_error(thread, task, &ci_env, compilable, failure_reason); 2309 } 2310 if (event.should_commit()) { 2311 post_compilation_event(event, task); 2312 } 2313 } 2314 2315 if (failure_reason != nullptr) { 2316 task->set_failure_reason(failure_reason, failure_reason_on_C_heap); 2317 if (CompilationLog::log() != nullptr) { 2318 CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message); 2319 } 2320 if (PrintCompilation) { 2321 FormatBufferResource msg = retry_message != nullptr ? 2322 FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) : 2323 FormatBufferResource("COMPILE SKIPPED: %s", failure_reason); 2324 task->print(tty, msg); 2325 } 2326 } 2327 2328 methodHandle method(thread, task->method()); 2329 2330 DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success()); 2331 2332 collect_statistics(thread, time, task); 2333 2334 if (PrintCompilation && PrintCompilation2) { 2335 tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp 2336 tty->print("%4d ", compile_id); // print compilation number 2337 tty->print("%s ", (is_osr ? "%" : " ")); 2338 if (task->is_success()) { 2339 tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size()); 2340 } 2341 tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes()); 2342 } 2343 2344 Log(compilation, codecache) log; 2345 if (log.is_debug()) { 2346 LogStream ls(log.debug()); 2347 codecache_print(&ls, /* detailed= */ false); 2348 } 2349 if (PrintCodeCacheOnCompilation) { 2350 codecache_print(/* detailed= */ false); 2351 } 2352 // Disable compilation, if required. 2353 switch (compilable) { 2354 case ciEnv::MethodCompilable_never: 2355 if (is_osr) 2356 method->set_not_osr_compilable_quietly("MethodCompilable_never"); 2357 else 2358 method->set_not_compilable_quietly("MethodCompilable_never"); 2359 break; 2360 case ciEnv::MethodCompilable_not_at_tier: 2361 if (is_osr) 2362 method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level); 2363 else 2364 method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level); 2365 break; 2366 } 2367 2368 // Note that the queued_for_compilation bits are cleared without 2369 // protection of a mutex. [They were set by the requester thread, 2370 // when adding the task to the compile queue -- at which time the 2371 // compile queue lock was held. Subsequently, we acquired the compile 2372 // queue lock to get this task off the compile queue; thus (to belabour 2373 // the point somewhat) our clearing of the bits must be occurring 2374 // only after the setting of the bits. See also 14012000 above. 2375 method->clear_queued_for_compilation(); 2376 } 2377 2378 /** 2379 * The CodeCache is full. Print warning and disable compilation. 2380 * Schedule code cache cleaning so compilation can continue later. 2381 * This function needs to be called only from CodeCache::allocate(), 2382 * since we currently handle a full code cache uniformly. 2383 */ 2384 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) { 2385 UseInterpreter = true; 2386 if (UseCompiler || AlwaysCompileLoopMethods ) { 2387 if (xtty != nullptr) { 2388 stringStream s; 2389 // Dump code cache state into a buffer before locking the tty, 2390 // because log_state() will use locks causing lock conflicts. 2391 CodeCache::log_state(&s); 2392 // Lock to prevent tearing 2393 ttyLocker ttyl; 2394 xtty->begin_elem("code_cache_full"); 2395 xtty->print("%s", s.freeze()); 2396 xtty->stamp(); 2397 xtty->end_elem(); 2398 } 2399 2400 #ifndef PRODUCT 2401 if (ExitOnFullCodeCache) { 2402 codecache_print(/* detailed= */ true); 2403 before_exit(JavaThread::current()); 2404 exit_globals(); // will delete tty 2405 vm_direct_exit(1); 2406 } 2407 #endif 2408 if (UseCodeCacheFlushing) { 2409 // Since code cache is full, immediately stop new compiles 2410 if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) { 2411 log_info(codecache)("Code cache is full - disabling compilation"); 2412 } 2413 } else { 2414 disable_compilation_forever(); 2415 } 2416 2417 CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning()); 2418 } 2419 } 2420 2421 // ------------------------------------------------------------------ 2422 // CompileBroker::update_compile_perf_data 2423 // 2424 // Record this compilation for debugging purposes. 2425 void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) { 2426 ResourceMark rm; 2427 char* method_name = method->name()->as_C_string(); 2428 char current_method[CompilerCounters::cmname_buffer_length]; 2429 size_t maxLen = CompilerCounters::cmname_buffer_length; 2430 2431 const char* class_name = method->method_holder()->name()->as_C_string(); 2432 2433 size_t s1len = strlen(class_name); 2434 size_t s2len = strlen(method_name); 2435 2436 // check if we need to truncate the string 2437 if (s1len + s2len + 2 > maxLen) { 2438 2439 // the strategy is to lop off the leading characters of the 2440 // class name and the trailing characters of the method name. 2441 2442 if (s2len + 2 > maxLen) { 2443 // lop of the entire class name string, let snprintf handle 2444 // truncation of the method name. 2445 class_name += s1len; // null string 2446 } 2447 else { 2448 // lop off the extra characters from the front of the class name 2449 class_name += ((s1len + s2len + 2) - maxLen); 2450 } 2451 } 2452 2453 jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name); 2454 2455 int last_compile_type = normal_compile; 2456 if (CICountOSR && is_osr) { 2457 last_compile_type = osr_compile; 2458 } else if (CICountNative && method->is_native()) { 2459 last_compile_type = native_compile; 2460 } 2461 2462 CompilerCounters* counters = thread->counters(); 2463 counters->set_current_method(current_method); 2464 counters->set_compile_type((jlong) last_compile_type); 2465 } 2466 2467 // ------------------------------------------------------------------ 2468 // CompileBroker::collect_statistics 2469 // 2470 // Collect statistics about the compilation. 2471 2472 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) { 2473 bool success = task->is_success(); 2474 methodHandle method (thread, task->method()); 2475 int compile_id = task->compile_id(); 2476 bool is_osr = (task->osr_bci() != standard_entry_bci); 2477 const int comp_level = task->comp_level(); 2478 CompilerCounters* counters = thread->counters(); 2479 2480 MutexLocker locker(CompileStatistics_lock); 2481 2482 // _perf variables are production performance counters which are 2483 // updated regardless of the setting of the CITime and CITimeEach flags 2484 // 2485 2486 // account all time, including bailouts and failures in this counter; 2487 // C1 and C2 counters are counting both successful and unsuccessful compiles 2488 _t_total_compilation.add(time); 2489 2490 if (!success) { 2491 _total_bailout_count++; 2492 if (UsePerfData) { 2493 _perf_last_failed_method->set_value(counters->current_method()); 2494 _perf_last_failed_type->set_value(counters->compile_type()); 2495 _perf_total_bailout_count->inc(); 2496 } 2497 _t_bailedout_compilation.add(time); 2498 } else if (!task->is_success()) { 2499 if (UsePerfData) { 2500 _perf_last_invalidated_method->set_value(counters->current_method()); 2501 _perf_last_invalidated_type->set_value(counters->compile_type()); 2502 _perf_total_invalidated_count->inc(); 2503 } 2504 _total_invalidated_count++; 2505 _t_invalidated_compilation.add(time); 2506 } else { 2507 // Compilation succeeded 2508 2509 // update compilation ticks - used by the implementation of 2510 // java.lang.management.CompilationMXBean 2511 _perf_total_compilation->inc(time.ticks()); 2512 _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time; 2513 2514 if (CITime) { 2515 int bytes_compiled = method->code_size() + task->num_inlined_bytecodes(); 2516 if (is_osr) { 2517 _t_osr_compilation.add(time); 2518 _sum_osr_bytes_compiled += bytes_compiled; 2519 } else { 2520 _t_standard_compilation.add(time); 2521 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes(); 2522 } 2523 2524 // Collect statistic per compilation level 2525 if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) { 2526 CompilerStatistics* stats = &_stats_per_level[comp_level-1]; 2527 if (is_osr) { 2528 stats->_osr.update(time, bytes_compiled); 2529 } else { 2530 stats->_standard.update(time, bytes_compiled); 2531 } 2532 stats->_nmethods_size += task->nm_total_size(); 2533 stats->_nmethods_code_size += task->nm_insts_size(); 2534 } else { 2535 assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level); 2536 } 2537 2538 // Collect statistic per compiler 2539 AbstractCompiler* comp = compiler(comp_level); 2540 if (comp) { 2541 CompilerStatistics* stats = comp->stats(); 2542 if (is_osr) { 2543 stats->_osr.update(time, bytes_compiled); 2544 } else { 2545 stats->_standard.update(time, bytes_compiled); 2546 } 2547 stats->_nmethods_size += task->nm_total_size(); 2548 stats->_nmethods_code_size += task->nm_insts_size(); 2549 } else { // if (!comp) 2550 assert(false, "Compiler object must exist"); 2551 } 2552 } 2553 2554 if (UsePerfData) { 2555 // save the name of the last method compiled 2556 _perf_last_method->set_value(counters->current_method()); 2557 _perf_last_compile_type->set_value(counters->compile_type()); 2558 _perf_last_compile_size->set_value(method->code_size() + 2559 task->num_inlined_bytecodes()); 2560 if (is_osr) { 2561 _perf_osr_compilation->inc(time.ticks()); 2562 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes()); 2563 } else { 2564 _perf_standard_compilation->inc(time.ticks()); 2565 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes()); 2566 } 2567 } 2568 2569 if (CITimeEach) { 2570 double compile_time = time.seconds(); 2571 double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time; 2572 tty->print_cr("%3d seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)", 2573 compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes()); 2574 } 2575 2576 // Collect counts of successful compilations 2577 _sum_nmethod_size += task->nm_total_size(); 2578 _sum_nmethod_code_size += task->nm_insts_size(); 2579 _total_compile_count++; 2580 2581 if (UsePerfData) { 2582 _perf_sum_nmethod_size->inc( task->nm_total_size()); 2583 _perf_sum_nmethod_code_size->inc(task->nm_insts_size()); 2584 _perf_total_compile_count->inc(); 2585 } 2586 2587 if (is_osr) { 2588 if (UsePerfData) _perf_total_osr_compile_count->inc(); 2589 _total_osr_compile_count++; 2590 } else { 2591 if (UsePerfData) _perf_total_standard_compile_count->inc(); 2592 _total_standard_compile_count++; 2593 } 2594 } 2595 // set the current method for the thread to null 2596 if (UsePerfData) counters->set_current_method(""); 2597 } 2598 2599 const char* CompileBroker::compiler_name(int comp_level) { 2600 AbstractCompiler *comp = CompileBroker::compiler(comp_level); 2601 if (comp == nullptr) { 2602 return "no compiler"; 2603 } else { 2604 return (comp->name()); 2605 } 2606 } 2607 2608 jlong CompileBroker::total_compilation_ticks() { 2609 return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0; 2610 } 2611 2612 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) { 2613 tty->print_cr(" %s {speed: %6.3f bytes/s; standard: %6.3f s, %u bytes, %u methods; osr: %6.3f s, %u bytes, %u methods; nmethods_size: %u bytes; nmethods_code_size: %u bytes}", 2614 name, stats->bytes_per_second(), 2615 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count, 2616 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count, 2617 stats->_nmethods_size, stats->_nmethods_code_size); 2618 } 2619 2620 void CompileBroker::print_times(bool per_compiler, bool aggregate) { 2621 if (per_compiler) { 2622 if (aggregate) { 2623 tty->cr(); 2624 tty->print_cr("Individual compiler times (for compiled methods only)"); 2625 tty->print_cr("------------------------------------------------"); 2626 tty->cr(); 2627 } 2628 for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) { 2629 AbstractCompiler* comp = _compilers[i]; 2630 if (comp != nullptr) { 2631 print_times(comp->name(), comp->stats()); 2632 } 2633 } 2634 if (aggregate) { 2635 tty->cr(); 2636 tty->print_cr("Individual compilation Tier times (for compiled methods only)"); 2637 tty->print_cr("------------------------------------------------"); 2638 tty->cr(); 2639 } 2640 char tier_name[256]; 2641 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) { 2642 CompilerStatistics* stats = &_stats_per_level[tier-1]; 2643 os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier); 2644 print_times(tier_name, stats); 2645 } 2646 } 2647 2648 if (!aggregate) { 2649 return; 2650 } 2651 2652 elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation; 2653 elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation; 2654 elapsedTimer total_compilation = CompileBroker::_t_total_compilation; 2655 2656 uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled; 2657 uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled; 2658 2659 uint standard_compile_count = CompileBroker::_total_standard_compile_count; 2660 uint osr_compile_count = CompileBroker::_total_osr_compile_count; 2661 uint total_compile_count = CompileBroker::_total_compile_count; 2662 uint total_bailout_count = CompileBroker::_total_bailout_count; 2663 uint total_invalidated_count = CompileBroker::_total_invalidated_count; 2664 2665 uint nmethods_size = CompileBroker::_sum_nmethod_code_size; 2666 uint nmethods_code_size = CompileBroker::_sum_nmethod_size; 2667 2668 tty->cr(); 2669 tty->print_cr("Accumulated compiler times"); 2670 tty->print_cr("----------------------------------------------------------"); 2671 //0000000000111111111122222222223333333333444444444455555555556666666666 2672 //0123456789012345678901234567890123456789012345678901234567890123456789 2673 tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds()); 2674 tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s", 2675 standard_compilation.seconds(), 2676 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count); 2677 tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s", 2678 CompileBroker::_t_bailedout_compilation.seconds(), 2679 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count); 2680 tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s", 2681 osr_compilation.seconds(), 2682 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count); 2683 tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s", 2684 CompileBroker::_t_invalidated_compilation.seconds(), 2685 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count); 2686 2687 AbstractCompiler *comp = compiler(CompLevel_simple); 2688 if (comp != nullptr) { 2689 tty->cr(); 2690 comp->print_timers(); 2691 } 2692 comp = compiler(CompLevel_full_optimization); 2693 if (comp != nullptr) { 2694 tty->cr(); 2695 comp->print_timers(); 2696 } 2697 #if INCLUDE_JVMCI 2698 if (EnableJVMCI) { 2699 JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null()); 2700 if (jvmci_comp != nullptr && jvmci_comp != comp) { 2701 tty->cr(); 2702 jvmci_comp->print_timers(); 2703 } 2704 } 2705 #endif 2706 2707 tty->cr(); 2708 tty->print_cr(" Total compiled methods : %8u methods", total_compile_count); 2709 tty->print_cr(" Standard compilation : %8u methods", standard_compile_count); 2710 tty->print_cr(" On stack replacement : %8u methods", osr_compile_count); 2711 uint tcb = osr_bytes_compiled + standard_bytes_compiled; 2712 tty->print_cr(" Total compiled bytecodes : %8u bytes", tcb); 2713 tty->print_cr(" Standard compilation : %8u bytes", standard_bytes_compiled); 2714 tty->print_cr(" On stack replacement : %8u bytes", osr_bytes_compiled); 2715 double tcs = total_compilation.seconds(); 2716 uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs); 2717 tty->print_cr(" Average compilation speed : %8u bytes/s", bps); 2718 tty->cr(); 2719 tty->print_cr(" nmethod code size : %8u bytes", nmethods_code_size); 2720 tty->print_cr(" nmethod total size : %8u bytes", nmethods_size); 2721 } 2722 2723 // Print general/accumulated JIT information. 2724 void CompileBroker::print_info(outputStream *out) { 2725 if (out == nullptr) out = tty; 2726 out->cr(); 2727 out->print_cr("======================"); 2728 out->print_cr(" General JIT info "); 2729 out->print_cr("======================"); 2730 out->cr(); 2731 out->print_cr(" JIT is : %7s", should_compile_new_jobs() ? "on" : "off"); 2732 out->print_cr(" Compiler threads : %7d", (int)CICompilerCount); 2733 out->cr(); 2734 out->print_cr("CodeCache overview"); 2735 out->print_cr("--------------------------------------------------------"); 2736 out->cr(); 2737 out->print_cr(" Reserved size : " SIZE_FORMAT_W(7) " KB", CodeCache::max_capacity() / K); 2738 out->print_cr(" Committed size : " SIZE_FORMAT_W(7) " KB", CodeCache::capacity() / K); 2739 out->print_cr(" Unallocated capacity : " SIZE_FORMAT_W(7) " KB", CodeCache::unallocated_capacity() / K); 2740 out->cr(); 2741 } 2742 2743 // Note: tty_lock must not be held upon entry to this function. 2744 // Print functions called from herein do "micro-locking" on tty_lock. 2745 // That's a tradeoff which keeps together important blocks of output. 2746 // At the same time, continuous tty_lock hold time is kept in check, 2747 // preventing concurrently printing threads from stalling a long time. 2748 void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) { 2749 TimeStamp ts_total; 2750 TimeStamp ts_global; 2751 TimeStamp ts; 2752 2753 bool allFun = !strcmp(function, "all"); 2754 bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun; 2755 bool usedSpace = !strcmp(function, "UsedSpace") || allFun; 2756 bool freeSpace = !strcmp(function, "FreeSpace") || allFun; 2757 bool methodCount = !strcmp(function, "MethodCount") || allFun; 2758 bool methodSpace = !strcmp(function, "MethodSpace") || allFun; 2759 bool methodAge = !strcmp(function, "MethodAge") || allFun; 2760 bool methodNames = !strcmp(function, "MethodNames") || allFun; 2761 bool discard = !strcmp(function, "discard") || allFun; 2762 2763 if (out == nullptr) { 2764 out = tty; 2765 } 2766 2767 if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) { 2768 out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function); 2769 out->cr(); 2770 return; 2771 } 2772 2773 ts_total.update(); // record starting point 2774 2775 if (aggregate) { 2776 print_info(out); 2777 } 2778 2779 // We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function. 2780 // That prevents other threads from destroying (making inconsistent) our view on the CodeHeap. 2781 // When we request individual parts of the analysis via the jcmd interface, it is possible 2782 // that in between another thread (another jcmd user or the vm running into CodeCache OOM) 2783 // updated the aggregated data. We will then see a modified, but again consistent, view 2784 // on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold 2785 // a lock across user interaction. 2786 2787 // We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock. 2788 // CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time, 2789 // leading to an unnecessarily long hold time of the other locks we acquired before. 2790 ts.update(); // record starting point 2791 MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag); 2792 out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds()); 2793 2794 // Holding the CodeCache_lock protects from concurrent alterations of the CodeCache. 2795 // Unfortunately, such protection is not sufficient: 2796 // When a new nmethod is created via ciEnv::register_method(), the 2797 // Compile_lock is taken first. After some initializations, 2798 // nmethod::new_nmethod() takes over, grabbing the CodeCache_lock 2799 // immediately (after finalizing the oop references). To lock out concurrent 2800 // modifiers, we have to grab both locks as well in the described sequence. 2801 // 2802 // If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock 2803 // for the entire duration of aggregation and printing. That makes sure we see 2804 // a consistent picture and do not run into issues caused by concurrent alterations. 2805 bool should_take_Compile_lock = !SafepointSynchronize::is_at_safepoint() && 2806 !Compile_lock->owned_by_self(); 2807 bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() && 2808 !CodeCache_lock->owned_by_self(); 2809 Mutex* global_lock_1 = allFun ? (should_take_Compile_lock ? Compile_lock : nullptr) : nullptr; 2810 Monitor* global_lock_2 = allFun ? (should_take_CodeCache_lock ? CodeCache_lock : nullptr) : nullptr; 2811 Mutex* function_lock_1 = allFun ? nullptr : (should_take_Compile_lock ? Compile_lock : nullptr); 2812 Monitor* function_lock_2 = allFun ? nullptr : (should_take_CodeCache_lock ? CodeCache_lock : nullptr); 2813 ts_global.update(); // record starting point 2814 MutexLocker mu1(global_lock_1, Mutex::_safepoint_check_flag); 2815 MutexLocker mu2(global_lock_2, Mutex::_no_safepoint_check_flag); 2816 if ((global_lock_1 != nullptr) || (global_lock_2 != nullptr)) { 2817 out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds()); 2818 ts_global.update(); // record starting point 2819 } 2820 2821 if (aggregate) { 2822 ts.update(); // record starting point 2823 MutexLocker mu11(function_lock_1, Mutex::_safepoint_check_flag); 2824 MutexLocker mu22(function_lock_2, Mutex::_no_safepoint_check_flag); 2825 if ((function_lock_1 != nullptr) || (function_lock_2 != nullptr)) { 2826 out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds()); 2827 } 2828 2829 ts.update(); // record starting point 2830 CodeCache::aggregate(out, granularity); 2831 if ((function_lock_1 != nullptr) || (function_lock_2 != nullptr)) { 2832 out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds()); 2833 } 2834 } 2835 2836 if (usedSpace) CodeCache::print_usedSpace(out); 2837 if (freeSpace) CodeCache::print_freeSpace(out); 2838 if (methodCount) CodeCache::print_count(out); 2839 if (methodSpace) CodeCache::print_space(out); 2840 if (methodAge) CodeCache::print_age(out); 2841 if (methodNames) { 2842 if (allFun) { 2843 // print_names() can only be used safely if the locks have been continuously held 2844 // since aggregation begin. That is true only for function "all". 2845 CodeCache::print_names(out); 2846 } else { 2847 out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'"); 2848 } 2849 } 2850 if (discard) CodeCache::discard(out); 2851 2852 if ((global_lock_1 != nullptr) || (global_lock_2 != nullptr)) { 2853 out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds()); 2854 } 2855 out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds()); 2856 }