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