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