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