1 /* 2 * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "classfile/symbolTable.hpp" 27 #include "classfile/systemDictionary.hpp" 28 #include "classfile/vmSymbols.hpp" 29 #include "code/codeCache.hpp" 30 #include "code/dependencyContext.hpp" 31 #include "compiler/compileBroker.hpp" 32 #include "compiler/compileLog.hpp" 33 #include "compiler/compilerOracle.hpp" 34 #include "compiler/directivesParser.hpp" 35 #include "interpreter/linkResolver.hpp" 36 #include "memory/allocation.inline.hpp" 37 #include "oops/methodData.hpp" 38 #include "oops/method.hpp" 39 #include "oops/oop.inline.hpp" 40 #include "prims/nativeLookup.hpp" 41 #include "prims/whitebox.hpp" 42 #include "runtime/arguments.hpp" 43 #include "runtime/atomic.inline.hpp" 44 #include "runtime/compilationPolicy.hpp" 45 #include "runtime/init.hpp" 46 #include "runtime/interfaceSupport.hpp" 47 #include "runtime/javaCalls.hpp" 48 #include "runtime/os.hpp" 49 #include "runtime/sharedRuntime.hpp" 50 #include "runtime/sweeper.hpp" 51 #include "trace/tracing.hpp" 52 #include "utilities/dtrace.hpp" 53 #include "utilities/events.hpp" 54 #ifdef COMPILER1 55 #include "c1/c1_Compiler.hpp" 56 #endif 57 #if INCLUDE_JVMCI 58 #include "jvmci/jvmciCompiler.hpp" 59 #include "jvmci/jvmciRuntime.hpp" 60 #include "jvmci/jvmciJavaClasses.hpp" 61 #include "runtime/vframe.hpp" 62 #endif 63 #ifdef COMPILER2 64 #include "opto/c2compiler.hpp" 65 #endif 66 #ifdef SHARK 67 #include "shark/sharkCompiler.hpp" 68 #endif 69 70 #ifdef DTRACE_ENABLED 71 72 // Only bother with this argument setup if dtrace is available 73 74 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) \ 75 { \ 76 Symbol* klass_name = (method)->klass_name(); \ 77 Symbol* name = (method)->name(); \ 78 Symbol* signature = (method)->signature(); \ 79 HOTSPOT_METHOD_COMPILE_BEGIN( \ 80 (char *) comp_name, strlen(comp_name), \ 81 (char *) klass_name->bytes(), klass_name->utf8_length(), \ 82 (char *) name->bytes(), name->utf8_length(), \ 83 (char *) signature->bytes(), signature->utf8_length()); \ 84 } 85 86 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success) \ 87 { \ 88 Symbol* klass_name = (method)->klass_name(); \ 89 Symbol* name = (method)->name(); \ 90 Symbol* signature = (method)->signature(); \ 91 HOTSPOT_METHOD_COMPILE_END( \ 92 (char *) comp_name, strlen(comp_name), \ 93 (char *) klass_name->bytes(), klass_name->utf8_length(), \ 94 (char *) name->bytes(), name->utf8_length(), \ 95 (char *) signature->bytes(), signature->utf8_length(), (success)); \ 96 } 97 98 #else // ndef DTRACE_ENABLED 99 100 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) 101 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success) 102 103 #endif // ndef DTRACE_ENABLED 104 105 bool CompileBroker::_initialized = false; 106 volatile bool CompileBroker::_should_block = false; 107 volatile jint CompileBroker::_print_compilation_warning = 0; 108 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation; 109 110 // The installed compiler(s) 111 AbstractCompiler* CompileBroker::_compilers[2]; 112 113 // These counters are used to assign an unique ID to each compilation. 114 volatile jint CompileBroker::_compilation_id = 0; 115 volatile jint CompileBroker::_osr_compilation_id = 0; 116 117 // Debugging information 118 int CompileBroker::_last_compile_type = no_compile; 119 int CompileBroker::_last_compile_level = CompLevel_none; 120 char CompileBroker::_last_method_compiled[CompileBroker::name_buffer_length]; 121 122 // Performance counters 123 PerfCounter* CompileBroker::_perf_total_compilation = NULL; 124 PerfCounter* CompileBroker::_perf_osr_compilation = NULL; 125 PerfCounter* CompileBroker::_perf_standard_compilation = NULL; 126 127 PerfCounter* CompileBroker::_perf_total_bailout_count = NULL; 128 PerfCounter* CompileBroker::_perf_total_invalidated_count = NULL; 129 PerfCounter* CompileBroker::_perf_total_compile_count = NULL; 130 PerfCounter* CompileBroker::_perf_total_osr_compile_count = NULL; 131 PerfCounter* CompileBroker::_perf_total_standard_compile_count = NULL; 132 133 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = NULL; 134 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = NULL; 135 PerfCounter* CompileBroker::_perf_sum_nmethod_size = NULL; 136 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = NULL; 137 138 PerfStringVariable* CompileBroker::_perf_last_method = NULL; 139 PerfStringVariable* CompileBroker::_perf_last_failed_method = NULL; 140 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = NULL; 141 PerfVariable* CompileBroker::_perf_last_compile_type = NULL; 142 PerfVariable* CompileBroker::_perf_last_compile_size = NULL; 143 PerfVariable* CompileBroker::_perf_last_failed_type = NULL; 144 PerfVariable* CompileBroker::_perf_last_invalidated_type = NULL; 145 146 // Timers and counters for generating statistics 147 elapsedTimer CompileBroker::_t_total_compilation; 148 elapsedTimer CompileBroker::_t_osr_compilation; 149 elapsedTimer CompileBroker::_t_standard_compilation; 150 elapsedTimer CompileBroker::_t_invalidated_compilation; 151 elapsedTimer CompileBroker::_t_bailedout_compilation; 152 153 int CompileBroker::_total_bailout_count = 0; 154 int CompileBroker::_total_invalidated_count = 0; 155 int CompileBroker::_total_compile_count = 0; 156 int CompileBroker::_total_osr_compile_count = 0; 157 int CompileBroker::_total_standard_compile_count = 0; 158 159 int CompileBroker::_sum_osr_bytes_compiled = 0; 160 int CompileBroker::_sum_standard_bytes_compiled = 0; 161 int CompileBroker::_sum_nmethod_size = 0; 162 int CompileBroker::_sum_nmethod_code_size = 0; 163 164 long CompileBroker::_peak_compilation_time = 0; 165 166 CompileQueue* CompileBroker::_c2_compile_queue = NULL; 167 CompileQueue* CompileBroker::_c1_compile_queue = NULL; 168 169 class CompilationLog : public StringEventLog { 170 public: 171 CompilationLog() : StringEventLog("Compilation events") { 172 } 173 174 void log_compile(JavaThread* thread, CompileTask* task) { 175 StringLogMessage lm; 176 stringStream sstr = lm.stream(); 177 // msg.time_stamp().update_to(tty->time_stamp().ticks()); 178 task->print(&sstr, NULL, true, false); 179 log(thread, "%s", (const char*)lm); 180 } 181 182 void log_nmethod(JavaThread* thread, nmethod* nm) { 183 log(thread, "nmethod %d%s " INTPTR_FORMAT " code [" INTPTR_FORMAT ", " INTPTR_FORMAT "]", 184 nm->compile_id(), nm->is_osr_method() ? "%" : "", 185 p2i(nm), p2i(nm->code_begin()), p2i(nm->code_end())); 186 } 187 188 void log_failure(JavaThread* thread, CompileTask* task, const char* reason, const char* retry_message) { 189 StringLogMessage lm; 190 lm.print("%4d COMPILE SKIPPED: %s", task->compile_id(), reason); 191 if (retry_message != NULL) { 192 lm.append(" (%s)", retry_message); 193 } 194 lm.print("\n"); 195 log(thread, "%s", (const char*)lm); 196 } 197 198 void log_metaspace_failure(const char* reason) { 199 ResourceMark rm; 200 StringLogMessage lm; 201 lm.print("%4d COMPILE PROFILING SKIPPED: %s", -1, reason); 202 lm.print("\n"); 203 log(JavaThread::current(), "%s", (const char*)lm); 204 } 205 }; 206 207 static CompilationLog* _compilation_log = NULL; 208 209 bool compileBroker_init() { 210 if (LogEvents) { 211 _compilation_log = new CompilationLog(); 212 } 213 214 // init directives stack, adding default directive 215 DirectivesStack::init(); 216 217 if (DirectivesParser::has_file()) { 218 return DirectivesParser::parse_from_flag(); 219 } else if (CompilerDirectivesPrint) { 220 // Print default directive even when no other was added 221 DirectivesStack::print(tty); 222 } 223 224 return true; 225 } 226 227 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) { 228 CompilerThread* thread = CompilerThread::current(); 229 thread->set_task(task); 230 CompileLog* log = thread->log(); 231 if (log != NULL) task->log_task_start(log); 232 } 233 234 CompileTaskWrapper::~CompileTaskWrapper() { 235 CompilerThread* thread = CompilerThread::current(); 236 CompileTask* task = thread->task(); 237 CompileLog* log = thread->log(); 238 if (log != NULL) task->log_task_done(log); 239 thread->set_task(NULL); 240 task->set_code_handle(NULL); 241 thread->set_env(NULL); 242 if (task->is_blocking()) { 243 bool free_task = false; 244 { 245 MutexLocker notifier(task->lock(), thread); 246 task->mark_complete(); 247 #if INCLUDE_JVMCI 248 if (CompileBroker::compiler(task->comp_level())->is_jvmci() && 249 !task->has_waiter()) { 250 // The waiting thread timed out and thus did not free the task. 251 free_task = true; 252 } 253 #endif 254 if (!free_task) { 255 // Notify the waiting thread that the compilation has completed 256 // so that it can free the task. 257 task->lock()->notify_all(); 258 } 259 } 260 if (free_task) { 261 // The task can only be freed once the task lock is released. 262 CompileTask::free(task); 263 } 264 } else { 265 task->mark_complete(); 266 267 // By convention, the compiling thread is responsible for 268 // recycling a non-blocking CompileTask. 269 CompileTask::free(task); 270 } 271 } 272 273 /** 274 * Add a CompileTask to a CompileQueue. 275 */ 276 void CompileQueue::add(CompileTask* task) { 277 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock"); 278 279 task->set_next(NULL); 280 task->set_prev(NULL); 281 282 if (_last == NULL) { 283 // The compile queue is empty. 284 assert(_first == NULL, "queue is empty"); 285 _first = task; 286 _last = task; 287 } else { 288 // Append the task to the queue. 289 assert(_last->next() == NULL, "not last"); 290 _last->set_next(task); 291 task->set_prev(_last); 292 _last = task; 293 } 294 ++_size; 295 296 // Mark the method as being in the compile queue. 297 task->method()->set_queued_for_compilation(); 298 299 if (CIPrintCompileQueue) { 300 print_tty(); 301 } 302 303 if (LogCompilation && xtty != NULL) { 304 task->log_task_queued(); 305 } 306 307 // Notify CompilerThreads that a task is available. 308 MethodCompileQueue_lock->notify_all(); 309 } 310 311 /** 312 * Empties compilation queue by putting all compilation tasks onto 313 * a freelist. Furthermore, the method wakes up all threads that are 314 * waiting on a compilation task to finish. This can happen if background 315 * compilation is disabled. 316 */ 317 void CompileQueue::free_all() { 318 MutexLocker mu(MethodCompileQueue_lock); 319 CompileTask* next = _first; 320 321 // Iterate over all tasks in the compile queue 322 while (next != NULL) { 323 CompileTask* current = next; 324 next = current->next(); 325 { 326 // Wake up thread that blocks on the compile task. 327 MutexLocker ct_lock(current->lock()); 328 current->lock()->notify(); 329 } 330 // Put the task back on the freelist. 331 CompileTask::free(current); 332 } 333 _first = NULL; 334 335 // Wake up all threads that block on the queue. 336 MethodCompileQueue_lock->notify_all(); 337 } 338 339 /** 340 * Get the next CompileTask from a CompileQueue 341 */ 342 CompileTask* CompileQueue::get() { 343 // save methods from RedefineClasses across safepoint 344 // across MethodCompileQueue_lock below. 345 methodHandle save_method; 346 methodHandle save_hot_method; 347 348 MutexLocker locker(MethodCompileQueue_lock); 349 // If _first is NULL we have no more compile jobs. There are two reasons for 350 // having no compile jobs: First, we compiled everything we wanted. Second, 351 // we ran out of code cache so compilation has been disabled. In the latter 352 // case we perform code cache sweeps to free memory such that we can re-enable 353 // compilation. 354 while (_first == NULL) { 355 // Exit loop if compilation is disabled forever 356 if (CompileBroker::is_compilation_disabled_forever()) { 357 return NULL; 358 } 359 360 // If there are no compilation tasks and we can compile new jobs 361 // (i.e., there is enough free space in the code cache) there is 362 // no need to invoke the sweeper. As a result, the hotness of methods 363 // remains unchanged. This behavior is desired, since we want to keep 364 // the stable state, i.e., we do not want to evict methods from the 365 // code cache if it is unnecessary. 366 // We need a timed wait here, since compiler threads can exit if compilation 367 // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads 368 // is not critical and we do not want idle compiler threads to wake up too often. 369 MethodCompileQueue_lock->wait(!Mutex::_no_safepoint_check_flag, 5*1000); 370 } 371 372 if (CompileBroker::is_compilation_disabled_forever()) { 373 return NULL; 374 } 375 376 CompileTask* task; 377 { 378 No_Safepoint_Verifier nsv; 379 task = CompilationPolicy::policy()->select_task(this); 380 } 381 382 // Save method pointers across unlock safepoint. The task is removed from 383 // the compilation queue, which is walked during RedefineClasses. 384 save_method = methodHandle(task->method()); 385 save_hot_method = methodHandle(task->hot_method()); 386 387 remove(task); 388 purge_stale_tasks(); // may temporarily release MCQ lock 389 return task; 390 } 391 392 // Clean & deallocate stale compile tasks. 393 // Temporarily releases MethodCompileQueue lock. 394 void CompileQueue::purge_stale_tasks() { 395 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock"); 396 if (_first_stale != NULL) { 397 // Stale tasks are purged when MCQ lock is released, 398 // but _first_stale updates are protected by MCQ lock. 399 // Once task processing starts and MCQ lock is released, 400 // other compiler threads can reuse _first_stale. 401 CompileTask* head = _first_stale; 402 _first_stale = NULL; 403 { 404 MutexUnlocker ul(MethodCompileQueue_lock); 405 for (CompileTask* task = head; task != NULL; ) { 406 CompileTask* next_task = task->next(); 407 CompileTaskWrapper ctw(task); // Frees the task 408 task->set_failure_reason("stale task"); 409 task = next_task; 410 } 411 } 412 } 413 } 414 415 void CompileQueue::remove(CompileTask* task) { 416 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock"); 417 if (task->prev() != NULL) { 418 task->prev()->set_next(task->next()); 419 } else { 420 // max is the first element 421 assert(task == _first, "Sanity"); 422 _first = task->next(); 423 } 424 425 if (task->next() != NULL) { 426 task->next()->set_prev(task->prev()); 427 } else { 428 // max is the last element 429 assert(task == _last, "Sanity"); 430 _last = task->prev(); 431 } 432 --_size; 433 } 434 435 void CompileQueue::remove_and_mark_stale(CompileTask* task) { 436 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock"); 437 remove(task); 438 439 // Enqueue the task for reclamation (should be done outside MCQ lock) 440 task->set_next(_first_stale); 441 task->set_prev(NULL); 442 _first_stale = task; 443 } 444 445 // methods in the compile queue need to be marked as used on the stack 446 // so that they don't get reclaimed by Redefine Classes 447 void CompileQueue::mark_on_stack() { 448 CompileTask* task = _first; 449 while (task != NULL) { 450 task->mark_on_stack(); 451 task = task->next(); 452 } 453 } 454 455 456 CompileQueue* CompileBroker::compile_queue(int comp_level) { 457 if (is_c2_compile(comp_level)) return _c2_compile_queue; 458 if (is_c1_compile(comp_level)) return _c1_compile_queue; 459 return NULL; 460 } 461 462 463 void CompileBroker::print_compile_queues(outputStream* st) { 464 MutexLocker locker(MethodCompileQueue_lock); 465 if (_c1_compile_queue != NULL) { 466 _c1_compile_queue->print(st); 467 } 468 if (_c2_compile_queue != NULL) { 469 _c2_compile_queue->print(st); 470 } 471 } 472 473 void CompileQueue::print(outputStream* st) { 474 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock"); 475 st->print_cr("Contents of %s", name()); 476 st->print_cr("----------------------------"); 477 CompileTask* task = _first; 478 if (task == NULL) { 479 st->print_cr("Empty"); 480 } else { 481 while (task != NULL) { 482 task->print(st, NULL, true, true); 483 task = task->next(); 484 } 485 } 486 st->print_cr("----------------------------"); 487 } 488 489 void CompileQueue::print_tty() { 490 ttyLocker ttyl; 491 print(tty); 492 } 493 494 CompilerCounters::CompilerCounters() { 495 _current_method[0] = '\0'; 496 _compile_type = CompileBroker::no_compile; 497 } 498 499 // ------------------------------------------------------------------ 500 // CompileBroker::compilation_init 501 // 502 // Initialize the Compilation object 503 void CompileBroker::compilation_init(TRAPS) { 504 _last_method_compiled[0] = '\0'; 505 506 // No need to initialize compilation system if we do not use it. 507 if (!UseCompiler) { 508 return; 509 } 510 #ifndef SHARK 511 // Set the interface to the current compiler(s). 512 int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple); 513 int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization); 514 515 #if INCLUDE_JVMCI 516 if (EnableJVMCI) { 517 // This is creating a JVMCICompiler singleton. 518 JVMCICompiler* jvmci = new JVMCICompiler(); 519 520 if (UseJVMCICompiler) { 521 _compilers[1] = jvmci; 522 if (FLAG_IS_DEFAULT(JVMCIThreads)) { 523 if (BootstrapJVMCI) { 524 // JVMCI will bootstrap so give it more threads 525 c2_count = MIN2(32, os::active_processor_count()); 526 } 527 } else { 528 c2_count = JVMCIThreads; 529 } 530 if (FLAG_IS_DEFAULT(JVMCIHostThreads)) { 531 } else { 532 c1_count = JVMCIHostThreads; 533 } 534 535 if (!UseInterpreter) { 536 // Force initialization of JVMCI compiler otherwise JVMCI 537 // compilations will not block until JVMCI is initialized 538 ResourceMark rm; 539 TempNewSymbol getCompiler = SymbolTable::new_symbol("getCompiler", CHECK); 540 TempNewSymbol sig = SymbolTable::new_symbol("()Ljdk/vm/ci/runtime/JVMCICompiler;", CHECK); 541 Handle jvmciRuntime = JVMCIRuntime::get_HotSpotJVMCIRuntime(CHECK); 542 JavaValue result(T_OBJECT); 543 JavaCalls::call_virtual(&result, jvmciRuntime, HotSpotJVMCIRuntime::klass(), getCompiler, sig, CHECK); 544 } 545 } 546 } 547 #endif // INCLUDE_JVMCI 548 549 #ifdef COMPILER1 550 if (c1_count > 0) { 551 _compilers[0] = new Compiler(); 552 } 553 #endif // COMPILER1 554 555 #ifdef COMPILER2 556 if (true JVMCI_ONLY( && !UseJVMCICompiler)) { 557 if (c2_count > 0) { 558 _compilers[1] = new C2Compiler(); 559 } 560 } 561 #endif // COMPILER2 562 563 #else // SHARK 564 int c1_count = 0; 565 int c2_count = 1; 566 567 _compilers[1] = new SharkCompiler(); 568 #endif // SHARK 569 570 // Start the compiler thread(s) and the sweeper thread 571 init_compiler_sweeper_threads(c1_count, c2_count); 572 // totalTime performance counter is always created as it is required 573 // by the implementation of java.lang.management.CompilationMBean. 574 { 575 EXCEPTION_MARK; 576 _perf_total_compilation = 577 PerfDataManager::create_counter(JAVA_CI, "totalTime", 578 PerfData::U_Ticks, CHECK); 579 } 580 581 if (UsePerfData) { 582 583 EXCEPTION_MARK; 584 585 // create the jvmstat performance counters 586 _perf_osr_compilation = 587 PerfDataManager::create_counter(SUN_CI, "osrTime", 588 PerfData::U_Ticks, CHECK); 589 590 _perf_standard_compilation = 591 PerfDataManager::create_counter(SUN_CI, "standardTime", 592 PerfData::U_Ticks, CHECK); 593 594 _perf_total_bailout_count = 595 PerfDataManager::create_counter(SUN_CI, "totalBailouts", 596 PerfData::U_Events, CHECK); 597 598 _perf_total_invalidated_count = 599 PerfDataManager::create_counter(SUN_CI, "totalInvalidates", 600 PerfData::U_Events, CHECK); 601 602 _perf_total_compile_count = 603 PerfDataManager::create_counter(SUN_CI, "totalCompiles", 604 PerfData::U_Events, CHECK); 605 _perf_total_osr_compile_count = 606 PerfDataManager::create_counter(SUN_CI, "osrCompiles", 607 PerfData::U_Events, CHECK); 608 609 _perf_total_standard_compile_count = 610 PerfDataManager::create_counter(SUN_CI, "standardCompiles", 611 PerfData::U_Events, CHECK); 612 613 _perf_sum_osr_bytes_compiled = 614 PerfDataManager::create_counter(SUN_CI, "osrBytes", 615 PerfData::U_Bytes, CHECK); 616 617 _perf_sum_standard_bytes_compiled = 618 PerfDataManager::create_counter(SUN_CI, "standardBytes", 619 PerfData::U_Bytes, CHECK); 620 621 _perf_sum_nmethod_size = 622 PerfDataManager::create_counter(SUN_CI, "nmethodSize", 623 PerfData::U_Bytes, CHECK); 624 625 _perf_sum_nmethod_code_size = 626 PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize", 627 PerfData::U_Bytes, CHECK); 628 629 _perf_last_method = 630 PerfDataManager::create_string_variable(SUN_CI, "lastMethod", 631 CompilerCounters::cmname_buffer_length, 632 "", CHECK); 633 634 _perf_last_failed_method = 635 PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod", 636 CompilerCounters::cmname_buffer_length, 637 "", CHECK); 638 639 _perf_last_invalidated_method = 640 PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod", 641 CompilerCounters::cmname_buffer_length, 642 "", CHECK); 643 644 _perf_last_compile_type = 645 PerfDataManager::create_variable(SUN_CI, "lastType", 646 PerfData::U_None, 647 (jlong)CompileBroker::no_compile, 648 CHECK); 649 650 _perf_last_compile_size = 651 PerfDataManager::create_variable(SUN_CI, "lastSize", 652 PerfData::U_Bytes, 653 (jlong)CompileBroker::no_compile, 654 CHECK); 655 656 657 _perf_last_failed_type = 658 PerfDataManager::create_variable(SUN_CI, "lastFailedType", 659 PerfData::U_None, 660 (jlong)CompileBroker::no_compile, 661 CHECK); 662 663 _perf_last_invalidated_type = 664 PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType", 665 PerfData::U_None, 666 (jlong)CompileBroker::no_compile, 667 CHECK); 668 } 669 670 _initialized = true; 671 } 672 673 674 JavaThread* CompileBroker::make_thread(const char* name, CompileQueue* queue, CompilerCounters* counters, 675 AbstractCompiler* comp, bool compiler_thread, TRAPS) { 676 JavaThread* thread = NULL; 677 Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_0); 678 instanceKlassHandle klass (THREAD, k); 679 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_0); 680 Handle string = java_lang_String::create_from_str(name, CHECK_0); 681 682 // Initialize thread_oop to put it into the system threadGroup 683 Handle thread_group (THREAD, Universe::system_thread_group()); 684 JavaValue result(T_VOID); 685 JavaCalls::call_special(&result, thread_oop, 686 klass, 687 vmSymbols::object_initializer_name(), 688 vmSymbols::threadgroup_string_void_signature(), 689 thread_group, 690 string, 691 CHECK_0); 692 693 { 694 MutexLocker mu(Threads_lock, THREAD); 695 if (compiler_thread) { 696 thread = new CompilerThread(queue, counters); 697 } else { 698 thread = new CodeCacheSweeperThread(); 699 } 700 // At this point the new CompilerThread data-races with this startup 701 // thread (which I believe is the primoridal thread and NOT the VM 702 // thread). This means Java bytecodes being executed at startup can 703 // queue compile jobs which will run at whatever default priority the 704 // newly created CompilerThread runs at. 705 706 707 // At this point it may be possible that no osthread was created for the 708 // JavaThread due to lack of memory. We would have to throw an exception 709 // in that case. However, since this must work and we do not allow 710 // exceptions anyway, check and abort if this fails. 711 712 if (thread == NULL || thread->osthread() == NULL) { 713 vm_exit_during_initialization("java.lang.OutOfMemoryError", 714 os::native_thread_creation_failed_msg()); 715 } 716 717 java_lang_Thread::set_thread(thread_oop(), thread); 718 719 // Note that this only sets the JavaThread _priority field, which by 720 // definition is limited to Java priorities and not OS priorities. 721 // The os-priority is set in the CompilerThread startup code itself 722 723 java_lang_Thread::set_priority(thread_oop(), NearMaxPriority); 724 725 // Note that we cannot call os::set_priority because it expects Java 726 // priorities and we are *explicitly* using OS priorities so that it's 727 // possible to set the compiler thread priority higher than any Java 728 // thread. 729 730 int native_prio = CompilerThreadPriority; 731 if (native_prio == -1) { 732 if (UseCriticalCompilerThreadPriority) { 733 native_prio = os::java_to_os_priority[CriticalPriority]; 734 } else { 735 native_prio = os::java_to_os_priority[NearMaxPriority]; 736 } 737 } 738 os::set_native_priority(thread, native_prio); 739 740 java_lang_Thread::set_daemon(thread_oop()); 741 742 thread->set_threadObj(thread_oop()); 743 if (compiler_thread) { 744 thread->as_CompilerThread()->set_compiler(comp); 745 } 746 Threads::add(thread); 747 Thread::start(thread); 748 } 749 750 // Let go of Threads_lock before yielding 751 os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS) 752 753 return thread; 754 } 755 756 757 void CompileBroker::init_compiler_sweeper_threads(int c1_compiler_count, int c2_compiler_count) { 758 EXCEPTION_MARK; 759 #if !defined(ZERO) && !defined(SHARK) 760 assert(c2_compiler_count > 0 || c1_compiler_count > 0, "No compilers?"); 761 #endif // !ZERO && !SHARK 762 // Initialize the compilation queue 763 if (c2_compiler_count > 0) { 764 _c2_compile_queue = new CompileQueue("C2 compile queue"); 765 _compilers[1]->set_num_compiler_threads(c2_compiler_count); 766 } 767 if (c1_compiler_count > 0) { 768 _c1_compile_queue = new CompileQueue("C1 compile queue"); 769 _compilers[0]->set_num_compiler_threads(c1_compiler_count); 770 } 771 772 int compiler_count = c1_compiler_count + c2_compiler_count; 773 774 char name_buffer[256]; 775 const bool compiler_thread = true; 776 for (int i = 0; i < c2_compiler_count; i++) { 777 // Create a name for our thread. 778 sprintf(name_buffer, "%s CompilerThread%d", _compilers[1]->name(), i); 779 CompilerCounters* counters = new CompilerCounters(); 780 // Shark and C2 781 make_thread(name_buffer, _c2_compile_queue, counters, _compilers[1], compiler_thread, CHECK); 782 } 783 784 for (int i = c2_compiler_count; i < compiler_count; i++) { 785 // Create a name for our thread. 786 sprintf(name_buffer, "C1 CompilerThread%d", i); 787 CompilerCounters* counters = new CompilerCounters(); 788 // C1 789 make_thread(name_buffer, _c1_compile_queue, counters, _compilers[0], compiler_thread, CHECK); 790 } 791 792 if (UsePerfData) { 793 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, compiler_count, CHECK); 794 } 795 796 if (MethodFlushing) { 797 // Initialize the sweeper thread 798 make_thread("Sweeper thread", NULL, NULL, NULL, false, CHECK); 799 } 800 } 801 802 803 /** 804 * Set the methods on the stack as on_stack so that redefine classes doesn't 805 * reclaim them. This method is executed at a safepoint. 806 */ 807 void CompileBroker::mark_on_stack() { 808 assert(SafepointSynchronize::is_at_safepoint(), "sanity check"); 809 // Since we are at a safepoint, we do not need a lock to access 810 // the compile queues. 811 if (_c2_compile_queue != NULL) { 812 _c2_compile_queue->mark_on_stack(); 813 } 814 if (_c1_compile_queue != NULL) { 815 _c1_compile_queue->mark_on_stack(); 816 } 817 } 818 819 // ------------------------------------------------------------------ 820 // CompileBroker::compile_method 821 // 822 // Request compilation of a method. 823 void CompileBroker::compile_method_base(const methodHandle& method, 824 int osr_bci, 825 int comp_level, 826 const methodHandle& hot_method, 827 int hot_count, 828 const char* comment, 829 Thread* thread) { 830 // do nothing if compiler thread(s) is not available 831 if (!_initialized) { 832 return; 833 } 834 835 guarantee(!method->is_abstract(), "cannot compile abstract methods"); 836 assert(method->method_holder()->is_instance_klass(), 837 "sanity check"); 838 assert(!method->method_holder()->is_not_initialized(), 839 "method holder must be initialized"); 840 assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys"); 841 842 if (CIPrintRequests) { 843 tty->print("request: "); 844 method->print_short_name(tty); 845 if (osr_bci != InvocationEntryBci) { 846 tty->print(" osr_bci: %d", osr_bci); 847 } 848 tty->print(" level: %d comment: %s count: %d", comp_level, comment, hot_count); 849 if (!hot_method.is_null()) { 850 tty->print(" hot: "); 851 if (hot_method() != method()) { 852 hot_method->print_short_name(tty); 853 } else { 854 tty->print("yes"); 855 } 856 } 857 tty->cr(); 858 } 859 860 // A request has been made for compilation. Before we do any 861 // real work, check to see if the method has been compiled 862 // in the meantime with a definitive result. 863 if (compilation_is_complete(method, osr_bci, comp_level)) { 864 return; 865 } 866 867 #ifndef PRODUCT 868 if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) { 869 if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) { 870 // Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI. 871 return; 872 } 873 } 874 #endif 875 876 // If this method is already in the compile queue, then 877 // we do not block the current thread. 878 if (compilation_is_in_queue(method)) { 879 // We may want to decay our counter a bit here to prevent 880 // multiple denied requests for compilation. This is an 881 // open compilation policy issue. Note: The other possibility, 882 // in the case that this is a blocking compile request, is to have 883 // all subsequent blocking requesters wait for completion of 884 // ongoing compiles. Note that in this case we'll need a protocol 885 // for freeing the associated compile tasks. [Or we could have 886 // a single static monitor on which all these waiters sleep.] 887 return; 888 } 889 890 // If the requesting thread is holding the pending list lock 891 // then we just return. We can't risk blocking while holding 892 // the pending list lock or a 3-way deadlock may occur 893 // between the reference handler thread, a GC (instigated 894 // by a compiler thread), and compiled method registration. 895 if (InstanceRefKlass::owns_pending_list_lock(JavaThread::current())) { 896 return; 897 } 898 899 if (TieredCompilation) { 900 // Tiered policy requires MethodCounters to exist before adding a method to 901 // the queue. Create if we don't have them yet. 902 method->get_method_counters(thread); 903 } 904 905 // Outputs from the following MutexLocker block: 906 CompileTask* task = NULL; 907 bool blocking = false; 908 CompileQueue* queue = compile_queue(comp_level); 909 910 // Acquire our lock. 911 { 912 MutexLocker locker(MethodCompileQueue_lock, thread); 913 914 // Make sure the method has not slipped into the queues since 915 // last we checked; note that those checks were "fast bail-outs". 916 // Here we need to be more careful, see 14012000 below. 917 if (compilation_is_in_queue(method)) { 918 return; 919 } 920 921 // We need to check again to see if the compilation has 922 // completed. A previous compilation may have registered 923 // some result. 924 if (compilation_is_complete(method, osr_bci, comp_level)) { 925 return; 926 } 927 928 // We now know that this compilation is not pending, complete, 929 // or prohibited. Assign a compile_id to this compilation 930 // and check to see if it is in our [Start..Stop) range. 931 int compile_id = assign_compile_id(method, osr_bci); 932 if (compile_id == 0) { 933 // The compilation falls outside the allowed range. 934 return; 935 } 936 937 // Should this thread wait for completion of the compile? 938 blocking = is_compile_blocking(); 939 940 #if INCLUDE_JVMCI 941 if (UseJVMCICompiler) { 942 if (blocking) { 943 // Don't allow blocking compiles for requests triggered by JVMCI. 944 if (thread->is_Compiler_thread()) { 945 blocking = false; 946 } 947 948 // Don't allow blocking compiles if inside a class initializer or while performing class loading 949 vframeStream vfst((JavaThread*) thread); 950 for (; !vfst.at_end(); vfst.next()) { 951 if (vfst.method()->is_static_initializer() || 952 (vfst.method()->method_holder()->is_subclass_of(SystemDictionary::ClassLoader_klass()) && 953 vfst.method()->name() == vmSymbols::loadClass_name())) { 954 blocking = false; 955 break; 956 } 957 } 958 959 // Don't allow blocking compilation requests to JVMCI 960 // if JVMCI itself is not yet initialized 961 if (!JVMCIRuntime::is_HotSpotJVMCIRuntime_initialized() && compiler(comp_level)->is_jvmci()) { 962 blocking = false; 963 } 964 965 // Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown 966 // to avoid deadlock between compiler thread(s) and threads run at shutdown 967 // such as the DestroyJavaVM thread. 968 if (JVMCIRuntime::shutdown_called()) { 969 blocking = false; 970 } 971 } 972 } 973 #endif // INCLUDE_JVMCI 974 975 // We will enter the compilation in the queue. 976 // 14012000: Note that this sets the queued_for_compile bits in 977 // the target method. We can now reason that a method cannot be 978 // queued for compilation more than once, as follows: 979 // Before a thread queues a task for compilation, it first acquires 980 // the compile queue lock, then checks if the method's queued bits 981 // are set or it has already been compiled. Thus there can not be two 982 // instances of a compilation task for the same method on the 983 // compilation queue. Consider now the case where the compilation 984 // thread has already removed a task for that method from the queue 985 // and is in the midst of compiling it. In this case, the 986 // queued_for_compile bits must be set in the method (and these 987 // will be visible to the current thread, since the bits were set 988 // under protection of the compile queue lock, which we hold now. 989 // When the compilation completes, the compiler thread first sets 990 // the compilation result and then clears the queued_for_compile 991 // bits. Neither of these actions are protected by a barrier (or done 992 // under the protection of a lock), so the only guarantee we have 993 // (on machines with TSO (Total Store Order)) is that these values 994 // will update in that order. As a result, the only combinations of 995 // these bits that the current thread will see are, in temporal order: 996 // <RESULT, QUEUE> : 997 // <0, 1> : in compile queue, but not yet compiled 998 // <1, 1> : compiled but queue bit not cleared 999 // <1, 0> : compiled and queue bit cleared 1000 // Because we first check the queue bits then check the result bits, 1001 // we are assured that we cannot introduce a duplicate task. 1002 // Note that if we did the tests in the reverse order (i.e. check 1003 // result then check queued bit), we could get the result bit before 1004 // the compilation completed, and the queue bit after the compilation 1005 // completed, and end up introducing a "duplicate" (redundant) task. 1006 // In that case, the compiler thread should first check if a method 1007 // has already been compiled before trying to compile it. 1008 // NOTE: in the event that there are multiple compiler threads and 1009 // there is de-optimization/recompilation, things will get hairy, 1010 // and in that case it's best to protect both the testing (here) of 1011 // these bits, and their updating (here and elsewhere) under a 1012 // common lock. 1013 task = create_compile_task(queue, 1014 compile_id, method, 1015 osr_bci, comp_level, 1016 hot_method, hot_count, comment, 1017 blocking); 1018 } 1019 1020 if (blocking) { 1021 wait_for_completion(task); 1022 } 1023 } 1024 1025 1026 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci, 1027 int comp_level, 1028 const methodHandle& hot_method, int hot_count, 1029 const char* comment, Thread* THREAD) { 1030 // make sure arguments make sense 1031 assert(method->method_holder()->is_instance_klass(), "not an instance method"); 1032 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range"); 1033 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods"); 1034 assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized"); 1035 // allow any levels for WhiteBox 1036 assert(WhiteBoxAPI || TieredCompilation || comp_level == CompLevel_highest_tier, "only CompLevel_highest_tier must be used in non-tiered"); 1037 // return quickly if possible 1038 1039 // lock, make sure that the compilation 1040 // isn't prohibited in a straightforward way. 1041 AbstractCompiler *comp = CompileBroker::compiler(comp_level); 1042 if (comp == NULL || !comp->can_compile_method(method) || 1043 compilation_is_prohibited(method, osr_bci, comp_level)) { 1044 return NULL; 1045 } 1046 1047 if (osr_bci == InvocationEntryBci) { 1048 // standard compilation 1049 nmethod* method_code = method->code(); 1050 if (method_code != NULL) { 1051 if (compilation_is_complete(method, osr_bci, comp_level)) { 1052 return method_code; 1053 } 1054 } 1055 if (method->is_not_compilable(comp_level)) { 1056 return NULL; 1057 } 1058 } else { 1059 // osr compilation 1060 #ifndef TIERED 1061 // seems like an assert of dubious value 1062 assert(comp_level == CompLevel_highest_tier, 1063 "all OSR compiles are assumed to be at a single compilation level"); 1064 #endif // TIERED 1065 // We accept a higher level osr method 1066 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false); 1067 if (nm != NULL) return nm; 1068 if (method->is_not_osr_compilable(comp_level)) return NULL; 1069 } 1070 1071 assert(!HAS_PENDING_EXCEPTION, "No exception should be present"); 1072 // some prerequisites that are compiler specific 1073 if (comp->is_c2() || comp->is_shark()) { 1074 method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NULL); 1075 // Resolve all classes seen in the signature of the method 1076 // we are compiling. 1077 Method::load_signature_classes(method, CHECK_AND_CLEAR_NULL); 1078 } 1079 1080 // If the method is native, do the lookup in the thread requesting 1081 // the compilation. Native lookups can load code, which is not 1082 // permitted during compilation. 1083 // 1084 // Note: A native method implies non-osr compilation which is 1085 // checked with an assertion at the entry of this method. 1086 if (method->is_native() && !method->is_method_handle_intrinsic()) { 1087 bool in_base_library; 1088 address adr = NativeLookup::lookup(method, in_base_library, THREAD); 1089 if (HAS_PENDING_EXCEPTION) { 1090 // In case of an exception looking up the method, we just forget 1091 // about it. The interpreter will kick-in and throw the exception. 1092 method->set_not_compilable(); // implies is_not_osr_compilable() 1093 CLEAR_PENDING_EXCEPTION; 1094 return NULL; 1095 } 1096 assert(method->has_native_function(), "must have native code by now"); 1097 } 1098 1099 // RedefineClasses() has replaced this method; just return 1100 if (method->is_old()) { 1101 return NULL; 1102 } 1103 1104 // JVMTI -- post_compile_event requires jmethod_id() that may require 1105 // a lock the compiling thread can not acquire. Prefetch it here. 1106 if (JvmtiExport::should_post_compiled_method_load()) { 1107 method->jmethod_id(); 1108 } 1109 1110 // do the compilation 1111 if (method->is_native()) { 1112 if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) { 1113 // The following native methods: 1114 // 1115 // java.lang.Float.intBitsToFloat 1116 // java.lang.Float.floatToRawIntBits 1117 // java.lang.Double.longBitsToDouble 1118 // java.lang.Double.doubleToRawLongBits 1119 // 1120 // are called through the interpreter even if interpreter native stubs 1121 // are not preferred (i.e., calling through adapter handlers is preferred). 1122 // The reason is that on x86_32 signaling NaNs (sNaNs) are not preserved 1123 // if the version of the methods from the native libraries is called. 1124 // As the interpreter and the C2-intrinsified version of the methods preserves 1125 // sNaNs, that would result in an inconsistent way of handling of sNaNs. 1126 if ((UseSSE >= 1 && 1127 (method->intrinsic_id() == vmIntrinsics::_intBitsToFloat || 1128 method->intrinsic_id() == vmIntrinsics::_floatToRawIntBits)) || 1129 (UseSSE >= 2 && 1130 (method->intrinsic_id() == vmIntrinsics::_longBitsToDouble || 1131 method->intrinsic_id() == vmIntrinsics::_doubleToRawLongBits))) { 1132 return NULL; 1133 } 1134 1135 // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that 1136 // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime). 1137 // 1138 // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter 1139 // in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls. 1140 AdapterHandlerLibrary::create_native_wrapper(method); 1141 } else { 1142 return NULL; 1143 } 1144 } else { 1145 // If the compiler is shut off due to code cache getting full 1146 // fail out now so blocking compiles dont hang the java thread 1147 if (!should_compile_new_jobs()) { 1148 CompilationPolicy::policy()->delay_compilation(method()); 1149 return NULL; 1150 } 1151 compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, THREAD); 1152 } 1153 1154 // return requested nmethod 1155 // We accept a higher level osr method 1156 if (osr_bci == InvocationEntryBci) { 1157 return method->code(); 1158 } 1159 return method->lookup_osr_nmethod_for(osr_bci, comp_level, false); 1160 } 1161 1162 1163 // ------------------------------------------------------------------ 1164 // CompileBroker::compilation_is_complete 1165 // 1166 // See if compilation of this method is already complete. 1167 bool CompileBroker::compilation_is_complete(const methodHandle& method, 1168 int osr_bci, 1169 int comp_level) { 1170 bool is_osr = (osr_bci != standard_entry_bci); 1171 if (is_osr) { 1172 if (method->is_not_osr_compilable(comp_level)) { 1173 return true; 1174 } else { 1175 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true); 1176 return (result != NULL); 1177 } 1178 } else { 1179 if (method->is_not_compilable(comp_level)) { 1180 return true; 1181 } else { 1182 nmethod* result = method->code(); 1183 if (result == NULL) return false; 1184 return comp_level == result->comp_level(); 1185 } 1186 } 1187 } 1188 1189 1190 /** 1191 * See if this compilation is already requested. 1192 * 1193 * Implementation note: there is only a single "is in queue" bit 1194 * for each method. This means that the check below is overly 1195 * conservative in the sense that an osr compilation in the queue 1196 * will block a normal compilation from entering the queue (and vice 1197 * versa). This can be remedied by a full queue search to disambiguate 1198 * cases. If it is deemed profitable, this may be done. 1199 */ 1200 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) { 1201 return method->queued_for_compilation(); 1202 } 1203 1204 // ------------------------------------------------------------------ 1205 // CompileBroker::compilation_is_prohibited 1206 // 1207 // See if this compilation is not allowed. 1208 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level) { 1209 bool is_native = method->is_native(); 1210 // Some compilers may not support the compilation of natives. 1211 AbstractCompiler *comp = compiler(comp_level); 1212 if (is_native && 1213 (!CICompileNatives || comp == NULL || !comp->supports_native())) { 1214 method->set_not_compilable_quietly(comp_level); 1215 return true; 1216 } 1217 1218 bool is_osr = (osr_bci != standard_entry_bci); 1219 // Some compilers may not support on stack replacement. 1220 if (is_osr && 1221 (!CICompileOSR || comp == NULL || !comp->supports_osr())) { 1222 method->set_not_osr_compilable(comp_level); 1223 return true; 1224 } 1225 1226 // Breaking the abstraction - directives are only used inside a compilation otherwise. 1227 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp); 1228 bool excluded = directive->ExcludeOption; 1229 DirectivesStack::release(directive); 1230 1231 // The method may be explicitly excluded by the user. 1232 double scale; 1233 if (excluded || (CompilerOracle::has_option_value(method, "CompileThresholdScaling", scale) && scale == 0)) { 1234 bool quietly = CompilerOracle::should_exclude_quietly(); 1235 if (PrintCompilation && !quietly) { 1236 // This does not happen quietly... 1237 ResourceMark rm; 1238 tty->print("### Excluding %s:%s", 1239 method->is_native() ? "generation of native wrapper" : "compile", 1240 (method->is_static() ? " static" : "")); 1241 method->print_short_name(tty); 1242 tty->cr(); 1243 } 1244 method->set_not_compilable(comp_level, !quietly, "excluded by CompileCommand"); 1245 } 1246 1247 return false; 1248 } 1249 1250 /** 1251 * Generate serialized IDs for compilation requests. If certain debugging flags are used 1252 * and the ID is not within the specified range, the method is not compiled and 0 is returned. 1253 * The function also allows to generate separate compilation IDs for OSR compilations. 1254 */ 1255 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) { 1256 #ifdef ASSERT 1257 bool is_osr = (osr_bci != standard_entry_bci); 1258 int id; 1259 if (method->is_native()) { 1260 assert(!is_osr, "can't be osr"); 1261 // Adapters, native wrappers and method handle intrinsics 1262 // should be generated always. 1263 return Atomic::add(1, &_compilation_id); 1264 } else if (CICountOSR && is_osr) { 1265 id = Atomic::add(1, &_osr_compilation_id); 1266 if (CIStartOSR <= id && id < CIStopOSR) { 1267 return id; 1268 } 1269 } else { 1270 id = Atomic::add(1, &_compilation_id); 1271 if (CIStart <= id && id < CIStop) { 1272 return id; 1273 } 1274 } 1275 1276 // Method was not in the appropriate compilation range. 1277 method->set_not_compilable_quietly(); 1278 return 0; 1279 #else 1280 // CICountOSR is a develop flag and set to 'false' by default. In a product built, 1281 // only _compilation_id is incremented. 1282 return Atomic::add(1, &_compilation_id); 1283 #endif 1284 } 1285 1286 // ------------------------------------------------------------------ 1287 // CompileBroker::assign_compile_id_unlocked 1288 // 1289 // Public wrapper for assign_compile_id that acquires the needed locks 1290 uint CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) { 1291 MutexLocker locker(MethodCompileQueue_lock, thread); 1292 return assign_compile_id(method, osr_bci); 1293 } 1294 1295 /** 1296 * Should the current thread block until this compilation request 1297 * has been fulfilled? 1298 */ 1299 bool CompileBroker::is_compile_blocking() { 1300 assert(!InstanceRefKlass::owns_pending_list_lock(JavaThread::current()), "possible deadlock"); 1301 return !BackgroundCompilation; 1302 } 1303 1304 1305 // ------------------------------------------------------------------ 1306 // CompileBroker::preload_classes 1307 void CompileBroker::preload_classes(const methodHandle& method, TRAPS) { 1308 // Move this code over from c1_Compiler.cpp 1309 ShouldNotReachHere(); 1310 } 1311 1312 1313 // ------------------------------------------------------------------ 1314 // CompileBroker::create_compile_task 1315 // 1316 // Create a CompileTask object representing the current request for 1317 // compilation. Add this task to the queue. 1318 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue, 1319 int compile_id, 1320 const methodHandle& method, 1321 int osr_bci, 1322 int comp_level, 1323 const methodHandle& hot_method, 1324 int hot_count, 1325 const char* comment, 1326 bool blocking) { 1327 CompileTask* new_task = CompileTask::allocate(); 1328 new_task->initialize(compile_id, method, osr_bci, comp_level, 1329 hot_method, hot_count, comment, 1330 blocking); 1331 queue->add(new_task); 1332 return new_task; 1333 } 1334 1335 // 1 second should be long enough to complete most JVMCI compilations 1336 // and not too long to stall a blocking JVMCI compilation that 1337 // is trying to acquire a lock held by the app thread that submitted the 1338 // compilation. 1339 static const long BLOCKING_JVMCI_COMPILATION_TIMEOUT = 1000; 1340 1341 /** 1342 * Wait for the compilation task to complete. 1343 */ 1344 void CompileBroker::wait_for_completion(CompileTask* task) { 1345 if (CIPrintCompileQueue) { 1346 ttyLocker ttyl; 1347 tty->print_cr("BLOCKING FOR COMPILE"); 1348 } 1349 1350 assert(task->is_blocking(), "can only wait on blocking task"); 1351 1352 JavaThread* thread = JavaThread::current(); 1353 thread->set_blocked_on_compilation(true); 1354 1355 methodHandle method(thread, task->method()); 1356 bool free_task; 1357 #if INCLUDE_JVMCI 1358 if (compiler(task->comp_level())->is_jvmci()) { 1359 MutexLocker waiter(task->lock(), thread); 1360 // No need to check if compilation has completed - just 1361 // rely on the time out. The JVMCI compiler thread will 1362 // recycle the CompileTask. 1363 task->lock()->wait(!Mutex::_no_safepoint_check_flag, BLOCKING_JVMCI_COMPILATION_TIMEOUT); 1364 // If the compilation completes while has_waiter is true then 1365 // this thread is responsible for freeing the task. Otherwise 1366 // the compiler thread will free the task. 1367 task->clear_waiter(); 1368 free_task = task->is_complete(); 1369 } else 1370 #endif 1371 { 1372 MutexLocker waiter(task->lock(), thread); 1373 free_task = true; 1374 while (!task->is_complete() && !is_compilation_disabled_forever()) { 1375 task->lock()->wait(); 1376 } 1377 } 1378 1379 thread->set_blocked_on_compilation(false); 1380 if (free_task) { 1381 if (is_compilation_disabled_forever()) { 1382 CompileTask::free(task); 1383 return; 1384 } 1385 1386 // It is harmless to check this status without the lock, because 1387 // completion is a stable property (until the task object is recycled). 1388 assert(task->is_complete(), "Compilation should have completed"); 1389 assert(task->code_handle() == NULL, "must be reset"); 1390 1391 // By convention, the waiter is responsible for recycling a 1392 // blocking CompileTask. Since there is only one waiter ever 1393 // waiting on a CompileTask, we know that no one else will 1394 // be using this CompileTask; we can free it. 1395 CompileTask::free(task); 1396 } 1397 } 1398 1399 /** 1400 * Initialize compiler thread(s) + compiler object(s). The postcondition 1401 * of this function is that the compiler runtimes are initialized and that 1402 * compiler threads can start compiling. 1403 */ 1404 bool CompileBroker::init_compiler_runtime() { 1405 CompilerThread* thread = CompilerThread::current(); 1406 AbstractCompiler* comp = thread->compiler(); 1407 // Final sanity check - the compiler object must exist 1408 guarantee(comp != NULL, "Compiler object must exist"); 1409 1410 int system_dictionary_modification_counter; 1411 { 1412 MutexLocker locker(Compile_lock, thread); 1413 system_dictionary_modification_counter = SystemDictionary::number_of_modifications(); 1414 } 1415 1416 { 1417 // Must switch to native to allocate ci_env 1418 ThreadToNativeFromVM ttn(thread); 1419 ciEnv ci_env(NULL, system_dictionary_modification_counter); 1420 // Cache Jvmti state 1421 ci_env.cache_jvmti_state(); 1422 // Cache DTrace flags 1423 ci_env.cache_dtrace_flags(); 1424 1425 // Switch back to VM state to do compiler initialization 1426 ThreadInVMfromNative tv(thread); 1427 ResetNoHandleMark rnhm; 1428 1429 if (!comp->is_shark()) { 1430 // Perform per-thread and global initializations 1431 comp->initialize(); 1432 } 1433 } 1434 1435 if (comp->is_failed()) { 1436 disable_compilation_forever(); 1437 // If compiler initialization failed, no compiler thread that is specific to a 1438 // particular compiler runtime will ever start to compile methods. 1439 shutdown_compiler_runtime(comp, thread); 1440 return false; 1441 } 1442 1443 // C1 specific check 1444 if (comp->is_c1() && (thread->get_buffer_blob() == NULL)) { 1445 warning("Initialization of %s thread failed (no space to run compilers)", thread->name()); 1446 return false; 1447 } 1448 1449 return true; 1450 } 1451 1452 /** 1453 * If C1 and/or C2 initialization failed, we shut down all compilation. 1454 * We do this to keep things simple. This can be changed if it ever turns 1455 * out to be a problem. 1456 */ 1457 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) { 1458 // Free buffer blob, if allocated 1459 if (thread->get_buffer_blob() != NULL) { 1460 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1461 CodeCache::free(thread->get_buffer_blob()); 1462 } 1463 1464 if (comp->should_perform_shutdown()) { 1465 // There are two reasons for shutting down the compiler 1466 // 1) compiler runtime initialization failed 1467 // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing 1468 warning("%s initialization failed. Shutting down all compilers", comp->name()); 1469 1470 // Only one thread per compiler runtime object enters here 1471 // Set state to shut down 1472 comp->set_shut_down(); 1473 1474 // Delete all queued compilation tasks to make compiler threads exit faster. 1475 if (_c1_compile_queue != NULL) { 1476 _c1_compile_queue->free_all(); 1477 } 1478 1479 if (_c2_compile_queue != NULL) { 1480 _c2_compile_queue->free_all(); 1481 } 1482 1483 // Set flags so that we continue execution with using interpreter only. 1484 UseCompiler = false; 1485 UseInterpreter = true; 1486 1487 // We could delete compiler runtimes also. However, there are references to 1488 // the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then 1489 // fail. This can be done later if necessary. 1490 } 1491 } 1492 1493 // ------------------------------------------------------------------ 1494 // CompileBroker::compiler_thread_loop 1495 // 1496 // The main loop run by a CompilerThread. 1497 void CompileBroker::compiler_thread_loop() { 1498 CompilerThread* thread = CompilerThread::current(); 1499 CompileQueue* queue = thread->queue(); 1500 // For the thread that initializes the ciObjectFactory 1501 // this resource mark holds all the shared objects 1502 ResourceMark rm; 1503 1504 // First thread to get here will initialize the compiler interface 1505 1506 if (!ciObjectFactory::is_initialized()) { 1507 ASSERT_IN_VM; 1508 MutexLocker only_one (CompileThread_lock, thread); 1509 if (!ciObjectFactory::is_initialized()) { 1510 ciObjectFactory::initialize(); 1511 } 1512 } 1513 1514 // Open a log. 1515 if (LogCompilation) { 1516 init_compiler_thread_log(); 1517 } 1518 CompileLog* log = thread->log(); 1519 if (log != NULL) { 1520 log->begin_elem("start_compile_thread name='%s' thread='" UINTX_FORMAT "' process='%d'", 1521 thread->name(), 1522 os::current_thread_id(), 1523 os::current_process_id()); 1524 log->stamp(); 1525 log->end_elem(); 1526 } 1527 1528 // If compiler thread/runtime initialization fails, exit the compiler thread 1529 if (!init_compiler_runtime()) { 1530 return; 1531 } 1532 1533 // Poll for new compilation tasks as long as the JVM runs. Compilation 1534 // should only be disabled if something went wrong while initializing the 1535 // compiler runtimes. This, in turn, should not happen. The only known case 1536 // when compiler runtime initialization fails is if there is not enough free 1537 // space in the code cache to generate the necessary stubs, etc. 1538 while (!is_compilation_disabled_forever()) { 1539 // We need this HandleMark to avoid leaking VM handles. 1540 HandleMark hm(thread); 1541 1542 CompileTask* task = queue->get(); 1543 if (task == NULL) { 1544 continue; 1545 } 1546 1547 // Give compiler threads an extra quanta. They tend to be bursty and 1548 // this helps the compiler to finish up the job. 1549 if (CompilerThreadHintNoPreempt) { 1550 os::hint_no_preempt(); 1551 } 1552 1553 // Assign the task to the current thread. Mark this compilation 1554 // thread as active for the profiler. 1555 CompileTaskWrapper ctw(task); 1556 nmethodLocker result_handle; // (handle for the nmethod produced by this task) 1557 task->set_code_handle(&result_handle); 1558 methodHandle method(thread, task->method()); 1559 1560 // Never compile a method if breakpoints are present in it 1561 if (method()->number_of_breakpoints() == 0) { 1562 // Compile the method. 1563 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) { 1564 invoke_compiler_on_method(task); 1565 } else { 1566 // After compilation is disabled, remove remaining methods from queue 1567 method->clear_queued_for_compilation(); 1568 task->set_failure_reason("compilation is disabled"); 1569 } 1570 } 1571 } 1572 1573 // Shut down compiler runtime 1574 shutdown_compiler_runtime(thread->compiler(), thread); 1575 } 1576 1577 // ------------------------------------------------------------------ 1578 // CompileBroker::init_compiler_thread_log 1579 // 1580 // Set up state required by +LogCompilation. 1581 void CompileBroker::init_compiler_thread_log() { 1582 CompilerThread* thread = CompilerThread::current(); 1583 char file_name[4*K]; 1584 FILE* fp = NULL; 1585 intx thread_id = os::current_thread_id(); 1586 for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) { 1587 const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL); 1588 if (dir == NULL) { 1589 jio_snprintf(file_name, sizeof(file_name), "hs_c" UINTX_FORMAT "_pid%u.log", 1590 thread_id, os::current_process_id()); 1591 } else { 1592 jio_snprintf(file_name, sizeof(file_name), 1593 "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir, 1594 os::file_separator(), thread_id, os::current_process_id()); 1595 } 1596 1597 fp = fopen(file_name, "wt"); 1598 if (fp != NULL) { 1599 if (LogCompilation && Verbose) { 1600 tty->print_cr("Opening compilation log %s", file_name); 1601 } 1602 CompileLog* log = new(ResourceObj::C_HEAP, mtCompiler) CompileLog(file_name, fp, thread_id); 1603 thread->init_log(log); 1604 1605 if (xtty != NULL) { 1606 ttyLocker ttyl; 1607 // Record any per thread log files 1608 xtty->elem("thread_logfile thread='" INTX_FORMAT "' filename='%s'", thread_id, file_name); 1609 } 1610 return; 1611 } 1612 } 1613 warning("Cannot open log file: %s", file_name); 1614 } 1615 1616 void CompileBroker::log_metaspace_failure() { 1617 const char* message = "some methods may not be compiled because metaspace " 1618 "is out of memory"; 1619 if (_compilation_log != NULL) { 1620 _compilation_log->log_metaspace_failure(message); 1621 } 1622 if (PrintCompilation) { 1623 tty->print_cr("COMPILE PROFILING SKIPPED: %s", message); 1624 } 1625 } 1626 1627 1628 // ------------------------------------------------------------------ 1629 // CompileBroker::set_should_block 1630 // 1631 // Set _should_block. 1632 // Call this from the VM, with Threads_lock held and a safepoint requested. 1633 void CompileBroker::set_should_block() { 1634 assert(Threads_lock->owner() == Thread::current(), "must have threads lock"); 1635 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already"); 1636 #ifndef PRODUCT 1637 if (PrintCompilation && (Verbose || WizardMode)) 1638 tty->print_cr("notifying compiler thread pool to block"); 1639 #endif 1640 _should_block = true; 1641 } 1642 1643 // ------------------------------------------------------------------ 1644 // CompileBroker::maybe_block 1645 // 1646 // Call this from the compiler at convenient points, to poll for _should_block. 1647 void CompileBroker::maybe_block() { 1648 if (_should_block) { 1649 #ifndef PRODUCT 1650 if (PrintCompilation && (Verbose || WizardMode)) 1651 tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current())); 1652 #endif 1653 ThreadInVMfromNative tivfn(JavaThread::current()); 1654 } 1655 } 1656 1657 // wrapper for CodeCache::print_summary() 1658 static void codecache_print(bool detailed) 1659 { 1660 ResourceMark rm; 1661 stringStream s; 1662 // Dump code cache into a buffer before locking the tty, 1663 { 1664 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1665 CodeCache::print_summary(&s, detailed); 1666 } 1667 ttyLocker ttyl; 1668 tty->print("%s", s.as_string()); 1669 } 1670 1671 void CompileBroker::post_compile(CompilerThread* thread, CompileTask* task, EventCompilation& event, bool success, ciEnv* ci_env) { 1672 1673 if (success) { 1674 task->mark_success(); 1675 if (ci_env != NULL) { 1676 task->set_num_inlined_bytecodes(ci_env->num_inlined_bytecodes()); 1677 } 1678 if (_compilation_log != NULL) { 1679 nmethod* code = task->code(); 1680 if (code != NULL) { 1681 _compilation_log->log_nmethod(thread, code); 1682 } 1683 } 1684 } 1685 1686 // simulate crash during compilation 1687 assert(task->compile_id() != CICrashAt, "just as planned"); 1688 if (event.should_commit()) { 1689 event.set_method(task->method()); 1690 event.set_compileID(task->compile_id()); 1691 event.set_compileLevel(task->comp_level()); 1692 event.set_succeded(task->is_success()); 1693 event.set_isOsr(task->osr_bci() != CompileBroker::standard_entry_bci); 1694 event.set_codeSize((task->code() == NULL) ? 0 : task->code()->total_size()); 1695 event.set_inlinedBytes(task->num_inlined_bytecodes()); 1696 event.commit(); 1697 } 1698 } 1699 1700 int DirectivesStack::_depth = 0; 1701 CompilerDirectives* DirectivesStack::_top = NULL; 1702 CompilerDirectives* DirectivesStack::_bottom = NULL; 1703 1704 // ------------------------------------------------------------------ 1705 // CompileBroker::invoke_compiler_on_method 1706 // 1707 // Compile a method. 1708 // 1709 void CompileBroker::invoke_compiler_on_method(CompileTask* task) { 1710 if (PrintCompilation) { 1711 ResourceMark rm; 1712 task->print_tty(); 1713 } 1714 elapsedTimer time; 1715 1716 CompilerThread* thread = CompilerThread::current(); 1717 ResourceMark rm(thread); 1718 1719 if (LogEvents) { 1720 _compilation_log->log_compile(thread, task); 1721 } 1722 1723 // Common flags. 1724 uint compile_id = task->compile_id(); 1725 int osr_bci = task->osr_bci(); 1726 bool is_osr = (osr_bci != standard_entry_bci); 1727 bool should_log = (thread->log() != NULL); 1728 bool should_break = false; 1729 int task_level = task->comp_level(); 1730 1731 DirectiveSet* directive; 1732 { 1733 // create the handle inside it's own block so it can't 1734 // accidentally be referenced once the thread transitions to 1735 // native. The NoHandleMark before the transition should catch 1736 // any cases where this occurs in the future. 1737 methodHandle method(thread, task->method()); 1738 assert(!method->is_native(), "no longer compile natives"); 1739 1740 // Look up matching directives 1741 directive = DirectivesStack::getMatchingDirective(method, compiler(task_level)); 1742 1743 // Save information about this method in case of failure. 1744 set_last_compile(thread, method, is_osr, task_level); 1745 1746 DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level)); 1747 } 1748 1749 should_break = directive->BreakAtExecuteOption || task->check_break_at_flags(); 1750 if (should_log && !directive->LogOption) { 1751 should_log = false; 1752 } 1753 1754 // Allocate a new set of JNI handles. 1755 push_jni_handle_block(); 1756 Method* target_handle = task->method(); 1757 int compilable = ciEnv::MethodCompilable; 1758 AbstractCompiler *comp = compiler(task_level); 1759 1760 int system_dictionary_modification_counter; 1761 { 1762 MutexLocker locker(Compile_lock, thread); 1763 system_dictionary_modification_counter = SystemDictionary::number_of_modifications(); 1764 } 1765 #if INCLUDE_JVMCI 1766 if (UseJVMCICompiler && comp != NULL && comp->is_jvmci()) { 1767 JVMCICompiler* jvmci = (JVMCICompiler*) comp; 1768 1769 TraceTime t1("compilation", &time); 1770 EventCompilation event; 1771 1772 JVMCIEnv env(task, system_dictionary_modification_counter); 1773 methodHandle method(thread, target_handle); 1774 jvmci->compile_method(method, osr_bci, &env); 1775 1776 post_compile(thread, task, event, task->code() != NULL, NULL); 1777 } else 1778 #endif // INCLUDE_JVMCI 1779 { 1780 1781 NoHandleMark nhm; 1782 ThreadToNativeFromVM ttn(thread); 1783 1784 ciEnv ci_env(task, system_dictionary_modification_counter); 1785 if (should_break) { 1786 ci_env.set_break_at_compile(true); 1787 } 1788 if (should_log) { 1789 ci_env.set_log(thread->log()); 1790 } 1791 assert(thread->env() == &ci_env, "set by ci_env"); 1792 // The thread-env() field is cleared in ~CompileTaskWrapper. 1793 1794 // Cache Jvmti state 1795 ci_env.cache_jvmti_state(); 1796 1797 // Cache DTrace flags 1798 ci_env.cache_dtrace_flags(); 1799 1800 ciMethod* target = ci_env.get_method_from_handle(target_handle); 1801 1802 TraceTime t1("compilation", &time); 1803 EventCompilation event; 1804 1805 if (comp == NULL) { 1806 ci_env.record_method_not_compilable("no compiler", !TieredCompilation); 1807 } else { 1808 if (WhiteBoxAPI && WhiteBox::compilation_locked) { 1809 MonitorLockerEx locker(Compilation_lock, Mutex::_no_safepoint_check_flag); 1810 while (WhiteBox::compilation_locked) { 1811 locker.wait(Mutex::_no_safepoint_check_flag); 1812 } 1813 } 1814 comp->compile_method(&ci_env, target, osr_bci, directive); 1815 } 1816 1817 if (!ci_env.failing() && task->code() == NULL) { 1818 //assert(false, "compiler should always document failure"); 1819 // The compiler elected, without comment, not to register a result. 1820 // Do not attempt further compilations of this method. 1821 ci_env.record_method_not_compilable("compile failed", !TieredCompilation); 1822 } 1823 1824 // Copy this bit to the enclosing block: 1825 compilable = ci_env.compilable(); 1826 1827 if (ci_env.failing()) { 1828 task->set_failure_reason(ci_env.failure_reason()); 1829 ci_env.report_failure(ci_env.failure_reason()); 1830 const char* retry_message = ci_env.retry_message(); 1831 if (_compilation_log != NULL) { 1832 _compilation_log->log_failure(thread, task, ci_env.failure_reason(), retry_message); 1833 } 1834 if (PrintCompilation) { 1835 FormatBufferResource msg = retry_message != NULL ? 1836 FormatBufferResource("COMPILE SKIPPED: %s (%s)", ci_env.failure_reason(), retry_message) : 1837 FormatBufferResource("COMPILE SKIPPED: %s", ci_env.failure_reason()); 1838 task->print(tty, msg); 1839 } 1840 } 1841 1842 post_compile(thread, task, event, !ci_env.failing(), &ci_env); 1843 } 1844 DirectivesStack::release(directive); 1845 pop_jni_handle_block(); 1846 1847 methodHandle method(thread, task->method()); 1848 1849 DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success()); 1850 1851 collect_statistics(thread, time, task); 1852 1853 if (PrintCompilation && PrintCompilation2) { 1854 tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp 1855 tty->print("%4d ", compile_id); // print compilation number 1856 tty->print("%s ", (is_osr ? "%" : " ")); 1857 if (task->code() != NULL) { 1858 tty->print("size: %d(%d) ", task->code()->total_size(), task->code()->insts_size()); 1859 } 1860 tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes()); 1861 } 1862 1863 if (PrintCodeCacheOnCompilation) 1864 codecache_print(/* detailed= */ false); 1865 1866 // Disable compilation, if required. 1867 switch (compilable) { 1868 case ciEnv::MethodCompilable_never: 1869 if (is_osr) 1870 method->set_not_osr_compilable_quietly(); 1871 else 1872 method->set_not_compilable_quietly(); 1873 break; 1874 case ciEnv::MethodCompilable_not_at_tier: 1875 if (is_osr) 1876 method->set_not_osr_compilable_quietly(task_level); 1877 else 1878 method->set_not_compilable_quietly(task_level); 1879 break; 1880 } 1881 1882 // Note that the queued_for_compilation bits are cleared without 1883 // protection of a mutex. [They were set by the requester thread, 1884 // when adding the task to the compile queue -- at which time the 1885 // compile queue lock was held. Subsequently, we acquired the compile 1886 // queue lock to get this task off the compile queue; thus (to belabour 1887 // the point somewhat) our clearing of the bits must be occurring 1888 // only after the setting of the bits. See also 14012000 above. 1889 method->clear_queued_for_compilation(); 1890 1891 #ifdef ASSERT 1892 if (CollectedHeap::fired_fake_oom()) { 1893 // The current compile received a fake OOM during compilation so 1894 // go ahead and exit the VM since the test apparently succeeded 1895 tty->print_cr("*** Shutting down VM after successful fake OOM"); 1896 vm_exit(0); 1897 } 1898 #endif 1899 } 1900 1901 /** 1902 * The CodeCache is full. Print warning and disable compilation. 1903 * Schedule code cache cleaning so compilation can continue later. 1904 * This function needs to be called only from CodeCache::allocate(), 1905 * since we currently handle a full code cache uniformly. 1906 */ 1907 void CompileBroker::handle_full_code_cache(int code_blob_type) { 1908 UseInterpreter = true; 1909 if (UseCompiler || AlwaysCompileLoopMethods ) { 1910 if (xtty != NULL) { 1911 ResourceMark rm; 1912 stringStream s; 1913 // Dump code cache state into a buffer before locking the tty, 1914 // because log_state() will use locks causing lock conflicts. 1915 CodeCache::log_state(&s); 1916 // Lock to prevent tearing 1917 ttyLocker ttyl; 1918 xtty->begin_elem("code_cache_full"); 1919 xtty->print("%s", s.as_string()); 1920 xtty->stamp(); 1921 xtty->end_elem(); 1922 } 1923 1924 #ifndef PRODUCT 1925 if (CompileTheWorld || ExitOnFullCodeCache) { 1926 codecache_print(/* detailed= */ true); 1927 before_exit(JavaThread::current()); 1928 exit_globals(); // will delete tty 1929 vm_direct_exit(CompileTheWorld ? 0 : 1); 1930 } 1931 #endif 1932 if (UseCodeCacheFlushing) { 1933 // Since code cache is full, immediately stop new compiles 1934 if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) { 1935 NMethodSweeper::log_sweep("disable_compiler"); 1936 } 1937 } else { 1938 disable_compilation_forever(); 1939 } 1940 1941 CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning()); 1942 } 1943 } 1944 1945 // ------------------------------------------------------------------ 1946 // CompileBroker::set_last_compile 1947 // 1948 // Record this compilation for debugging purposes. 1949 void CompileBroker::set_last_compile(CompilerThread* thread, const methodHandle& method, bool is_osr, int comp_level) { 1950 ResourceMark rm; 1951 char* method_name = method->name()->as_C_string(); 1952 strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length); 1953 _last_method_compiled[CompileBroker::name_buffer_length - 1] = '\0'; // ensure null terminated 1954 char current_method[CompilerCounters::cmname_buffer_length]; 1955 size_t maxLen = CompilerCounters::cmname_buffer_length; 1956 1957 if (UsePerfData) { 1958 const char* class_name = method->method_holder()->name()->as_C_string(); 1959 1960 size_t s1len = strlen(class_name); 1961 size_t s2len = strlen(method_name); 1962 1963 // check if we need to truncate the string 1964 if (s1len + s2len + 2 > maxLen) { 1965 1966 // the strategy is to lop off the leading characters of the 1967 // class name and the trailing characters of the method name. 1968 1969 if (s2len + 2 > maxLen) { 1970 // lop of the entire class name string, let snprintf handle 1971 // truncation of the method name. 1972 class_name += s1len; // null string 1973 } 1974 else { 1975 // lop off the extra characters from the front of the class name 1976 class_name += ((s1len + s2len + 2) - maxLen); 1977 } 1978 } 1979 1980 jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name); 1981 } 1982 1983 if (CICountOSR && is_osr) { 1984 _last_compile_type = osr_compile; 1985 } else { 1986 _last_compile_type = normal_compile; 1987 } 1988 _last_compile_level = comp_level; 1989 1990 if (UsePerfData) { 1991 CompilerCounters* counters = thread->counters(); 1992 counters->set_current_method(current_method); 1993 counters->set_compile_type((jlong)_last_compile_type); 1994 } 1995 } 1996 1997 1998 // ------------------------------------------------------------------ 1999 // CompileBroker::push_jni_handle_block 2000 // 2001 // Push on a new block of JNI handles. 2002 void CompileBroker::push_jni_handle_block() { 2003 JavaThread* thread = JavaThread::current(); 2004 2005 // Allocate a new block for JNI handles. 2006 // Inlined code from jni_PushLocalFrame() 2007 JNIHandleBlock* java_handles = thread->active_handles(); 2008 JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread); 2009 assert(compile_handles != NULL && java_handles != NULL, "should not be NULL"); 2010 compile_handles->set_pop_frame_link(java_handles); // make sure java handles get gc'd. 2011 thread->set_active_handles(compile_handles); 2012 } 2013 2014 2015 // ------------------------------------------------------------------ 2016 // CompileBroker::pop_jni_handle_block 2017 // 2018 // Pop off the current block of JNI handles. 2019 void CompileBroker::pop_jni_handle_block() { 2020 JavaThread* thread = JavaThread::current(); 2021 2022 // Release our JNI handle block 2023 JNIHandleBlock* compile_handles = thread->active_handles(); 2024 JNIHandleBlock* java_handles = compile_handles->pop_frame_link(); 2025 thread->set_active_handles(java_handles); 2026 compile_handles->set_pop_frame_link(NULL); 2027 JNIHandleBlock::release_block(compile_handles, thread); // may block 2028 } 2029 2030 // ------------------------------------------------------------------ 2031 // CompileBroker::collect_statistics 2032 // 2033 // Collect statistics about the compilation. 2034 2035 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) { 2036 bool success = task->is_success(); 2037 methodHandle method (thread, task->method()); 2038 uint compile_id = task->compile_id(); 2039 bool is_osr = (task->osr_bci() != standard_entry_bci); 2040 nmethod* code = task->code(); 2041 CompilerCounters* counters = thread->counters(); 2042 2043 assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker"); 2044 MutexLocker locker(CompileStatistics_lock); 2045 2046 // _perf variables are production performance counters which are 2047 // updated regardless of the setting of the CITime and CITimeEach flags 2048 // 2049 2050 // account all time, including bailouts and failures in this counter; 2051 // C1 and C2 counters are counting both successful and unsuccessful compiles 2052 _t_total_compilation.add(time); 2053 2054 if (!success) { 2055 _total_bailout_count++; 2056 if (UsePerfData) { 2057 _perf_last_failed_method->set_value(counters->current_method()); 2058 _perf_last_failed_type->set_value(counters->compile_type()); 2059 _perf_total_bailout_count->inc(); 2060 } 2061 _t_bailedout_compilation.add(time); 2062 } else if (code == NULL) { 2063 if (UsePerfData) { 2064 _perf_last_invalidated_method->set_value(counters->current_method()); 2065 _perf_last_invalidated_type->set_value(counters->compile_type()); 2066 _perf_total_invalidated_count->inc(); 2067 } 2068 _total_invalidated_count++; 2069 _t_invalidated_compilation.add(time); 2070 } else { 2071 // Compilation succeeded 2072 2073 // update compilation ticks - used by the implementation of 2074 // java.lang.management.CompilationMBean 2075 _perf_total_compilation->inc(time.ticks()); 2076 _peak_compilation_time = time.milliseconds() > _peak_compilation_time ? time.milliseconds() : _peak_compilation_time; 2077 2078 if (CITime) { 2079 int bytes_compiled = method->code_size() + task->num_inlined_bytecodes(); 2080 JVMCI_ONLY(CompilerStatistics* stats = compiler(task->comp_level())->stats();) 2081 if (is_osr) { 2082 _t_osr_compilation.add(time); 2083 _sum_osr_bytes_compiled += bytes_compiled; 2084 JVMCI_ONLY(stats->_osr.update(time, bytes_compiled);) 2085 } else { 2086 _t_standard_compilation.add(time); 2087 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes(); 2088 JVMCI_ONLY(stats->_standard.update(time, bytes_compiled);) 2089 } 2090 JVMCI_ONLY(stats->_nmethods_size += code->total_size();) 2091 JVMCI_ONLY(stats->_nmethods_code_size += code->insts_size();) 2092 } 2093 2094 if (UsePerfData) { 2095 // save the name of the last method compiled 2096 _perf_last_method->set_value(counters->current_method()); 2097 _perf_last_compile_type->set_value(counters->compile_type()); 2098 _perf_last_compile_size->set_value(method->code_size() + 2099 task->num_inlined_bytecodes()); 2100 if (is_osr) { 2101 _perf_osr_compilation->inc(time.ticks()); 2102 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes()); 2103 } else { 2104 _perf_standard_compilation->inc(time.ticks()); 2105 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes()); 2106 } 2107 } 2108 2109 if (CITimeEach) { 2110 float bytes_per_sec = 1.0 * (method->code_size() + task->num_inlined_bytecodes()) / time.seconds(); 2111 tty->print_cr("%3d seconds: %f bytes/sec : %f (bytes %d + %d inlined)", 2112 compile_id, time.seconds(), bytes_per_sec, method->code_size(), task->num_inlined_bytecodes()); 2113 } 2114 2115 // Collect counts of successful compilations 2116 _sum_nmethod_size += code->total_size(); 2117 _sum_nmethod_code_size += code->insts_size(); 2118 _total_compile_count++; 2119 2120 if (UsePerfData) { 2121 _perf_sum_nmethod_size->inc( code->total_size()); 2122 _perf_sum_nmethod_code_size->inc(code->insts_size()); 2123 _perf_total_compile_count->inc(); 2124 } 2125 2126 if (is_osr) { 2127 if (UsePerfData) _perf_total_osr_compile_count->inc(); 2128 _total_osr_compile_count++; 2129 } else { 2130 if (UsePerfData) _perf_total_standard_compile_count->inc(); 2131 _total_standard_compile_count++; 2132 } 2133 } 2134 // set the current method for the thread to null 2135 if (UsePerfData) counters->set_current_method(""); 2136 } 2137 2138 const char* CompileBroker::compiler_name(int comp_level) { 2139 AbstractCompiler *comp = CompileBroker::compiler(comp_level); 2140 if (comp == NULL) { 2141 return "no compiler"; 2142 } else { 2143 return (comp->name()); 2144 } 2145 } 2146 2147 #if INCLUDE_JVMCI 2148 void CompileBroker::print_times(AbstractCompiler* comp) { 2149 CompilerStatistics* stats = comp->stats(); 2150 tty->print_cr(" %s {speed: %d 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}", 2151 comp->name(), stats->bytes_per_second(), 2152 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count, 2153 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count, 2154 stats->_nmethods_size, stats->_nmethods_code_size); 2155 comp->print_timers(); 2156 } 2157 #endif // INCLUDE_JVMCI 2158 2159 void CompileBroker::print_times(bool per_compiler, bool aggregate) { 2160 #if INCLUDE_JVMCI 2161 elapsedTimer standard_compilation; 2162 elapsedTimer total_compilation; 2163 elapsedTimer osr_compilation; 2164 2165 int standard_bytes_compiled = 0; 2166 int osr_bytes_compiled = 0; 2167 2168 int standard_compile_count = 0; 2169 int osr_compile_count = 0; 2170 int total_compile_count = 0; 2171 2172 int nmethods_size = 0; 2173 int nmethods_code_size = 0; 2174 bool printedHeader = false; 2175 2176 for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) { 2177 AbstractCompiler* comp = _compilers[i]; 2178 if (comp != NULL) { 2179 if (per_compiler && aggregate && !printedHeader) { 2180 printedHeader = true; 2181 tty->cr(); 2182 tty->print_cr("Individual compiler times (for compiled methods only)"); 2183 tty->print_cr("------------------------------------------------"); 2184 tty->cr(); 2185 } 2186 CompilerStatistics* stats = comp->stats(); 2187 2188 standard_compilation.add(stats->_standard._time); 2189 osr_compilation.add(stats->_osr._time); 2190 2191 standard_bytes_compiled += stats->_standard._bytes; 2192 osr_bytes_compiled += stats->_osr._bytes; 2193 2194 standard_compile_count += stats->_standard._count; 2195 osr_compile_count += stats->_osr._count; 2196 2197 nmethods_size += stats->_nmethods_size; 2198 nmethods_code_size += stats->_nmethods_code_size; 2199 2200 if (per_compiler) { 2201 print_times(comp); 2202 } 2203 } 2204 } 2205 total_compile_count = osr_compile_count + standard_compile_count; 2206 total_compilation.add(osr_compilation); 2207 total_compilation.add(standard_compilation); 2208 2209 // In hosted mode, print the JVMCI compiler specific counters manually. 2210 if (!UseJVMCICompiler) { 2211 JVMCICompiler::print_compilation_timers(); 2212 } 2213 #else // INCLUDE_JVMCI 2214 elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation; 2215 elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation; 2216 elapsedTimer total_compilation = CompileBroker::_t_total_compilation; 2217 2218 int standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled; 2219 int osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled; 2220 2221 int standard_compile_count = CompileBroker::_total_standard_compile_count; 2222 int osr_compile_count = CompileBroker::_total_osr_compile_count; 2223 int total_compile_count = CompileBroker::_total_compile_count; 2224 2225 int nmethods_size = CompileBroker::_sum_nmethod_code_size; 2226 int nmethods_code_size = CompileBroker::_sum_nmethod_size; 2227 #endif // INCLUDE_JVMCI 2228 2229 if (!aggregate) { 2230 return; 2231 } 2232 tty->cr(); 2233 tty->print_cr("Accumulated compiler times"); 2234 tty->print_cr("----------------------------------------------------------"); 2235 //0000000000111111111122222222223333333333444444444455555555556666666666 2236 //0123456789012345678901234567890123456789012345678901234567890123456789 2237 tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds()); 2238 tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s", 2239 standard_compilation.seconds(), 2240 standard_compilation.seconds() / standard_compile_count); 2241 tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s", 2242 CompileBroker::_t_bailedout_compilation.seconds(), 2243 CompileBroker::_t_bailedout_compilation.seconds() / CompileBroker::_total_bailout_count); 2244 tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s", 2245 osr_compilation.seconds(), 2246 osr_compilation.seconds() / osr_compile_count); 2247 tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s", 2248 CompileBroker::_t_invalidated_compilation.seconds(), 2249 CompileBroker::_t_invalidated_compilation.seconds() / CompileBroker::_total_invalidated_count); 2250 2251 AbstractCompiler *comp = compiler(CompLevel_simple); 2252 if (comp != NULL) { 2253 tty->cr(); 2254 comp->print_timers(); 2255 } 2256 comp = compiler(CompLevel_full_optimization); 2257 if (comp != NULL) { 2258 tty->cr(); 2259 comp->print_timers(); 2260 } 2261 tty->cr(); 2262 tty->print_cr(" Total compiled methods : %8d methods", total_compile_count); 2263 tty->print_cr(" Standard compilation : %8d methods", standard_compile_count); 2264 tty->print_cr(" On stack replacement : %8d methods", osr_compile_count); 2265 int tcb = osr_bytes_compiled + standard_bytes_compiled; 2266 tty->print_cr(" Total compiled bytecodes : %8d bytes", tcb); 2267 tty->print_cr(" Standard compilation : %8d bytes", standard_bytes_compiled); 2268 tty->print_cr(" On stack replacement : %8d bytes", osr_bytes_compiled); 2269 double tcs = total_compilation.seconds(); 2270 int bps = tcs == 0.0 ? 0 : (int)(tcb / tcs); 2271 tty->print_cr(" Average compilation speed : %8d bytes/s", bps); 2272 tty->cr(); 2273 tty->print_cr(" nmethod code size : %8d bytes", nmethods_code_size); 2274 tty->print_cr(" nmethod total size : %8d bytes", nmethods_size); 2275 } 2276 2277 // Debugging output for failure 2278 void CompileBroker::print_last_compile() { 2279 if ( _last_compile_level != CompLevel_none && 2280 compiler(_last_compile_level) != NULL && 2281 _last_method_compiled != NULL && 2282 _last_compile_type != no_compile) { 2283 if (_last_compile_type == osr_compile) { 2284 tty->print_cr("Last parse: [osr]%d+++(%d) %s", 2285 _osr_compilation_id, _last_compile_level, _last_method_compiled); 2286 } else { 2287 tty->print_cr("Last parse: %d+++(%d) %s", 2288 _compilation_id, _last_compile_level, _last_method_compiled); 2289 } 2290 } 2291 } 2292 2293 2294 void CompileBroker::print_compiler_threads_on(outputStream* st) { 2295 #ifndef PRODUCT 2296 st->print_cr("Compiler thread printing unimplemented."); 2297 st->cr(); 2298 #endif 2299 }