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