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