1 /* 2 * Copyright (c) 1999, 2022, 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 = NULL; 136 jobject* CompileBroker::_compiler2_objects = NULL; 137 138 CompileLog** CompileBroker::_compiler1_logs = NULL; 139 CompileLog** CompileBroker::_compiler2_logs = NULL; 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 = NULL; 148 PerfCounter* CompileBroker::_perf_osr_compilation = NULL; 149 PerfCounter* CompileBroker::_perf_standard_compilation = NULL; 150 151 PerfCounter* CompileBroker::_perf_total_bailout_count = NULL; 152 PerfCounter* CompileBroker::_perf_total_invalidated_count = NULL; 153 PerfCounter* CompileBroker::_perf_total_compile_count = NULL; 154 PerfCounter* CompileBroker::_perf_total_osr_compile_count = NULL; 155 PerfCounter* CompileBroker::_perf_total_standard_compile_count = NULL; 156 157 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = NULL; 158 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = NULL; 159 PerfCounter* CompileBroker::_perf_sum_nmethod_size = NULL; 160 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = NULL; 161 162 PerfStringVariable* CompileBroker::_perf_last_method = NULL; 163 PerfStringVariable* CompileBroker::_perf_last_failed_method = NULL; 164 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = NULL; 165 PerfVariable* CompileBroker::_perf_last_compile_type = NULL; 166 PerfVariable* CompileBroker::_perf_last_compile_size = NULL; 167 PerfVariable* CompileBroker::_perf_last_failed_type = NULL; 168 PerfVariable* CompileBroker::_perf_last_invalidated_type = NULL; 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 int CompileBroker::_total_bailout_count = 0; 178 int CompileBroker::_total_invalidated_count = 0; 179 int CompileBroker::_total_compile_count = 0; 180 int CompileBroker::_total_osr_compile_count = 0; 181 int CompileBroker::_total_standard_compile_count = 0; 182 int CompileBroker::_total_compiler_stopped_count = 0; 183 int CompileBroker::_total_compiler_restarted_count = 0; 184 185 int CompileBroker::_sum_osr_bytes_compiled = 0; 186 int CompileBroker::_sum_standard_bytes_compiled = 0; 187 int CompileBroker::_sum_nmethod_size = 0; 188 int 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 = NULL; 195 CompileQueue* CompileBroker::_c1_compile_queue = NULL; 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 != NULL && !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 != NULL && !task->is_unloaded()) task->log_task_done(log); 227 thread->set_task(NULL); 228 thread->set_env(NULL); 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(NULL); 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] = NULL; 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(NULL); 318 task->set_prev(NULL); 319 320 if (_last == NULL) { 321 // The compile queue is empty. 322 assert(_first == NULL, "queue is empty"); 323 _first = task; 324 _last = task; 325 } else { 326 // Append the task to the queue. 327 assert(_last->next() == NULL, "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 != NULL) { 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 != NULL) { 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 = NULL; 372 _last = NULL; 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 == NULL) { 394 // Exit loop if compilation is disabled forever 395 if (CompileBroker::is_compilation_disabled_forever()) { 396 return NULL; 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 == NULL) { 417 // Still nothing to compile. Give caller a chance to stop this thread. 418 if (CompileBroker::can_remove(CompilerThread::current(), false)) return NULL; 419 } 420 } 421 422 if (CompileBroker::is_compilation_disabled_forever()) { 423 return NULL; 424 } 425 426 CompileTask* task; 427 { 428 NoSafepointVerifier nsv; 429 task = CompilationPolicy::select_task(this); 430 if (task != NULL) { 431 task = task->select_for_compilation(); 432 } 433 } 434 435 if (task != NULL) { 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 != NULL) { 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 = NULL; 459 { 460 MutexUnlocker ul(MethodCompileQueue_lock); 461 for (CompileTask* task = head; task != NULL; ) { 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() != NULL) { 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() != NULL) { 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(NULL); 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 != NULL) { 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 NULL; 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 != NULL) { 527 _c1_compile_queue->print(st); 528 } 529 if (_c2_compile_queue != NULL) { 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 == NULL) { 539 st->print_cr("Empty"); 540 } else { 541 while (task != NULL) { 542 task->print(st, NULL, 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, false /* not visible */, 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 = NULL; 836 837 switch (type) { 838 case compiler_t: 839 assert(comp != NULL, "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 != NULL && new_thread->osthread() != NULL) { 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 NULL; 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 908 void CompileBroker::init_compiler_threads() { 909 // Ensure any exceptions lead to vm_exit_during_initialization. 910 EXCEPTION_MARK; 911 #if !defined(ZERO) 912 assert(_c2_count > 0 || _c1_count > 0, "No compilers?"); 913 #endif // !ZERO 914 // Initialize the compilation queue 915 if (_c2_count > 0) { 916 const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue"; 917 _c2_compile_queue = new CompileQueue(name); 918 _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler); 919 _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler); 920 } 921 if (_c1_count > 0) { 922 _c1_compile_queue = new CompileQueue("C1 compile queue"); 923 _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler); 924 _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler); 925 } 926 927 char name_buffer[256]; 928 929 for (int i = 0; i < _c2_count; i++) { 930 jobject thread_handle = NULL; 931 // Create all j.l.Thread objects for C1 and C2 threads here, but only one 932 // for JVMCI compiler which can create further ones on demand. 933 JVMCI_ONLY(if (!UseJVMCICompiler || !UseDynamicNumberOfCompilerThreads || i == 0) {) 934 // Create a name for our thread. 935 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", _compilers[1]->name(), i); 936 Handle thread_oop = create_thread_oop(name_buffer, CHECK); 937 thread_handle = JNIHandles::make_global(thread_oop); 938 JVMCI_ONLY(}) 939 _compiler2_objects[i] = thread_handle; 940 _compiler2_logs[i] = NULL; 941 942 if (!UseDynamicNumberOfCompilerThreads || i == 0) { 943 JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD); 944 assert(ct != NULL, "should have been handled for initial thread"); 945 _compilers[1]->set_num_compiler_threads(i + 1); 946 if (TraceCompilerThreads) { 947 ResourceMark rm; 948 ThreadsListHandle tlh; // name() depends on the TLH. 949 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct)); 950 tty->print_cr("Added initial compiler thread %s", ct->name()); 951 } 952 } 953 } 954 955 for (int i = 0; i < _c1_count; i++) { 956 // Create a name for our thread. 957 os::snprintf_checked(name_buffer, sizeof(name_buffer), "C1 CompilerThread%d", i); 958 Handle thread_oop = create_thread_oop(name_buffer, CHECK); 959 jobject thread_handle = JNIHandles::make_global(thread_oop); 960 _compiler1_objects[i] = thread_handle; 961 _compiler1_logs[i] = NULL; 962 963 if (!UseDynamicNumberOfCompilerThreads || i == 0) { 964 JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD); 965 assert(ct != NULL, "should have been handled for initial thread"); 966 _compilers[0]->set_num_compiler_threads(i + 1); 967 if (TraceCompilerThreads) { 968 ResourceMark rm; 969 ThreadsListHandle tlh; // name() depends on the TLH. 970 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct)); 971 tty->print_cr("Added initial compiler thread %s", ct->name()); 972 } 973 } 974 } 975 976 if (UsePerfData) { 977 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK); 978 } 979 980 #if defined(ASSERT) && COMPILER2_OR_JVMCI 981 if (DeoptimizeObjectsALot) { 982 // Initialize and start the object deoptimizer threads 983 const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll; 984 for (int count = 0; count < total_count; count++) { 985 Handle thread_oop = create_thread_oop("Deoptimize objects a lot single mode", CHECK); 986 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop()); 987 make_thread(deoptimizer_t, thread_handle, NULL, NULL, THREAD); 988 } 989 } 990 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI 991 } 992 993 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) { 994 995 julong available_memory = os::available_memory(); 996 // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All). 997 size_t available_cc_np = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled), 998 available_cc_p = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled); 999 1000 // Only do attempt to start additional threads if the lock is free. 1001 if (!CompileThread_lock->try_lock()) return; 1002 1003 if (_c2_compile_queue != NULL) { 1004 int old_c2_count = _compilers[1]->num_compiler_threads(); 1005 int new_c2_count = MIN4(_c2_count, 1006 _c2_compile_queue->size() / 2, 1007 (int)(available_memory / (200*M)), 1008 (int)(available_cc_np / (128*K))); 1009 1010 for (int i = old_c2_count; i < new_c2_count; i++) { 1011 #if INCLUDE_JVMCI 1012 if (UseJVMCICompiler) { 1013 // Native compiler threads as used in C1/C2 can reuse the j.l.Thread 1014 // objects as their existence is completely hidden from the rest of 1015 // the VM (and those compiler threads can't call Java code to do the 1016 // creation anyway). For JVMCI we have to create new j.l.Thread objects 1017 // as they are visible and we can see unexpected thread lifecycle 1018 // transitions if we bind them to new JavaThreads. 1019 if (!THREAD->can_call_java()) break; 1020 char name_buffer[256]; 1021 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", _compilers[1]->name(), i); 1022 Handle thread_oop; 1023 { 1024 // We have to give up the lock temporarily for the Java calls. 1025 MutexUnlocker mu(CompileThread_lock); 1026 thread_oop = create_thread_oop(name_buffer, THREAD); 1027 } 1028 if (HAS_PENDING_EXCEPTION) { 1029 if (TraceCompilerThreads) { 1030 ResourceMark rm; 1031 tty->print_cr("JVMCI compiler thread creation failed:"); 1032 PENDING_EXCEPTION->print(); 1033 } 1034 CLEAR_PENDING_EXCEPTION; 1035 break; 1036 } 1037 // Check if another thread has beaten us during the Java calls. 1038 if (_compilers[1]->num_compiler_threads() != i) break; 1039 jobject thread_handle = JNIHandles::make_global(thread_oop); 1040 assert(compiler2_object(i) == NULL, "Old one must be released!"); 1041 _compiler2_objects[i] = thread_handle; 1042 } 1043 #endif 1044 JavaThread *ct = make_thread(compiler_t, compiler2_object(i), _c2_compile_queue, _compilers[1], THREAD); 1045 if (ct == NULL) break; 1046 _compilers[1]->set_num_compiler_threads(i + 1); 1047 if (TraceCompilerThreads) { 1048 ResourceMark rm; 1049 ThreadsListHandle tlh; // name() depends on the TLH. 1050 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct)); 1051 tty->print_cr("Added compiler thread %s (available memory: %dMB, available non-profiled code cache: %dMB)", 1052 ct->name(), (int)(available_memory/M), (int)(available_cc_np/M)); 1053 } 1054 } 1055 } 1056 1057 if (_c1_compile_queue != NULL) { 1058 int old_c1_count = _compilers[0]->num_compiler_threads(); 1059 int new_c1_count = MIN4(_c1_count, 1060 _c1_compile_queue->size() / 4, 1061 (int)(available_memory / (100*M)), 1062 (int)(available_cc_p / (128*K))); 1063 1064 for (int i = old_c1_count; i < new_c1_count; i++) { 1065 JavaThread *ct = make_thread(compiler_t, compiler1_object(i), _c1_compile_queue, _compilers[0], THREAD); 1066 if (ct == NULL) break; 1067 _compilers[0]->set_num_compiler_threads(i + 1); 1068 if (TraceCompilerThreads) { 1069 ResourceMark rm; 1070 ThreadsListHandle tlh; // name() depends on the TLH. 1071 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct)); 1072 tty->print_cr("Added compiler thread %s (available memory: %dMB, available profiled code cache: %dMB)", 1073 ct->name(), (int)(available_memory/M), (int)(available_cc_p/M)); 1074 } 1075 } 1076 } 1077 1078 CompileThread_lock->unlock(); 1079 } 1080 1081 1082 /** 1083 * Set the methods on the stack as on_stack so that redefine classes doesn't 1084 * reclaim them. This method is executed at a safepoint. 1085 */ 1086 void CompileBroker::mark_on_stack() { 1087 assert(SafepointSynchronize::is_at_safepoint(), "sanity check"); 1088 // Since we are at a safepoint, we do not need a lock to access 1089 // the compile queues. 1090 if (_c2_compile_queue != NULL) { 1091 _c2_compile_queue->mark_on_stack(); 1092 } 1093 if (_c1_compile_queue != NULL) { 1094 _c1_compile_queue->mark_on_stack(); 1095 } 1096 } 1097 1098 // ------------------------------------------------------------------ 1099 // CompileBroker::compile_method 1100 // 1101 // Request compilation of a method. 1102 void CompileBroker::compile_method_base(const methodHandle& method, 1103 int osr_bci, 1104 int comp_level, 1105 const methodHandle& hot_method, 1106 int hot_count, 1107 CompileTask::CompileReason compile_reason, 1108 bool blocking, 1109 Thread* thread) { 1110 guarantee(!method->is_abstract(), "cannot compile abstract methods"); 1111 assert(method->method_holder()->is_instance_klass(), 1112 "sanity check"); 1113 assert(!method->method_holder()->is_not_initialized(), 1114 "method holder must be initialized"); 1115 assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys"); 1116 1117 if (CIPrintRequests) { 1118 tty->print("request: "); 1119 method->print_short_name(tty); 1120 if (osr_bci != InvocationEntryBci) { 1121 tty->print(" osr_bci: %d", osr_bci); 1122 } 1123 tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count); 1124 if (!hot_method.is_null()) { 1125 tty->print(" hot: "); 1126 if (hot_method() != method()) { 1127 hot_method->print_short_name(tty); 1128 } else { 1129 tty->print("yes"); 1130 } 1131 } 1132 tty->cr(); 1133 } 1134 1135 // A request has been made for compilation. Before we do any 1136 // real work, check to see if the method has been compiled 1137 // in the meantime with a definitive result. 1138 if (compilation_is_complete(method, osr_bci, comp_level)) { 1139 return; 1140 } 1141 1142 #ifndef PRODUCT 1143 if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) { 1144 if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) { 1145 // Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI. 1146 return; 1147 } 1148 } 1149 #endif 1150 1151 // If this method is already in the compile queue, then 1152 // we do not block the current thread. 1153 if (compilation_is_in_queue(method)) { 1154 // We may want to decay our counter a bit here to prevent 1155 // multiple denied requests for compilation. This is an 1156 // open compilation policy issue. Note: The other possibility, 1157 // in the case that this is a blocking compile request, is to have 1158 // all subsequent blocking requesters wait for completion of 1159 // ongoing compiles. Note that in this case we'll need a protocol 1160 // for freeing the associated compile tasks. [Or we could have 1161 // a single static monitor on which all these waiters sleep.] 1162 return; 1163 } 1164 1165 // Tiered policy requires MethodCounters to exist before adding a method to 1166 // the queue. Create if we don't have them yet. 1167 method->get_method_counters(thread); 1168 1169 // Outputs from the following MutexLocker block: 1170 CompileTask* task = NULL; 1171 CompileQueue* queue = compile_queue(comp_level); 1172 1173 // Acquire our lock. 1174 { 1175 MutexLocker locker(thread, MethodCompileQueue_lock); 1176 1177 // Make sure the method has not slipped into the queues since 1178 // last we checked; note that those checks were "fast bail-outs". 1179 // Here we need to be more careful, see 14012000 below. 1180 if (compilation_is_in_queue(method)) { 1181 return; 1182 } 1183 1184 // We need to check again to see if the compilation has 1185 // completed. A previous compilation may have registered 1186 // some result. 1187 if (compilation_is_complete(method, osr_bci, comp_level)) { 1188 return; 1189 } 1190 1191 // We now know that this compilation is not pending, complete, 1192 // or prohibited. Assign a compile_id to this compilation 1193 // and check to see if it is in our [Start..Stop) range. 1194 int compile_id = assign_compile_id(method, osr_bci); 1195 if (compile_id == 0) { 1196 // The compilation falls outside the allowed range. 1197 return; 1198 } 1199 1200 #if INCLUDE_JVMCI 1201 if (UseJVMCICompiler && blocking) { 1202 // Don't allow blocking compiles for requests triggered by JVMCI. 1203 if (thread->is_Compiler_thread()) { 1204 blocking = false; 1205 } 1206 1207 if (!UseJVMCINativeLibrary) { 1208 // Don't allow blocking compiles if inside a class initializer or while performing class loading 1209 vframeStream vfst(JavaThread::cast(thread)); 1210 for (; !vfst.at_end(); vfst.next()) { 1211 if (vfst.method()->is_static_initializer() || 1212 (vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass()) && 1213 vfst.method()->name() == vmSymbols::loadClass_name())) { 1214 blocking = false; 1215 break; 1216 } 1217 } 1218 } 1219 1220 // Don't allow blocking compilation requests to JVMCI 1221 // if JVMCI itself is not yet initialized 1222 if (!JVMCI::is_compiler_initialized() && compiler(comp_level)->is_jvmci()) { 1223 blocking = false; 1224 } 1225 1226 // Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown 1227 // to avoid deadlock between compiler thread(s) and threads run at shutdown 1228 // such as the DestroyJavaVM thread. 1229 if (JVMCI::in_shutdown()) { 1230 blocking = false; 1231 } 1232 } 1233 #endif // INCLUDE_JVMCI 1234 1235 // We will enter the compilation in the queue. 1236 // 14012000: Note that this sets the queued_for_compile bits in 1237 // the target method. We can now reason that a method cannot be 1238 // queued for compilation more than once, as follows: 1239 // Before a thread queues a task for compilation, it first acquires 1240 // the compile queue lock, then checks if the method's queued bits 1241 // are set or it has already been compiled. Thus there can not be two 1242 // instances of a compilation task for the same method on the 1243 // compilation queue. Consider now the case where the compilation 1244 // thread has already removed a task for that method from the queue 1245 // and is in the midst of compiling it. In this case, the 1246 // queued_for_compile bits must be set in the method (and these 1247 // will be visible to the current thread, since the bits were set 1248 // under protection of the compile queue lock, which we hold now. 1249 // When the compilation completes, the compiler thread first sets 1250 // the compilation result and then clears the queued_for_compile 1251 // bits. Neither of these actions are protected by a barrier (or done 1252 // under the protection of a lock), so the only guarantee we have 1253 // (on machines with TSO (Total Store Order)) is that these values 1254 // will update in that order. As a result, the only combinations of 1255 // these bits that the current thread will see are, in temporal order: 1256 // <RESULT, QUEUE> : 1257 // <0, 1> : in compile queue, but not yet compiled 1258 // <1, 1> : compiled but queue bit not cleared 1259 // <1, 0> : compiled and queue bit cleared 1260 // Because we first check the queue bits then check the result bits, 1261 // we are assured that we cannot introduce a duplicate task. 1262 // Note that if we did the tests in the reverse order (i.e. check 1263 // result then check queued bit), we could get the result bit before 1264 // the compilation completed, and the queue bit after the compilation 1265 // completed, and end up introducing a "duplicate" (redundant) task. 1266 // In that case, the compiler thread should first check if a method 1267 // has already been compiled before trying to compile it. 1268 // NOTE: in the event that there are multiple compiler threads and 1269 // there is de-optimization/recompilation, things will get hairy, 1270 // and in that case it's best to protect both the testing (here) of 1271 // these bits, and their updating (here and elsewhere) under a 1272 // common lock. 1273 task = create_compile_task(queue, 1274 compile_id, method, 1275 osr_bci, comp_level, 1276 hot_method, hot_count, compile_reason, 1277 blocking); 1278 } 1279 1280 if (blocking) { 1281 wait_for_completion(task); 1282 } 1283 } 1284 1285 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci, 1286 int comp_level, 1287 const methodHandle& hot_method, int hot_count, 1288 CompileTask::CompileReason compile_reason, 1289 TRAPS) { 1290 // Do nothing if compilebroker is not initialized or compiles are submitted on level none 1291 if (!_initialized || comp_level == CompLevel_none) { 1292 return NULL; 1293 } 1294 1295 AbstractCompiler *comp = CompileBroker::compiler(comp_level); 1296 assert(comp != NULL, "Ensure we have a compiler"); 1297 1298 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp); 1299 // CompileBroker::compile_method can trap and can have pending async exception. 1300 nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, directive, THREAD); 1301 DirectivesStack::release(directive); 1302 return nm; 1303 } 1304 1305 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci, 1306 int comp_level, 1307 const methodHandle& hot_method, int hot_count, 1308 CompileTask::CompileReason compile_reason, 1309 DirectiveSet* directive, 1310 TRAPS) { 1311 1312 // make sure arguments make sense 1313 assert(method->method_holder()->is_instance_klass(), "not an instance method"); 1314 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range"); 1315 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods"); 1316 assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized"); 1317 // return quickly if possible 1318 1319 // lock, make sure that the compilation 1320 // isn't prohibited in a straightforward way. 1321 AbstractCompiler* comp = CompileBroker::compiler(comp_level); 1322 if (comp == NULL || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) { 1323 return NULL; 1324 } 1325 1326 #if INCLUDE_JVMCI 1327 if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) { 1328 return NULL; 1329 } 1330 #endif 1331 1332 if (osr_bci == InvocationEntryBci) { 1333 // standard compilation 1334 CompiledMethod* method_code = method->code(); 1335 if (method_code != NULL && method_code->is_nmethod()) { 1336 if (compilation_is_complete(method, osr_bci, comp_level)) { 1337 return (nmethod*) method_code; 1338 } 1339 } 1340 if (method->is_not_compilable(comp_level)) { 1341 return NULL; 1342 } 1343 } else { 1344 // osr compilation 1345 // We accept a higher level osr method 1346 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false); 1347 if (nm != NULL) return nm; 1348 if (method->is_not_osr_compilable(comp_level)) return NULL; 1349 } 1350 1351 assert(!HAS_PENDING_EXCEPTION, "No exception should be present"); 1352 // some prerequisites that are compiler specific 1353 if (comp->is_c2() || comp->is_jvmci()) { 1354 method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL); 1355 // Resolve all classes seen in the signature of the method 1356 // we are compiling. 1357 Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL); 1358 } 1359 1360 // If the method is native, do the lookup in the thread requesting 1361 // the compilation. Native lookups can load code, which is not 1362 // permitted during compilation. 1363 // 1364 // Note: A native method implies non-osr compilation which is 1365 // checked with an assertion at the entry of this method. 1366 if (method->is_native() && !method->is_method_handle_intrinsic()) { 1367 address adr = NativeLookup::lookup(method, THREAD); 1368 if (HAS_PENDING_EXCEPTION) { 1369 // In case of an exception looking up the method, we just forget 1370 // about it. The interpreter will kick-in and throw the exception. 1371 method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable() 1372 CLEAR_PENDING_EXCEPTION; 1373 return NULL; 1374 } 1375 assert(method->has_native_function(), "must have native code by now"); 1376 } 1377 1378 // RedefineClasses() has replaced this method; just return 1379 if (method->is_old()) { 1380 return NULL; 1381 } 1382 1383 // JVMTI -- post_compile_event requires jmethod_id() that may require 1384 // a lock the compiling thread can not acquire. Prefetch it here. 1385 if (JvmtiExport::should_post_compiled_method_load()) { 1386 method->jmethod_id(); 1387 } 1388 1389 // do the compilation 1390 if (method->is_native()) { 1391 if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) { 1392 #if defined(X86) && !defined(ZERO) 1393 // The following native methods: 1394 // 1395 // java.lang.Float.intBitsToFloat 1396 // java.lang.Float.floatToRawIntBits 1397 // java.lang.Double.longBitsToDouble 1398 // java.lang.Double.doubleToRawLongBits 1399 // 1400 // are called through the interpreter even if interpreter native stubs 1401 // are not preferred (i.e., calling through adapter handlers is preferred). 1402 // The reason is that on x86_32 signaling NaNs (sNaNs) are not preserved 1403 // if the version of the methods from the native libraries is called. 1404 // As the interpreter and the C2-intrinsified version of the methods preserves 1405 // sNaNs, that would result in an inconsistent way of handling of sNaNs. 1406 if ((UseSSE >= 1 && 1407 (method->intrinsic_id() == vmIntrinsics::_intBitsToFloat || 1408 method->intrinsic_id() == vmIntrinsics::_floatToRawIntBits)) || 1409 (UseSSE >= 2 && 1410 (method->intrinsic_id() == vmIntrinsics::_longBitsToDouble || 1411 method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) { 1412 return NULL; 1413 } 1414 #endif // X86 && !ZERO 1415 1416 // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that 1417 // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime). 1418 // 1419 // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter 1420 // in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls. 1421 AdapterHandlerLibrary::create_native_wrapper(method); 1422 } else { 1423 return NULL; 1424 } 1425 } else { 1426 // If the compiler is shut off due to code cache getting full 1427 // fail out now so blocking compiles dont hang the java thread 1428 if (!should_compile_new_jobs()) { 1429 return NULL; 1430 } 1431 bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles; 1432 compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, compile_reason, is_blocking, THREAD); 1433 } 1434 1435 // return requested nmethod 1436 // We accept a higher level osr method 1437 if (osr_bci == InvocationEntryBci) { 1438 CompiledMethod* code = method->code(); 1439 if (code == NULL) { 1440 return (nmethod*) code; 1441 } else { 1442 return code->as_nmethod_or_null(); 1443 } 1444 } 1445 return method->lookup_osr_nmethod_for(osr_bci, comp_level, false); 1446 } 1447 1448 1449 // ------------------------------------------------------------------ 1450 // CompileBroker::compilation_is_complete 1451 // 1452 // See if compilation of this method is already complete. 1453 bool CompileBroker::compilation_is_complete(const methodHandle& method, 1454 int osr_bci, 1455 int comp_level) { 1456 bool is_osr = (osr_bci != standard_entry_bci); 1457 if (is_osr) { 1458 if (method->is_not_osr_compilable(comp_level)) { 1459 return true; 1460 } else { 1461 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true); 1462 return (result != NULL); 1463 } 1464 } else { 1465 if (method->is_not_compilable(comp_level)) { 1466 return true; 1467 } else { 1468 CompiledMethod* result = method->code(); 1469 if (result == NULL) return false; 1470 return comp_level == result->comp_level(); 1471 } 1472 } 1473 } 1474 1475 1476 /** 1477 * See if this compilation is already requested. 1478 * 1479 * Implementation note: there is only a single "is in queue" bit 1480 * for each method. This means that the check below is overly 1481 * conservative in the sense that an osr compilation in the queue 1482 * will block a normal compilation from entering the queue (and vice 1483 * versa). This can be remedied by a full queue search to disambiguate 1484 * cases. If it is deemed profitable, this may be done. 1485 */ 1486 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) { 1487 return method->queued_for_compilation(); 1488 } 1489 1490 // ------------------------------------------------------------------ 1491 // CompileBroker::compilation_is_prohibited 1492 // 1493 // See if this compilation is not allowed. 1494 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) { 1495 bool is_native = method->is_native(); 1496 // Some compilers may not support the compilation of natives. 1497 AbstractCompiler *comp = compiler(comp_level); 1498 if (is_native && (!CICompileNatives || comp == NULL)) { 1499 method->set_not_compilable_quietly("native methods not supported", comp_level); 1500 return true; 1501 } 1502 1503 bool is_osr = (osr_bci != standard_entry_bci); 1504 // Some compilers may not support on stack replacement. 1505 if (is_osr && (!CICompileOSR || comp == NULL)) { 1506 method->set_not_osr_compilable("OSR not supported", comp_level); 1507 return true; 1508 } 1509 1510 // The method may be explicitly excluded by the user. 1511 double scale; 1512 if (excluded || (CompilerOracle::has_option_value(method, CompileCommand::CompileThresholdScaling, scale) && scale == 0)) { 1513 bool quietly = CompilerOracle::be_quiet(); 1514 if (PrintCompilation && !quietly) { 1515 // This does not happen quietly... 1516 ResourceMark rm; 1517 tty->print("### Excluding %s:%s", 1518 method->is_native() ? "generation of native wrapper" : "compile", 1519 (method->is_static() ? " static" : "")); 1520 method->print_short_name(tty); 1521 tty->cr(); 1522 } 1523 method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly); 1524 } 1525 1526 return false; 1527 } 1528 1529 /** 1530 * Generate serialized IDs for compilation requests. If certain debugging flags are used 1531 * and the ID is not within the specified range, the method is not compiled and 0 is returned. 1532 * The function also allows to generate separate compilation IDs for OSR compilations. 1533 */ 1534 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) { 1535 #ifdef ASSERT 1536 bool is_osr = (osr_bci != standard_entry_bci); 1537 int id; 1538 if (method->is_native()) { 1539 assert(!is_osr, "can't be osr"); 1540 // Adapters, native wrappers and method handle intrinsics 1541 // should be generated always. 1542 return Atomic::add(CICountNative ? &_native_compilation_id : &_compilation_id, 1); 1543 } else if (CICountOSR && is_osr) { 1544 id = Atomic::add(&_osr_compilation_id, 1); 1545 if (CIStartOSR <= id && id < CIStopOSR) { 1546 return id; 1547 } 1548 } else { 1549 id = Atomic::add(&_compilation_id, 1); 1550 if (CIStart <= id && id < CIStop) { 1551 return id; 1552 } 1553 } 1554 1555 // Method was not in the appropriate compilation range. 1556 method->set_not_compilable_quietly("Not in requested compile id range"); 1557 return 0; 1558 #else 1559 // CICountOSR is a develop flag and set to 'false' by default. In a product built, 1560 // only _compilation_id is incremented. 1561 return Atomic::add(&_compilation_id, 1); 1562 #endif 1563 } 1564 1565 // ------------------------------------------------------------------ 1566 // CompileBroker::assign_compile_id_unlocked 1567 // 1568 // Public wrapper for assign_compile_id that acquires the needed locks 1569 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) { 1570 MutexLocker locker(thread, MethodCompileQueue_lock); 1571 return assign_compile_id(method, osr_bci); 1572 } 1573 1574 // ------------------------------------------------------------------ 1575 // CompileBroker::create_compile_task 1576 // 1577 // Create a CompileTask object representing the current request for 1578 // compilation. Add this task to the queue. 1579 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue, 1580 int compile_id, 1581 const methodHandle& method, 1582 int osr_bci, 1583 int comp_level, 1584 const methodHandle& hot_method, 1585 int hot_count, 1586 CompileTask::CompileReason compile_reason, 1587 bool blocking) { 1588 CompileTask* new_task = CompileTask::allocate(); 1589 new_task->initialize(compile_id, method, osr_bci, comp_level, 1590 hot_method, hot_count, compile_reason, 1591 blocking); 1592 queue->add(new_task); 1593 return new_task; 1594 } 1595 1596 #if INCLUDE_JVMCI 1597 // The number of milliseconds to wait before checking if 1598 // JVMCI compilation has made progress. 1599 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000; 1600 1601 // The number of JVMCI compilation progress checks that must fail 1602 // before unblocking a thread waiting for a blocking compilation. 1603 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10; 1604 1605 /** 1606 * Waits for a JVMCI compiler to complete a given task. This thread 1607 * waits until either the task completes or it sees no JVMCI compilation 1608 * progress for N consecutive milliseconds where N is 1609 * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE * 1610 * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS. 1611 * 1612 * @return true if this thread needs to free/recycle the task 1613 */ 1614 bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) { 1615 assert(UseJVMCICompiler, "sanity"); 1616 MonitorLocker ml(thread, task->lock()); 1617 int progress_wait_attempts = 0; 1618 jint thread_jvmci_compilation_ticks = 0; 1619 jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks(); 1620 while (!task->is_complete() && !is_compilation_disabled_forever() && 1621 ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) { 1622 JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state(); 1623 1624 bool progress; 1625 if (jvmci_compile_state != NULL) { 1626 jint ticks = jvmci_compile_state->compilation_ticks(); 1627 progress = (ticks - thread_jvmci_compilation_ticks) != 0; 1628 JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks); 1629 thread_jvmci_compilation_ticks = ticks; 1630 } else { 1631 // Still waiting on JVMCI compiler queue. This thread may be holding a lock 1632 // that all JVMCI compiler threads are blocked on. We use the global JVMCI 1633 // compilation ticks to determine whether JVMCI compilation 1634 // is still making progress through the JVMCI compiler queue. 1635 jint ticks = jvmci->global_compilation_ticks(); 1636 progress = (ticks - global_jvmci_compilation_ticks) != 0; 1637 JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks); 1638 global_jvmci_compilation_ticks = ticks; 1639 } 1640 1641 if (!progress) { 1642 if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) { 1643 if (PrintCompilation) { 1644 task->print(tty, "wait for blocking compilation timed out"); 1645 } 1646 JVMCI_event_1("waiting on compilation %d timed out", task->compile_id()); 1647 break; 1648 } 1649 } else { 1650 progress_wait_attempts = 0; 1651 } 1652 } 1653 task->clear_waiter(); 1654 return task->is_complete(); 1655 } 1656 #endif 1657 1658 /** 1659 * Wait for the compilation task to complete. 1660 */ 1661 void CompileBroker::wait_for_completion(CompileTask* task) { 1662 if (CIPrintCompileQueue) { 1663 ttyLocker ttyl; 1664 tty->print_cr("BLOCKING FOR COMPILE"); 1665 } 1666 1667 assert(task->is_blocking(), "can only wait on blocking task"); 1668 1669 JavaThread* thread = JavaThread::current(); 1670 1671 methodHandle method(thread, task->method()); 1672 bool free_task; 1673 #if INCLUDE_JVMCI 1674 AbstractCompiler* comp = compiler(task->comp_level()); 1675 if (comp->is_jvmci() && !task->should_wait_for_compilation()) { 1676 // It may return before compilation is completed. 1677 free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread); 1678 } else 1679 #endif 1680 { 1681 MonitorLocker ml(thread, task->lock()); 1682 free_task = true; 1683 while (!task->is_complete() && !is_compilation_disabled_forever()) { 1684 ml.wait(); 1685 } 1686 } 1687 1688 if (free_task) { 1689 if (is_compilation_disabled_forever()) { 1690 CompileTask::free(task); 1691 return; 1692 } 1693 1694 // It is harmless to check this status without the lock, because 1695 // completion is a stable property (until the task object is recycled). 1696 assert(task->is_complete(), "Compilation should have completed"); 1697 1698 // By convention, the waiter is responsible for recycling a 1699 // blocking CompileTask. Since there is only one waiter ever 1700 // waiting on a CompileTask, we know that no one else will 1701 // be using this CompileTask; we can free it. 1702 CompileTask::free(task); 1703 } 1704 } 1705 1706 /** 1707 * Initialize compiler thread(s) + compiler object(s). The postcondition 1708 * of this function is that the compiler runtimes are initialized and that 1709 * compiler threads can start compiling. 1710 */ 1711 bool CompileBroker::init_compiler_runtime() { 1712 CompilerThread* thread = CompilerThread::current(); 1713 AbstractCompiler* comp = thread->compiler(); 1714 // Final sanity check - the compiler object must exist 1715 guarantee(comp != NULL, "Compiler object must exist"); 1716 1717 { 1718 // Must switch to native to allocate ci_env 1719 ThreadToNativeFromVM ttn(thread); 1720 ciEnv ci_env((CompileTask*)NULL); 1721 // Cache Jvmti state 1722 ci_env.cache_jvmti_state(); 1723 // Cache DTrace flags 1724 ci_env.cache_dtrace_flags(); 1725 1726 // Switch back to VM state to do compiler initialization 1727 ThreadInVMfromNative tv(thread); 1728 1729 // Perform per-thread and global initializations 1730 comp->initialize(); 1731 } 1732 1733 if (comp->is_failed()) { 1734 disable_compilation_forever(); 1735 // If compiler initialization failed, no compiler thread that is specific to a 1736 // particular compiler runtime will ever start to compile methods. 1737 shutdown_compiler_runtime(comp, thread); 1738 return false; 1739 } 1740 1741 // C1 specific check 1742 if (comp->is_c1() && (thread->get_buffer_blob() == NULL)) { 1743 warning("Initialization of %s thread failed (no space to run compilers)", thread->name()); 1744 return false; 1745 } 1746 1747 return true; 1748 } 1749 1750 /** 1751 * If C1 and/or C2 initialization failed, we shut down all compilation. 1752 * We do this to keep things simple. This can be changed if it ever turns 1753 * out to be a problem. 1754 */ 1755 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) { 1756 // Free buffer blob, if allocated 1757 if (thread->get_buffer_blob() != NULL) { 1758 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1759 CodeCache::free(thread->get_buffer_blob()); 1760 } 1761 1762 if (comp->should_perform_shutdown()) { 1763 // There are two reasons for shutting down the compiler 1764 // 1) compiler runtime initialization failed 1765 // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing 1766 warning("%s initialization failed. Shutting down all compilers", comp->name()); 1767 1768 // Only one thread per compiler runtime object enters here 1769 // Set state to shut down 1770 comp->set_shut_down(); 1771 1772 // Delete all queued compilation tasks to make compiler threads exit faster. 1773 if (_c1_compile_queue != NULL) { 1774 _c1_compile_queue->free_all(); 1775 } 1776 1777 if (_c2_compile_queue != NULL) { 1778 _c2_compile_queue->free_all(); 1779 } 1780 1781 // Set flags so that we continue execution with using interpreter only. 1782 UseCompiler = false; 1783 UseInterpreter = true; 1784 1785 // We could delete compiler runtimes also. However, there are references to 1786 // the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then 1787 // fail. This can be done later if necessary. 1788 } 1789 } 1790 1791 /** 1792 * Helper function to create new or reuse old CompileLog. 1793 */ 1794 CompileLog* CompileBroker::get_log(CompilerThread* ct) { 1795 if (!LogCompilation) return NULL; 1796 1797 AbstractCompiler *compiler = ct->compiler(); 1798 bool c1 = compiler->is_c1(); 1799 jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects; 1800 assert(compiler_objects != NULL, "must be initialized at this point"); 1801 CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs; 1802 assert(logs != NULL, "must be initialized at this point"); 1803 int count = c1 ? _c1_count : _c2_count; 1804 1805 // Find Compiler number by its threadObj. 1806 oop compiler_obj = ct->threadObj(); 1807 int compiler_number = 0; 1808 bool found = false; 1809 for (; compiler_number < count; compiler_number++) { 1810 if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) { 1811 found = true; 1812 break; 1813 } 1814 } 1815 assert(found, "Compiler must exist at this point"); 1816 1817 // Determine pointer for this thread's log. 1818 CompileLog** log_ptr = &logs[compiler_number]; 1819 1820 // Return old one if it exists. 1821 CompileLog* log = *log_ptr; 1822 if (log != NULL) { 1823 ct->init_log(log); 1824 return log; 1825 } 1826 1827 // Create a new one and remember it. 1828 init_compiler_thread_log(); 1829 log = ct->log(); 1830 *log_ptr = log; 1831 return log; 1832 } 1833 1834 // ------------------------------------------------------------------ 1835 // CompileBroker::compiler_thread_loop 1836 // 1837 // The main loop run by a CompilerThread. 1838 void CompileBroker::compiler_thread_loop() { 1839 CompilerThread* thread = CompilerThread::current(); 1840 CompileQueue* queue = thread->queue(); 1841 // For the thread that initializes the ciObjectFactory 1842 // this resource mark holds all the shared objects 1843 ResourceMark rm; 1844 1845 // First thread to get here will initialize the compiler interface 1846 1847 { 1848 ASSERT_IN_VM; 1849 MutexLocker only_one (thread, CompileThread_lock); 1850 if (!ciObjectFactory::is_initialized()) { 1851 ciObjectFactory::initialize(); 1852 } 1853 } 1854 1855 // Open a log. 1856 CompileLog* log = get_log(thread); 1857 if (log != NULL) { 1858 log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'", 1859 thread->name(), 1860 os::current_thread_id(), 1861 os::current_process_id()); 1862 log->stamp(); 1863 log->end_elem(); 1864 } 1865 1866 // If compiler thread/runtime initialization fails, exit the compiler thread 1867 if (!init_compiler_runtime()) { 1868 return; 1869 } 1870 1871 thread->start_idle_timer(); 1872 1873 // Poll for new compilation tasks as long as the JVM runs. Compilation 1874 // should only be disabled if something went wrong while initializing the 1875 // compiler runtimes. This, in turn, should not happen. The only known case 1876 // when compiler runtime initialization fails is if there is not enough free 1877 // space in the code cache to generate the necessary stubs, etc. 1878 while (!is_compilation_disabled_forever()) { 1879 // We need this HandleMark to avoid leaking VM handles. 1880 HandleMark hm(thread); 1881 1882 CompileTask* task = queue->get(thread); 1883 if (task == NULL) { 1884 if (UseDynamicNumberOfCompilerThreads) { 1885 // Access compiler_count under lock to enforce consistency. 1886 MutexLocker only_one(CompileThread_lock); 1887 if (can_remove(thread, true)) { 1888 if (TraceCompilerThreads) { 1889 tty->print_cr("Removing compiler thread %s after " JLONG_FORMAT " ms idle time", 1890 thread->name(), thread->idle_time_millis()); 1891 } 1892 1893 // Notify compiler that the compiler thread is about to stop 1894 thread->compiler()->stopping_compiler_thread(thread); 1895 1896 // Free buffer blob, if allocated 1897 if (thread->get_buffer_blob() != NULL) { 1898 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1899 CodeCache::free(thread->get_buffer_blob()); 1900 } 1901 return; // Stop this thread. 1902 } 1903 } 1904 } else { 1905 // Assign the task to the current thread. Mark this compilation 1906 // thread as active for the profiler. 1907 // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition 1908 // occurs after fetching the compile task off the queue. 1909 CompileTaskWrapper ctw(task); 1910 methodHandle method(thread, task->method()); 1911 1912 // Never compile a method if breakpoints are present in it 1913 if (method()->number_of_breakpoints() == 0) { 1914 // Compile the method. 1915 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) { 1916 invoke_compiler_on_method(task); 1917 thread->start_idle_timer(); 1918 } else { 1919 // After compilation is disabled, remove remaining methods from queue 1920 method->clear_queued_for_compilation(); 1921 task->set_failure_reason("compilation is disabled"); 1922 } 1923 } else { 1924 task->set_failure_reason("breakpoints are present"); 1925 } 1926 1927 if (UseDynamicNumberOfCompilerThreads) { 1928 possibly_add_compiler_threads(thread); 1929 assert(!thread->has_pending_exception(), "should have been handled"); 1930 } 1931 } 1932 } 1933 1934 // Shut down compiler runtime 1935 shutdown_compiler_runtime(thread->compiler(), thread); 1936 } 1937 1938 // ------------------------------------------------------------------ 1939 // CompileBroker::init_compiler_thread_log 1940 // 1941 // Set up state required by +LogCompilation. 1942 void CompileBroker::init_compiler_thread_log() { 1943 CompilerThread* thread = CompilerThread::current(); 1944 char file_name[4*K]; 1945 FILE* fp = NULL; 1946 intx thread_id = os::current_thread_id(); 1947 for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) { 1948 const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL); 1949 if (dir == NULL) { 1950 jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log", 1951 thread_id, os::current_process_id()); 1952 } else { 1953 jio_snprintf(file_name, sizeof(file_name), 1954 "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir, 1955 os::file_separator(), thread_id, os::current_process_id()); 1956 } 1957 1958 fp = os::fopen(file_name, "wt"); 1959 if (fp != NULL) { 1960 if (LogCompilation && Verbose) { 1961 tty->print_cr("Opening compilation log %s", file_name); 1962 } 1963 CompileLog* log = new(mtCompiler) CompileLog(file_name, fp, thread_id); 1964 if (log == NULL) { 1965 fclose(fp); 1966 return; 1967 } 1968 thread->init_log(log); 1969 1970 if (xtty != NULL) { 1971 ttyLocker ttyl; 1972 // Record any per thread log files 1973 xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name); 1974 } 1975 return; 1976 } 1977 } 1978 warning("Cannot open log file: %s", file_name); 1979 } 1980 1981 void CompileBroker::log_metaspace_failure() { 1982 const char* message = "some methods may not be compiled because metaspace " 1983 "is out of memory"; 1984 if (CompilationLog::log() != NULL) { 1985 CompilationLog::log()->log_metaspace_failure(message); 1986 } 1987 if (PrintCompilation) { 1988 tty->print_cr("COMPILE PROFILING SKIPPED: %s", message); 1989 } 1990 } 1991 1992 1993 // ------------------------------------------------------------------ 1994 // CompileBroker::set_should_block 1995 // 1996 // Set _should_block. 1997 // Call this from the VM, with Threads_lock held and a safepoint requested. 1998 void CompileBroker::set_should_block() { 1999 assert(Threads_lock->owner() == Thread::current(), "must have threads lock"); 2000 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already"); 2001 #ifndef PRODUCT 2002 if (PrintCompilation && (Verbose || WizardMode)) 2003 tty->print_cr("notifying compiler thread pool to block"); 2004 #endif 2005 _should_block = true; 2006 } 2007 2008 // ------------------------------------------------------------------ 2009 // CompileBroker::maybe_block 2010 // 2011 // Call this from the compiler at convenient points, to poll for _should_block. 2012 void CompileBroker::maybe_block() { 2013 if (_should_block) { 2014 #ifndef PRODUCT 2015 if (PrintCompilation && (Verbose || WizardMode)) 2016 tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current())); 2017 #endif 2018 ThreadInVMfromNative tivfn(JavaThread::current()); 2019 } 2020 } 2021 2022 // wrapper for CodeCache::print_summary() 2023 static void codecache_print(bool detailed) 2024 { 2025 stringStream s; 2026 // Dump code cache into a buffer before locking the tty, 2027 { 2028 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 2029 CodeCache::print_summary(&s, detailed); 2030 } 2031 ttyLocker ttyl; 2032 tty->print("%s", s.freeze()); 2033 } 2034 2035 // wrapper for CodeCache::print_summary() using outputStream 2036 static void codecache_print(outputStream* out, bool detailed) { 2037 stringStream s; 2038 2039 // Dump code cache into a buffer 2040 { 2041 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 2042 CodeCache::print_summary(&s, detailed); 2043 } 2044 2045 char* remaining_log = s.as_string(); 2046 while (*remaining_log != '\0') { 2047 char* eol = strchr(remaining_log, '\n'); 2048 if (eol == NULL) { 2049 out->print_cr("%s", remaining_log); 2050 remaining_log = remaining_log + strlen(remaining_log); 2051 } else { 2052 *eol = '\0'; 2053 out->print_cr("%s", remaining_log); 2054 remaining_log = eol + 1; 2055 } 2056 } 2057 } 2058 2059 void CompileBroker::handle_compile_error(CompilerThread* thread, CompileTask* task, ciEnv* ci_env, 2060 int compilable, const char* failure_reason) { 2061 if (!AbortVMOnCompilationFailure) { 2062 return; 2063 } 2064 if (compilable == ciEnv::MethodCompilable_not_at_tier) { 2065 fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason); 2066 } 2067 if (compilable == ciEnv::MethodCompilable_never) { 2068 fatal("Never compilable: %s", failure_reason); 2069 } 2070 } 2071 2072 static void post_compilation_event(EventCompilation& event, CompileTask* task) { 2073 assert(task != NULL, "invariant"); 2074 CompilerEvent::CompilationEvent::post(event, 2075 task->compile_id(), 2076 task->compiler()->type(), 2077 task->method(), 2078 task->comp_level(), 2079 task->is_success(), 2080 task->osr_bci() != CompileBroker::standard_entry_bci, 2081 task->nm_total_size(), 2082 task->num_inlined_bytecodes()); 2083 } 2084 2085 int DirectivesStack::_depth = 0; 2086 CompilerDirectives* DirectivesStack::_top = NULL; 2087 CompilerDirectives* DirectivesStack::_bottom = NULL; 2088 2089 // ------------------------------------------------------------------ 2090 // CompileBroker::invoke_compiler_on_method 2091 // 2092 // Compile a method. 2093 // 2094 void CompileBroker::invoke_compiler_on_method(CompileTask* task) { 2095 task->print_ul(); 2096 elapsedTimer time; 2097 2098 DirectiveSet* directive = task->directive(); 2099 if (directive->PrintCompilationOption) { 2100 ResourceMark rm; 2101 task->print_tty(); 2102 } 2103 2104 CompilerThread* thread = CompilerThread::current(); 2105 ResourceMark rm(thread); 2106 2107 if (CompilationLog::log() != NULL) { 2108 CompilationLog::log()->log_compile(thread, task); 2109 } 2110 2111 // Common flags. 2112 int compile_id = task->compile_id(); 2113 int osr_bci = task->osr_bci(); 2114 bool is_osr = (osr_bci != standard_entry_bci); 2115 bool should_log = (thread->log() != NULL); 2116 bool should_break = false; 2117 const int task_level = task->comp_level(); 2118 AbstractCompiler* comp = task->compiler(); 2119 { 2120 // create the handle inside it's own block so it can't 2121 // accidentally be referenced once the thread transitions to 2122 // native. The NoHandleMark before the transition should catch 2123 // any cases where this occurs in the future. 2124 methodHandle method(thread, task->method()); 2125 2126 assert(!method->is_native(), "no longer compile natives"); 2127 2128 // Update compile information when using perfdata. 2129 if (UsePerfData) { 2130 update_compile_perf_data(thread, method, is_osr); 2131 } 2132 2133 DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level)); 2134 } 2135 2136 should_break = directive->BreakAtCompileOption || task->check_break_at_flags(); 2137 if (should_log && !directive->LogOption) { 2138 should_log = false; 2139 } 2140 2141 // Allocate a new set of JNI handles. 2142 JNIHandleMark jhm(thread); 2143 Method* target_handle = task->method(); 2144 int compilable = ciEnv::MethodCompilable; 2145 const char* failure_reason = NULL; 2146 bool failure_reason_on_C_heap = false; 2147 const char* retry_message = NULL; 2148 2149 #if INCLUDE_JVMCI 2150 if (UseJVMCICompiler && comp != NULL && comp->is_jvmci()) { 2151 JVMCICompiler* jvmci = (JVMCICompiler*) comp; 2152 2153 TraceTime t1("compilation", &time); 2154 EventCompilation event; 2155 JVMCICompileState compile_state(task, jvmci); 2156 JVMCIRuntime *runtime = NULL; 2157 2158 if (JVMCI::in_shutdown()) { 2159 failure_reason = "in JVMCI shutdown"; 2160 retry_message = "not retryable"; 2161 compilable = ciEnv::MethodCompilable_never; 2162 } else if (compile_state.target_method_is_old()) { 2163 // Skip redefined methods 2164 failure_reason = "redefined method"; 2165 retry_message = "not retryable"; 2166 compilable = ciEnv::MethodCompilable_never; 2167 } else { 2168 JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__); 2169 failure_reason = compile_state.failure_reason(); 2170 if (failure_reason == nullptr) { 2171 methodHandle method(thread, target_handle); 2172 runtime = env.runtime(); 2173 runtime->compile_method(&env, jvmci, method, osr_bci); 2174 2175 failure_reason = compile_state.failure_reason(); 2176 failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap(); 2177 if (!compile_state.retryable()) { 2178 retry_message = "not retryable"; 2179 compilable = ciEnv::MethodCompilable_not_at_tier; 2180 } 2181 if (!task->is_success()) { 2182 assert(failure_reason != NULL, "must specify failure_reason"); 2183 } 2184 } 2185 } 2186 if (!task->is_success()) { 2187 handle_compile_error(thread, task, NULL, compilable, failure_reason); 2188 } 2189 if (event.should_commit()) { 2190 post_compilation_event(event, task); 2191 } 2192 2193 if (runtime != nullptr) { 2194 runtime->post_compile(thread); 2195 } 2196 } else 2197 #endif // INCLUDE_JVMCI 2198 { 2199 NoHandleMark nhm; 2200 ThreadToNativeFromVM ttn(thread); 2201 2202 ciEnv ci_env(task); 2203 if (should_break) { 2204 ci_env.set_break_at_compile(true); 2205 } 2206 if (should_log) { 2207 ci_env.set_log(thread->log()); 2208 } 2209 assert(thread->env() == &ci_env, "set by ci_env"); 2210 // The thread-env() field is cleared in ~CompileTaskWrapper. 2211 2212 // Cache Jvmti state 2213 bool method_is_old = ci_env.cache_jvmti_state(); 2214 2215 // Skip redefined methods 2216 if (method_is_old) { 2217 ci_env.record_method_not_compilable("redefined method", true); 2218 } 2219 2220 // Cache DTrace flags 2221 ci_env.cache_dtrace_flags(); 2222 2223 ciMethod* target = ci_env.get_method_from_handle(target_handle); 2224 2225 TraceTime t1("compilation", &time); 2226 EventCompilation event; 2227 2228 if (comp == NULL) { 2229 ci_env.record_method_not_compilable("no compiler"); 2230 } else if (!ci_env.failing()) { 2231 if (WhiteBoxAPI && WhiteBox::compilation_locked) { 2232 MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag); 2233 while (WhiteBox::compilation_locked) { 2234 locker.wait(); 2235 } 2236 } 2237 comp->compile_method(&ci_env, target, osr_bci, true, directive); 2238 2239 /* Repeat compilation without installing code for profiling purposes */ 2240 int repeat_compilation_count = directive->RepeatCompilationOption; 2241 while (repeat_compilation_count > 0) { 2242 ResourceMark rm(thread); 2243 task->print_ul("NO CODE INSTALLED"); 2244 comp->compile_method(&ci_env, target, osr_bci, false, directive); 2245 repeat_compilation_count--; 2246 } 2247 } 2248 2249 DirectivesStack::release(directive); 2250 2251 if (!ci_env.failing() && !task->is_success()) { 2252 //assert(false, "compiler should always document failure"); 2253 // The compiler elected, without comment, not to register a result. 2254 // Do not attempt further compilations of this method. 2255 ci_env.record_method_not_compilable("compile failed"); 2256 } 2257 2258 // Copy this bit to the enclosing block: 2259 compilable = ci_env.compilable(); 2260 2261 if (ci_env.failing()) { 2262 failure_reason = ci_env.failure_reason(); 2263 retry_message = ci_env.retry_message(); 2264 ci_env.report_failure(failure_reason); 2265 } 2266 2267 if (ci_env.failing()) { 2268 handle_compile_error(thread, task, &ci_env, compilable, failure_reason); 2269 } 2270 if (event.should_commit()) { 2271 post_compilation_event(event, task); 2272 } 2273 } 2274 2275 if (failure_reason != NULL) { 2276 task->set_failure_reason(failure_reason, failure_reason_on_C_heap); 2277 if (CompilationLog::log() != NULL) { 2278 CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message); 2279 } 2280 if (PrintCompilation) { 2281 FormatBufferResource msg = retry_message != NULL ? 2282 FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) : 2283 FormatBufferResource("COMPILE SKIPPED: %s", failure_reason); 2284 task->print(tty, msg); 2285 } 2286 } 2287 2288 methodHandle method(thread, task->method()); 2289 2290 DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success()); 2291 2292 collect_statistics(thread, time, task); 2293 2294 if (PrintCompilation && PrintCompilation2) { 2295 tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp 2296 tty->print("%4d ", compile_id); // print compilation number 2297 tty->print("%s ", (is_osr ? "%" : " ")); 2298 if (task->is_success()) { 2299 tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size()); 2300 } 2301 tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes()); 2302 } 2303 2304 Log(compilation, codecache) log; 2305 if (log.is_debug()) { 2306 LogStream ls(log.debug()); 2307 codecache_print(&ls, /* detailed= */ false); 2308 } 2309 if (PrintCodeCacheOnCompilation) { 2310 codecache_print(/* detailed= */ false); 2311 } 2312 // Disable compilation, if required. 2313 switch (compilable) { 2314 case ciEnv::MethodCompilable_never: 2315 if (is_osr) 2316 method->set_not_osr_compilable_quietly("MethodCompilable_never"); 2317 else 2318 method->set_not_compilable_quietly("MethodCompilable_never"); 2319 break; 2320 case ciEnv::MethodCompilable_not_at_tier: 2321 if (is_osr) 2322 method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level); 2323 else 2324 method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level); 2325 break; 2326 } 2327 2328 // Note that the queued_for_compilation bits are cleared without 2329 // protection of a mutex. [They were set by the requester thread, 2330 // when adding the task to the compile queue -- at which time the 2331 // compile queue lock was held. Subsequently, we acquired the compile 2332 // queue lock to get this task off the compile queue; thus (to belabour 2333 // the point somewhat) our clearing of the bits must be occurring 2334 // only after the setting of the bits. See also 14012000 above. 2335 method->clear_queued_for_compilation(); 2336 } 2337 2338 /** 2339 * The CodeCache is full. Print warning and disable compilation. 2340 * Schedule code cache cleaning so compilation can continue later. 2341 * This function needs to be called only from CodeCache::allocate(), 2342 * since we currently handle a full code cache uniformly. 2343 */ 2344 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) { 2345 UseInterpreter = true; 2346 if (UseCompiler || AlwaysCompileLoopMethods ) { 2347 if (xtty != NULL) { 2348 stringStream s; 2349 // Dump code cache state into a buffer before locking the tty, 2350 // because log_state() will use locks causing lock conflicts. 2351 CodeCache::log_state(&s); 2352 // Lock to prevent tearing 2353 ttyLocker ttyl; 2354 xtty->begin_elem("code_cache_full"); 2355 xtty->print("%s", s.freeze()); 2356 xtty->stamp(); 2357 xtty->end_elem(); 2358 } 2359 2360 #ifndef PRODUCT 2361 if (ExitOnFullCodeCache) { 2362 codecache_print(/* detailed= */ true); 2363 before_exit(JavaThread::current()); 2364 exit_globals(); // will delete tty 2365 vm_direct_exit(1); 2366 } 2367 #endif 2368 if (UseCodeCacheFlushing) { 2369 // Since code cache is full, immediately stop new compiles 2370 if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) { 2371 log_info(codecache)("Code cache is full - disabling compilation"); 2372 } 2373 } else { 2374 disable_compilation_forever(); 2375 } 2376 2377 CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning()); 2378 } 2379 } 2380 2381 // ------------------------------------------------------------------ 2382 // CompileBroker::update_compile_perf_data 2383 // 2384 // Record this compilation for debugging purposes. 2385 void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) { 2386 ResourceMark rm; 2387 char* method_name = method->name()->as_C_string(); 2388 char current_method[CompilerCounters::cmname_buffer_length]; 2389 size_t maxLen = CompilerCounters::cmname_buffer_length; 2390 2391 const char* class_name = method->method_holder()->name()->as_C_string(); 2392 2393 size_t s1len = strlen(class_name); 2394 size_t s2len = strlen(method_name); 2395 2396 // check if we need to truncate the string 2397 if (s1len + s2len + 2 > maxLen) { 2398 2399 // the strategy is to lop off the leading characters of the 2400 // class name and the trailing characters of the method name. 2401 2402 if (s2len + 2 > maxLen) { 2403 // lop of the entire class name string, let snprintf handle 2404 // truncation of the method name. 2405 class_name += s1len; // null string 2406 } 2407 else { 2408 // lop off the extra characters from the front of the class name 2409 class_name += ((s1len + s2len + 2) - maxLen); 2410 } 2411 } 2412 2413 jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name); 2414 2415 int last_compile_type = normal_compile; 2416 if (CICountOSR && is_osr) { 2417 last_compile_type = osr_compile; 2418 } else if (CICountNative && method->is_native()) { 2419 last_compile_type = native_compile; 2420 } 2421 2422 CompilerCounters* counters = thread->counters(); 2423 counters->set_current_method(current_method); 2424 counters->set_compile_type((jlong) last_compile_type); 2425 } 2426 2427 // ------------------------------------------------------------------ 2428 // CompileBroker::collect_statistics 2429 // 2430 // Collect statistics about the compilation. 2431 2432 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) { 2433 bool success = task->is_success(); 2434 methodHandle method (thread, task->method()); 2435 int compile_id = task->compile_id(); 2436 bool is_osr = (task->osr_bci() != standard_entry_bci); 2437 const int comp_level = task->comp_level(); 2438 CompilerCounters* counters = thread->counters(); 2439 2440 MutexLocker locker(CompileStatistics_lock); 2441 2442 // _perf variables are production performance counters which are 2443 // updated regardless of the setting of the CITime and CITimeEach flags 2444 // 2445 2446 // account all time, including bailouts and failures in this counter; 2447 // C1 and C2 counters are counting both successful and unsuccessful compiles 2448 _t_total_compilation.add(time); 2449 2450 if (!success) { 2451 _total_bailout_count++; 2452 if (UsePerfData) { 2453 _perf_last_failed_method->set_value(counters->current_method()); 2454 _perf_last_failed_type->set_value(counters->compile_type()); 2455 _perf_total_bailout_count->inc(); 2456 } 2457 _t_bailedout_compilation.add(time); 2458 } else if (!task->is_success()) { 2459 if (UsePerfData) { 2460 _perf_last_invalidated_method->set_value(counters->current_method()); 2461 _perf_last_invalidated_type->set_value(counters->compile_type()); 2462 _perf_total_invalidated_count->inc(); 2463 } 2464 _total_invalidated_count++; 2465 _t_invalidated_compilation.add(time); 2466 } else { 2467 // Compilation succeeded 2468 2469 // update compilation ticks - used by the implementation of 2470 // java.lang.management.CompilationMXBean 2471 _perf_total_compilation->inc(time.ticks()); 2472 _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time; 2473 2474 if (CITime) { 2475 int bytes_compiled = method->code_size() + task->num_inlined_bytecodes(); 2476 if (is_osr) { 2477 _t_osr_compilation.add(time); 2478 _sum_osr_bytes_compiled += bytes_compiled; 2479 } else { 2480 _t_standard_compilation.add(time); 2481 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes(); 2482 } 2483 2484 // Collect statistic per compilation level 2485 if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) { 2486 CompilerStatistics* stats = &_stats_per_level[comp_level-1]; 2487 if (is_osr) { 2488 stats->_osr.update(time, bytes_compiled); 2489 } else { 2490 stats->_standard.update(time, bytes_compiled); 2491 } 2492 stats->_nmethods_size += task->nm_total_size(); 2493 stats->_nmethods_code_size += task->nm_insts_size(); 2494 } else { 2495 assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level); 2496 } 2497 2498 // Collect statistic per compiler 2499 AbstractCompiler* comp = compiler(comp_level); 2500 if (comp) { 2501 CompilerStatistics* stats = comp->stats(); 2502 if (is_osr) { 2503 stats->_osr.update(time, bytes_compiled); 2504 } else { 2505 stats->_standard.update(time, bytes_compiled); 2506 } 2507 stats->_nmethods_size += task->nm_total_size(); 2508 stats->_nmethods_code_size += task->nm_insts_size(); 2509 } else { // if (!comp) 2510 assert(false, "Compiler object must exist"); 2511 } 2512 } 2513 2514 if (UsePerfData) { 2515 // save the name of the last method compiled 2516 _perf_last_method->set_value(counters->current_method()); 2517 _perf_last_compile_type->set_value(counters->compile_type()); 2518 _perf_last_compile_size->set_value(method->code_size() + 2519 task->num_inlined_bytecodes()); 2520 if (is_osr) { 2521 _perf_osr_compilation->inc(time.ticks()); 2522 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes()); 2523 } else { 2524 _perf_standard_compilation->inc(time.ticks()); 2525 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes()); 2526 } 2527 } 2528 2529 if (CITimeEach) { 2530 double compile_time = time.seconds(); 2531 double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time; 2532 tty->print_cr("%3d seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)", 2533 compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes()); 2534 } 2535 2536 // Collect counts of successful compilations 2537 _sum_nmethod_size += task->nm_total_size(); 2538 _sum_nmethod_code_size += task->nm_insts_size(); 2539 _total_compile_count++; 2540 2541 if (UsePerfData) { 2542 _perf_sum_nmethod_size->inc( task->nm_total_size()); 2543 _perf_sum_nmethod_code_size->inc(task->nm_insts_size()); 2544 _perf_total_compile_count->inc(); 2545 } 2546 2547 if (is_osr) { 2548 if (UsePerfData) _perf_total_osr_compile_count->inc(); 2549 _total_osr_compile_count++; 2550 } else { 2551 if (UsePerfData) _perf_total_standard_compile_count->inc(); 2552 _total_standard_compile_count++; 2553 } 2554 } 2555 // set the current method for the thread to null 2556 if (UsePerfData) counters->set_current_method(""); 2557 } 2558 2559 const char* CompileBroker::compiler_name(int comp_level) { 2560 AbstractCompiler *comp = CompileBroker::compiler(comp_level); 2561 if (comp == NULL) { 2562 return "no compiler"; 2563 } else { 2564 return (comp->name()); 2565 } 2566 } 2567 2568 jlong CompileBroker::total_compilation_ticks() { 2569 return _perf_total_compilation != NULL ? _perf_total_compilation->get_value() : 0; 2570 } 2571 2572 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) { 2573 tty->print_cr(" %s {speed: %6.3f bytes/s; standard: %6.3f s, %d bytes, %d methods; osr: %6.3f s, %d bytes, %d methods; nmethods_size: %d bytes; nmethods_code_size: %d bytes}", 2574 name, stats->bytes_per_second(), 2575 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count, 2576 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count, 2577 stats->_nmethods_size, stats->_nmethods_code_size); 2578 } 2579 2580 void CompileBroker::print_times(bool per_compiler, bool aggregate) { 2581 if (per_compiler) { 2582 if (aggregate) { 2583 tty->cr(); 2584 tty->print_cr("Individual compiler times (for compiled methods only)"); 2585 tty->print_cr("------------------------------------------------"); 2586 tty->cr(); 2587 } 2588 for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) { 2589 AbstractCompiler* comp = _compilers[i]; 2590 if (comp != NULL) { 2591 print_times(comp->name(), comp->stats()); 2592 } 2593 } 2594 if (aggregate) { 2595 tty->cr(); 2596 tty->print_cr("Individual compilation Tier times (for compiled methods only)"); 2597 tty->print_cr("------------------------------------------------"); 2598 tty->cr(); 2599 } 2600 char tier_name[256]; 2601 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) { 2602 CompilerStatistics* stats = &_stats_per_level[tier-1]; 2603 os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier); 2604 print_times(tier_name, stats); 2605 } 2606 } 2607 2608 if (!aggregate) { 2609 return; 2610 } 2611 2612 elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation; 2613 elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation; 2614 elapsedTimer total_compilation = CompileBroker::_t_total_compilation; 2615 2616 int standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled; 2617 int osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled; 2618 2619 int standard_compile_count = CompileBroker::_total_standard_compile_count; 2620 int osr_compile_count = CompileBroker::_total_osr_compile_count; 2621 int total_compile_count = CompileBroker::_total_compile_count; 2622 int total_bailout_count = CompileBroker::_total_bailout_count; 2623 int total_invalidated_count = CompileBroker::_total_invalidated_count; 2624 2625 int nmethods_size = CompileBroker::_sum_nmethod_code_size; 2626 int nmethods_code_size = CompileBroker::_sum_nmethod_size; 2627 2628 tty->cr(); 2629 tty->print_cr("Accumulated compiler times"); 2630 tty->print_cr("----------------------------------------------------------"); 2631 //0000000000111111111122222222223333333333444444444455555555556666666666 2632 //0123456789012345678901234567890123456789012345678901234567890123456789 2633 tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds()); 2634 tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s", 2635 standard_compilation.seconds(), 2636 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count); 2637 tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s", 2638 CompileBroker::_t_bailedout_compilation.seconds(), 2639 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count); 2640 tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s", 2641 osr_compilation.seconds(), 2642 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count); 2643 tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s", 2644 CompileBroker::_t_invalidated_compilation.seconds(), 2645 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count); 2646 2647 AbstractCompiler *comp = compiler(CompLevel_simple); 2648 if (comp != NULL) { 2649 tty->cr(); 2650 comp->print_timers(); 2651 } 2652 comp = compiler(CompLevel_full_optimization); 2653 if (comp != NULL) { 2654 tty->cr(); 2655 comp->print_timers(); 2656 } 2657 #if INCLUDE_JVMCI 2658 if (EnableJVMCI) { 2659 JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null()); 2660 if (jvmci_comp != nullptr && jvmci_comp != comp) { 2661 tty->cr(); 2662 jvmci_comp->print_timers(); 2663 } 2664 } 2665 #endif 2666 2667 tty->cr(); 2668 tty->print_cr(" Total compiled methods : %8d methods", total_compile_count); 2669 tty->print_cr(" Standard compilation : %8d methods", standard_compile_count); 2670 tty->print_cr(" On stack replacement : %8d methods", osr_compile_count); 2671 int tcb = osr_bytes_compiled + standard_bytes_compiled; 2672 tty->print_cr(" Total compiled bytecodes : %8d bytes", tcb); 2673 tty->print_cr(" Standard compilation : %8d bytes", standard_bytes_compiled); 2674 tty->print_cr(" On stack replacement : %8d bytes", osr_bytes_compiled); 2675 double tcs = total_compilation.seconds(); 2676 int bps = tcs == 0.0 ? 0 : (int)(tcb / tcs); 2677 tty->print_cr(" Average compilation speed : %8d bytes/s", bps); 2678 tty->cr(); 2679 tty->print_cr(" nmethod code size : %8d bytes", nmethods_code_size); 2680 tty->print_cr(" nmethod total size : %8d bytes", nmethods_size); 2681 } 2682 2683 // Print general/accumulated JIT information. 2684 void CompileBroker::print_info(outputStream *out) { 2685 if (out == NULL) out = tty; 2686 out->cr(); 2687 out->print_cr("======================"); 2688 out->print_cr(" General JIT info "); 2689 out->print_cr("======================"); 2690 out->cr(); 2691 out->print_cr(" JIT is : %7s", should_compile_new_jobs() ? "on" : "off"); 2692 out->print_cr(" Compiler threads : %7d", (int)CICompilerCount); 2693 out->cr(); 2694 out->print_cr("CodeCache overview"); 2695 out->print_cr("--------------------------------------------------------"); 2696 out->cr(); 2697 out->print_cr(" Reserved size : " SIZE_FORMAT_W(7) " KB", CodeCache::max_capacity() / K); 2698 out->print_cr(" Committed size : " SIZE_FORMAT_W(7) " KB", CodeCache::capacity() / K); 2699 out->print_cr(" Unallocated capacity : " SIZE_FORMAT_W(7) " KB", CodeCache::unallocated_capacity() / K); 2700 out->cr(); 2701 } 2702 2703 // Note: tty_lock must not be held upon entry to this function. 2704 // Print functions called from herein do "micro-locking" on tty_lock. 2705 // That's a tradeoff which keeps together important blocks of output. 2706 // At the same time, continuous tty_lock hold time is kept in check, 2707 // preventing concurrently printing threads from stalling a long time. 2708 void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) { 2709 TimeStamp ts_total; 2710 TimeStamp ts_global; 2711 TimeStamp ts; 2712 2713 bool allFun = !strcmp(function, "all"); 2714 bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun; 2715 bool usedSpace = !strcmp(function, "UsedSpace") || allFun; 2716 bool freeSpace = !strcmp(function, "FreeSpace") || allFun; 2717 bool methodCount = !strcmp(function, "MethodCount") || allFun; 2718 bool methodSpace = !strcmp(function, "MethodSpace") || allFun; 2719 bool methodAge = !strcmp(function, "MethodAge") || allFun; 2720 bool methodNames = !strcmp(function, "MethodNames") || allFun; 2721 bool discard = !strcmp(function, "discard") || allFun; 2722 2723 if (out == NULL) { 2724 out = tty; 2725 } 2726 2727 if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) { 2728 out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function); 2729 out->cr(); 2730 return; 2731 } 2732 2733 ts_total.update(); // record starting point 2734 2735 if (aggregate) { 2736 print_info(out); 2737 } 2738 2739 // We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function. 2740 // That prevents other threads from destroying (making inconsistent) our view on the CodeHeap. 2741 // When we request individual parts of the analysis via the jcmd interface, it is possible 2742 // that in between another thread (another jcmd user or the vm running into CodeCache OOM) 2743 // updated the aggregated data. We will then see a modified, but again consistent, view 2744 // on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold 2745 // a lock across user interaction. 2746 2747 // We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock. 2748 // CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time, 2749 // leading to an unnecessarily long hold time of the other locks we acquired before. 2750 ts.update(); // record starting point 2751 MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag); 2752 out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds()); 2753 2754 // Holding the CodeCache_lock protects from concurrent alterations of the CodeCache. 2755 // Unfortunately, such protection is not sufficient: 2756 // When a new nmethod is created via ciEnv::register_method(), the 2757 // Compile_lock is taken first. After some initializations, 2758 // nmethod::new_nmethod() takes over, grabbing the CodeCache_lock 2759 // immediately (after finalizing the oop references). To lock out concurrent 2760 // modifiers, we have to grab both locks as well in the described sequence. 2761 // 2762 // If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock 2763 // for the entire duration of aggregation and printing. That makes sure we see 2764 // a consistent picture and do not run into issues caused by concurrent alterations. 2765 bool should_take_Compile_lock = !SafepointSynchronize::is_at_safepoint() && 2766 !Compile_lock->owned_by_self(); 2767 bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() && 2768 !CodeCache_lock->owned_by_self(); 2769 Mutex* global_lock_1 = allFun ? (should_take_Compile_lock ? Compile_lock : NULL) : NULL; 2770 Monitor* global_lock_2 = allFun ? (should_take_CodeCache_lock ? CodeCache_lock : NULL) : NULL; 2771 Mutex* function_lock_1 = allFun ? NULL : (should_take_Compile_lock ? Compile_lock : NULL); 2772 Monitor* function_lock_2 = allFun ? NULL : (should_take_CodeCache_lock ? CodeCache_lock : NULL); 2773 ts_global.update(); // record starting point 2774 MutexLocker mu1(global_lock_1, Mutex::_safepoint_check_flag); 2775 MutexLocker mu2(global_lock_2, Mutex::_no_safepoint_check_flag); 2776 if ((global_lock_1 != NULL) || (global_lock_2 != NULL)) { 2777 out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds()); 2778 ts_global.update(); // record starting point 2779 } 2780 2781 if (aggregate) { 2782 ts.update(); // record starting point 2783 MutexLocker mu11(function_lock_1, Mutex::_safepoint_check_flag); 2784 MutexLocker mu22(function_lock_2, Mutex::_no_safepoint_check_flag); 2785 if ((function_lock_1 != NULL) || (function_lock_1 != NULL)) { 2786 out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds()); 2787 } 2788 2789 ts.update(); // record starting point 2790 CodeCache::aggregate(out, granularity); 2791 if ((function_lock_1 != NULL) || (function_lock_1 != NULL)) { 2792 out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds()); 2793 } 2794 } 2795 2796 if (usedSpace) CodeCache::print_usedSpace(out); 2797 if (freeSpace) CodeCache::print_freeSpace(out); 2798 if (methodCount) CodeCache::print_count(out); 2799 if (methodSpace) CodeCache::print_space(out); 2800 if (methodAge) CodeCache::print_age(out); 2801 if (methodNames) { 2802 if (allFun) { 2803 // print_names() can only be used safely if the locks have been continuously held 2804 // since aggregation begin. That is true only for function "all". 2805 CodeCache::print_names(out); 2806 } else { 2807 out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'"); 2808 } 2809 } 2810 if (discard) CodeCache::discard(out); 2811 2812 if ((global_lock_1 != NULL) || (global_lock_2 != NULL)) { 2813 out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds()); 2814 } 2815 out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds()); 2816 }