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