comparison src/share/vm/compiler/compileBroker.cpp @ 0:a61af66fc99e jdk7-b24

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