1 /* 2 * Copyright (c) 1999, 2010, 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 "incls/_precompiled.incl" 26 #include "incls/_compileBroker.cpp.incl" 27 28 #ifdef DTRACE_ENABLED 29 30 // Only bother with this argument setup if dtrace is available 31 32 HS_DTRACE_PROBE_DECL8(hotspot, method__compile__begin, 33 char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t); 34 HS_DTRACE_PROBE_DECL9(hotspot, method__compile__end, 35 char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t, bool); 36 37 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method) \ 38 { \ 39 char* comp_name = (char*)(compiler)->name(); \ 40 symbolOop klass_name = (method)->klass_name(); \ 41 symbolOop name = (method)->name(); \ 42 symbolOop signature = (method)->signature(); \ 43 HS_DTRACE_PROBE8(hotspot, method__compile__begin, \ 44 comp_name, strlen(comp_name), \ 45 klass_name->bytes(), klass_name->utf8_length(), \ 46 name->bytes(), name->utf8_length(), \ 47 signature->bytes(), signature->utf8_length()); \ 48 } 49 50 #define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success) \ 51 { \ 52 char* comp_name = (char*)(compiler)->name(); \ 53 symbolOop klass_name = (method)->klass_name(); \ 54 symbolOop name = (method)->name(); \ 55 symbolOop signature = (method)->signature(); \ 56 HS_DTRACE_PROBE9(hotspot, method__compile__end, \ 57 comp_name, strlen(comp_name), \ 58 klass_name->bytes(), klass_name->utf8_length(), \ 59 name->bytes(), name->utf8_length(), \ 60 signature->bytes(), signature->utf8_length(), (success)); \ 61 } 62 63 #else // ndef DTRACE_ENABLED 64 65 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method) 66 #define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success) 67 68 #endif // ndef DTRACE_ENABLED 69 70 bool CompileBroker::_initialized = false; 71 volatile bool CompileBroker::_should_block = false; 72 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation; 73 74 // The installed compiler(s) 75 AbstractCompiler* CompileBroker::_compilers[2]; 76 77 // These counters are used for assigning id's to each compilation 78 uint CompileBroker::_compilation_id = 0; 79 uint CompileBroker::_osr_compilation_id = 0; 80 81 // Debugging information 82 int CompileBroker::_last_compile_type = no_compile; 83 int CompileBroker::_last_compile_level = CompLevel_none; 84 char CompileBroker::_last_method_compiled[CompileBroker::name_buffer_length]; 85 86 // Performance counters 87 PerfCounter* CompileBroker::_perf_total_compilation = NULL; 88 PerfCounter* CompileBroker::_perf_osr_compilation = NULL; 89 PerfCounter* CompileBroker::_perf_standard_compilation = NULL; 90 91 PerfCounter* CompileBroker::_perf_total_bailout_count = NULL; 92 PerfCounter* CompileBroker::_perf_total_invalidated_count = NULL; 93 PerfCounter* CompileBroker::_perf_total_compile_count = NULL; 94 PerfCounter* CompileBroker::_perf_total_osr_compile_count = NULL; 95 PerfCounter* CompileBroker::_perf_total_standard_compile_count = NULL; 96 97 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = NULL; 98 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = NULL; 99 PerfCounter* CompileBroker::_perf_sum_nmethod_size = NULL; 100 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = NULL; 101 102 PerfStringVariable* CompileBroker::_perf_last_method = NULL; 103 PerfStringVariable* CompileBroker::_perf_last_failed_method = NULL; 104 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = NULL; 105 PerfVariable* CompileBroker::_perf_last_compile_type = NULL; 106 PerfVariable* CompileBroker::_perf_last_compile_size = NULL; 107 PerfVariable* CompileBroker::_perf_last_failed_type = NULL; 108 PerfVariable* CompileBroker::_perf_last_invalidated_type = NULL; 109 110 // Timers and counters for generating statistics 111 elapsedTimer CompileBroker::_t_total_compilation; 112 elapsedTimer CompileBroker::_t_osr_compilation; 113 elapsedTimer CompileBroker::_t_standard_compilation; 114 115 int CompileBroker::_total_bailout_count = 0; 116 int CompileBroker::_total_invalidated_count = 0; 117 int CompileBroker::_total_compile_count = 0; 118 int CompileBroker::_total_osr_compile_count = 0; 119 int CompileBroker::_total_standard_compile_count = 0; 120 121 int CompileBroker::_sum_osr_bytes_compiled = 0; 122 int CompileBroker::_sum_standard_bytes_compiled = 0; 123 int CompileBroker::_sum_nmethod_size = 0; 124 int CompileBroker::_sum_nmethod_code_size = 0; 125 126 CompileQueue* CompileBroker::_c2_method_queue = NULL; 127 CompileQueue* CompileBroker::_c1_method_queue = NULL; 128 CompileTask* CompileBroker::_task_free_list = NULL; 129 130 GrowableArray<CompilerThread*>* CompileBroker::_method_threads = NULL; 131 132 133 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) { 134 CompilerThread* thread = CompilerThread::current(); 135 thread->set_task(task); 136 CompileLog* log = thread->log(); 137 if (log != NULL) task->log_task_start(log); 138 } 139 140 CompileTaskWrapper::~CompileTaskWrapper() { 141 CompilerThread* thread = CompilerThread::current(); 142 CompileTask* task = thread->task(); 143 CompileLog* log = thread->log(); 144 if (log != NULL) task->log_task_done(log); 145 thread->set_task(NULL); 146 task->set_code_handle(NULL); 147 DEBUG_ONLY(thread->set_env((ciEnv*)badAddress)); 148 if (task->is_blocking()) { 149 MutexLocker notifier(task->lock(), thread); 150 task->mark_complete(); 151 // Notify the waiting thread that the compilation has completed. 152 task->lock()->notify_all(); 153 } else { 154 task->mark_complete(); 155 156 // By convention, the compiling thread is responsible for 157 // recycling a non-blocking CompileTask. 158 CompileBroker::free_task(task); 159 } 160 } 161 162 163 // ------------------------------------------------------------------ 164 // CompileTask::initialize 165 void CompileTask::initialize(int compile_id, 166 methodHandle method, 167 int osr_bci, 168 int comp_level, 169 methodHandle hot_method, 170 int hot_count, 171 const char* comment, 172 bool is_blocking) { 173 assert(!_lock->is_locked(), "bad locking"); 174 175 _compile_id = compile_id; 176 _method = JNIHandles::make_global(method); 177 _osr_bci = osr_bci; 178 _is_blocking = is_blocking; 179 _comp_level = comp_level; 180 _num_inlined_bytecodes = 0; 181 182 _is_complete = false; 183 _is_success = false; 184 _code_handle = NULL; 185 186 _hot_method = NULL; 187 _hot_count = hot_count; 188 _time_queued = 0; // tidy 189 _comment = comment; 190 191 if (LogCompilation) { 192 _time_queued = os::elapsed_counter(); 193 if (hot_method.not_null()) { 194 if (hot_method == method) { 195 _hot_method = _method; 196 } else { 197 _hot_method = JNIHandles::make_global(hot_method); 198 } 199 } 200 } 201 202 _next = NULL; 203 } 204 205 // ------------------------------------------------------------------ 206 // CompileTask::code/set_code 207 nmethod* CompileTask::code() const { 208 if (_code_handle == NULL) return NULL; 209 return _code_handle->code(); 210 } 211 void CompileTask::set_code(nmethod* nm) { 212 if (_code_handle == NULL && nm == NULL) return; 213 guarantee(_code_handle != NULL, ""); 214 _code_handle->set_code(nm); 215 if (nm == NULL) _code_handle = NULL; // drop the handle also 216 } 217 218 // ------------------------------------------------------------------ 219 // CompileTask::free 220 void CompileTask::free() { 221 set_code(NULL); 222 assert(!_lock->is_locked(), "Should not be locked when freed"); 223 if (_hot_method != NULL && _hot_method != _method) { 224 JNIHandles::destroy_global(_hot_method); 225 } 226 JNIHandles::destroy_global(_method); 227 } 228 229 230 // ------------------------------------------------------------------ 231 // CompileTask::print 232 void CompileTask::print() { 233 tty->print("<CompileTask compile_id=%d ", _compile_id); 234 tty->print("method="); 235 ((methodOop)JNIHandles::resolve(_method))->print_name(tty); 236 tty->print_cr(" osr_bci=%d is_blocking=%s is_complete=%s is_success=%s>", 237 _osr_bci, bool_to_str(_is_blocking), 238 bool_to_str(_is_complete), bool_to_str(_is_success)); 239 } 240 241 242 void CompileTask::print_compilation(outputStream *st, methodOop method, char* method_name) { 243 nmethod::print_compilation(st, method_name,/*title*/ NULL, method, 244 is_blocking(), compile_id(), osr_bci(), comp_level()); 245 } 246 247 // ------------------------------------------------------------------ 248 // CompileTask::print_line_on_error 249 // 250 // This function is called by fatal error handler when the thread 251 // causing troubles is a compiler thread. 252 // 253 // Do not grab any lock, do not allocate memory. 254 // 255 // Otherwise it's the same as CompileTask::print_line() 256 // 257 void CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) { 258 methodOop method = (methodOop)JNIHandles::resolve(_method); 259 // print compiler name 260 st->print("%s:", CompileBroker::compiler(comp_level())->name()); 261 char* method_name = NULL; 262 if (method != NULL) { 263 method_name = method->name_and_sig_as_C_string(buf, buflen); 264 } 265 print_compilation(st, method, method_name); 266 } 267 268 // ------------------------------------------------------------------ 269 // CompileTask::print_line 270 void CompileTask::print_line() { 271 Thread *thread = Thread::current(); 272 methodHandle method(thread, 273 (methodOop)JNIHandles::resolve(method_handle())); 274 ResourceMark rm(thread); 275 276 ttyLocker ttyl; // keep the following output all in one block 277 278 // print compiler name if requested 279 if (CIPrintCompilerName) tty->print("%s:", CompileBroker::compiler(comp_level())->name()); 280 print_compilation(tty, method(), NULL); 281 } 282 283 284 // ------------------------------------------------------------------ 285 // CompileTask::log_task 286 void CompileTask::log_task(xmlStream* log) { 287 Thread* thread = Thread::current(); 288 methodHandle method(thread, 289 (methodOop)JNIHandles::resolve(method_handle())); 290 ResourceMark rm(thread); 291 292 // <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'> 293 if (_compile_id != 0) log->print(" compile_id='%d'", _compile_id); 294 if (_osr_bci != CompileBroker::standard_entry_bci) { 295 log->print(" compile_kind='osr'"); // same as nmethod::compile_kind 296 } // else compile_kind='c2c' 297 if (!method.is_null()) log->method(method); 298 if (_osr_bci != CompileBroker::standard_entry_bci) { 299 log->print(" osr_bci='%d'", _osr_bci); 300 } 301 if (_comp_level != CompLevel_highest_tier) { 302 log->print(" level='%d'", _comp_level); 303 } 304 if (_is_blocking) { 305 log->print(" blocking='1'"); 306 } 307 log->stamp(); 308 } 309 310 311 // ------------------------------------------------------------------ 312 // CompileTask::log_task_queued 313 void CompileTask::log_task_queued() { 314 Thread* thread = Thread::current(); 315 ttyLocker ttyl; 316 ResourceMark rm(thread); 317 318 xtty->begin_elem("task_queued"); 319 log_task(xtty); 320 if (_comment != NULL) { 321 xtty->print(" comment='%s'", _comment); 322 } 323 if (_hot_method != NULL) { 324 methodHandle hot(thread, 325 (methodOop)JNIHandles::resolve(_hot_method)); 326 methodHandle method(thread, 327 (methodOop)JNIHandles::resolve(_method)); 328 if (hot() != method()) { 329 xtty->method(hot); 330 } 331 } 332 if (_hot_count != 0) { 333 xtty->print(" hot_count='%d'", _hot_count); 334 } 335 xtty->end_elem(); 336 } 337 338 339 // ------------------------------------------------------------------ 340 // CompileTask::log_task_start 341 void CompileTask::log_task_start(CompileLog* log) { 342 log->begin_head("task"); 343 log_task(log); 344 log->end_head(); 345 } 346 347 348 // ------------------------------------------------------------------ 349 // CompileTask::log_task_done 350 void CompileTask::log_task_done(CompileLog* log) { 351 Thread* thread = Thread::current(); 352 methodHandle method(thread, 353 (methodOop)JNIHandles::resolve(method_handle())); 354 ResourceMark rm(thread); 355 356 // <task_done ... stamp='1.234'> </task> 357 nmethod* nm = code(); 358 log->begin_elem("task_done success='%d' nmsize='%d' count='%d'", 359 _is_success, nm == NULL ? 0 : nm->content_size(), 360 method->invocation_count()); 361 int bec = method->backedge_count(); 362 if (bec != 0) log->print(" backedge_count='%d'", bec); 363 // Note: "_is_complete" is about to be set, but is not. 364 if (_num_inlined_bytecodes != 0) { 365 log->print(" inlined_bytes='%d'", _num_inlined_bytecodes); 366 } 367 log->stamp(); 368 log->end_elem(); 369 log->tail("task"); 370 log->clear_identities(); // next task will have different CI 371 if (log->unflushed_count() > 2000) { 372 log->flush(); 373 } 374 log->mark_file_end(); 375 } 376 377 378 379 // ------------------------------------------------------------------ 380 // CompileQueue::add 381 // 382 // Add a CompileTask to a CompileQueue 383 void CompileQueue::add(CompileTask* task) { 384 assert(lock()->owned_by_self(), "must own lock"); 385 386 task->set_next(NULL); 387 task->set_prev(NULL); 388 389 if (_last == NULL) { 390 // The compile queue is empty. 391 assert(_first == NULL, "queue is empty"); 392 _first = task; 393 _last = task; 394 } else { 395 // Append the task to the queue. 396 assert(_last->next() == NULL, "not last"); 397 _last->set_next(task); 398 task->set_prev(_last); 399 _last = task; 400 } 401 ++_size; 402 403 // Mark the method as being in the compile queue. 404 ((methodOop)JNIHandles::resolve(task->method_handle()))->set_queued_for_compilation(); 405 406 if (CIPrintCompileQueue) { 407 print(); 408 } 409 410 if (LogCompilation && xtty != NULL) { 411 task->log_task_queued(); 412 } 413 414 // Notify CompilerThreads that a task is available. 415 lock()->notify_all(); 416 } 417 418 // ------------------------------------------------------------------ 419 // CompileQueue::get 420 // 421 // Get the next CompileTask from a CompileQueue 422 CompileTask* CompileQueue::get() { 423 NMethodSweeper::possibly_sweep(); 424 425 MutexLocker locker(lock()); 426 // Wait for an available CompileTask. 427 while (_first == NULL) { 428 // There is no work to be done right now. Wait. 429 if (UseCodeCacheFlushing && (!CompileBroker::should_compile_new_jobs() || CodeCache::needs_flushing())) { 430 // During the emergency sweeping periods, wake up and sweep occasionally 431 bool timedout = lock()->wait(!Mutex::_no_safepoint_check_flag, NmethodSweepCheckInterval*1000); 432 if (timedout) { 433 MutexUnlocker ul(lock()); 434 // When otherwise not busy, run nmethod sweeping 435 NMethodSweeper::possibly_sweep(); 436 } 437 } else { 438 // During normal operation no need to wake up on timer 439 lock()->wait(); 440 } 441 } 442 CompileTask* task = CompilationPolicy::policy()->select_task(this); 443 remove(task); 444 return task; 445 } 446 447 void CompileQueue::remove(CompileTask* task) 448 { 449 assert(lock()->owned_by_self(), "must own lock"); 450 if (task->prev() != NULL) { 451 task->prev()->set_next(task->next()); 452 } else { 453 // max is the first element 454 assert(task == _first, "Sanity"); 455 _first = task->next(); 456 } 457 458 if (task->next() != NULL) { 459 task->next()->set_prev(task->prev()); 460 } else { 461 // max is the last element 462 assert(task == _last, "Sanity"); 463 _last = task->prev(); 464 } 465 --_size; 466 } 467 468 // ------------------------------------------------------------------ 469 // CompileQueue::print 470 void CompileQueue::print() { 471 tty->print_cr("Contents of %s", name()); 472 tty->print_cr("----------------------"); 473 CompileTask* task = _first; 474 while (task != NULL) { 475 task->print_line(); 476 task = task->next(); 477 } 478 tty->print_cr("----------------------"); 479 } 480 481 CompilerCounters::CompilerCounters(const char* thread_name, int instance, TRAPS) { 482 483 _current_method[0] = '\0'; 484 _compile_type = CompileBroker::no_compile; 485 486 if (UsePerfData) { 487 ResourceMark rm; 488 489 // create the thread instance name space string - don't create an 490 // instance subspace if instance is -1 - keeps the adapterThread 491 // counters from having a ".0" namespace. 492 const char* thread_i = (instance == -1) ? thread_name : 493 PerfDataManager::name_space(thread_name, instance); 494 495 496 char* name = PerfDataManager::counter_name(thread_i, "method"); 497 _perf_current_method = 498 PerfDataManager::create_string_variable(SUN_CI, name, 499 cmname_buffer_length, 500 _current_method, CHECK); 501 502 name = PerfDataManager::counter_name(thread_i, "type"); 503 _perf_compile_type = PerfDataManager::create_variable(SUN_CI, name, 504 PerfData::U_None, 505 (jlong)_compile_type, 506 CHECK); 507 508 name = PerfDataManager::counter_name(thread_i, "time"); 509 _perf_time = PerfDataManager::create_counter(SUN_CI, name, 510 PerfData::U_Ticks, CHECK); 511 512 name = PerfDataManager::counter_name(thread_i, "compiles"); 513 _perf_compiles = PerfDataManager::create_counter(SUN_CI, name, 514 PerfData::U_Events, CHECK); 515 } 516 } 517 518 // ------------------------------------------------------------------ 519 // CompileBroker::compilation_init 520 // 521 // Initialize the Compilation object 522 void CompileBroker::compilation_init() { 523 _last_method_compiled[0] = '\0'; 524 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 #ifdef COMPILER1 529 if (c1_count > 0) { 530 _compilers[0] = new Compiler(); 531 } 532 #endif // COMPILER1 533 534 #ifdef COMPILER2 535 if (c2_count > 0) { 536 _compilers[1] = new C2Compiler(); 537 } 538 #endif // COMPILER2 539 540 #ifdef SHARK 541 #if defined(COMPILER1) || defined(COMPILER2) 542 #error "Can't use COMPILER1 or COMPILER2 with shark" 543 #endif 544 _compilers[0] = new SharkCompiler(); 545 _compilers[1] = _compilers[0]; 546 #endif 547 548 // Initialize the CompileTask free list 549 _task_free_list = NULL; 550 551 // Start the CompilerThreads 552 init_compiler_threads(c1_count, c2_count); 553 // totalTime performance counter is always created as it is required 554 // by the implementation of java.lang.management.CompilationMBean. 555 { 556 EXCEPTION_MARK; 557 _perf_total_compilation = 558 PerfDataManager::create_counter(JAVA_CI, "totalTime", 559 PerfData::U_Ticks, CHECK); 560 } 561 562 563 if (UsePerfData) { 564 565 EXCEPTION_MARK; 566 567 // create the jvmstat performance counters 568 _perf_osr_compilation = 569 PerfDataManager::create_counter(SUN_CI, "osrTime", 570 PerfData::U_Ticks, CHECK); 571 572 _perf_standard_compilation = 573 PerfDataManager::create_counter(SUN_CI, "standardTime", 574 PerfData::U_Ticks, CHECK); 575 576 _perf_total_bailout_count = 577 PerfDataManager::create_counter(SUN_CI, "totalBailouts", 578 PerfData::U_Events, CHECK); 579 580 _perf_total_invalidated_count = 581 PerfDataManager::create_counter(SUN_CI, "totalInvalidates", 582 PerfData::U_Events, CHECK); 583 584 _perf_total_compile_count = 585 PerfDataManager::create_counter(SUN_CI, "totalCompiles", 586 PerfData::U_Events, CHECK); 587 _perf_total_osr_compile_count = 588 PerfDataManager::create_counter(SUN_CI, "osrCompiles", 589 PerfData::U_Events, CHECK); 590 591 _perf_total_standard_compile_count = 592 PerfDataManager::create_counter(SUN_CI, "standardCompiles", 593 PerfData::U_Events, CHECK); 594 595 _perf_sum_osr_bytes_compiled = 596 PerfDataManager::create_counter(SUN_CI, "osrBytes", 597 PerfData::U_Bytes, CHECK); 598 599 _perf_sum_standard_bytes_compiled = 600 PerfDataManager::create_counter(SUN_CI, "standardBytes", 601 PerfData::U_Bytes, CHECK); 602 603 _perf_sum_nmethod_size = 604 PerfDataManager::create_counter(SUN_CI, "nmethodSize", 605 PerfData::U_Bytes, CHECK); 606 607 _perf_sum_nmethod_code_size = 608 PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize", 609 PerfData::U_Bytes, CHECK); 610 611 _perf_last_method = 612 PerfDataManager::create_string_variable(SUN_CI, "lastMethod", 613 CompilerCounters::cmname_buffer_length, 614 "", CHECK); 615 616 _perf_last_failed_method = 617 PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod", 618 CompilerCounters::cmname_buffer_length, 619 "", CHECK); 620 621 _perf_last_invalidated_method = 622 PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod", 623 CompilerCounters::cmname_buffer_length, 624 "", CHECK); 625 626 _perf_last_compile_type = 627 PerfDataManager::create_variable(SUN_CI, "lastType", 628 PerfData::U_None, 629 (jlong)CompileBroker::no_compile, 630 CHECK); 631 632 _perf_last_compile_size = 633 PerfDataManager::create_variable(SUN_CI, "lastSize", 634 PerfData::U_Bytes, 635 (jlong)CompileBroker::no_compile, 636 CHECK); 637 638 639 _perf_last_failed_type = 640 PerfDataManager::create_variable(SUN_CI, "lastFailedType", 641 PerfData::U_None, 642 (jlong)CompileBroker::no_compile, 643 CHECK); 644 645 _perf_last_invalidated_type = 646 PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType", 647 PerfData::U_None, 648 (jlong)CompileBroker::no_compile, 649 CHECK); 650 } 651 652 _initialized = true; 653 } 654 655 656 657 // ------------------------------------------------------------------ 658 // CompileBroker::make_compiler_thread 659 CompilerThread* CompileBroker::make_compiler_thread(const char* name, CompileQueue* queue, CompilerCounters* counters, TRAPS) { 660 CompilerThread* compiler_thread = NULL; 661 662 klassOop k = 663 SystemDictionary::resolve_or_fail(vmSymbolHandles::java_lang_Thread(), 664 true, CHECK_0); 665 instanceKlassHandle klass (THREAD, k); 666 instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_0); 667 Handle string = java_lang_String::create_from_str(name, CHECK_0); 668 669 // Initialize thread_oop to put it into the system threadGroup 670 Handle thread_group (THREAD, Universe::system_thread_group()); 671 JavaValue result(T_VOID); 672 JavaCalls::call_special(&result, thread_oop, 673 klass, 674 vmSymbolHandles::object_initializer_name(), 675 vmSymbolHandles::threadgroup_string_void_signature(), 676 thread_group, 677 string, 678 CHECK_0); 679 680 { 681 MutexLocker mu(Threads_lock, THREAD); 682 compiler_thread = new CompilerThread(queue, counters); 683 // At this point the new CompilerThread data-races with this startup 684 // thread (which I believe is the primoridal thread and NOT the VM 685 // thread). This means Java bytecodes being executed at startup can 686 // queue compile jobs which will run at whatever default priority the 687 // newly created CompilerThread runs at. 688 689 690 // At this point it may be possible that no osthread was created for the 691 // JavaThread due to lack of memory. We would have to throw an exception 692 // in that case. However, since this must work and we do not allow 693 // exceptions anyway, check and abort if this fails. 694 695 if (compiler_thread == NULL || compiler_thread->osthread() == NULL){ 696 vm_exit_during_initialization("java.lang.OutOfMemoryError", 697 "unable to create new native thread"); 698 } 699 700 java_lang_Thread::set_thread(thread_oop(), compiler_thread); 701 702 // Note that this only sets the JavaThread _priority field, which by 703 // definition is limited to Java priorities and not OS priorities. 704 // The os-priority is set in the CompilerThread startup code itself 705 java_lang_Thread::set_priority(thread_oop(), NearMaxPriority); 706 // CLEANUP PRIORITIES: This -if- statement hids a bug whereby the compiler 707 // threads never have their OS priority set. The assumption here is to 708 // enable the Performance group to do flag tuning, figure out a suitable 709 // CompilerThreadPriority, and then remove this 'if' statement (and 710 // comment) and unconditionally set the priority. 711 712 // Compiler Threads should be at the highest Priority 713 if ( CompilerThreadPriority != -1 ) 714 os::set_native_priority( compiler_thread, CompilerThreadPriority ); 715 else 716 os::set_native_priority( compiler_thread, os::java_to_os_priority[NearMaxPriority]); 717 718 // Note that I cannot call os::set_priority because it expects Java 719 // priorities and I am *explicitly* using OS priorities so that it's 720 // possible to set the compiler thread priority higher than any Java 721 // thread. 722 723 java_lang_Thread::set_daemon(thread_oop()); 724 725 compiler_thread->set_threadObj(thread_oop()); 726 Threads::add(compiler_thread); 727 Thread::start(compiler_thread); 728 } 729 // Let go of Threads_lock before yielding 730 os::yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS) 731 732 return compiler_thread; 733 } 734 735 736 // ------------------------------------------------------------------ 737 // CompileBroker::init_compiler_threads 738 // 739 // Initialize the compilation queue 740 void CompileBroker::init_compiler_threads(int c1_compiler_count, int c2_compiler_count) { 741 EXCEPTION_MARK; 742 assert(c2_compiler_count > 0 || c1_compiler_count > 0, "No compilers?"); 743 if (c2_compiler_count > 0) { 744 _c2_method_queue = new CompileQueue("C2MethodQueue", MethodCompileQueue_lock); 745 } 746 if (c1_compiler_count > 0) { 747 _c1_method_queue = new CompileQueue("C1MethodQueue", MethodCompileQueue_lock); 748 } 749 750 int compiler_count = c1_compiler_count + c2_compiler_count; 751 752 _method_threads = 753 new (ResourceObj::C_HEAP) GrowableArray<CompilerThread*>(compiler_count, true); 754 755 char name_buffer[256]; 756 for (int i = 0; i < c2_compiler_count; i++) { 757 // Create a name for our thread. 758 sprintf(name_buffer, "C2 CompilerThread%d", i); 759 CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK); 760 CompilerThread* new_thread = make_compiler_thread(name_buffer, _c2_method_queue, counters, CHECK); 761 _method_threads->append(new_thread); 762 } 763 764 for (int i = c2_compiler_count; i < compiler_count; i++) { 765 // Create a name for our thread. 766 sprintf(name_buffer, "C1 CompilerThread%d", i); 767 CompilerCounters* counters = new CompilerCounters("compilerThread", i, CHECK); 768 CompilerThread* new_thread = make_compiler_thread(name_buffer, _c1_method_queue, counters, CHECK); 769 _method_threads->append(new_thread); 770 } 771 772 if (UsePerfData) { 773 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, 774 compiler_count, CHECK); 775 } 776 } 777 778 // ------------------------------------------------------------------ 779 // CompileBroker::is_idle 780 bool CompileBroker::is_idle() { 781 if (_c2_method_queue != NULL && !_c2_method_queue->is_empty()) { 782 return false; 783 } else if (_c1_method_queue != NULL && !_c1_method_queue->is_empty()) { 784 return false; 785 } else { 786 int num_threads = _method_threads->length(); 787 for (int i=0; i<num_threads; i++) { 788 if (_method_threads->at(i)->task() != NULL) { 789 return false; 790 } 791 } 792 793 // No pending or active compilations. 794 return true; 795 } 796 } 797 798 799 // ------------------------------------------------------------------ 800 // CompileBroker::compile_method 801 // 802 // Request compilation of a method. 803 void CompileBroker::compile_method_base(methodHandle method, 804 int osr_bci, 805 int comp_level, 806 methodHandle hot_method, 807 int hot_count, 808 const char* comment, 809 TRAPS) { 810 // do nothing if compiler thread(s) is not available 811 if (!_initialized ) { 812 return; 813 } 814 815 guarantee(!method->is_abstract(), "cannot compile abstract methods"); 816 assert(method->method_holder()->klass_part()->oop_is_instance(), 817 "sanity check"); 818 assert(!instanceKlass::cast(method->method_holder())->is_not_initialized(), 819 "method holder must be initialized"); 820 821 if (CIPrintRequests) { 822 tty->print("request: "); 823 method->print_short_name(tty); 824 if (osr_bci != InvocationEntryBci) { 825 tty->print(" osr_bci: %d", osr_bci); 826 } 827 tty->print(" comment: %s count: %d", comment, hot_count); 828 if (!hot_method.is_null()) { 829 tty->print(" hot: "); 830 if (hot_method() != method()) { 831 hot_method->print_short_name(tty); 832 } else { 833 tty->print("yes"); 834 } 835 } 836 tty->cr(); 837 } 838 839 // A request has been made for compilation. Before we do any 840 // real work, check to see if the method has been compiled 841 // in the meantime with a definitive result. 842 if (compilation_is_complete(method, osr_bci, comp_level)) { 843 return; 844 } 845 846 847 // If this method is already in the compile queue, then 848 // we do not block the current thread. 849 if (compilation_is_in_queue(method, osr_bci)) { 850 // We may want to decay our counter a bit here to prevent 851 // multiple denied requests for compilation. This is an 852 // open compilation policy issue. Note: The other possibility, 853 // in the case that this is a blocking compile request, is to have 854 // all subsequent blocking requesters wait for completion of 855 // ongoing compiles. Note that in this case we'll need a protocol 856 // for freeing the associated compile tasks. [Or we could have 857 // a single static monitor on which all these waiters sleep.] 858 return; 859 } 860 861 // Outputs from the following MutexLocker block: 862 CompileTask* task = NULL; 863 bool blocking = false; 864 CompileQueue* queue = compile_queue(comp_level); 865 866 // Acquire our lock. 867 { 868 MutexLocker locker(queue->lock(), THREAD); 869 870 // Make sure the method has not slipped into the queues since 871 // last we checked; note that those checks were "fast bail-outs". 872 // Here we need to be more careful, see 14012000 below. 873 if (compilation_is_in_queue(method, osr_bci)) { 874 return; 875 } 876 877 // We need to check again to see if the compilation has 878 // completed. A previous compilation may have registered 879 // some result. 880 if (compilation_is_complete(method, osr_bci, comp_level)) { 881 return; 882 } 883 884 // We now know that this compilation is not pending, complete, 885 // or prohibited. Assign a compile_id to this compilation 886 // and check to see if it is in our [Start..Stop) range. 887 uint compile_id = assign_compile_id(method, osr_bci); 888 if (compile_id == 0) { 889 // The compilation falls outside the allowed range. 890 return; 891 } 892 893 // Should this thread wait for completion of the compile? 894 blocking = is_compile_blocking(method, osr_bci); 895 896 // We will enter the compilation in the queue. 897 // 14012000: Note that this sets the queued_for_compile bits in 898 // the target method. We can now reason that a method cannot be 899 // queued for compilation more than once, as follows: 900 // Before a thread queues a task for compilation, it first acquires 901 // the compile queue lock, then checks if the method's queued bits 902 // are set or it has already been compiled. Thus there can not be two 903 // instances of a compilation task for the same method on the 904 // compilation queue. Consider now the case where the compilation 905 // thread has already removed a task for that method from the queue 906 // and is in the midst of compiling it. In this case, the 907 // queued_for_compile bits must be set in the method (and these 908 // will be visible to the current thread, since the bits were set 909 // under protection of the compile queue lock, which we hold now. 910 // When the compilation completes, the compiler thread first sets 911 // the compilation result and then clears the queued_for_compile 912 // bits. Neither of these actions are protected by a barrier (or done 913 // under the protection of a lock), so the only guarantee we have 914 // (on machines with TSO (Total Store Order)) is that these values 915 // will update in that order. As a result, the only combinations of 916 // these bits that the current thread will see are, in temporal order: 917 // <RESULT, QUEUE> : 918 // <0, 1> : in compile queue, but not yet compiled 919 // <1, 1> : compiled but queue bit not cleared 920 // <1, 0> : compiled and queue bit cleared 921 // Because we first check the queue bits then check the result bits, 922 // we are assured that we cannot introduce a duplicate task. 923 // Note that if we did the tests in the reverse order (i.e. check 924 // result then check queued bit), we could get the result bit before 925 // the compilation completed, and the queue bit after the compilation 926 // completed, and end up introducing a "duplicate" (redundant) task. 927 // In that case, the compiler thread should first check if a method 928 // has already been compiled before trying to compile it. 929 // NOTE: in the event that there are multiple compiler threads and 930 // there is de-optimization/recompilation, things will get hairy, 931 // and in that case it's best to protect both the testing (here) of 932 // these bits, and their updating (here and elsewhere) under a 933 // common lock. 934 task = create_compile_task(queue, 935 compile_id, method, 936 osr_bci, comp_level, 937 hot_method, hot_count, comment, 938 blocking); 939 } 940 941 if (blocking) { 942 wait_for_completion(task); 943 } 944 } 945 946 947 nmethod* CompileBroker::compile_method(methodHandle method, int osr_bci, 948 int comp_level, 949 methodHandle hot_method, int hot_count, 950 const char* comment, TRAPS) { 951 // make sure arguments make sense 952 assert(method->method_holder()->klass_part()->oop_is_instance(), "not an instance method"); 953 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range"); 954 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods"); 955 assert(!instanceKlass::cast(method->method_holder())->is_not_initialized(), "method holder must be initialized"); 956 957 if (!TieredCompilation) { 958 comp_level = CompLevel_highest_tier; 959 } 960 961 // return quickly if possible 962 963 // lock, make sure that the compilation 964 // isn't prohibited in a straightforward way. 965 966 if (compiler(comp_level) == NULL || compilation_is_prohibited(method, osr_bci, comp_level)) { 967 return NULL; 968 } 969 970 if (osr_bci == InvocationEntryBci) { 971 // standard compilation 972 nmethod* method_code = method->code(); 973 if (method_code != NULL) { 974 if (compilation_is_complete(method, osr_bci, comp_level)) { 975 return method_code; 976 } 977 } 978 if (method->is_not_compilable(comp_level)) return NULL; 979 980 if (UseCodeCacheFlushing) { 981 nmethod* saved = CodeCache::find_and_remove_saved_code(method()); 982 if (saved != NULL) { 983 method->set_code(method, saved); 984 return saved; 985 } 986 } 987 988 } else { 989 // osr compilation 990 #ifndef TIERED 991 // seems like an assert of dubious value 992 assert(comp_level == CompLevel_highest_tier, 993 "all OSR compiles are assumed to be at a single compilation lavel"); 994 #endif // TIERED 995 // We accept a higher level osr method 996 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false); 997 if (nm != NULL) return nm; 998 if (method->is_not_osr_compilable()) return NULL; 999 } 1000 1001 assert(!HAS_PENDING_EXCEPTION, "No exception should be present"); 1002 // some prerequisites that are compiler specific 1003 if (compiler(comp_level)->is_c2()) { 1004 method->constants()->resolve_string_constants(CHECK_0); 1005 // Resolve all classes seen in the signature of the method 1006 // we are compiling. 1007 methodOopDesc::load_signature_classes(method, CHECK_0); 1008 } 1009 1010 // If the method is native, do the lookup in the thread requesting 1011 // the compilation. Native lookups can load code, which is not 1012 // permitted during compilation. 1013 // 1014 // Note: A native method implies non-osr compilation which is 1015 // checked with an assertion at the entry of this method. 1016 if (method->is_native()) { 1017 bool in_base_library; 1018 address adr = NativeLookup::lookup(method, in_base_library, THREAD); 1019 if (HAS_PENDING_EXCEPTION) { 1020 // In case of an exception looking up the method, we just forget 1021 // about it. The interpreter will kick-in and throw the exception. 1022 method->set_not_compilable(); // implies is_not_osr_compilable() 1023 CLEAR_PENDING_EXCEPTION; 1024 return NULL; 1025 } 1026 assert(method->has_native_function(), "must have native code by now"); 1027 } 1028 1029 // RedefineClasses() has replaced this method; just return 1030 if (method->is_old()) { 1031 return NULL; 1032 } 1033 1034 // JVMTI -- post_compile_event requires jmethod_id() that may require 1035 // a lock the compiling thread can not acquire. Prefetch it here. 1036 if (JvmtiExport::should_post_compiled_method_load()) { 1037 method->jmethod_id(); 1038 } 1039 1040 // If the compiler is shut off due to code cache flushing or otherwise, 1041 // fail out now so blocking compiles dont hang the java thread 1042 if (!should_compile_new_jobs() || (UseCodeCacheFlushing && CodeCache::needs_flushing())) { 1043 CompilationPolicy::policy()->delay_compilation(method()); 1044 return NULL; 1045 } 1046 1047 // do the compilation 1048 if (method->is_native()) { 1049 if (!PreferInterpreterNativeStubs) { 1050 (void) AdapterHandlerLibrary::create_native_wrapper(method); 1051 } else { 1052 return NULL; 1053 } 1054 } else { 1055 compile_method_base(method, osr_bci, comp_level, hot_method, hot_count, comment, CHECK_0); 1056 } 1057 1058 // return requested nmethod 1059 // We accept a higher level osr method 1060 return osr_bci == InvocationEntryBci ? method->code() : method->lookup_osr_nmethod_for(osr_bci, comp_level, false); 1061 } 1062 1063 1064 // ------------------------------------------------------------------ 1065 // CompileBroker::compilation_is_complete 1066 // 1067 // See if compilation of this method is already complete. 1068 bool CompileBroker::compilation_is_complete(methodHandle method, 1069 int osr_bci, 1070 int comp_level) { 1071 bool is_osr = (osr_bci != standard_entry_bci); 1072 if (is_osr) { 1073 if (method->is_not_osr_compilable()) { 1074 return true; 1075 } else { 1076 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true); 1077 return (result != NULL); 1078 } 1079 } else { 1080 if (method->is_not_compilable(comp_level)) { 1081 return true; 1082 } else { 1083 nmethod* result = method->code(); 1084 if (result == NULL) return false; 1085 return comp_level == result->comp_level(); 1086 } 1087 } 1088 } 1089 1090 1091 // ------------------------------------------------------------------ 1092 // CompileBroker::compilation_is_in_queue 1093 // 1094 // See if this compilation is already requested. 1095 // 1096 // Implementation note: there is only a single "is in queue" bit 1097 // for each method. This means that the check below is overly 1098 // conservative in the sense that an osr compilation in the queue 1099 // will block a normal compilation from entering the queue (and vice 1100 // versa). This can be remedied by a full queue search to disambiguate 1101 // cases. If it is deemed profitible, this may be done. 1102 bool CompileBroker::compilation_is_in_queue(methodHandle method, 1103 int osr_bci) { 1104 return method->queued_for_compilation(); 1105 } 1106 1107 // ------------------------------------------------------------------ 1108 // CompileBroker::compilation_is_prohibited 1109 // 1110 // See if this compilation is not allowed. 1111 bool CompileBroker::compilation_is_prohibited(methodHandle method, int osr_bci, int comp_level) { 1112 bool is_native = method->is_native(); 1113 // Some compilers may not support the compilation of natives. 1114 if (is_native && 1115 (!CICompileNatives || !compiler(comp_level)->supports_native())) { 1116 method->set_not_compilable_quietly(comp_level); 1117 return true; 1118 } 1119 1120 bool is_osr = (osr_bci != standard_entry_bci); 1121 // Some compilers may not support on stack replacement. 1122 if (is_osr && 1123 (!CICompileOSR || !compiler(comp_level)->supports_osr())) { 1124 method->set_not_osr_compilable(); 1125 return true; 1126 } 1127 1128 // The method may be explicitly excluded by the user. 1129 bool quietly; 1130 if (CompilerOracle::should_exclude(method, quietly)) { 1131 if (!quietly) { 1132 // This does not happen quietly... 1133 ResourceMark rm; 1134 tty->print("### Excluding %s:%s", 1135 method->is_native() ? "generation of native wrapper" : "compile", 1136 (method->is_static() ? " static" : "")); 1137 method->print_short_name(tty); 1138 tty->cr(); 1139 } 1140 method->set_not_compilable_quietly(); 1141 } 1142 1143 return false; 1144 } 1145 1146 1147 // ------------------------------------------------------------------ 1148 // CompileBroker::assign_compile_id 1149 // 1150 // Assign a serialized id number to this compilation request. If the 1151 // number falls out of the allowed range, return a 0. OSR 1152 // compilations may be numbered separately from regular compilations 1153 // if certain debugging flags are used. 1154 uint CompileBroker::assign_compile_id(methodHandle method, int osr_bci) { 1155 assert(MethodCompileQueue_lock->owner() == Thread::current(), 1156 "must hold the compilation queue lock"); 1157 bool is_osr = (osr_bci != standard_entry_bci); 1158 assert(!method->is_native(), "no longer compile natives"); 1159 uint id; 1160 if (CICountOSR && is_osr) { 1161 id = ++_osr_compilation_id; 1162 if ((uint)CIStartOSR <= id && id < (uint)CIStopOSR) { 1163 return id; 1164 } 1165 } else { 1166 id = ++_compilation_id; 1167 if ((uint)CIStart <= id && id < (uint)CIStop) { 1168 return id; 1169 } 1170 } 1171 1172 // Method was not in the appropriate compilation range. 1173 method->set_not_compilable_quietly(); 1174 return 0; 1175 } 1176 1177 1178 // ------------------------------------------------------------------ 1179 // CompileBroker::is_compile_blocking 1180 // 1181 // Should the current thread be blocked until this compilation request 1182 // has been fulfilled? 1183 bool CompileBroker::is_compile_blocking(methodHandle method, int osr_bci) { 1184 return !BackgroundCompilation; 1185 } 1186 1187 1188 // ------------------------------------------------------------------ 1189 // CompileBroker::preload_classes 1190 void CompileBroker::preload_classes(methodHandle method, TRAPS) { 1191 // Move this code over from c1_Compiler.cpp 1192 ShouldNotReachHere(); 1193 } 1194 1195 1196 // ------------------------------------------------------------------ 1197 // CompileBroker::create_compile_task 1198 // 1199 // Create a CompileTask object representing the current request for 1200 // compilation. Add this task to the queue. 1201 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue, 1202 int compile_id, 1203 methodHandle method, 1204 int osr_bci, 1205 int comp_level, 1206 methodHandle hot_method, 1207 int hot_count, 1208 const char* comment, 1209 bool blocking) { 1210 CompileTask* new_task = allocate_task(); 1211 new_task->initialize(compile_id, method, osr_bci, comp_level, 1212 hot_method, hot_count, comment, 1213 blocking); 1214 queue->add(new_task); 1215 return new_task; 1216 } 1217 1218 1219 // ------------------------------------------------------------------ 1220 // CompileBroker::allocate_task 1221 // 1222 // Allocate a CompileTask, from the free list if possible. 1223 CompileTask* CompileBroker::allocate_task() { 1224 MutexLocker locker(CompileTaskAlloc_lock); 1225 CompileTask* task = NULL; 1226 if (_task_free_list != NULL) { 1227 task = _task_free_list; 1228 _task_free_list = task->next(); 1229 task->set_next(NULL); 1230 } else { 1231 task = new CompileTask(); 1232 task->set_next(NULL); 1233 } 1234 return task; 1235 } 1236 1237 1238 // ------------------------------------------------------------------ 1239 // CompileBroker::free_task 1240 // 1241 // Add a task to the free list. 1242 void CompileBroker::free_task(CompileTask* task) { 1243 MutexLocker locker(CompileTaskAlloc_lock); 1244 task->free(); 1245 task->set_next(_task_free_list); 1246 _task_free_list = task; 1247 } 1248 1249 1250 // ------------------------------------------------------------------ 1251 // CompileBroker::wait_for_completion 1252 // 1253 // Wait for the given method CompileTask to complete. 1254 void CompileBroker::wait_for_completion(CompileTask* task) { 1255 if (CIPrintCompileQueue) { 1256 tty->print_cr("BLOCKING FOR COMPILE"); 1257 } 1258 1259 assert(task->is_blocking(), "can only wait on blocking task"); 1260 1261 JavaThread *thread = JavaThread::current(); 1262 thread->set_blocked_on_compilation(true); 1263 1264 methodHandle method(thread, 1265 (methodOop)JNIHandles::resolve(task->method_handle())); 1266 { 1267 MutexLocker waiter(task->lock(), thread); 1268 1269 while (!task->is_complete()) 1270 task->lock()->wait(); 1271 } 1272 // It is harmless to check this status without the lock, because 1273 // completion is a stable property (until the task object is recycled). 1274 assert(task->is_complete(), "Compilation should have completed"); 1275 assert(task->code_handle() == NULL, "must be reset"); 1276 1277 thread->set_blocked_on_compilation(false); 1278 1279 // By convention, the waiter is responsible for recycling a 1280 // blocking CompileTask. Since there is only one waiter ever 1281 // waiting on a CompileTask, we know that no one else will 1282 // be using this CompileTask; we can free it. 1283 free_task(task); 1284 } 1285 1286 // ------------------------------------------------------------------ 1287 // CompileBroker::compiler_thread_loop 1288 // 1289 // The main loop run by a CompilerThread. 1290 void CompileBroker::compiler_thread_loop() { 1291 CompilerThread* thread = CompilerThread::current(); 1292 CompileQueue* queue = thread->queue(); 1293 1294 // For the thread that initializes the ciObjectFactory 1295 // this resource mark holds all the shared objects 1296 ResourceMark rm; 1297 1298 // First thread to get here will initialize the compiler interface 1299 1300 if (!ciObjectFactory::is_initialized()) { 1301 ASSERT_IN_VM; 1302 MutexLocker only_one (CompileThread_lock, thread); 1303 if (!ciObjectFactory::is_initialized()) { 1304 ciObjectFactory::initialize(); 1305 } 1306 } 1307 1308 // Open a log. 1309 if (LogCompilation) { 1310 init_compiler_thread_log(); 1311 } 1312 CompileLog* log = thread->log(); 1313 if (log != NULL) { 1314 log->begin_elem("start_compile_thread thread='" UINTX_FORMAT "' process='%d'", 1315 os::current_thread_id(), 1316 os::current_process_id()); 1317 log->stamp(); 1318 log->end_elem(); 1319 } 1320 1321 while (true) { 1322 { 1323 // We need this HandleMark to avoid leaking VM handles. 1324 HandleMark hm(thread); 1325 1326 if (CodeCache::unallocated_capacity() < CodeCacheMinimumFreeSpace) { 1327 // the code cache is really full 1328 handle_full_code_cache(); 1329 } else if (UseCodeCacheFlushing && CodeCache::needs_flushing()) { 1330 // Attempt to start cleaning the code cache while there is still a little headroom 1331 NMethodSweeper::handle_full_code_cache(false); 1332 } 1333 1334 CompileTask* task = queue->get(); 1335 1336 // Give compiler threads an extra quanta. They tend to be bursty and 1337 // this helps the compiler to finish up the job. 1338 if( CompilerThreadHintNoPreempt ) 1339 os::hint_no_preempt(); 1340 1341 // trace per thread time and compile statistics 1342 CompilerCounters* counters = ((CompilerThread*)thread)->counters(); 1343 PerfTraceTimedEvent(counters->time_counter(), counters->compile_counter()); 1344 1345 // Assign the task to the current thread. Mark this compilation 1346 // thread as active for the profiler. 1347 CompileTaskWrapper ctw(task); 1348 nmethodLocker result_handle; // (handle for the nmethod produced by this task) 1349 task->set_code_handle(&result_handle); 1350 methodHandle method(thread, 1351 (methodOop)JNIHandles::resolve(task->method_handle())); 1352 1353 // Never compile a method if breakpoints are present in it 1354 if (method()->number_of_breakpoints() == 0) { 1355 // Compile the method. 1356 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) { 1357 #ifdef COMPILER1 1358 // Allow repeating compilations for the purpose of benchmarking 1359 // compile speed. This is not useful for customers. 1360 if (CompilationRepeat != 0) { 1361 int compile_count = CompilationRepeat; 1362 while (compile_count > 0) { 1363 invoke_compiler_on_method(task); 1364 nmethod* nm = method->code(); 1365 if (nm != NULL) { 1366 nm->make_zombie(); 1367 method->clear_code(); 1368 } 1369 compile_count--; 1370 } 1371 } 1372 #endif /* COMPILER1 */ 1373 invoke_compiler_on_method(task); 1374 } else { 1375 // After compilation is disabled, remove remaining methods from queue 1376 method->clear_queued_for_compilation(); 1377 } 1378 } 1379 } 1380 } 1381 } 1382 1383 1384 // ------------------------------------------------------------------ 1385 // CompileBroker::init_compiler_thread_log 1386 // 1387 // Set up state required by +LogCompilation. 1388 void CompileBroker::init_compiler_thread_log() { 1389 CompilerThread* thread = CompilerThread::current(); 1390 char fileBuf[4*K]; 1391 FILE* fp = NULL; 1392 char* file = NULL; 1393 intx thread_id = os::current_thread_id(); 1394 for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) { 1395 const char* dir = (try_temp_dir ? os::get_temp_directory() : NULL); 1396 if (dir == NULL) { 1397 jio_snprintf(fileBuf, sizeof(fileBuf), "hs_c" UINTX_FORMAT "_pid%u.log", 1398 thread_id, os::current_process_id()); 1399 } else { 1400 jio_snprintf(fileBuf, sizeof(fileBuf), 1401 "%s%shs_c" UINTX_FORMAT "_pid%u.log", dir, 1402 os::file_separator(), thread_id, os::current_process_id()); 1403 } 1404 fp = fopen(fileBuf, "at"); 1405 if (fp != NULL) { 1406 file = NEW_C_HEAP_ARRAY(char, strlen(fileBuf)+1); 1407 strcpy(file, fileBuf); 1408 break; 1409 } 1410 } 1411 if (fp == NULL) { 1412 warning("Cannot open log file: %s", fileBuf); 1413 } else { 1414 if (LogCompilation && Verbose) 1415 tty->print_cr("Opening compilation log %s", file); 1416 CompileLog* log = new(ResourceObj::C_HEAP) CompileLog(file, fp, thread_id); 1417 thread->init_log(log); 1418 1419 if (xtty != NULL) { 1420 ttyLocker ttyl; 1421 1422 // Record any per thread log files 1423 xtty->elem("thread_logfile thread='%d' filename='%s'", thread_id, file); 1424 } 1425 } 1426 } 1427 1428 // ------------------------------------------------------------------ 1429 // CompileBroker::set_should_block 1430 // 1431 // Set _should_block. 1432 // Call this from the VM, with Threads_lock held and a safepoint requested. 1433 void CompileBroker::set_should_block() { 1434 assert(Threads_lock->owner() == Thread::current(), "must have threads lock"); 1435 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already"); 1436 #ifndef PRODUCT 1437 if (PrintCompilation && (Verbose || WizardMode)) 1438 tty->print_cr("notifying compiler thread pool to block"); 1439 #endif 1440 _should_block = true; 1441 } 1442 1443 // ------------------------------------------------------------------ 1444 // CompileBroker::maybe_block 1445 // 1446 // Call this from the compiler at convenient points, to poll for _should_block. 1447 void CompileBroker::maybe_block() { 1448 if (_should_block) { 1449 #ifndef PRODUCT 1450 if (PrintCompilation && (Verbose || WizardMode)) 1451 tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", Thread::current()); 1452 #endif 1453 ThreadInVMfromNative tivfn(JavaThread::current()); 1454 } 1455 } 1456 1457 1458 // ------------------------------------------------------------------ 1459 // CompileBroker::invoke_compiler_on_method 1460 // 1461 // Compile a method. 1462 // 1463 void CompileBroker::invoke_compiler_on_method(CompileTask* task) { 1464 if (PrintCompilation) { 1465 ResourceMark rm; 1466 task->print_line(); 1467 } 1468 elapsedTimer time; 1469 1470 CompilerThread* thread = CompilerThread::current(); 1471 ResourceMark rm(thread); 1472 1473 // Common flags. 1474 uint compile_id = task->compile_id(); 1475 int osr_bci = task->osr_bci(); 1476 bool is_osr = (osr_bci != standard_entry_bci); 1477 bool should_log = (thread->log() != NULL); 1478 bool should_break = false; 1479 { 1480 // create the handle inside it's own block so it can't 1481 // accidentally be referenced once the thread transitions to 1482 // native. The NoHandleMark before the transition should catch 1483 // any cases where this occurs in the future. 1484 methodHandle method(thread, 1485 (methodOop)JNIHandles::resolve(task->method_handle())); 1486 should_break = check_break_at(method, compile_id, is_osr); 1487 if (should_log && !CompilerOracle::should_log(method)) { 1488 should_log = false; 1489 } 1490 assert(!method->is_native(), "no longer compile natives"); 1491 1492 // Save information about this method in case of failure. 1493 set_last_compile(thread, method, is_osr, task->comp_level()); 1494 1495 DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler(task->comp_level()), method); 1496 } 1497 1498 // Allocate a new set of JNI handles. 1499 push_jni_handle_block(); 1500 jobject target_handle = JNIHandles::make_local(thread, JNIHandles::resolve(task->method_handle())); 1501 int compilable = ciEnv::MethodCompilable; 1502 { 1503 int system_dictionary_modification_counter; 1504 { 1505 MutexLocker locker(Compile_lock, thread); 1506 system_dictionary_modification_counter = SystemDictionary::number_of_modifications(); 1507 } 1508 1509 NoHandleMark nhm; 1510 ThreadToNativeFromVM ttn(thread); 1511 1512 ciEnv ci_env(task, system_dictionary_modification_counter); 1513 if (should_break) { 1514 ci_env.set_break_at_compile(true); 1515 } 1516 if (should_log) { 1517 ci_env.set_log(thread->log()); 1518 } 1519 assert(thread->env() == &ci_env, "set by ci_env"); 1520 // The thread-env() field is cleared in ~CompileTaskWrapper. 1521 1522 // Cache Jvmti state 1523 ci_env.cache_jvmti_state(); 1524 1525 // Cache DTrace flags 1526 ci_env.cache_dtrace_flags(); 1527 1528 ciMethod* target = ci_env.get_method_from_handle(target_handle); 1529 1530 TraceTime t1("compilation", &time); 1531 1532 compiler(task->comp_level())->compile_method(&ci_env, target, osr_bci); 1533 1534 if (!ci_env.failing() && task->code() == NULL) { 1535 //assert(false, "compiler should always document failure"); 1536 // The compiler elected, without comment, not to register a result. 1537 // Do not attempt further compilations of this method. 1538 ci_env.record_method_not_compilable("compile failed", !TieredCompilation); 1539 } 1540 1541 if (ci_env.failing()) { 1542 // Copy this bit to the enclosing block: 1543 compilable = ci_env.compilable(); 1544 if (PrintCompilation) { 1545 const char* reason = ci_env.failure_reason(); 1546 if (compilable == ciEnv::MethodCompilable_not_at_tier) { 1547 tty->print_cr("%3d COMPILE SKIPPED: %s (retry at different tier)", compile_id, reason); 1548 } else if (compilable == ciEnv::MethodCompilable_never) { 1549 tty->print_cr("%3d COMPILE SKIPPED: %s (not retryable)", compile_id, reason); 1550 } else if (compilable == ciEnv::MethodCompilable) { 1551 tty->print_cr("%3d COMPILE SKIPPED: %s", compile_id, reason); 1552 } 1553 } 1554 } else { 1555 task->mark_success(); 1556 task->set_num_inlined_bytecodes(ci_env.num_inlined_bytecodes()); 1557 } 1558 } 1559 pop_jni_handle_block(); 1560 1561 methodHandle method(thread, 1562 (methodOop)JNIHandles::resolve(task->method_handle())); 1563 1564 DTRACE_METHOD_COMPILE_END_PROBE(compiler(task->comp_level()), method, task->is_success()); 1565 1566 collect_statistics(thread, time, task); 1567 1568 if (compilable == ciEnv::MethodCompilable_never) { 1569 if (is_osr) { 1570 method->set_not_osr_compilable(); 1571 } else { 1572 method->set_not_compilable_quietly(); 1573 } 1574 } else if (compilable == ciEnv::MethodCompilable_not_at_tier) { 1575 method->set_not_compilable_quietly(task->comp_level()); 1576 } 1577 1578 // Note that the queued_for_compilation bits are cleared without 1579 // protection of a mutex. [They were set by the requester thread, 1580 // when adding the task to the complie queue -- at which time the 1581 // compile queue lock was held. Subsequently, we acquired the compile 1582 // queue lock to get this task off the compile queue; thus (to belabour 1583 // the point somewhat) our clearing of the bits must be occurring 1584 // only after the setting of the bits. See also 14012000 above. 1585 method->clear_queued_for_compilation(); 1586 1587 #ifdef ASSERT 1588 if (CollectedHeap::fired_fake_oom()) { 1589 // The current compile received a fake OOM during compilation so 1590 // go ahead and exit the VM since the test apparently succeeded 1591 tty->print_cr("*** Shutting down VM after successful fake OOM"); 1592 vm_exit(0); 1593 } 1594 #endif 1595 } 1596 1597 // ------------------------------------------------------------------ 1598 // CompileBroker::handle_full_code_cache 1599 // 1600 // The CodeCache is full. Print out warning and disable compilation or 1601 // try code cache cleaning so compilation can continue later. 1602 void CompileBroker::handle_full_code_cache() { 1603 UseInterpreter = true; 1604 if (UseCompiler || AlwaysCompileLoopMethods ) { 1605 if (xtty != NULL) { 1606 xtty->begin_elem("code_cache_full"); 1607 xtty->stamp(); 1608 xtty->end_elem(); 1609 } 1610 warning("CodeCache is full. Compiler has been disabled."); 1611 warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize="); 1612 #ifndef PRODUCT 1613 if (CompileTheWorld || ExitOnFullCodeCache) { 1614 before_exit(JavaThread::current()); 1615 exit_globals(); // will delete tty 1616 vm_direct_exit(CompileTheWorld ? 0 : 1); 1617 } 1618 #endif 1619 if (UseCodeCacheFlushing) { 1620 NMethodSweeper::handle_full_code_cache(true); 1621 } else { 1622 UseCompiler = false; 1623 AlwaysCompileLoopMethods = false; 1624 } 1625 } 1626 } 1627 1628 // ------------------------------------------------------------------ 1629 // CompileBroker::set_last_compile 1630 // 1631 // Record this compilation for debugging purposes. 1632 void CompileBroker::set_last_compile(CompilerThread* thread, methodHandle method, bool is_osr, int comp_level) { 1633 ResourceMark rm; 1634 char* method_name = method->name()->as_C_string(); 1635 strncpy(_last_method_compiled, method_name, CompileBroker::name_buffer_length); 1636 char current_method[CompilerCounters::cmname_buffer_length]; 1637 size_t maxLen = CompilerCounters::cmname_buffer_length; 1638 1639 if (UsePerfData) { 1640 const char* class_name = method->method_holder()->klass_part()->name()->as_C_string(); 1641 1642 size_t s1len = strlen(class_name); 1643 size_t s2len = strlen(method_name); 1644 1645 // check if we need to truncate the string 1646 if (s1len + s2len + 2 > maxLen) { 1647 1648 // the strategy is to lop off the leading characters of the 1649 // class name and the trailing characters of the method name. 1650 1651 if (s2len + 2 > maxLen) { 1652 // lop of the entire class name string, let snprintf handle 1653 // truncation of the method name. 1654 class_name += s1len; // null string 1655 } 1656 else { 1657 // lop off the extra characters from the front of the class name 1658 class_name += ((s1len + s2len + 2) - maxLen); 1659 } 1660 } 1661 1662 jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name); 1663 } 1664 1665 if (CICountOSR && is_osr) { 1666 _last_compile_type = osr_compile; 1667 } else { 1668 _last_compile_type = normal_compile; 1669 } 1670 _last_compile_level = comp_level; 1671 1672 if (UsePerfData) { 1673 CompilerCounters* counters = thread->counters(); 1674 counters->set_current_method(current_method); 1675 counters->set_compile_type((jlong)_last_compile_type); 1676 } 1677 } 1678 1679 1680 // ------------------------------------------------------------------ 1681 // CompileBroker::push_jni_handle_block 1682 // 1683 // Push on a new block of JNI handles. 1684 void CompileBroker::push_jni_handle_block() { 1685 JavaThread* thread = JavaThread::current(); 1686 1687 // Allocate a new block for JNI handles. 1688 // Inlined code from jni_PushLocalFrame() 1689 JNIHandleBlock* java_handles = thread->active_handles(); 1690 JNIHandleBlock* compile_handles = JNIHandleBlock::allocate_block(thread); 1691 assert(compile_handles != NULL && java_handles != NULL, "should not be NULL"); 1692 compile_handles->set_pop_frame_link(java_handles); // make sure java handles get gc'd. 1693 thread->set_active_handles(compile_handles); 1694 } 1695 1696 1697 // ------------------------------------------------------------------ 1698 // CompileBroker::pop_jni_handle_block 1699 // 1700 // Pop off the current block of JNI handles. 1701 void CompileBroker::pop_jni_handle_block() { 1702 JavaThread* thread = JavaThread::current(); 1703 1704 // Release our JNI handle block 1705 JNIHandleBlock* compile_handles = thread->active_handles(); 1706 JNIHandleBlock* java_handles = compile_handles->pop_frame_link(); 1707 thread->set_active_handles(java_handles); 1708 compile_handles->set_pop_frame_link(NULL); 1709 JNIHandleBlock::release_block(compile_handles, thread); // may block 1710 } 1711 1712 1713 // ------------------------------------------------------------------ 1714 // CompileBroker::check_break_at 1715 // 1716 // Should the compilation break at the current compilation. 1717 bool CompileBroker::check_break_at(methodHandle method, int compile_id, bool is_osr) { 1718 if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) { 1719 return true; 1720 } else if( CompilerOracle::should_break_at(method) ) { // break when compiling 1721 return true; 1722 } else { 1723 return (compile_id == CIBreakAt); 1724 } 1725 } 1726 1727 // ------------------------------------------------------------------ 1728 // CompileBroker::collect_statistics 1729 // 1730 // Collect statistics about the compilation. 1731 1732 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) { 1733 bool success = task->is_success(); 1734 methodHandle method (thread, (methodOop)JNIHandles::resolve(task->method_handle())); 1735 uint compile_id = task->compile_id(); 1736 bool is_osr = (task->osr_bci() != standard_entry_bci); 1737 nmethod* code = task->code(); 1738 CompilerCounters* counters = thread->counters(); 1739 1740 assert(code == NULL || code->is_locked_by_vm(), "will survive the MutexLocker"); 1741 MutexLocker locker(CompileStatistics_lock); 1742 1743 // _perf variables are production performance counters which are 1744 // updated regardless of the setting of the CITime and CITimeEach flags 1745 // 1746 if (!success) { 1747 _total_bailout_count++; 1748 if (UsePerfData) { 1749 _perf_last_failed_method->set_value(counters->current_method()); 1750 _perf_last_failed_type->set_value(counters->compile_type()); 1751 _perf_total_bailout_count->inc(); 1752 } 1753 } else if (code == NULL) { 1754 if (UsePerfData) { 1755 _perf_last_invalidated_method->set_value(counters->current_method()); 1756 _perf_last_invalidated_type->set_value(counters->compile_type()); 1757 _perf_total_invalidated_count->inc(); 1758 } 1759 _total_invalidated_count++; 1760 } else { 1761 // Compilation succeeded 1762 1763 // update compilation ticks - used by the implementation of 1764 // java.lang.management.CompilationMBean 1765 _perf_total_compilation->inc(time.ticks()); 1766 1767 if (CITime) { 1768 _t_total_compilation.add(time); 1769 if (is_osr) { 1770 _t_osr_compilation.add(time); 1771 _sum_osr_bytes_compiled += method->code_size() + task->num_inlined_bytecodes(); 1772 } else { 1773 _t_standard_compilation.add(time); 1774 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes(); 1775 } 1776 } 1777 1778 if (UsePerfData) { 1779 // save the name of the last method compiled 1780 _perf_last_method->set_value(counters->current_method()); 1781 _perf_last_compile_type->set_value(counters->compile_type()); 1782 _perf_last_compile_size->set_value(method->code_size() + 1783 task->num_inlined_bytecodes()); 1784 if (is_osr) { 1785 _perf_osr_compilation->inc(time.ticks()); 1786 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes()); 1787 } else { 1788 _perf_standard_compilation->inc(time.ticks()); 1789 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes()); 1790 } 1791 } 1792 1793 if (CITimeEach) { 1794 float bytes_per_sec = 1.0 * (method->code_size() + task->num_inlined_bytecodes()) / time.seconds(); 1795 tty->print_cr("%3d seconds: %f bytes/sec : %f (bytes %d + %d inlined)", 1796 compile_id, time.seconds(), bytes_per_sec, method->code_size(), task->num_inlined_bytecodes()); 1797 } 1798 1799 // Collect counts of successful compilations 1800 _sum_nmethod_size += code->total_size(); 1801 _sum_nmethod_code_size += code->insts_size(); 1802 _total_compile_count++; 1803 1804 if (UsePerfData) { 1805 _perf_sum_nmethod_size->inc( code->total_size()); 1806 _perf_sum_nmethod_code_size->inc(code->insts_size()); 1807 _perf_total_compile_count->inc(); 1808 } 1809 1810 if (is_osr) { 1811 if (UsePerfData) _perf_total_osr_compile_count->inc(); 1812 _total_osr_compile_count++; 1813 } else { 1814 if (UsePerfData) _perf_total_standard_compile_count->inc(); 1815 _total_standard_compile_count++; 1816 } 1817 } 1818 // set the current method for the thread to null 1819 if (UsePerfData) counters->set_current_method(""); 1820 } 1821 1822 1823 1824 void CompileBroker::print_times() { 1825 tty->cr(); 1826 tty->print_cr("Accumulated compiler times (for compiled methods only)"); 1827 tty->print_cr("------------------------------------------------"); 1828 //0000000000111111111122222222223333333333444444444455555555556666666666 1829 //0123456789012345678901234567890123456789012345678901234567890123456789 1830 tty->print_cr(" Total compilation time : %6.3f s", CompileBroker::_t_total_compilation.seconds()); 1831 tty->print_cr(" Standard compilation : %6.3f s, Average : %2.3f", 1832 CompileBroker::_t_standard_compilation.seconds(), 1833 CompileBroker::_t_standard_compilation.seconds() / CompileBroker::_total_standard_compile_count); 1834 tty->print_cr(" On stack replacement : %6.3f s, Average : %2.3f", CompileBroker::_t_osr_compilation.seconds(), CompileBroker::_t_osr_compilation.seconds() / CompileBroker::_total_osr_compile_count); 1835 1836 if (compiler(CompLevel_simple) != NULL) { 1837 compiler(CompLevel_simple)->print_timers(); 1838 } 1839 if (compiler(CompLevel_full_optimization) != NULL) { 1840 compiler(CompLevel_full_optimization)->print_timers(); 1841 } 1842 tty->cr(); 1843 int tcb = CompileBroker::_sum_osr_bytes_compiled + CompileBroker::_sum_standard_bytes_compiled; 1844 tty->print_cr(" Total compiled bytecodes : %6d bytes", tcb); 1845 tty->print_cr(" Standard compilation : %6d bytes", CompileBroker::_sum_standard_bytes_compiled); 1846 tty->print_cr(" On stack replacement : %6d bytes", CompileBroker::_sum_osr_bytes_compiled); 1847 int bps = (int)(tcb / CompileBroker::_t_total_compilation.seconds()); 1848 tty->print_cr(" Average compilation speed: %6d bytes/s", bps); 1849 tty->cr(); 1850 tty->print_cr(" nmethod code size : %6d bytes", CompileBroker::_sum_nmethod_code_size); 1851 tty->print_cr(" nmethod total size : %6d bytes", CompileBroker::_sum_nmethod_size); 1852 } 1853 1854 1855 // Debugging output for failure 1856 void CompileBroker::print_last_compile() { 1857 if ( _last_compile_level != CompLevel_none && 1858 compiler(_last_compile_level) != NULL && 1859 _last_method_compiled != NULL && 1860 _last_compile_type != no_compile) { 1861 if (_last_compile_type == osr_compile) { 1862 tty->print_cr("Last parse: [osr]%d+++(%d) %s", 1863 _osr_compilation_id, _last_compile_level, _last_method_compiled); 1864 } else { 1865 tty->print_cr("Last parse: %d+++(%d) %s", 1866 _compilation_id, _last_compile_level, _last_method_compiled); 1867 } 1868 } 1869 } 1870 1871 1872 void CompileBroker::print_compiler_threads_on(outputStream* st) { 1873 #ifndef PRODUCT 1874 st->print_cr("Compiler thread printing unimplemented."); 1875 st->cr(); 1876 #endif 1877 }