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 "cds/cdsConfig.hpp"
26 #include "classfile/javaClasses.inline.hpp"
27 #include "classfile/symbolTable.hpp"
28 #include "classfile/vmClasses.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "code/codeCache.hpp"
31 #include "code/codeHeapState.hpp"
32 #include "code/dependencyContext.hpp"
33 #include "compiler/compilationLog.hpp"
34 #include "compiler/compilationMemoryStatistic.hpp"
35 #include "compiler/compilationPolicy.hpp"
36 #include "compiler/compileBroker.hpp"
37 #include "compiler/compileLog.hpp"
38 #include "compiler/compilerEvent.hpp"
39 #include "compiler/compilerOracle.hpp"
40 #include "compiler/directivesParser.hpp"
41 #include "gc/shared/memAllocator.hpp"
42 #include "interpreter/linkResolver.hpp"
43 #include "jfr/jfrEvents.hpp"
44 #include "jvm.h"
45 #include "logging/log.hpp"
46 #include "logging/logStream.hpp"
47 #include "memory/allocation.inline.hpp"
48 #include "memory/resourceArea.hpp"
49 #include "memory/universe.hpp"
50 #include "oops/method.inline.hpp"
51 #include "oops/methodData.hpp"
52 #include "oops/oop.inline.hpp"
53 #include "prims/jvmtiExport.hpp"
54 #include "prims/nativeLookup.hpp"
55 #include "prims/whitebox.hpp"
56 #include "runtime/atomic.hpp"
57 #include "runtime/escapeBarrier.hpp"
58 #include "runtime/globals_extension.hpp"
59 #include "runtime/handles.inline.hpp"
60 #include "runtime/init.hpp"
61 #include "runtime/interfaceSupport.inline.hpp"
62 #include "runtime/java.hpp"
63 #include "runtime/javaCalls.hpp"
64 #include "runtime/jniHandles.inline.hpp"
65 #include "runtime/os.hpp"
66 #include "runtime/perfData.hpp"
67 #include "runtime/safepointVerifiers.hpp"
68 #include "runtime/sharedRuntime.hpp"
69 #include "runtime/threads.hpp"
70 #include "runtime/threadSMR.hpp"
71 #include "runtime/timerTrace.hpp"
72 #include "runtime/vframe.inline.hpp"
73 #include "utilities/debug.hpp"
74 #include "utilities/dtrace.hpp"
75 #include "utilities/events.hpp"
76 #include "utilities/formatBuffer.hpp"
77 #include "utilities/macros.hpp"
78 #ifdef COMPILER1
79 #include "c1/c1_Compiler.hpp"
80 #endif
81 #ifdef COMPILER2
82 #include "opto/c2compiler.hpp"
83 #endif
84 #if INCLUDE_JVMCI
85 #include "jvmci/jvmciEnv.hpp"
86 #include "jvmci/jvmciRuntime.hpp"
87 #endif
88
89 #ifdef DTRACE_ENABLED
90
91 // Only bother with this argument setup if dtrace is available
92
93 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) \
94 { \
95 Symbol* klass_name = (method)->klass_name(); \
96 Symbol* name = (method)->name(); \
97 Symbol* signature = (method)->signature(); \
110 HOTSPOT_METHOD_COMPILE_END( \
111 (char *) comp_name, strlen(comp_name), \
112 (char *) klass_name->bytes(), klass_name->utf8_length(), \
113 (char *) name->bytes(), name->utf8_length(), \
114 (char *) signature->bytes(), signature->utf8_length(), (success)); \
115 }
116
117 #else // ndef DTRACE_ENABLED
118
119 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
120 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
121
122 #endif // ndef DTRACE_ENABLED
123
124 bool CompileBroker::_initialized = false;
125 volatile bool CompileBroker::_should_block = false;
126 volatile int CompileBroker::_print_compilation_warning = 0;
127 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
128
129 // The installed compiler(s)
130 AbstractCompiler* CompileBroker::_compilers[2];
131
132 // The maximum numbers of compiler threads to be determined during startup.
133 int CompileBroker::_c1_count = 0;
134 int CompileBroker::_c2_count = 0;
135
136 // An array of compiler names as Java String objects
137 jobject* CompileBroker::_compiler1_objects = nullptr;
138 jobject* CompileBroker::_compiler2_objects = nullptr;
139
140 CompileLog** CompileBroker::_compiler1_logs = nullptr;
141 CompileLog** CompileBroker::_compiler2_logs = nullptr;
142
143 // These counters are used to assign an unique ID to each compilation.
144 volatile jint CompileBroker::_compilation_id = 0;
145 volatile jint CompileBroker::_osr_compilation_id = 0;
146 volatile jint CompileBroker::_native_compilation_id = 0;
147
148 // Performance counters
149 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
150 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
151 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
152
153 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
154 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
155 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
156 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
157 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
158
159 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
160 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
161 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
162 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
163
164 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
165 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
166 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
167 PerfVariable* CompileBroker::_perf_last_compile_type = nullptr;
168 PerfVariable* CompileBroker::_perf_last_compile_size = nullptr;
169 PerfVariable* CompileBroker::_perf_last_failed_type = nullptr;
170 PerfVariable* CompileBroker::_perf_last_invalidated_type = nullptr;
171
172 // Timers and counters for generating statistics
173 elapsedTimer CompileBroker::_t_total_compilation;
174 elapsedTimer CompileBroker::_t_osr_compilation;
175 elapsedTimer CompileBroker::_t_standard_compilation;
176 elapsedTimer CompileBroker::_t_invalidated_compilation;
177 elapsedTimer CompileBroker::_t_bailedout_compilation;
178
179 uint CompileBroker::_total_bailout_count = 0;
180 uint CompileBroker::_total_invalidated_count = 0;
181 uint CompileBroker::_total_compile_count = 0;
182 uint CompileBroker::_total_osr_compile_count = 0;
183 uint CompileBroker::_total_standard_compile_count = 0;
184 uint CompileBroker::_total_compiler_stopped_count = 0;
185 uint CompileBroker::_total_compiler_restarted_count = 0;
186
187 uint CompileBroker::_sum_osr_bytes_compiled = 0;
188 uint CompileBroker::_sum_standard_bytes_compiled = 0;
189 uint CompileBroker::_sum_nmethod_size = 0;
190 uint CompileBroker::_sum_nmethod_code_size = 0;
191
192 jlong CompileBroker::_peak_compilation_time = 0;
193
194 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
195
196 CompileQueue* CompileBroker::_c2_compile_queue = nullptr;
197 CompileQueue* CompileBroker::_c1_compile_queue = nullptr;
198
199 bool compileBroker_init() {
200 if (LogEvents) {
201 CompilationLog::init();
202 }
203
204 // init directives stack, adding default directive
205 DirectivesStack::init();
206
207 if (DirectivesParser::has_file()) {
208 return DirectivesParser::parse_from_flag();
209 } else if (CompilerDirectivesPrint) {
210 // Print default directive even when no other was added
211 DirectivesStack::print(tty);
212 }
213
214 return true;
215 }
216
217 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
218 CompilerThread* thread = CompilerThread::current();
219 thread->set_task(task);
220 CompileLog* log = thread->log();
221 if (log != nullptr && !task->is_unloaded()) task->log_task_start(log);
222 }
223
224 CompileTaskWrapper::~CompileTaskWrapper() {
225 CompilerThread* thread = CompilerThread::current();
226 CompileTask* task = thread->task();
227 CompileLog* log = thread->log();
228 if (log != nullptr && !task->is_unloaded()) task->log_task_done(log);
229 thread->set_task(nullptr);
230 thread->set_env(nullptr);
231 if (task->is_blocking()) {
232 bool free_task = false;
233 {
234 MutexLocker notifier(thread, task->lock());
235 task->mark_complete();
236 #if INCLUDE_JVMCI
237 if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {
238 if (!task->has_waiter()) {
239 // The waiting thread timed out and thus did not free the task.
240 free_task = true;
241 }
242 task->set_blocking_jvmci_compile_state(nullptr);
243 }
244 #endif
245 if (!free_task) {
246 // Notify the waiting thread that the compilation has completed
247 // so that it can free the task.
248 task->lock()->notify_all();
249 }
250 }
251 if (free_task) {
252 // The task can only be freed once the task lock is released.
253 CompileTask::free(task);
254 }
255 } else {
256 task->mark_complete();
257
258 // By convention, the compiling thread is responsible for
259 // recycling a non-blocking CompileTask.
260 CompileTask::free(task);
261 }
262 }
263
264 /**
265 * Check if a CompilerThread can be removed and update count if requested.
266 */
267 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
268 assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
269 if (!ReduceNumberOfCompilerThreads) return false;
270
271 AbstractCompiler *compiler = ct->compiler();
272 int compiler_count = compiler->num_compiler_threads();
273 bool c1 = compiler->is_c1();
274
275 // Keep at least 1 compiler thread of each type.
276 if (compiler_count < 2) return false;
277
278 // Keep thread alive for at least some time.
279 if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
280
281 #if INCLUDE_JVMCI
282 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
283 // Handles for JVMCI thread objects may get released concurrently.
284 if (do_it) {
285 assert(CompileThread_lock->owner() == ct, "must be holding lock");
286 } else {
287 // Skip check if it's the last thread and let caller check again.
288 return true;
289 }
290 }
297 if (do_it) {
298 assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
299 compiler->set_num_compiler_threads(compiler_count - 1);
300 #if INCLUDE_JVMCI
301 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
302 // Old j.l.Thread object can die when no longer referenced elsewhere.
303 JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
304 _compiler2_objects[compiler_count - 1] = nullptr;
305 }
306 #endif
307 }
308 return true;
309 }
310 return false;
311 }
312
313 /**
314 * Add a CompileTask to a CompileQueue.
315 */
316 void CompileQueue::add(CompileTask* task) {
317 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
318
319 task->set_next(nullptr);
320 task->set_prev(nullptr);
321
322 if (_last == nullptr) {
323 // The compile queue is empty.
324 assert(_first == nullptr, "queue is empty");
325 _first = task;
326 _last = task;
327 } else {
328 // Append the task to the queue.
329 assert(_last->next() == nullptr, "not last");
330 _last->set_next(task);
331 task->set_prev(_last);
332 _last = task;
333 }
334 ++_size;
335 ++_total_added;
336 if (_size > _peak_size) {
337 _peak_size = _size;
338 }
339
340 // Mark the method as being in the compile queue.
341 task->method()->set_queued_for_compilation();
342
343 if (CIPrintCompileQueue) {
344 print_tty();
345 }
346
347 if (LogCompilation && xtty != nullptr) {
348 task->log_task_queued();
349 }
350
351 if (TrainingData::need_data() && !CDSConfig::is_dumping_final_static_archive()) {
352 CompileTrainingData* ctd = CompileTrainingData::make(task);
353 if (ctd != nullptr) {
354 task->set_training_data(ctd);
355 }
356 }
357
358 // Notify CompilerThreads that a task is available.
359 MethodCompileQueue_lock->notify_all();
360 }
361
362 /**
363 * Empties compilation queue by putting all compilation tasks onto
364 * a freelist. Furthermore, the method wakes up all threads that are
365 * waiting on a compilation task to finish. This can happen if background
366 * compilation is disabled.
367 */
368 void CompileQueue::free_all() {
369 MutexLocker mu(MethodCompileQueue_lock);
370 CompileTask* next = _first;
371
372 // Iterate over all tasks in the compile queue
373 while (next != nullptr) {
374 CompileTask* current = next;
375 next = current->next();
376 bool found_waiter = false;
377 {
378 MutexLocker ct_lock(current->lock());
379 assert(current->waiting_for_completion_count() <= 1, "more than one thread are waiting for task");
380 if (current->waiting_for_completion_count() > 0) {
381 // If another thread waits for this task, we must wake them up
382 // so they will stop waiting and free the task.
383 current->lock()->notify();
384 found_waiter = true;
385 }
386 }
387 if (!found_waiter) {
388 // If no one was waiting for this task, we need to free it ourselves. In this case, the task
389 // is also certainly unlocked, because, again, there is no waiter.
390 // Otherwise, by convention, it's the waiters responsibility to free the task.
391 // Put the task back on the freelist.
392 CompileTask::free(current);
393 }
394 }
395 _first = nullptr;
396 _last = nullptr;
397
398 // Wake up all threads that block on the queue.
399 MethodCompileQueue_lock->notify_all();
400 }
401
402 /**
403 * Get the next CompileTask from a CompileQueue
404 */
405 CompileTask* CompileQueue::get(CompilerThread* thread) {
406 // save methods from RedefineClasses across safepoint
407 // across MethodCompileQueue_lock below.
408 methodHandle save_method;
409
410 MonitorLocker locker(MethodCompileQueue_lock);
411 // If _first is null we have no more compile jobs. There are two reasons for
412 // having no compile jobs: First, we compiled everything we wanted. Second,
413 // we ran out of code cache so compilation has been disabled. In the latter
414 // case we perform code cache sweeps to free memory such that we can re-enable
415 // compilation.
416 while (_first == nullptr) {
417 // Exit loop if compilation is disabled forever
418 if (CompileBroker::is_compilation_disabled_forever()) {
419 return nullptr;
420 }
421
422 AbstractCompiler* compiler = thread->compiler();
423 guarantee(compiler != nullptr, "Compiler object must exist");
424 compiler->on_empty_queue(this, thread);
425 if (_first != nullptr) {
426 // The call to on_empty_queue may have temporarily unlocked the MCQ lock
427 // so check again whether any tasks were added to the queue.
428 break;
429 }
430
431 // If there are no compilation tasks and we can compile new jobs
432 // (i.e., there is enough free space in the code cache) there is
433 // no need to invoke the GC.
434 // We need a timed wait here, since compiler threads can exit if compilation
435 // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
436 // is not critical and we do not want idle compiler threads to wake up too often.
437 locker.wait(5*1000);
438
439 if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
440 // Still nothing to compile. Give caller a chance to stop this thread.
441 if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
442 }
443 }
444
445 if (CompileBroker::is_compilation_disabled_forever()) {
446 return nullptr;
447 }
448
449 CompileTask* task;
450 {
451 NoSafepointVerifier nsv;
452 task = CompilationPolicy::select_task(this, thread);
453 if (task != nullptr) {
454 task = task->select_for_compilation();
455 }
456 }
457
458 if (task != nullptr) {
459 // Save method pointers across unlock safepoint. The task is removed from
460 // the compilation queue, which is walked during RedefineClasses.
461 Thread* thread = Thread::current();
462 save_method = methodHandle(thread, task->method());
463
464 remove(task);
465 }
466 purge_stale_tasks(); // may temporarily release MCQ lock
467 return task;
468 }
469
470 // Clean & deallocate stale compile tasks.
471 // Temporarily releases MethodCompileQueue lock.
472 void CompileQueue::purge_stale_tasks() {
473 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
474 if (_first_stale != nullptr) {
475 // Stale tasks are purged when MCQ lock is released,
476 // but _first_stale updates are protected by MCQ lock.
477 // Once task processing starts and MCQ lock is released,
478 // other compiler threads can reuse _first_stale.
479 CompileTask* head = _first_stale;
480 _first_stale = nullptr;
481 {
482 MutexUnlocker ul(MethodCompileQueue_lock);
483 for (CompileTask* task = head; task != nullptr; ) {
484 CompileTask* next_task = task->next();
485 CompileTaskWrapper ctw(task); // Frees the task
486 task->set_failure_reason("stale task");
487 task = next_task;
488 }
489 }
490 }
491 }
492
493 void CompileQueue::remove(CompileTask* task) {
494 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
495 if (task->prev() != nullptr) {
496 task->prev()->set_next(task->next());
497 } else {
498 // max is the first element
499 assert(task == _first, "Sanity");
500 _first = task->next();
501 }
502
503 if (task->next() != nullptr) {
504 task->next()->set_prev(task->prev());
505 } else {
506 // max is the last element
507 assert(task == _last, "Sanity");
508 _last = task->prev();
509 }
510 --_size;
511 ++_total_removed;
512 }
513
514 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
515 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
516 remove(task);
517
518 // Enqueue the task for reclamation (should be done outside MCQ lock)
519 task->set_next(_first_stale);
520 task->set_prev(nullptr);
521 _first_stale = task;
522 }
523
524 // methods in the compile queue need to be marked as used on the stack
525 // so that they don't get reclaimed by Redefine Classes
526 void CompileQueue::mark_on_stack() {
527 CompileTask* task = _first;
528 while (task != nullptr) {
529 task->mark_on_stack();
530 task = task->next();
531 }
532 }
533
534
535 CompileQueue* CompileBroker::compile_queue(int comp_level) {
536 if (is_c2_compile(comp_level)) return _c2_compile_queue;
537 if (is_c1_compile(comp_level)) return _c1_compile_queue;
538 return nullptr;
539 }
540
541 CompileQueue* CompileBroker::c1_compile_queue() {
542 return _c1_compile_queue;
543 }
544
545 CompileQueue* CompileBroker::c2_compile_queue() {
546 return _c2_compile_queue;
547 }
548
549 void CompileBroker::print_compile_queues(outputStream* st) {
550 st->print_cr("Current compiles: ");
551
552 char buf[2000];
553 int buflen = sizeof(buf);
554 Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
555
556 st->cr();
557 if (_c1_compile_queue != nullptr) {
558 _c1_compile_queue->print(st);
559 }
560 if (_c2_compile_queue != nullptr) {
561 _c2_compile_queue->print(st);
562 }
563 }
564
565 void CompileQueue::print(outputStream* st) {
566 assert_locked_or_safepoint(MethodCompileQueue_lock);
567 st->print_cr("%s:", name());
568 CompileTask* task = _first;
569 if (task == nullptr) {
570 st->print_cr("Empty");
571 } else {
572 while (task != nullptr) {
573 task->print(st, nullptr, true, true);
574 task = task->next();
575 }
576 }
577 st->cr();
578 }
579
580 void CompileQueue::print_tty() {
581 stringStream ss;
582 // Dump the compile queue into a buffer before locking the tty
583 print(&ss);
584 {
585 ttyLocker ttyl;
586 tty->print("%s", ss.freeze());
613 CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
614 }
615 first_registration = false;
616 #endif // COMPILER2
617 }
618 }
619 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
620
621 // ------------------------------------------------------------------
622 // CompileBroker::compilation_init
623 //
624 // Initialize the Compilation object
625 void CompileBroker::compilation_init(JavaThread* THREAD) {
626 // No need to initialize compilation system if we do not use it.
627 if (!UseCompiler) {
628 return;
629 }
630 // Set the interface to the current compiler(s).
631 _c1_count = CompilationPolicy::c1_count();
632 _c2_count = CompilationPolicy::c2_count();
633
634 #if INCLUDE_JVMCI
635 if (EnableJVMCI) {
636 // This is creating a JVMCICompiler singleton.
637 JVMCICompiler* jvmci = new JVMCICompiler();
638
639 if (UseJVMCICompiler) {
640 _compilers[1] = jvmci;
641 if (FLAG_IS_DEFAULT(JVMCIThreads)) {
642 if (BootstrapJVMCI) {
643 // JVMCI will bootstrap so give it more threads
644 _c2_count = MIN2(32, os::active_processor_count());
645 }
646 } else {
647 _c2_count = JVMCIThreads;
648 }
649 if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
650 } else {
651 #ifdef COMPILER1
652 _c1_count = JVMCIHostThreads;
653 #endif // COMPILER1
654 }
655 }
656 }
657 #endif // INCLUDE_JVMCI
658
659 #ifdef COMPILER1
660 if (_c1_count > 0) {
661 _compilers[0] = new Compiler();
662 }
663 #endif // COMPILER1
664
665 #ifdef COMPILER2
666 if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
667 if (_c2_count > 0) {
668 _compilers[1] = new C2Compiler();
669 // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
670 // idToPhase mapping for c2 is in opto/phasetype.hpp
671 JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
672 }
673 }
674 #endif // COMPILER2
769 _perf_last_compile_size =
770 PerfDataManager::create_variable(SUN_CI, "lastSize",
771 PerfData::U_Bytes,
772 (jlong)CompileBroker::no_compile,
773 CHECK);
774
775
776 _perf_last_failed_type =
777 PerfDataManager::create_variable(SUN_CI, "lastFailedType",
778 PerfData::U_None,
779 (jlong)CompileBroker::no_compile,
780 CHECK);
781
782 _perf_last_invalidated_type =
783 PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
784 PerfData::U_None,
785 (jlong)CompileBroker::no_compile,
786 CHECK);
787 }
788
789 _initialized = true;
790 }
791
792 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
793 CompilationPolicy::replay_training_at_init_loop(thread);
794 }
795
796 #if defined(ASSERT) && COMPILER2_OR_JVMCI
797 // Entry for DeoptimizeObjectsALotThread. The threads are started in
798 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
799 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
800 DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
801 bool enter_single_loop;
802 {
803 MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
804 static int single_thread_count = 0;
805 enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
806 }
807 if (enter_single_loop) {
808 dt->deoptimize_objects_alot_loop_single();
809 } else {
810 dt->deoptimize_objects_alot_loop_all();
811 }
935 }
936
937 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
938 char name_buffer[256];
939 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
940 Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
941 return JNIHandles::make_global(thread_oop);
942 }
943
944 static void print_compiler_threads(stringStream& msg) {
945 if (TraceCompilerThreads) {
946 tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
947 }
948 LogTarget(Debug, jit, thread) lt;
949 if (lt.is_enabled()) {
950 LogStream ls(lt);
951 ls.print_cr("%s", msg.as_string());
952 }
953 }
954
955 void CompileBroker::init_compiler_threads() {
956 // Ensure any exceptions lead to vm_exit_during_initialization.
957 EXCEPTION_MARK;
958 #if !defined(ZERO)
959 assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
960 #endif // !ZERO
961 // Initialize the compilation queue
962 if (_c2_count > 0) {
963 const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
964 _c2_compile_queue = new CompileQueue(name);
965 _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
966 _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
967 }
968 if (_c1_count > 0) {
969 _c1_compile_queue = new CompileQueue("C1 compile queue");
970 _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
971 _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
972 }
973
974 for (int i = 0; i < _c2_count; i++) {
975 // Create a name for our thread.
976 jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
977 _compiler2_objects[i] = thread_handle;
978 _compiler2_logs[i] = nullptr;
979
980 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
981 JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
982 assert(ct != nullptr, "should have been handled for initial thread");
983 _compilers[1]->set_num_compiler_threads(i + 1);
984 if (trace_compiler_threads()) {
985 ResourceMark rm;
986 ThreadsListHandle tlh; // name() depends on the TLH.
987 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
988 stringStream msg;
989 msg.print("Added initial compiler thread %s", ct->name());
990 print_compiler_threads(msg);
991 }
992 }
993 }
994
995 for (int i = 0; i < _c1_count; i++) {
996 // Create a name for our thread.
997 jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
998 _compiler1_objects[i] = thread_handle;
999 _compiler1_logs[i] = nullptr;
1000
1001 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1002 JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1003 assert(ct != nullptr, "should have been handled for initial thread");
1004 _compilers[0]->set_num_compiler_threads(i + 1);
1005 if (trace_compiler_threads()) {
1006 ResourceMark rm;
1007 ThreadsListHandle tlh; // name() depends on the TLH.
1008 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1009 stringStream msg;
1010 msg.print("Added initial compiler thread %s", ct->name());
1011 print_compiler_threads(msg);
1012 }
1013 }
1014 }
1015
1016 if (UsePerfData) {
1017 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);
1018 }
1019
1020 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1021 if (DeoptimizeObjectsALot) {
1022 // Initialize and start the object deoptimizer threads
1023 const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1024 for (int count = 0; count < total_count; count++) {
1025 Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1026 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1027 make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1028 }
1029 }
1030 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1031 }
1032
1033 void CompileBroker::init_training_replay() {
1034 // Ensure any exceptions lead to vm_exit_during_initialization.
1035 EXCEPTION_MARK;
1036 if (TrainingData::have_data()) {
1037 Handle thread_oop = JavaThread::create_system_thread_object("Training replay thread", CHECK);
1038 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1039 make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1040 }
1041 }
1042
1043 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1044
1045 int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1046 const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1047
1048 // Quick check if we already have enough compiler threads without taking the lock.
1049 // Numbers may change concurrently, so we read them again after we have the lock.
1050 if (_c2_compile_queue != nullptr) {
1051 old_c2_count = get_c2_thread_count();
1052 new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1053 }
1054 if (_c1_compile_queue != nullptr) {
1055 old_c1_count = get_c1_thread_count();
1056 new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1057 }
1145 stringStream msg;
1146 msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1147 ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1148 print_compiler_threads(msg);
1149 }
1150 }
1151 }
1152
1153 CompileThread_lock->unlock();
1154 }
1155
1156
1157 /**
1158 * Set the methods on the stack as on_stack so that redefine classes doesn't
1159 * reclaim them. This method is executed at a safepoint.
1160 */
1161 void CompileBroker::mark_on_stack() {
1162 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1163 // Since we are at a safepoint, we do not need a lock to access
1164 // the compile queues.
1165 if (_c2_compile_queue != nullptr) {
1166 _c2_compile_queue->mark_on_stack();
1167 }
1168 if (_c1_compile_queue != nullptr) {
1169 _c1_compile_queue->mark_on_stack();
1170 }
1171 }
1172
1173 // ------------------------------------------------------------------
1174 // CompileBroker::compile_method
1175 //
1176 // Request compilation of a method.
1177 void CompileBroker::compile_method_base(const methodHandle& method,
1178 int osr_bci,
1179 int comp_level,
1180 int hot_count,
1181 CompileTask::CompileReason compile_reason,
1182 bool blocking,
1183 Thread* thread) {
1184 guarantee(!method->is_abstract(), "cannot compile abstract methods");
1185 assert(method->method_holder()->is_instance_klass(),
1186 "sanity check");
1187 assert(!method->method_holder()->is_not_initialized(),
1188 "method holder must be initialized");
1189 assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1190
1191 if (CIPrintRequests) {
1192 tty->print("request: ");
1193 method->print_short_name(tty);
1194 if (osr_bci != InvocationEntryBci) {
1195 tty->print(" osr_bci: %d", osr_bci);
1196 }
1197 tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1198 if (hot_count > 0) {
1199 tty->print(" hot: yes");
1200 }
1201 tty->cr();
1202 }
1203
1204 // A request has been made for compilation. Before we do any
1205 // real work, check to see if the method has been compiled
1206 // in the meantime with a definitive result.
1207 if (compilation_is_complete(method, osr_bci, comp_level)) {
1208 return;
1209 }
1210
1211 #ifndef PRODUCT
1212 if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1213 if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1214 // Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI.
1215 return;
1216 }
1217 }
1218 #endif
1219
1220 // If this method is already in the compile queue, then
1221 // we do not block the current thread.
1222 if (compilation_is_in_queue(method)) {
1223 // We may want to decay our counter a bit here to prevent
1224 // multiple denied requests for compilation. This is an
1225 // open compilation policy issue. Note: The other possibility,
1226 // in the case that this is a blocking compile request, is to have
1227 // all subsequent blocking requesters wait for completion of
1228 // ongoing compiles. Note that in this case we'll need a protocol
1229 // for freeing the associated compile tasks. [Or we could have
1230 // a single static monitor on which all these waiters sleep.]
1231 return;
1232 }
1233
1234 // Tiered policy requires MethodCounters to exist before adding a method to
1235 // the queue. Create if we don't have them yet.
1236 method->get_method_counters(thread);
1237
1238 // Outputs from the following MutexLocker block:
1239 CompileTask* task = nullptr;
1240 CompileQueue* queue = compile_queue(comp_level);
1241
1242 // Acquire our lock.
1243 {
1244 MutexLocker locker(thread, MethodCompileQueue_lock);
1245
1246 // Make sure the method has not slipped into the queues since
1247 // last we checked; note that those checks were "fast bail-outs".
1248 // Here we need to be more careful, see 14012000 below.
1249 if (compilation_is_in_queue(method)) {
1250 return;
1251 }
1252
1253 // We need to check again to see if the compilation has
1254 // completed. A previous compilation may have registered
1255 // some result.
1256 if (compilation_is_complete(method, osr_bci, comp_level)) {
1257 return;
1258 }
1259
1260 // We now know that this compilation is not pending, complete,
1261 // or prohibited. Assign a compile_id to this compilation
1262 // and check to see if it is in our [Start..Stop) range.
1263 int compile_id = assign_compile_id(method, osr_bci);
1264 if (compile_id == 0) {
1265 // The compilation falls outside the allowed range.
1266 return;
1267 }
1268
1269 #if INCLUDE_JVMCI
1270 if (UseJVMCICompiler && blocking) {
1271 // Don't allow blocking compiles for requests triggered by JVMCI.
1272 if (thread->is_Compiler_thread()) {
1273 blocking = false;
1274 }
1275
1276 // In libjvmci, JVMCI initialization should not deadlock with other threads
1326 // <RESULT, QUEUE> :
1327 // <0, 1> : in compile queue, but not yet compiled
1328 // <1, 1> : compiled but queue bit not cleared
1329 // <1, 0> : compiled and queue bit cleared
1330 // Because we first check the queue bits then check the result bits,
1331 // we are assured that we cannot introduce a duplicate task.
1332 // Note that if we did the tests in the reverse order (i.e. check
1333 // result then check queued bit), we could get the result bit before
1334 // the compilation completed, and the queue bit after the compilation
1335 // completed, and end up introducing a "duplicate" (redundant) task.
1336 // In that case, the compiler thread should first check if a method
1337 // has already been compiled before trying to compile it.
1338 // NOTE: in the event that there are multiple compiler threads and
1339 // there is de-optimization/recompilation, things will get hairy,
1340 // and in that case it's best to protect both the testing (here) of
1341 // these bits, and their updating (here and elsewhere) under a
1342 // common lock.
1343 task = create_compile_task(queue,
1344 compile_id, method,
1345 osr_bci, comp_level,
1346 hot_count, compile_reason,
1347 blocking);
1348 }
1349
1350 if (blocking) {
1351 wait_for_completion(task);
1352 }
1353 }
1354
1355 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1356 int comp_level,
1357 int hot_count,
1358 CompileTask::CompileReason compile_reason,
1359 TRAPS) {
1360 // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1361 if (!_initialized || comp_level == CompLevel_none) {
1362 return nullptr;
1363 }
1364
1365 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1366 assert(comp != nullptr, "Ensure we have a compiler");
1367
1368 #if INCLUDE_JVMCI
1369 if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1370 // JVMCI compilation is not yet initializable.
1371 return nullptr;
1372 }
1373 #endif
1374
1375 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1376 // CompileBroker::compile_method can trap and can have pending async exception.
1377 nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_count, compile_reason, directive, THREAD);
1378 DirectivesStack::release(directive);
1379 return nm;
1380 }
1381
1382 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1383 int comp_level,
1384 int hot_count,
1385 CompileTask::CompileReason compile_reason,
1386 DirectiveSet* directive,
1387 TRAPS) {
1388
1389 // make sure arguments make sense
1390 assert(method->method_holder()->is_instance_klass(), "not an instance method");
1391 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1392 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1393 assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");
1394 // return quickly if possible
1395
1396 // lock, make sure that the compilation
1397 // isn't prohibited in a straightforward way.
1398 AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1399 if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1400 return nullptr;
1401 }
1402
1403 if (osr_bci == InvocationEntryBci) {
1404 // standard compilation
1405 nmethod* method_code = method->code();
1406 if (method_code != nullptr) {
1407 if (compilation_is_complete(method, osr_bci, comp_level)) {
1408 return method_code;
1409 }
1410 }
1411 if (method->is_not_compilable(comp_level)) {
1412 return nullptr;
1413 }
1414 } else {
1415 // osr compilation
1416 // We accept a higher level osr method
1417 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1418 if (nm != nullptr) return nm;
1419 if (method->is_not_osr_compilable(comp_level)) return nullptr;
1420 }
1421
1422 assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1423 // some prerequisites that are compiler specific
1424 if (comp->is_c2() || comp->is_jvmci()) {
1425 InternalOOMEMark iom(THREAD);
1426 method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1427 // Resolve all classes seen in the signature of the method
1428 // we are compiling.
1429 Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1430 }
1431
1432 // If the method is native, do the lookup in the thread requesting
1433 // the compilation. Native lookups can load code, which is not
1434 // permitted during compilation.
1435 //
1436 // Note: A native method implies non-osr compilation which is
1437 // checked with an assertion at the entry of this method.
1438 if (method->is_native() && !method->is_method_handle_intrinsic()) {
1439 address adr = NativeLookup::lookup(method, THREAD);
1440 if (HAS_PENDING_EXCEPTION) {
1441 // In case of an exception looking up the method, we just forget
1442 // about it. The interpreter will kick-in and throw the exception.
1443 method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1444 CLEAR_PENDING_EXCEPTION;
1459 }
1460
1461 // do the compilation
1462 if (method->is_native()) {
1463 if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1464 // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1465 // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1466 //
1467 // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1468 // in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls.
1469 AdapterHandlerLibrary::create_native_wrapper(method);
1470 } else {
1471 return nullptr;
1472 }
1473 } else {
1474 // If the compiler is shut off due to code cache getting full
1475 // fail out now so blocking compiles dont hang the java thread
1476 if (!should_compile_new_jobs()) {
1477 return nullptr;
1478 }
1479 bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;
1480 compile_method_base(method, osr_bci, comp_level, hot_count, compile_reason, is_blocking, THREAD);
1481 }
1482
1483 // return requested nmethod
1484 // We accept a higher level osr method
1485 if (osr_bci == InvocationEntryBci) {
1486 return method->code();
1487 }
1488 return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1489 }
1490
1491
1492 // ------------------------------------------------------------------
1493 // CompileBroker::compilation_is_complete
1494 //
1495 // See if compilation of this method is already complete.
1496 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1497 int osr_bci,
1498 int comp_level) {
1499 bool is_osr = (osr_bci != standard_entry_bci);
1500 if (is_osr) {
1501 if (method->is_not_osr_compilable(comp_level)) {
1502 return true;
1503 } else {
1504 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1505 return (result != nullptr);
1506 }
1507 } else {
1508 if (method->is_not_compilable(comp_level)) {
1509 return true;
1510 } else {
1511 nmethod* result = method->code();
1512 if (result == nullptr) return false;
1513 return comp_level == result->comp_level();
1514 }
1515 }
1516 }
1517
1518
1519 /**
1520 * See if this compilation is already requested.
1521 *
1522 * Implementation note: there is only a single "is in queue" bit
1523 * for each method. This means that the check below is overly
1524 * conservative in the sense that an osr compilation in the queue
1525 * will block a normal compilation from entering the queue (and vice
1526 * versa). This can be remedied by a full queue search to disambiguate
1527 * cases. If it is deemed profitable, this may be done.
1528 */
1529 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1530 return method->queued_for_compilation();
1531 }
1532
1533 // ------------------------------------------------------------------
1593 if (CIStart <= id && id < CIStop) {
1594 return id;
1595 }
1596 }
1597
1598 // Method was not in the appropriate compilation range.
1599 method->set_not_compilable_quietly("Not in requested compile id range");
1600 return 0;
1601 #else
1602 // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1603 // only _compilation_id is incremented.
1604 return Atomic::add(&_compilation_id, 1);
1605 #endif
1606 }
1607
1608 // ------------------------------------------------------------------
1609 // CompileBroker::assign_compile_id_unlocked
1610 //
1611 // Public wrapper for assign_compile_id that acquires the needed locks
1612 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1613 MutexLocker locker(thread, MethodCompileQueue_lock);
1614 return assign_compile_id(method, osr_bci);
1615 }
1616
1617 // ------------------------------------------------------------------
1618 // CompileBroker::create_compile_task
1619 //
1620 // Create a CompileTask object representing the current request for
1621 // compilation. Add this task to the queue.
1622 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1623 int compile_id,
1624 const methodHandle& method,
1625 int osr_bci,
1626 int comp_level,
1627 int hot_count,
1628 CompileTask::CompileReason compile_reason,
1629 bool blocking) {
1630 CompileTask* new_task = CompileTask::allocate();
1631 new_task->initialize(compile_id, method, osr_bci, comp_level,
1632 hot_count, compile_reason,
1633 blocking);
1634 queue->add(new_task);
1635 return new_task;
1636 }
1637
1638 #if INCLUDE_JVMCI
1639 // The number of milliseconds to wait before checking if
1640 // JVMCI compilation has made progress.
1641 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1642
1643 // The number of JVMCI compilation progress checks that must fail
1644 // before unblocking a thread waiting for a blocking compilation.
1645 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1646
1647 /**
1648 * Waits for a JVMCI compiler to complete a given task. This thread
1649 * waits until either the task completes or it sees no JVMCI compilation
1650 * progress for N consecutive milliseconds where N is
1651 * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1652 * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1653 *
1654 * @return true if this thread needs to free/recycle the task
1733 }
1734
1735 if (free_task) {
1736 if (is_compilation_disabled_forever()) {
1737 CompileTask::free(task);
1738 return;
1739 }
1740
1741 // It is harmless to check this status without the lock, because
1742 // completion is a stable property (until the task object is recycled).
1743 assert(task->is_complete(), "Compilation should have completed");
1744
1745 // By convention, the waiter is responsible for recycling a
1746 // blocking CompileTask. Since there is only one waiter ever
1747 // waiting on a CompileTask, we know that no one else will
1748 // be using this CompileTask; we can free it.
1749 CompileTask::free(task);
1750 }
1751 }
1752
1753 /**
1754 * Initialize compiler thread(s) + compiler object(s). The postcondition
1755 * of this function is that the compiler runtimes are initialized and that
1756 * compiler threads can start compiling.
1757 */
1758 bool CompileBroker::init_compiler_runtime() {
1759 CompilerThread* thread = CompilerThread::current();
1760 AbstractCompiler* comp = thread->compiler();
1761 // Final sanity check - the compiler object must exist
1762 guarantee(comp != nullptr, "Compiler object must exist");
1763
1764 {
1765 // Must switch to native to allocate ci_env
1766 ThreadToNativeFromVM ttn(thread);
1767 ciEnv ci_env((CompileTask*)nullptr);
1768 // Cache Jvmti state
1769 ci_env.cache_jvmti_state();
1770 // Cache DTrace flags
1771 ci_env.cache_dtrace_flags();
1772
1773 // Switch back to VM state to do compiler initialization
1774 ThreadInVMfromNative tv(thread);
1775
1776 // Perform per-thread and global initializations
1777 comp->initialize();
1778 }
1779
1780 if (comp->is_failed()) {
1781 disable_compilation_forever();
1782 // If compiler initialization failed, no compiler thread that is specific to a
1783 // particular compiler runtime will ever start to compile methods.
1784 shutdown_compiler_runtime(comp, thread);
1785 return false;
1786 }
1787
1788 // C1 specific check
1789 if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
1790 warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1791 return false;
1792 }
1793
1794 return true;
1795 }
1796
1797 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
1798 BufferBlob* blob = thread->get_buffer_blob();
1799 if (blob != nullptr) {
1800 blob->purge();
1801 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1802 CodeCache::free(blob);
1803 }
1804 }
1805
1806 /**
1807 * If C1 and/or C2 initialization failed, we shut down all compilation.
1808 * We do this to keep things simple. This can be changed if it ever turns
1809 * out to be a problem.
1810 */
1811 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1812 free_buffer_blob_if_allocated(thread);
1813
1814 if (comp->should_perform_shutdown()) {
1815 // There are two reasons for shutting down the compiler
1816 // 1) compiler runtime initialization failed
1817 // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1818 warning("%s initialization failed. Shutting down all compilers", comp->name());
1819
1820 // Only one thread per compiler runtime object enters here
1821 // Set state to shut down
1822 comp->set_shut_down();
1823
1824 // Delete all queued compilation tasks to make compiler threads exit faster.
1825 if (_c1_compile_queue != nullptr) {
1826 _c1_compile_queue->free_all();
1827 }
1828
1829 if (_c2_compile_queue != nullptr) {
1830 _c2_compile_queue->free_all();
1831 }
1832
1833 // Set flags so that we continue execution with using interpreter only.
1834 UseCompiler = false;
1835 UseInterpreter = true;
1836
1837 // We could delete compiler runtimes also. However, there are references to
1838 // the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then
1839 // fail. This can be done later if necessary.
1840 }
1841 }
1842
1843 /**
1844 * Helper function to create new or reuse old CompileLog.
1845 */
1846 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
1847 if (!LogCompilation) return nullptr;
1848
1849 AbstractCompiler *compiler = ct->compiler();
1850 bool c1 = compiler->is_c1();
1851 jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
1852 assert(compiler_objects != nullptr, "must be initialized at this point");
1853 CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
1854 assert(logs != nullptr, "must be initialized at this point");
1855 int count = c1 ? _c1_count : _c2_count;
1856
1857 // Find Compiler number by its threadObj.
1858 oop compiler_obj = ct->threadObj();
1859 int compiler_number = 0;
1860 bool found = false;
1861 for (; compiler_number < count; compiler_number++) {
1862 if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
1863 found = true;
1864 break;
1865 }
1866 }
1867 assert(found, "Compiler must exist at this point");
1868
1869 // Determine pointer for this thread's log.
1870 CompileLog** log_ptr = &logs[compiler_number];
1871
1872 // Return old one if it exists.
1873 CompileLog* log = *log_ptr;
1874 if (log != nullptr) {
1875 ct->init_log(log);
1876 return log;
1914 log->stamp();
1915 log->end_elem();
1916 }
1917
1918 // If compiler thread/runtime initialization fails, exit the compiler thread
1919 if (!init_compiler_runtime()) {
1920 return;
1921 }
1922
1923 thread->start_idle_timer();
1924
1925 // Poll for new compilation tasks as long as the JVM runs. Compilation
1926 // should only be disabled if something went wrong while initializing the
1927 // compiler runtimes. This, in turn, should not happen. The only known case
1928 // when compiler runtime initialization fails is if there is not enough free
1929 // space in the code cache to generate the necessary stubs, etc.
1930 while (!is_compilation_disabled_forever()) {
1931 // We need this HandleMark to avoid leaking VM handles.
1932 HandleMark hm(thread);
1933
1934 CompileTask* task = queue->get(thread);
1935 if (task == nullptr) {
1936 if (UseDynamicNumberOfCompilerThreads) {
1937 // Access compiler_count under lock to enforce consistency.
1938 MutexLocker only_one(CompileThread_lock);
1939 if (can_remove(thread, true)) {
1940 if (trace_compiler_threads()) {
1941 ResourceMark rm;
1942 stringStream msg;
1943 msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
1944 thread->name(), thread->idle_time_millis());
1945 print_compiler_threads(msg);
1946 }
1947
1948 // Notify compiler that the compiler thread is about to stop
1949 thread->compiler()->stopping_compiler_thread(thread);
1950
1951 free_buffer_blob_if_allocated(thread);
1952 return; // Stop this thread.
1953 }
1954 }
1955 } else {
1956 // Assign the task to the current thread. Mark this compilation
1957 // thread as active for the profiler.
1958 // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
1959 // occurs after fetching the compile task off the queue.
1960 CompileTaskWrapper ctw(task);
1961 methodHandle method(thread, task->method());
1962
1963 // Never compile a method if breakpoints are present in it
1964 if (method()->number_of_breakpoints() == 0) {
1965 // Compile the method.
1966 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1967 invoke_compiler_on_method(task);
1968 thread->start_idle_timer();
1969 } else {
1970 // After compilation is disabled, remove remaining methods from queue
1971 method->clear_queued_for_compilation();
1972 task->set_failure_reason("compilation is disabled");
1973 }
1974 } else {
1975 task->set_failure_reason("breakpoints are present");
1976 }
1977
1978 if (UseDynamicNumberOfCompilerThreads) {
1979 possibly_add_compiler_threads(thread);
1980 assert(!thread->has_pending_exception(), "should have been handled");
1981 }
1982 }
1983 }
1984
1985 // Shut down compiler runtime
1986 shutdown_compiler_runtime(thread->compiler(), thread);
1987 }
1988
1989 // ------------------------------------------------------------------
1990 // CompileBroker::init_compiler_thread_log
1991 //
2154
2155 // Acquires Compilation_lock and waits for it to be notified
2156 // as long as WhiteBox::compilation_locked is true.
2157 static void whitebox_lock_compilation() {
2158 MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2159 while (WhiteBox::compilation_locked) {
2160 locker.wait();
2161 }
2162 }
2163
2164 // ------------------------------------------------------------------
2165 // CompileBroker::invoke_compiler_on_method
2166 //
2167 // Compile a method.
2168 //
2169 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2170 task->print_ul();
2171 elapsedTimer time;
2172
2173 DirectiveSet* directive = task->directive();
2174 if (directive->PrintCompilationOption) {
2175 ResourceMark rm;
2176 task->print_tty();
2177 }
2178
2179 CompilerThread* thread = CompilerThread::current();
2180 ResourceMark rm(thread);
2181
2182 if (CompilationLog::log() != nullptr) {
2183 CompilationLog::log()->log_compile(thread, task);
2184 }
2185
2186 // Common flags.
2187 int compile_id = task->compile_id();
2188 int osr_bci = task->osr_bci();
2189 bool is_osr = (osr_bci != standard_entry_bci);
2190 bool should_log = (thread->log() != nullptr);
2191 bool should_break = false;
2192 const int task_level = task->comp_level();
2193 AbstractCompiler* comp = task->compiler();
2194 {
2195 // create the handle inside it's own block so it can't
2196 // accidentally be referenced once the thread transitions to
2197 // native. The NoHandleMark before the transition should catch
2198 // any cases where this occurs in the future.
2199 methodHandle method(thread, task->method());
2200
2201 assert(!method->is_native(), "no longer compile natives");
2202
2203 // Update compile information when using perfdata.
2204 if (UsePerfData) {
2205 update_compile_perf_data(thread, method, is_osr);
2206 }
2207
2208 DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2209 }
2210
2211 should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2316
2317 if (comp == nullptr) {
2318 ci_env.record_method_not_compilable("no compiler");
2319 } else if (!ci_env.failing()) {
2320 if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2321 whitebox_lock_compilation();
2322 }
2323 comp->compile_method(&ci_env, target, osr_bci, true, directive);
2324
2325 /* Repeat compilation without installing code for profiling purposes */
2326 int repeat_compilation_count = directive->RepeatCompilationOption;
2327 while (repeat_compilation_count > 0) {
2328 ResourceMark rm(thread);
2329 task->print_ul("NO CODE INSTALLED");
2330 comp->compile_method(&ci_env, target, osr_bci, false, directive);
2331 repeat_compilation_count--;
2332 }
2333 }
2334
2335
2336 if (!ci_env.failing() && !task->is_success()) {
2337 assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2338 assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2339 // The compiler elected, without comment, not to register a result.
2340 // Do not attempt further compilations of this method.
2341 ci_env.record_method_not_compilable("compile failed");
2342 }
2343
2344 // Copy this bit to the enclosing block:
2345 compilable = ci_env.compilable();
2346
2347 if (ci_env.failing()) {
2348 // Duplicate the failure reason string, so that it outlives ciEnv
2349 failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2350 failure_reason_on_C_heap = true;
2351 retry_message = ci_env.retry_message();
2352 ci_env.report_failure(failure_reason);
2353 }
2354
2355 if (ci_env.failing()) {
2356 handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2357 }
2358 if (event.should_commit()) {
2359 post_compilation_event(event, task);
2360 }
2361 }
2362
2363 if (failure_reason != nullptr) {
2364 task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2365 if (CompilationLog::log() != nullptr) {
2366 CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2367 }
2368 if (PrintCompilation || directive->PrintCompilationOption) {
2369 FormatBufferResource msg = retry_message != nullptr ?
2370 FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2371 FormatBufferResource("COMPILE SKIPPED: %s", failure_reason);
2372 task->print(tty, msg);
2373 }
2374 }
2375
2376 DirectivesStack::release(directive);
2377
2378 methodHandle method(thread, task->method());
2379
2380 DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2381
2382 collect_statistics(thread, time, task);
2383
2384 if (PrintCompilation && PrintCompilation2) {
2385 tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp
2386 tty->print("%4d ", compile_id); // print compilation number
2387 tty->print("%s ", (is_osr ? "%" : " "));
2388 if (task->is_success()) {
2389 tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2390 }
2391 tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2392 }
2393
2394 Log(compilation, codecache) log;
2395 if (log.is_debug()) {
2396 LogStream ls(log.debug());
2397 codecache_print(&ls, /* detailed= */ false);
2398 }
2399 if (PrintCodeCacheOnCompilation) {
2400 codecache_print(/* detailed= */ false);
2401 }
2402 // Disable compilation, if required.
2403 switch (compilable) {
2404 case ciEnv::MethodCompilable_never:
2405 if (is_osr)
2406 method->set_not_osr_compilable_quietly("MethodCompilable_never");
2407 else
2408 method->set_not_compilable_quietly("MethodCompilable_never");
2409 break;
2410 case ciEnv::MethodCompilable_not_at_tier:
2411 if (is_osr)
2412 method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2413 else
2414 method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2415 break;
2416 }
2417
2418 // Note that the queued_for_compilation bits are cleared without
2419 // protection of a mutex. [They were set by the requester thread,
2420 // when adding the task to the compile queue -- at which time the
2421 // compile queue lock was held. Subsequently, we acquired the compile
2422 // queue lock to get this task off the compile queue; thus (to belabour
2423 // the point somewhat) our clearing of the bits must be occurring
2424 // only after the setting of the bits. See also 14012000 above.
2425 method->clear_queued_for_compilation();
2426 }
2427
2428 /**
2429 * The CodeCache is full. Print warning and disable compilation.
2430 * Schedule code cache cleaning so compilation can continue later.
2431 * This function needs to be called only from CodeCache::allocate(),
2432 * since we currently handle a full code cache uniformly.
2433 */
2434 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2435 UseInterpreter = true;
2436 if (UseCompiler || AlwaysCompileLoopMethods ) {
2437 if (xtty != nullptr) {
2438 stringStream s;
2439 // Dump code cache state into a buffer before locking the tty,
2440 // because log_state() will use locks causing lock conflicts.
2441 CodeCache::log_state(&s);
2442 // Lock to prevent tearing
2443 ttyLocker ttyl;
2444 xtty->begin_elem("code_cache_full");
2445 xtty->print("%s", s.freeze());
2518 // CompileBroker::collect_statistics
2519 //
2520 // Collect statistics about the compilation.
2521
2522 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2523 bool success = task->is_success();
2524 methodHandle method (thread, task->method());
2525 int compile_id = task->compile_id();
2526 bool is_osr = (task->osr_bci() != standard_entry_bci);
2527 const int comp_level = task->comp_level();
2528 CompilerCounters* counters = thread->counters();
2529
2530 MutexLocker locker(CompileStatistics_lock);
2531
2532 // _perf variables are production performance counters which are
2533 // updated regardless of the setting of the CITime and CITimeEach flags
2534 //
2535
2536 // account all time, including bailouts and failures in this counter;
2537 // C1 and C2 counters are counting both successful and unsuccessful compiles
2538 _t_total_compilation.add(time);
2539
2540 // Update compilation times. Used by the implementation of JFR CompilerStatistics
2541 // and java.lang.management.CompilationMXBean.
2542 _perf_total_compilation->inc(time.ticks());
2543 _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2544
2545 if (!success) {
2546 _total_bailout_count++;
2547 if (UsePerfData) {
2548 _perf_last_failed_method->set_value(counters->current_method());
2549 _perf_last_failed_type->set_value(counters->compile_type());
2550 _perf_total_bailout_count->inc();
2551 }
2552 _t_bailedout_compilation.add(time);
2553 } else if (!task->is_success()) {
2554 if (UsePerfData) {
2555 _perf_last_invalidated_method->set_value(counters->current_method());
2556 _perf_last_invalidated_type->set_value(counters->compile_type());
2557 _perf_total_invalidated_count->inc();
2558 }
2559 _total_invalidated_count++;
2560 _t_invalidated_compilation.add(time);
2561 } else {
2562 // Compilation succeeded
2563 if (CITime) {
2564 int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2565 if (is_osr) {
2566 _t_osr_compilation.add(time);
2567 _sum_osr_bytes_compiled += bytes_compiled;
2568 } else {
2569 _t_standard_compilation.add(time);
2570 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2571 }
2572
2573 // Collect statistic per compilation level
2574 if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2575 CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2576 if (is_osr) {
2577 stats->_osr.update(time, bytes_compiled);
2578 } else {
2579 stats->_standard.update(time, bytes_compiled);
2580 }
2581 stats->_nmethods_size += task->nm_total_size();
2582 stats->_nmethods_code_size += task->nm_insts_size();
2583 } else {
2584 assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2585 }
2586
2587 // Collect statistic per compiler
2588 AbstractCompiler* comp = compiler(comp_level);
2589 if (comp) {
2590 CompilerStatistics* stats = comp->stats();
2591 if (is_osr) {
2592 stats->_osr.update(time, bytes_compiled);
2593 } else {
2594 stats->_standard.update(time, bytes_compiled);
2595 }
2596 stats->_nmethods_size += task->nm_total_size();
2597 stats->_nmethods_code_size += task->nm_insts_size();
2598 } else { // if (!comp)
2599 assert(false, "Compiler object must exist");
2600 }
2601 }
2602
2603 if (UsePerfData) {
2604 // save the name of the last method compiled
2605 _perf_last_method->set_value(counters->current_method());
2606 _perf_last_compile_type->set_value(counters->compile_type());
2607 _perf_last_compile_size->set_value(method->code_size() +
2608 task->num_inlined_bytecodes());
2609 if (is_osr) {
2610 _perf_osr_compilation->inc(time.ticks());
2611 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2612 } else {
2613 _perf_standard_compilation->inc(time.ticks());
2614 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2615 }
2616 }
2617
2618 if (CITimeEach) {
2641 _total_standard_compile_count++;
2642 }
2643 }
2644 // set the current method for the thread to null
2645 if (UsePerfData) counters->set_current_method("");
2646 }
2647
2648 const char* CompileBroker::compiler_name(int comp_level) {
2649 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2650 if (comp == nullptr) {
2651 return "no compiler";
2652 } else {
2653 return (comp->name());
2654 }
2655 }
2656
2657 jlong CompileBroker::total_compilation_ticks() {
2658 return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2659 }
2660
2661 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2662 tty->print_cr(" %s {speed: %6.3f bytes/s; standard: %6.3f s, %u bytes, %u methods; osr: %6.3f s, %u bytes, %u methods; nmethods_size: %u bytes; nmethods_code_size: %u bytes}",
2663 name, stats->bytes_per_second(),
2664 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2665 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2666 stats->_nmethods_size, stats->_nmethods_code_size);
2667 }
2668
2669 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
2670 if (per_compiler) {
2671 if (aggregate) {
2672 tty->cr();
2673 tty->print_cr("Individual compiler times (for compiled methods only)");
2674 tty->print_cr("------------------------------------------------");
2675 tty->cr();
2676 }
2677 for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
2678 AbstractCompiler* comp = _compilers[i];
2679 if (comp != nullptr) {
2680 print_times(comp->name(), comp->stats());
2681 }
2682 }
2683 if (aggregate) {
2684 tty->cr();
2685 tty->print_cr("Individual compilation Tier times (for compiled methods only)");
2686 tty->print_cr("------------------------------------------------");
2687 tty->cr();
2688 }
2689 char tier_name[256];
2690 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
2691 CompilerStatistics* stats = &_stats_per_level[tier-1];
2692 os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
2693 print_times(tier_name, stats);
2694 }
2695 }
2696
2697 if (!aggregate) {
2698 return;
2699 }
2700
2701 elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
2702 elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
2703 elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
2704
2705 uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
2706 uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
2707
2708 uint standard_compile_count = CompileBroker::_total_standard_compile_count;
2709 uint osr_compile_count = CompileBroker::_total_osr_compile_count;
2710 uint total_compile_count = CompileBroker::_total_compile_count;
2711 uint total_bailout_count = CompileBroker::_total_bailout_count;
2712 uint total_invalidated_count = CompileBroker::_total_invalidated_count;
2713
2714 uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
2716
2717 tty->cr();
2718 tty->print_cr("Accumulated compiler times");
2719 tty->print_cr("----------------------------------------------------------");
2720 //0000000000111111111122222222223333333333444444444455555555556666666666
2721 //0123456789012345678901234567890123456789012345678901234567890123456789
2722 tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds());
2723 tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s",
2724 standard_compilation.seconds(),
2725 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
2726 tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s",
2727 CompileBroker::_t_bailedout_compilation.seconds(),
2728 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
2729 tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s",
2730 osr_compilation.seconds(),
2731 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
2732 tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s",
2733 CompileBroker::_t_invalidated_compilation.seconds(),
2734 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
2735
2736 AbstractCompiler *comp = compiler(CompLevel_simple);
2737 if (comp != nullptr) {
2738 tty->cr();
2739 comp->print_timers();
2740 }
2741 comp = compiler(CompLevel_full_optimization);
2742 if (comp != nullptr) {
2743 tty->cr();
2744 comp->print_timers();
2745 }
2746 #if INCLUDE_JVMCI
2747 if (EnableJVMCI) {
2748 JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
2749 if (jvmci_comp != nullptr && jvmci_comp != comp) {
2750 tty->cr();
2751 jvmci_comp->print_timers();
2752 }
2753 }
2754 #endif
2755
2756 tty->cr();
2757 tty->print_cr(" Total compiled methods : %8u methods", total_compile_count);
2758 tty->print_cr(" Standard compilation : %8u methods", standard_compile_count);
2759 tty->print_cr(" On stack replacement : %8u methods", osr_compile_count);
2760 uint tcb = osr_bytes_compiled + standard_bytes_compiled;
2761 tty->print_cr(" Total compiled bytecodes : %8u bytes", tcb);
2762 tty->print_cr(" Standard compilation : %8u bytes", standard_bytes_compiled);
2763 tty->print_cr(" On stack replacement : %8u bytes", osr_bytes_compiled);
2764 double tcs = total_compilation.seconds();
2765 uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
|
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 "cds/aotLinkedClassBulkLoader.hpp"
26 #include "cds/cdsConfig.hpp"
27 #include "classfile/javaClasses.inline.hpp"
28 #include "classfile/symbolTable.hpp"
29 #include "classfile/vmClasses.hpp"
30 #include "classfile/vmSymbols.hpp"
31 #include "code/aotCodeCache.hpp"
32 #include "code/codeCache.hpp"
33 #include "code/codeHeapState.hpp"
34 #include "code/dependencyContext.hpp"
35 #include "compiler/compilationLog.hpp"
36 #include "compiler/compilationMemoryStatistic.hpp"
37 #include "compiler/compilationPolicy.hpp"
38 #include "compiler/compileBroker.hpp"
39 #include "compiler/compileLog.hpp"
40 #include "compiler/compilerDefinitions.inline.hpp"
41 #include "compiler/compilerEvent.hpp"
42 #include "compiler/compilerOracle.hpp"
43 #include "compiler/directivesParser.hpp"
44 #include "compiler/recompilationPolicy.hpp"
45 #include "gc/shared/memAllocator.hpp"
46 #include "interpreter/linkResolver.hpp"
47 #include "jfr/jfrEvents.hpp"
48 #include "jvm.h"
49 #include "logging/log.hpp"
50 #include "logging/logStream.hpp"
51 #include "memory/allocation.inline.hpp"
52 #include "memory/resourceArea.hpp"
53 #include "memory/universe.hpp"
54 #include "oops/method.inline.hpp"
55 #include "oops/methodData.hpp"
56 #include "oops/oop.inline.hpp"
57 #include "prims/jvmtiExport.hpp"
58 #include "prims/nativeLookup.hpp"
59 #include "prims/whitebox.hpp"
60 #include "runtime/atomic.hpp"
61 #include "runtime/escapeBarrier.hpp"
62 #include "runtime/globals_extension.hpp"
63 #include "runtime/handles.inline.hpp"
64 #include "runtime/init.hpp"
65 #include "runtime/interfaceSupport.inline.hpp"
66 #include "runtime/java.hpp"
67 #include "runtime/javaCalls.hpp"
68 #include "runtime/jniHandles.inline.hpp"
69 #include "runtime/os.hpp"
70 #include "runtime/perfData.hpp"
71 #include "runtime/safepointVerifiers.hpp"
72 #include "runtime/sharedRuntime.hpp"
73 #include "runtime/threads.hpp"
74 #include "runtime/threadSMR.inline.hpp"
75 #include "runtime/timerTrace.hpp"
76 #include "runtime/vframe.inline.hpp"
77 #include "services/management.hpp"
78 #include "utilities/debug.hpp"
79 #include "utilities/dtrace.hpp"
80 #include "utilities/events.hpp"
81 #include "utilities/formatBuffer.hpp"
82 #include "utilities/macros.hpp"
83 #include "utilities/nonblockingQueue.inline.hpp"
84 #ifdef COMPILER1
85 #include "c1/c1_Compiler.hpp"
86 #endif
87 #ifdef COMPILER2
88 #include "opto/c2compiler.hpp"
89 #endif
90 #if INCLUDE_JVMCI
91 #include "jvmci/jvmciEnv.hpp"
92 #include "jvmci/jvmciRuntime.hpp"
93 #endif
94
95 #ifdef DTRACE_ENABLED
96
97 // Only bother with this argument setup if dtrace is available
98
99 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name) \
100 { \
101 Symbol* klass_name = (method)->klass_name(); \
102 Symbol* name = (method)->name(); \
103 Symbol* signature = (method)->signature(); \
116 HOTSPOT_METHOD_COMPILE_END( \
117 (char *) comp_name, strlen(comp_name), \
118 (char *) klass_name->bytes(), klass_name->utf8_length(), \
119 (char *) name->bytes(), name->utf8_length(), \
120 (char *) signature->bytes(), signature->utf8_length(), (success)); \
121 }
122
123 #else // ndef DTRACE_ENABLED
124
125 #define DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, comp_name)
126 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success)
127
128 #endif // ndef DTRACE_ENABLED
129
130 bool CompileBroker::_initialized = false;
131 volatile bool CompileBroker::_should_block = false;
132 volatile int CompileBroker::_print_compilation_warning = 0;
133 volatile jint CompileBroker::_should_compile_new_jobs = run_compilation;
134
135 // The installed compiler(s)
136 AbstractCompiler* CompileBroker::_compilers[3];
137
138 // The maximum numbers of compiler threads to be determined during startup.
139 int CompileBroker::_c1_count = 0;
140 int CompileBroker::_c2_count = 0;
141 int CompileBroker::_c3_count = 0;
142 int CompileBroker::_ac_count = 0;
143
144 // An array of compiler names as Java String objects
145 jobject* CompileBroker::_compiler1_objects = nullptr;
146 jobject* CompileBroker::_compiler2_objects = nullptr;
147 jobject* CompileBroker::_compiler3_objects = nullptr;
148 jobject* CompileBroker::_ac_objects = nullptr;
149
150 CompileLog** CompileBroker::_compiler1_logs = nullptr;
151 CompileLog** CompileBroker::_compiler2_logs = nullptr;
152 CompileLog** CompileBroker::_compiler3_logs = nullptr;
153 CompileLog** CompileBroker::_ac_logs = nullptr;
154
155 // These counters are used to assign an unique ID to each compilation.
156 volatile jint CompileBroker::_compilation_id = 0;
157 volatile jint CompileBroker::_osr_compilation_id = 0;
158 volatile jint CompileBroker::_native_compilation_id = 0;
159
160 // Performance counters
161 PerfCounter* CompileBroker::_perf_total_compilation = nullptr;
162 PerfCounter* CompileBroker::_perf_osr_compilation = nullptr;
163 PerfCounter* CompileBroker::_perf_standard_compilation = nullptr;
164
165 PerfCounter* CompileBroker::_perf_total_bailout_count = nullptr;
166 PerfCounter* CompileBroker::_perf_total_invalidated_count = nullptr;
167 PerfCounter* CompileBroker::_perf_total_compile_count = nullptr;
168 PerfCounter* CompileBroker::_perf_total_osr_compile_count = nullptr;
169 PerfCounter* CompileBroker::_perf_total_standard_compile_count = nullptr;
170
171 PerfCounter* CompileBroker::_perf_sum_osr_bytes_compiled = nullptr;
172 PerfCounter* CompileBroker::_perf_sum_standard_bytes_compiled = nullptr;
173 PerfCounter* CompileBroker::_perf_sum_nmethod_size = nullptr;
174 PerfCounter* CompileBroker::_perf_sum_nmethod_code_size = nullptr;
175
176 PerfStringVariable* CompileBroker::_perf_last_method = nullptr;
177 PerfStringVariable* CompileBroker::_perf_last_failed_method = nullptr;
178 PerfStringVariable* CompileBroker::_perf_last_invalidated_method = nullptr;
179 PerfVariable* CompileBroker::_perf_last_compile_type = nullptr;
180 PerfVariable* CompileBroker::_perf_last_compile_size = nullptr;
181 PerfVariable* CompileBroker::_perf_last_failed_type = nullptr;
182 PerfVariable* CompileBroker::_perf_last_invalidated_type = nullptr;
183
184 // Timers and counters for generating statistics
185 elapsedTimer CompileBroker::_t_total_compilation;
186 elapsedTimer CompileBroker::_t_osr_compilation;
187 elapsedTimer CompileBroker::_t_standard_compilation;
188 elapsedTimer CompileBroker::_t_invalidated_compilation;
189 elapsedTimer CompileBroker::_t_bailedout_compilation;
190
191 uint CompileBroker::_total_bailout_count = 0;
192 uint CompileBroker::_total_invalidated_count = 0;
193 uint CompileBroker::_total_not_entrant_count = 0;
194 uint CompileBroker::_total_compile_count = 0;
195 uint CompileBroker::_total_osr_compile_count = 0;
196 uint CompileBroker::_total_standard_compile_count = 0;
197 uint CompileBroker::_total_compiler_stopped_count = 0;
198 uint CompileBroker::_total_compiler_restarted_count = 0;
199
200 uint CompileBroker::_sum_osr_bytes_compiled = 0;
201 uint CompileBroker::_sum_standard_bytes_compiled = 0;
202 uint CompileBroker::_sum_nmethod_size = 0;
203 uint CompileBroker::_sum_nmethod_code_size = 0;
204
205 jlong CompileBroker::_peak_compilation_time = 0;
206
207 CompilerStatistics CompileBroker::_stats_per_level[CompLevel_full_optimization];
208 CompilerStatistics CompileBroker::_aot_stats;
209 CompilerStatistics CompileBroker::_aot_stats_per_level[CompLevel_full_optimization + 1];
210
211 CompileQueue* CompileBroker::_c3_compile_queue = nullptr;
212 CompileQueue* CompileBroker::_c2_compile_queue = nullptr;
213 CompileQueue* CompileBroker::_c1_compile_queue = nullptr;
214 CompileQueue* CompileBroker::_ac1_compile_queue = nullptr;
215 CompileQueue* CompileBroker::_ac2_compile_queue = nullptr;
216
217 bool compileBroker_init() {
218 if (LogEvents) {
219 CompilationLog::init();
220 }
221
222 // init directives stack, adding default directive
223 DirectivesStack::init();
224
225 if (DirectivesParser::has_file()) {
226 return DirectivesParser::parse_from_flag();
227 } else if (CompilerDirectivesPrint) {
228 // Print default directive even when no other was added
229 DirectivesStack::print(tty);
230 }
231
232 return true;
233 }
234
235 CompileTaskWrapper::CompileTaskWrapper(CompileTask* task) {
236 CompilerThread* thread = CompilerThread::current();
237 thread->set_task(task);
238 CompileLog* log = thread->log();
239 if (log != nullptr && !task->is_unloaded()) task->log_task_start(log);
240 }
241
242 CompileTaskWrapper::~CompileTaskWrapper() {
243 CompilerThread* thread = CompilerThread::current();
244 CompileTask* task = thread->task();
245 CompileLog* log = thread->log();
246 AbstractCompiler* comp = thread->compiler();
247 if (log != nullptr && !task->is_unloaded()) task->log_task_done(log);
248 thread->set_task(nullptr);
249 thread->set_env(nullptr);
250 if (task->is_blocking()) {
251 bool free_task = false;
252 {
253 MutexLocker notifier(thread, task->lock());
254 task->mark_complete();
255 #if INCLUDE_JVMCI
256 if (comp->is_jvmci()) {
257 if (!task->has_waiter()) {
258 // The waiting thread timed out and thus did not free the task.
259 free_task = true;
260 }
261 task->set_blocking_jvmci_compile_state(nullptr);
262 }
263 #endif
264 if (!free_task) {
265 // Notify the waiting thread that the compilation has completed
266 // so that it can free the task.
267 task->lock()->notify_all();
268 }
269 }
270 if (free_task) {
271 // The task can only be freed once the task lock is released.
272 CompileTask::free(task);
273 }
274 } else {
275 task->mark_complete();
276
277 // By convention, the compiling thread is responsible for
278 // recycling a non-blocking CompileTask.
279 CompileTask::free(task);
280 }
281 }
282
283 /**
284 * Check if a CompilerThread can be removed and update count if requested.
285 */
286 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
287 assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
288 if (!ReduceNumberOfCompilerThreads) return false;
289
290 if (RecompilationPolicy::have_recompilation_work()) return false;
291
292 AbstractCompiler *compiler = ct->compiler();
293 int compiler_count = compiler->num_compiler_threads();
294 bool c1 = compiler->is_c1();
295
296 // Keep at least 1 compiler thread of each type.
297 if (compiler_count < 2) return false;
298
299 // Keep thread alive for at least some time.
300 if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
301
302 #if INCLUDE_JVMCI
303 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
304 // Handles for JVMCI thread objects may get released concurrently.
305 if (do_it) {
306 assert(CompileThread_lock->owner() == ct, "must be holding lock");
307 } else {
308 // Skip check if it's the last thread and let caller check again.
309 return true;
310 }
311 }
318 if (do_it) {
319 assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
320 compiler->set_num_compiler_threads(compiler_count - 1);
321 #if INCLUDE_JVMCI
322 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
323 // Old j.l.Thread object can die when no longer referenced elsewhere.
324 JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
325 _compiler2_objects[compiler_count - 1] = nullptr;
326 }
327 #endif
328 }
329 return true;
330 }
331 return false;
332 }
333
334 /**
335 * Add a CompileTask to a CompileQueue.
336 */
337 void CompileQueue::add(CompileTask* task) {
338 assert(_lock->owned_by_self(), "must own lock");
339
340 task->set_next(nullptr);
341 task->set_prev(nullptr);
342
343 if (_last == nullptr) {
344 // The compile queue is empty.
345 assert(_first == nullptr, "queue is empty");
346 _first = task;
347 _last = task;
348 } else {
349 // Append the task to the queue.
350 assert(_last->next() == nullptr, "not last");
351 _last->set_next(task);
352 task->set_prev(_last);
353 _last = task;
354 }
355 ++_size;
356 ++_total_added;
357 if (_size > _peak_size) {
358 _peak_size = _size;
359 }
360
361 // Mark the method as being in the compile queue.
362 task->method()->set_queued_for_compilation();
363
364 task->mark_queued(os::elapsed_counter());
365
366 if (CIPrintCompileQueue) {
367 print_tty();
368 }
369
370 if (LogCompilation && xtty != nullptr) {
371 task->log_task_queued();
372 }
373
374 if (TrainingData::need_data() && !CDSConfig::is_dumping_final_static_archive()) {
375 CompileTrainingData* ctd = CompileTrainingData::make(task);
376 if (ctd != nullptr) {
377 task->set_training_data(ctd);
378 }
379 }
380
381 // Notify CompilerThreads that a task is available.
382 _lock->notify_all();
383 }
384
385 void CompileQueue::add_pending(CompileTask* task) {
386 assert(_lock->owned_by_self() == false, "must NOT own lock");
387 assert(UseLockFreeCompileQueues, "");
388 task->method()->set_queued_for_compilation();
389 _queue.push(*task);
390 // FIXME: additional coordination needed? e.g., is it possible for compiler thread to block w/o processing pending tasks?
391 if (is_empty()) {
392 MutexLocker ml(_lock);
393 _lock->notify_all();
394 }
395 }
396
397 static bool process_pending(CompileTask* task) {
398 // guarantee(task->method()->queued_for_compilation(), "");
399 if (task->is_unloaded()) {
400 return true; // unloaded
401 }
402 task->method()->set_queued_for_compilation(); // FIXME
403 if (task->method()->pending_queue_processed()) {
404 return true; // already queued
405 }
406 // Mark the method as being in the compile queue.
407 task->method()->set_pending_queue_processed();
408 if (CompileBroker::compilation_is_complete(task->method(), task->osr_bci(), task->comp_level(),
409 task->requires_online_compilation(), task->compile_reason())) {
410 return true; // already compiled
411 }
412 return false; // active
413 }
414
415 void CompileQueue::transfer_pending() {
416 assert(_lock->owned_by_self(), "must own lock");
417
418 CompileTask* task;
419 while ((task = _queue.pop()) != nullptr) {
420 bool is_stale = process_pending(task);
421 if (is_stale) {
422 task->set_next(_first_stale);
423 task->set_prev(nullptr);
424 _first_stale = task;
425 } else {
426 add(task);
427 }
428 }
429 }
430
431 /**
432 * Empties compilation queue by putting all compilation tasks onto
433 * a freelist. Furthermore, the method wakes up all threads that are
434 * waiting on a compilation task to finish. This can happen if background
435 * compilation is disabled.
436 */
437 void CompileQueue::free_all() {
438 MutexLocker mu(_lock);
439 transfer_pending();
440
441 CompileTask* next = _first;
442
443 // Iterate over all tasks in the compile queue
444 while (next != nullptr) {
445 CompileTask* current = next;
446 next = current->next();
447 bool found_waiter = false;
448 {
449 MutexLocker ct_lock(current->lock());
450 assert(current->waiting_for_completion_count() <= 1, "more than one thread are waiting for task");
451 if (current->waiting_for_completion_count() > 0) {
452 // If another thread waits for this task, we must wake them up
453 // so they will stop waiting and free the task.
454 current->lock()->notify();
455 found_waiter = true;
456 }
457 }
458 if (!found_waiter) {
459 // If no one was waiting for this task, we need to free it ourselves. In this case, the task
460 // is also certainly unlocked, because, again, there is no waiter.
461 // Otherwise, by convention, it's the waiters responsibility to free the task.
462 // Put the task back on the freelist.
463 CompileTask::free(current);
464 }
465 }
466 _first = nullptr;
467 _last = nullptr;
468
469 // Wake up all threads that block on the queue.
470 _lock->notify_all();
471 }
472
473 /**
474 * Get the next CompileTask from a CompileQueue
475 */
476 CompileTask* CompileQueue::get(CompilerThread* thread) {
477 // save methods from RedefineClasses across safepoint
478 // across compile queue lock below.
479 methodHandle save_method;
480
481 MonitorLocker locker(_lock);
482 transfer_pending();
483
484 RecompilationPolicy::sample_load_average();
485
486 // If _first is null we have no more compile jobs. There are two reasons for
487 // having no compile jobs: First, we compiled everything we wanted. Second,
488 // we ran out of code cache so compilation has been disabled. In the latter
489 // case we perform code cache sweeps to free memory such that we can re-enable
490 // compilation.
491 while (_first == nullptr) {
492 // Exit loop if compilation is disabled forever
493 if (CompileBroker::is_compilation_disabled_forever()) {
494 return nullptr;
495 }
496
497 AbstractCompiler* compiler = thread->compiler();
498 guarantee(compiler != nullptr, "Compiler object must exist");
499 compiler->on_empty_queue(this, thread);
500 if (_first != nullptr) {
501 // The call to on_empty_queue may have temporarily unlocked the MCQ lock
502 // so check again whether any tasks were added to the queue.
503 break;
504 }
505
506 // If we have added stale tasks, there might be waiters that want
507 // the notification these tasks have failed. Normally, this would
508 // be done by a compiler thread that would perform the purge at
509 // the end of some compilation. But, if compile queue is empty,
510 // there is no guarantee compilers would run and do the purge.
511 // Do the purge here and now to unblock the waiters.
512 // Perform this until we run out of stale tasks.
513 while (_first_stale != nullptr) {
514 purge_stale_tasks();
515 }
516 if (_first != nullptr) {
517 // Purge stale tasks may have transferred some new tasks,
518 // so check again.
519 break;
520 }
521
522 // If there are no compilation tasks and we can compile new jobs
523 // (i.e., there is enough free space in the code cache) there is
524 // no need to invoke the GC.
525 // We need a timed wait here, since compiler threads can exit if compilation
526 // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
527 // is not critical and we do not want idle compiler threads to wake up too often.
528 locker.wait(5*1000);
529
530 transfer_pending(); // reacquired lock
531
532 if (RecompilationPolicy::have_recompilation_work()) return nullptr;
533
534 if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
535 // Still nothing to compile. Give caller a chance to stop this thread.
536 if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
537 }
538 }
539
540 if (CompileBroker::is_compilation_disabled_forever()) {
541 return nullptr;
542 }
543
544 CompileTask* task;
545 {
546 NoSafepointVerifier nsv;
547 task = CompilationPolicy::select_task(this, thread);
548 if (task != nullptr) {
549 task = task->select_for_compilation();
550 }
551 }
552
553 if (task != nullptr) {
554 // Save method pointers across unlock safepoint. The task is removed from
555 // the compilation queue, which is walked during RedefineClasses.
556 Thread* thread = Thread::current();
557 save_method = methodHandle(thread, task->method());
558
559 remove(task);
560 }
561 purge_stale_tasks(); // may temporarily release MCQ lock
562 return task;
563 }
564
565 // Clean & deallocate stale compile tasks.
566 // Temporarily releases MethodCompileQueue lock.
567 void CompileQueue::purge_stale_tasks() {
568 assert(_lock->owned_by_self(), "must own lock");
569 if (_first_stale != nullptr) {
570 // Stale tasks are purged when MCQ lock is released,
571 // but _first_stale updates are protected by MCQ lock.
572 // Once task processing starts and MCQ lock is released,
573 // other compiler threads can reuse _first_stale.
574 CompileTask* head = _first_stale;
575 _first_stale = nullptr;
576 {
577 MutexUnlocker ul(_lock);
578 for (CompileTask* task = head; task != nullptr; ) {
579 CompileTask* next_task = task->next();
580 CompileTaskWrapper ctw(task); // Frees the task
581 task->set_failure_reason("stale task");
582 task = next_task;
583 }
584 }
585 transfer_pending(); // transfer pending after reacquiring MCQ lock
586 }
587 }
588
589 void CompileQueue::remove(CompileTask* task) {
590 assert(_lock->owned_by_self(), "must own lock");
591 if (task->prev() != nullptr) {
592 task->prev()->set_next(task->next());
593 } else {
594 // max is the first element
595 assert(task == _first, "Sanity");
596 _first = task->next();
597 }
598
599 if (task->next() != nullptr) {
600 task->next()->set_prev(task->prev());
601 } else {
602 // max is the last element
603 assert(task == _last, "Sanity");
604 _last = task->prev();
605 }
606 --_size;
607 ++_total_removed;
608 }
609
610 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
611 assert(_lock->owned_by_self(), "must own lock");
612 remove(task);
613
614 // Enqueue the task for reclamation (should be done outside MCQ lock)
615 task->set_next(_first_stale);
616 task->set_prev(nullptr);
617 _first_stale = task;
618 }
619
620 // methods in the compile queue need to be marked as used on the stack
621 // so that they don't get reclaimed by Redefine Classes
622 void CompileQueue::mark_on_stack() {
623 for (CompileTask* task = _first; task != nullptr; task = task->next()) {
624 task->mark_on_stack();
625 }
626 for (CompileTask* task = _queue.first(); !_queue.is_end(task); task = task->next()) {
627 assert(task != nullptr, "");
628 task->mark_on_stack();
629 }
630 }
631
632
633 CompileQueue* CompileBroker::compile_queue(int comp_level, bool is_aot) {
634 if (is_c2_compile(comp_level)) return ((is_aot && (_ac_count > 0)) ? _ac2_compile_queue : _c2_compile_queue);
635 if (is_c1_compile(comp_level)) return ((is_aot && (_ac_count > 0)) ? _ac1_compile_queue : _c1_compile_queue);
636 return nullptr;
637 }
638
639 CompileQueue* CompileBroker::c1_compile_queue() {
640 return _c1_compile_queue;
641 }
642
643 CompileQueue* CompileBroker::c2_compile_queue() {
644 return _c2_compile_queue;
645 }
646
647 void CompileBroker::print_compile_queues(outputStream* st) {
648 st->print_cr("Current compiles: ");
649
650 char buf[2000];
651 int buflen = sizeof(buf);
652 Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
653
654 st->cr();
655 if (_c1_compile_queue != nullptr) {
656 _c1_compile_queue->print(st);
657 }
658 if (_c2_compile_queue != nullptr) {
659 _c2_compile_queue->print(st);
660 }
661 if (_c3_compile_queue != nullptr) {
662 _c3_compile_queue->print(st);
663 }
664 if (_ac1_compile_queue != nullptr) {
665 _ac1_compile_queue->print(st);
666 }
667 if (_ac2_compile_queue != nullptr) {
668 _ac2_compile_queue->print(st);
669 }
670 }
671
672 void CompileQueue::print(outputStream* st) {
673 assert_locked_or_safepoint(_lock);
674 st->print_cr("%s:", name());
675 CompileTask* task = _first;
676 if (task == nullptr) {
677 st->print_cr("Empty");
678 } else {
679 while (task != nullptr) {
680 task->print(st, nullptr, true, true);
681 task = task->next();
682 }
683 }
684 st->cr();
685 }
686
687 void CompileQueue::print_tty() {
688 stringStream ss;
689 // Dump the compile queue into a buffer before locking the tty
690 print(&ss);
691 {
692 ttyLocker ttyl;
693 tty->print("%s", ss.freeze());
720 CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
721 }
722 first_registration = false;
723 #endif // COMPILER2
724 }
725 }
726 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
727
728 // ------------------------------------------------------------------
729 // CompileBroker::compilation_init
730 //
731 // Initialize the Compilation object
732 void CompileBroker::compilation_init(JavaThread* THREAD) {
733 // No need to initialize compilation system if we do not use it.
734 if (!UseCompiler) {
735 return;
736 }
737 // Set the interface to the current compiler(s).
738 _c1_count = CompilationPolicy::c1_count();
739 _c2_count = CompilationPolicy::c2_count();
740 _c3_count = CompilationPolicy::c3_count();
741 _ac_count = CompilationPolicy::ac_count();
742
743 #if INCLUDE_JVMCI
744 if (EnableJVMCI) {
745 // This is creating a JVMCICompiler singleton.
746 JVMCICompiler* jvmci = new JVMCICompiler();
747
748 if (UseJVMCICompiler) {
749 _compilers[1] = jvmci;
750 if (FLAG_IS_DEFAULT(JVMCIThreads)) {
751 if (BootstrapJVMCI) {
752 // JVMCI will bootstrap so give it more threads
753 _c2_count = MIN2(32, os::active_processor_count());
754 }
755 } else {
756 _c2_count = JVMCIThreads;
757 }
758 if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
759 } else {
760 #ifdef COMPILER1
761 _c1_count = JVMCIHostThreads;
762 #endif // COMPILER1
763 }
764 #ifdef COMPILER2
765 if (AOTCodeCache::is_on() && (_c3_count > 0)) {
766 _compilers[2] = new C2Compiler();
767 }
768 #endif
769 }
770 }
771 #endif // INCLUDE_JVMCI
772
773 #ifdef COMPILER1
774 if (_c1_count > 0) {
775 _compilers[0] = new Compiler();
776 }
777 #endif // COMPILER1
778
779 #ifdef COMPILER2
780 if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
781 if (_c2_count > 0) {
782 _compilers[1] = new C2Compiler();
783 // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
784 // idToPhase mapping for c2 is in opto/phasetype.hpp
785 JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
786 }
787 }
788 #endif // COMPILER2
883 _perf_last_compile_size =
884 PerfDataManager::create_variable(SUN_CI, "lastSize",
885 PerfData::U_Bytes,
886 (jlong)CompileBroker::no_compile,
887 CHECK);
888
889
890 _perf_last_failed_type =
891 PerfDataManager::create_variable(SUN_CI, "lastFailedType",
892 PerfData::U_None,
893 (jlong)CompileBroker::no_compile,
894 CHECK);
895
896 _perf_last_invalidated_type =
897 PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
898 PerfData::U_None,
899 (jlong)CompileBroker::no_compile,
900 CHECK);
901 }
902
903 log_info(aot, codecache, init)("CompileBroker is initialized");
904 _initialized = true;
905 }
906
907 Handle CompileBroker::create_thread_oop(const char* name, TRAPS) {
908 Handle thread_oop = JavaThread::create_system_thread_object(name, CHECK_NH);
909 return thread_oop;
910 }
911
912 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
913 CompilationPolicy::replay_training_at_init_loop(thread);
914 }
915
916 #if defined(ASSERT) && COMPILER2_OR_JVMCI
917 // Entry for DeoptimizeObjectsALotThread. The threads are started in
918 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
919 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
920 DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
921 bool enter_single_loop;
922 {
923 MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
924 static int single_thread_count = 0;
925 enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
926 }
927 if (enter_single_loop) {
928 dt->deoptimize_objects_alot_loop_single();
929 } else {
930 dt->deoptimize_objects_alot_loop_all();
931 }
1055 }
1056
1057 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
1058 char name_buffer[256];
1059 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
1060 Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
1061 return JNIHandles::make_global(thread_oop);
1062 }
1063
1064 static void print_compiler_threads(stringStream& msg) {
1065 if (TraceCompilerThreads) {
1066 tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
1067 }
1068 LogTarget(Debug, jit, thread) lt;
1069 if (lt.is_enabled()) {
1070 LogStream ls(lt);
1071 ls.print_cr("%s", msg.as_string());
1072 }
1073 }
1074
1075 static void print_compiler_thread(JavaThread *ct) {
1076 if (trace_compiler_threads()) {
1077 ResourceMark rm;
1078 ThreadsListHandle tlh; // name() depends on the TLH.
1079 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1080 stringStream msg;
1081 msg.print("Added initial compiler thread %s", ct->name());
1082 print_compiler_threads(msg);
1083 }
1084 }
1085
1086 void CompileBroker::init_compiler_threads() {
1087 // Ensure any exceptions lead to vm_exit_during_initialization.
1088 EXCEPTION_MARK;
1089 #if !defined(ZERO)
1090 assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
1091 #endif // !ZERO
1092 // Initialize the compilation queue
1093 if (_c2_count > 0) {
1094 const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
1095 _c2_compile_queue = new CompileQueue(name, MethodCompileQueueC2_lock);
1096 _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
1097 _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
1098 }
1099 if (_c1_count > 0) {
1100 _c1_compile_queue = new CompileQueue("C1 compile queue", MethodCompileQueueC1_lock);
1101 _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
1102 _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
1103 }
1104
1105 if (_c3_count > 0) {
1106 const char* name = "C2 compile queue";
1107 _c3_compile_queue = new CompileQueue(name, MethodCompileQueueC3_lock);
1108 _compiler3_objects = NEW_C_HEAP_ARRAY(jobject, _c3_count, mtCompiler);
1109 _compiler3_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c3_count, mtCompiler);
1110 }
1111 if (_ac_count > 0) {
1112 if (_c1_count > 0) { // C1 is present
1113 _ac1_compile_queue = new CompileQueue("C1 AOT code compile queue", MethodCompileQueueSC1_lock);
1114 }
1115 if (_c2_count > 0) { // C2 is present
1116 _ac2_compile_queue = new CompileQueue("C2 AOT code compile queue", MethodCompileQueueSC2_lock);
1117 }
1118 _ac_objects = NEW_C_HEAP_ARRAY(jobject, _ac_count, mtCompiler);
1119 _ac_logs = NEW_C_HEAP_ARRAY(CompileLog*, _ac_count, mtCompiler);
1120 }
1121 char name_buffer[256];
1122
1123 for (int i = 0; i < _c2_count; i++) {
1124 // Create a name for our thread.
1125 jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
1126 _compiler2_objects[i] = thread_handle;
1127 _compiler2_logs[i] = nullptr;
1128
1129 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1130 JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
1131 assert(ct != nullptr, "should have been handled for initial thread");
1132 _compilers[1]->set_num_compiler_threads(i + 1);
1133 print_compiler_thread(ct);
1134 }
1135 }
1136
1137 for (int i = 0; i < _c1_count; i++) {
1138 // Create a name for our thread.
1139 jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1140 _compiler1_objects[i] = thread_handle;
1141 _compiler1_logs[i] = nullptr;
1142
1143 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1144 JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1145 assert(ct != nullptr, "should have been handled for initial thread");
1146 _compilers[0]->set_num_compiler_threads(i + 1);
1147 print_compiler_thread(ct);
1148 }
1149 }
1150
1151 for (int i = 0; i < _c3_count; i++) {
1152 // Create a name for our thread.
1153 os::snprintf_checked(name_buffer, sizeof(name_buffer), "C2 CompilerThread%d", i);
1154 Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1155 jobject thread_handle = JNIHandles::make_global(thread_oop);
1156 _compiler3_objects[i] = thread_handle;
1157 _compiler3_logs[i] = nullptr;
1158
1159 JavaThread *ct = make_thread(compiler_t, thread_handle, _c3_compile_queue, _compilers[2], THREAD);
1160 assert(ct != nullptr, "should have been handled for initial thread");
1161 _compilers[2]->set_num_compiler_threads(i + 1);
1162 print_compiler_thread(ct);
1163 }
1164
1165 if (_ac_count > 0) {
1166 int i = 0;
1167 if (_c1_count > 0) { // C1 is present
1168 os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d AOT code caching CompilerThread", 1);
1169 Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1170 jobject thread_handle = JNIHandles::make_global(thread_oop);
1171 _ac_objects[i] = thread_handle;
1172 _ac_logs[i] = nullptr;
1173 i++;
1174
1175 JavaThread *ct = make_thread(compiler_t, thread_handle, _ac1_compile_queue, _compilers[0], THREAD);
1176 assert(ct != nullptr, "should have been handled for initial thread");
1177 print_compiler_thread(ct);
1178 }
1179 if (_c2_count > 0) { // C2 is present
1180 os::snprintf_checked(name_buffer, sizeof(name_buffer), "C%d AOT code caching CompilerThread", 2);
1181 Handle thread_oop = create_thread_oop(name_buffer, CHECK);
1182 jobject thread_handle = JNIHandles::make_global(thread_oop);
1183 _ac_objects[i] = thread_handle;
1184 _ac_logs[i] = nullptr;
1185
1186 JavaThread *ct = make_thread(compiler_t, thread_handle, _ac2_compile_queue, _compilers[1], THREAD);
1187 assert(ct != nullptr, "should have been handled for initial thread");
1188 print_compiler_thread(ct);
1189 }
1190 }
1191
1192 if (UsePerfData) {
1193 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count + _c3_count, CHECK);
1194 }
1195
1196 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1197 if (DeoptimizeObjectsALot) {
1198 // Initialize and start the object deoptimizer threads
1199 const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1200 for (int count = 0; count < total_count; count++) {
1201 Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1202 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1203 make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1204 }
1205 }
1206 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1207 }
1208
1209 void CompileBroker::init_training_replay() {
1210 // Ensure any exceptions lead to vm_exit_during_initialization.
1211 EXCEPTION_MARK;
1212 if (TrainingData::have_data()) {
1213 Handle thread_oop = create_thread_oop("Training replay thread", CHECK);
1214 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1215 make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1216 }
1217 }
1218
1219 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1220
1221 int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1222 const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1223
1224 // Quick check if we already have enough compiler threads without taking the lock.
1225 // Numbers may change concurrently, so we read them again after we have the lock.
1226 if (_c2_compile_queue != nullptr) {
1227 old_c2_count = get_c2_thread_count();
1228 new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1229 }
1230 if (_c1_compile_queue != nullptr) {
1231 old_c1_count = get_c1_thread_count();
1232 new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1233 }
1321 stringStream msg;
1322 msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1323 ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1324 print_compiler_threads(msg);
1325 }
1326 }
1327 }
1328
1329 CompileThread_lock->unlock();
1330 }
1331
1332
1333 /**
1334 * Set the methods on the stack as on_stack so that redefine classes doesn't
1335 * reclaim them. This method is executed at a safepoint.
1336 */
1337 void CompileBroker::mark_on_stack() {
1338 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1339 // Since we are at a safepoint, we do not need a lock to access
1340 // the compile queues.
1341 if (_c3_compile_queue != nullptr) {
1342 _c3_compile_queue->mark_on_stack();
1343 }
1344 if (_c2_compile_queue != nullptr) {
1345 _c2_compile_queue->mark_on_stack();
1346 }
1347 if (_c1_compile_queue != nullptr) {
1348 _c1_compile_queue->mark_on_stack();
1349 }
1350 if (_ac1_compile_queue != nullptr) {
1351 _ac1_compile_queue->mark_on_stack();
1352 }
1353 if (_ac2_compile_queue != nullptr) {
1354 _ac2_compile_queue->mark_on_stack();
1355 }
1356 }
1357
1358 // ------------------------------------------------------------------
1359 // CompileBroker::compile_method
1360 //
1361 // Request compilation of a method.
1362 void CompileBroker::compile_method_base(const methodHandle& method,
1363 int osr_bci,
1364 int comp_level,
1365 int hot_count,
1366 CompileTask::CompileReason compile_reason,
1367 bool requires_online_compilation,
1368 bool blocking,
1369 Thread* thread) {
1370 guarantee(!method->is_abstract(), "cannot compile abstract methods");
1371 assert(method->method_holder()->is_instance_klass(),
1372 "sanity check");
1373 assert(!method->method_holder()->is_not_initialized() ||
1374 compile_reason == CompileTask::Reason_Preload ||
1375 compile_reason == CompileTask::Reason_Precompile ||
1376 compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1377 assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1378
1379 if (CIPrintRequests) {
1380 tty->print("request: ");
1381 method->print_short_name(tty);
1382 if (osr_bci != InvocationEntryBci) {
1383 tty->print(" osr_bci: %d", osr_bci);
1384 }
1385 tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1386 if (hot_count > 0) {
1387 tty->print(" hot: yes");
1388 }
1389 tty->cr();
1390 }
1391
1392 // A request has been made for compilation. Before we do any
1393 // real work, check to see if the method has been compiled
1394 // in the meantime with a definitive result.
1395 if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1396 return;
1397 }
1398
1399 #ifndef PRODUCT
1400 if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1401 if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1402 // Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI.
1403 return;
1404 }
1405 }
1406 #endif
1407
1408 // If this method is already in the compile queue, then
1409 // we do not block the current thread.
1410 if (compilation_is_in_queue(method)) {
1411 // We may want to decay our counter a bit here to prevent
1412 // multiple denied requests for compilation. This is an
1413 // open compilation policy issue. Note: The other possibility,
1414 // in the case that this is a blocking compile request, is to have
1415 // all subsequent blocking requesters wait for completion of
1416 // ongoing compiles. Note that in this case we'll need a protocol
1417 // for freeing the associated compile tasks. [Or we could have
1418 // a single static monitor on which all these waiters sleep.]
1419 return;
1420 }
1421
1422 // Tiered policy requires MethodCounters to exist before adding a method to
1423 // the queue. Create if we don't have them yet.
1424 if (compile_reason != CompileTask::Reason_Preload) {
1425 method->get_method_counters(thread);
1426 }
1427
1428 AOTCodeEntry* aot_code_entry = find_aot_code_entry(method, osr_bci, comp_level, compile_reason, requires_online_compilation);
1429 bool is_aot = (aot_code_entry != nullptr);
1430
1431 // Outputs from the following MutexLocker block:
1432 CompileTask* task = nullptr;
1433 CompileQueue* queue;
1434 #if INCLUDE_JVMCI
1435 if (is_c2_compile(comp_level) && compiler2()->is_jvmci() && compiler3() != nullptr &&
1436 ((JVMCICompiler*)compiler2())->force_comp_at_level_simple(method)) {
1437 assert(_c3_compile_queue != nullptr, "sanity");
1438 queue = _c3_compile_queue; // JVMCI compiler's methods compilation
1439 } else
1440 #endif
1441 queue = compile_queue(comp_level, is_aot);
1442
1443 // Acquire our lock.
1444 {
1445 ConditionalMutexLocker locker(thread, queue->lock(), !UseLockFreeCompileQueues);
1446
1447 // Make sure the method has not slipped into the queues since
1448 // last we checked; note that those checks were "fast bail-outs".
1449 // Here we need to be more careful, see 14012000 below.
1450 if (compilation_is_in_queue(method)) {
1451 return;
1452 }
1453
1454 // We need to check again to see if the compilation has
1455 // completed. A previous compilation may have registered
1456 // some result.
1457 if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1458 return;
1459 }
1460
1461 // We now know that this compilation is not pending, complete,
1462 // or prohibited. Assign a compile_id to this compilation
1463 // and check to see if it is in our [Start..Stop) range.
1464 int compile_id = assign_compile_id(method, osr_bci);
1465 if (compile_id == 0) {
1466 // The compilation falls outside the allowed range.
1467 return;
1468 }
1469
1470 #if INCLUDE_JVMCI
1471 if (UseJVMCICompiler && blocking) {
1472 // Don't allow blocking compiles for requests triggered by JVMCI.
1473 if (thread->is_Compiler_thread()) {
1474 blocking = false;
1475 }
1476
1477 // In libjvmci, JVMCI initialization should not deadlock with other threads
1527 // <RESULT, QUEUE> :
1528 // <0, 1> : in compile queue, but not yet compiled
1529 // <1, 1> : compiled but queue bit not cleared
1530 // <1, 0> : compiled and queue bit cleared
1531 // Because we first check the queue bits then check the result bits,
1532 // we are assured that we cannot introduce a duplicate task.
1533 // Note that if we did the tests in the reverse order (i.e. check
1534 // result then check queued bit), we could get the result bit before
1535 // the compilation completed, and the queue bit after the compilation
1536 // completed, and end up introducing a "duplicate" (redundant) task.
1537 // In that case, the compiler thread should first check if a method
1538 // has already been compiled before trying to compile it.
1539 // NOTE: in the event that there are multiple compiler threads and
1540 // there is de-optimization/recompilation, things will get hairy,
1541 // and in that case it's best to protect both the testing (here) of
1542 // these bits, and their updating (here and elsewhere) under a
1543 // common lock.
1544 task = create_compile_task(queue,
1545 compile_id, method,
1546 osr_bci, comp_level,
1547 hot_count, aot_code_entry, compile_reason,
1548 requires_online_compilation, blocking);
1549
1550 if (task->is_aot() && (_ac_count > 0)) {
1551 // Put it on AOT code caching queue
1552 queue = is_c1_compile(comp_level) ? _ac1_compile_queue : _ac2_compile_queue;
1553 }
1554
1555 if (UseLockFreeCompileQueues) {
1556 assert(queue->lock()->owned_by_self() == false, "");
1557 queue->add_pending(task);
1558 } else {
1559 queue->add(task);
1560 }
1561 }
1562
1563 if (blocking) {
1564 wait_for_completion(task);
1565 }
1566 }
1567
1568 AOTCodeEntry* CompileBroker::find_aot_code_entry(const methodHandle& method, int osr_bci, int comp_level,
1569 CompileTask::CompileReason compile_reason,
1570 bool requires_online_compilation) {
1571 AOTCodeEntry* aot_code_entry = nullptr;
1572 if (osr_bci == InvocationEntryBci && !requires_online_compilation && AOTCodeCache::is_on_for_use()) {
1573 // Check for cached code.
1574 if (compile_reason == CompileTask::Reason_Preload) {
1575 aot_code_entry = method->aot_code_entry();
1576 assert(aot_code_entry != nullptr && aot_code_entry->for_preload(), "sanity");
1577 } else {
1578 aot_code_entry = AOTCodeCache::find_code_entry(method, comp_level);
1579 }
1580 }
1581 return aot_code_entry;
1582 }
1583
1584 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1585 int comp_level,
1586 int hot_count,
1587 bool requires_online_compilation,
1588 CompileTask::CompileReason compile_reason,
1589 TRAPS) {
1590 // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1591 if (!_initialized || comp_level == CompLevel_none) {
1592 return nullptr;
1593 }
1594
1595 #if INCLUDE_JVMCI
1596 if (EnableJVMCI && UseJVMCICompiler &&
1597 comp_level == CompLevel_full_optimization && !AOTLinkedClassBulkLoader::class_preloading_finished()) {
1598 return nullptr;
1599 }
1600 #endif
1601
1602 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1603 assert(comp != nullptr, "Ensure we have a compiler");
1604
1605 #if INCLUDE_JVMCI
1606 if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1607 // JVMCI compilation is not yet initializable.
1608 return nullptr;
1609 }
1610 #endif
1611
1612 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
1613 // CompileBroker::compile_method can trap and can have pending async exception.
1614 nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_count, requires_online_compilation, compile_reason, directive, THREAD);
1615 DirectivesStack::release(directive);
1616 return nm;
1617 }
1618
1619 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1620 int comp_level,
1621 int hot_count,
1622 bool requires_online_compilation,
1623 CompileTask::CompileReason compile_reason,
1624 DirectiveSet* directive,
1625 TRAPS) {
1626
1627 // make sure arguments make sense
1628 assert(method->method_holder()->is_instance_klass(), "not an instance method");
1629 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1630 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1631 assert(!method->method_holder()->is_not_initialized() ||
1632 compile_reason == CompileTask::Reason_Preload ||
1633 compile_reason == CompileTask::Reason_Precompile ||
1634 compile_reason == CompileTask::Reason_PrecompileForPreload, "method holder must be initialized");
1635 // return quickly if possible
1636
1637 if (PrecompileOnlyAndExit && !CompileTask::reason_is_precompiled(compile_reason)) {
1638 return nullptr;
1639 }
1640
1641 // lock, make sure that the compilation
1642 // isn't prohibited in a straightforward way.
1643 AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1644 if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1645 return nullptr;
1646 }
1647
1648 if (osr_bci == InvocationEntryBci) {
1649 // standard compilation
1650 nmethod* method_code = method->code();
1651 if (method_code != nullptr) {
1652 if (compilation_is_complete(method(), osr_bci, comp_level, requires_online_compilation, compile_reason)) {
1653 return method_code;
1654 }
1655 }
1656 if (method->is_not_compilable(comp_level)) {
1657 return nullptr;
1658 }
1659 } else {
1660 // osr compilation
1661 // We accept a higher level osr method
1662 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1663 if (nm != nullptr) return nm;
1664 if (method->is_not_osr_compilable(comp_level)) return nullptr;
1665 }
1666
1667 assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1668 // some prerequisites that are compiler specific
1669 if (compile_reason != CompileTask::Reason_Preload &&
1670 !CompileTask::reason_is_precompiled(compile_reason) &&
1671 (comp->is_c2() || comp->is_jvmci())) {
1672 InternalOOMEMark iom(THREAD);
1673 method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1674 // Resolve all classes seen in the signature of the method
1675 // we are compiling.
1676 Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1677 }
1678
1679 // If the method is native, do the lookup in the thread requesting
1680 // the compilation. Native lookups can load code, which is not
1681 // permitted during compilation.
1682 //
1683 // Note: A native method implies non-osr compilation which is
1684 // checked with an assertion at the entry of this method.
1685 if (method->is_native() && !method->is_method_handle_intrinsic()) {
1686 address adr = NativeLookup::lookup(method, THREAD);
1687 if (HAS_PENDING_EXCEPTION) {
1688 // In case of an exception looking up the method, we just forget
1689 // about it. The interpreter will kick-in and throw the exception.
1690 method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1691 CLEAR_PENDING_EXCEPTION;
1706 }
1707
1708 // do the compilation
1709 if (method->is_native()) {
1710 if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1711 // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1712 // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1713 //
1714 // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1715 // in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls.
1716 AdapterHandlerLibrary::create_native_wrapper(method);
1717 } else {
1718 return nullptr;
1719 }
1720 } else {
1721 // If the compiler is shut off due to code cache getting full
1722 // fail out now so blocking compiles dont hang the java thread
1723 if (!should_compile_new_jobs()) {
1724 return nullptr;
1725 }
1726 bool is_blocking = ReplayCompiles ||
1727 !directive->BackgroundCompilationOption ||
1728 (PreloadBlocking && (compile_reason == CompileTask::Reason_Preload));
1729 compile_method_base(method, osr_bci, comp_level, hot_count, compile_reason, requires_online_compilation, is_blocking, THREAD);
1730 }
1731
1732 // return requested nmethod
1733 // We accept a higher level osr method
1734 if (osr_bci == InvocationEntryBci) {
1735 return method->code();
1736 }
1737 return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1738 }
1739
1740
1741 // ------------------------------------------------------------------
1742 // CompileBroker::compilation_is_complete
1743 //
1744 // See if compilation of this method is already complete.
1745 bool CompileBroker::compilation_is_complete(Method* method,
1746 int osr_bci,
1747 int comp_level,
1748 bool online_only,
1749 CompileTask::CompileReason compile_reason) {
1750 if (compile_reason == CompileTask::Reason_Precompile ||
1751 compile_reason == CompileTask::Reason_PrecompileForPreload) {
1752 return false; // FIXME: any restrictions?
1753 }
1754 bool is_osr = (osr_bci != standard_entry_bci);
1755 if (is_osr) {
1756 if (method->is_not_osr_compilable(comp_level)) {
1757 return true;
1758 } else {
1759 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1760 return (result != nullptr);
1761 }
1762 } else {
1763 if (method->is_not_compilable(comp_level)) {
1764 return true;
1765 } else {
1766 nmethod* result = method->code();
1767 if (result == nullptr) {
1768 return false;
1769 }
1770 if (online_only && result->is_aot()) {
1771 return false;
1772 }
1773 bool same_level = (comp_level == result->comp_level());
1774 if (result->has_clinit_barriers()) {
1775 return !same_level; // Allow replace preloaded code with new code of the same level
1776 }
1777 return same_level;
1778 }
1779 }
1780 }
1781
1782
1783 /**
1784 * See if this compilation is already requested.
1785 *
1786 * Implementation note: there is only a single "is in queue" bit
1787 * for each method. This means that the check below is overly
1788 * conservative in the sense that an osr compilation in the queue
1789 * will block a normal compilation from entering the queue (and vice
1790 * versa). This can be remedied by a full queue search to disambiguate
1791 * cases. If it is deemed profitable, this may be done.
1792 */
1793 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1794 return method->queued_for_compilation();
1795 }
1796
1797 // ------------------------------------------------------------------
1857 if (CIStart <= id && id < CIStop) {
1858 return id;
1859 }
1860 }
1861
1862 // Method was not in the appropriate compilation range.
1863 method->set_not_compilable_quietly("Not in requested compile id range");
1864 return 0;
1865 #else
1866 // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1867 // only _compilation_id is incremented.
1868 return Atomic::add(&_compilation_id, 1);
1869 #endif
1870 }
1871
1872 // ------------------------------------------------------------------
1873 // CompileBroker::assign_compile_id_unlocked
1874 //
1875 // Public wrapper for assign_compile_id that acquires the needed locks
1876 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1877 return assign_compile_id(method, osr_bci);
1878 }
1879
1880 // ------------------------------------------------------------------
1881 // CompileBroker::create_compile_task
1882 //
1883 // Create a CompileTask object representing the current request for
1884 // compilation. Add this task to the queue.
1885 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1886 int compile_id,
1887 const methodHandle& method,
1888 int osr_bci,
1889 int comp_level,
1890 int hot_count,
1891 AOTCodeEntry* aot_code_entry,
1892 CompileTask::CompileReason compile_reason,
1893 bool requires_online_compilation,
1894 bool blocking) {
1895 CompileTask* new_task = CompileTask::allocate();
1896 new_task->initialize(compile_id, method, osr_bci, comp_level,
1897 hot_count, aot_code_entry, compile_reason, queue,
1898 requires_online_compilation, blocking);
1899 return new_task;
1900 }
1901
1902 #if INCLUDE_JVMCI
1903 // The number of milliseconds to wait before checking if
1904 // JVMCI compilation has made progress.
1905 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1906
1907 // The number of JVMCI compilation progress checks that must fail
1908 // before unblocking a thread waiting for a blocking compilation.
1909 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1910
1911 /**
1912 * Waits for a JVMCI compiler to complete a given task. This thread
1913 * waits until either the task completes or it sees no JVMCI compilation
1914 * progress for N consecutive milliseconds where N is
1915 * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1916 * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1917 *
1918 * @return true if this thread needs to free/recycle the task
1997 }
1998
1999 if (free_task) {
2000 if (is_compilation_disabled_forever()) {
2001 CompileTask::free(task);
2002 return;
2003 }
2004
2005 // It is harmless to check this status without the lock, because
2006 // completion is a stable property (until the task object is recycled).
2007 assert(task->is_complete(), "Compilation should have completed");
2008
2009 // By convention, the waiter is responsible for recycling a
2010 // blocking CompileTask. Since there is only one waiter ever
2011 // waiting on a CompileTask, we know that no one else will
2012 // be using this CompileTask; we can free it.
2013 CompileTask::free(task);
2014 }
2015 }
2016
2017 void CompileBroker::wait_for_no_active_tasks() {
2018 CompileTask::wait_for_no_active_tasks();
2019 }
2020
2021 /**
2022 * Initialize compiler thread(s) + compiler object(s). The postcondition
2023 * of this function is that the compiler runtimes are initialized and that
2024 * compiler threads can start compiling.
2025 */
2026 bool CompileBroker::init_compiler_runtime() {
2027 CompilerThread* thread = CompilerThread::current();
2028 AbstractCompiler* comp = thread->compiler();
2029 // Final sanity check - the compiler object must exist
2030 guarantee(comp != nullptr, "Compiler object must exist");
2031
2032 {
2033 // Must switch to native to allocate ci_env
2034 ThreadToNativeFromVM ttn(thread);
2035 ciEnv ci_env((CompileTask*)nullptr);
2036 // Cache Jvmti state
2037 ci_env.cache_jvmti_state();
2038 // Cache DTrace flags
2039 ci_env.cache_dtrace_flags();
2040
2041 // Switch back to VM state to do compiler initialization
2042 ThreadInVMfromNative tv(thread);
2043
2044 comp->initialize();
2045 }
2046
2047 if (comp->is_failed()) {
2048 disable_compilation_forever();
2049 // If compiler initialization failed, no compiler thread that is specific to a
2050 // particular compiler runtime will ever start to compile methods.
2051 shutdown_compiler_runtime(comp, thread);
2052 return false;
2053 }
2054
2055 // C1 specific check
2056 if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
2057 warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
2058 return false;
2059 }
2060
2061 return true;
2062 }
2063
2064 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
2065 BufferBlob* blob = thread->get_buffer_blob();
2066 if (blob != nullptr) {
2067 blob->purge();
2068 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2069 CodeCache::free(blob);
2070 }
2071 }
2072
2073 /**
2074 * If C1 and/or C2 initialization failed, we shut down all compilation.
2075 * We do this to keep things simple. This can be changed if it ever turns
2076 * out to be a problem.
2077 */
2078 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
2079 free_buffer_blob_if_allocated(thread);
2080
2081 log_info(compilation)("shutdown_compiler_runtime: " INTPTR_FORMAT, p2i(thread));
2082
2083 if (comp->should_perform_shutdown()) {
2084 // There are two reasons for shutting down the compiler
2085 // 1) compiler runtime initialization failed
2086 // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
2087 warning("%s initialization failed. Shutting down all compilers", comp->name());
2088
2089 // Only one thread per compiler runtime object enters here
2090 // Set state to shut down
2091 comp->set_shut_down();
2092
2093 // Delete all queued compilation tasks to make compiler threads exit faster.
2094 if (_c1_compile_queue != nullptr) {
2095 _c1_compile_queue->free_all();
2096 }
2097
2098 if (_c2_compile_queue != nullptr) {
2099 _c2_compile_queue->free_all();
2100 }
2101
2102 if (_c3_compile_queue != nullptr) {
2103 _c3_compile_queue->free_all();
2104 }
2105
2106 // Set flags so that we continue execution with using interpreter only.
2107 UseCompiler = false;
2108 UseInterpreter = true;
2109
2110 // We could delete compiler runtimes also. However, there are references to
2111 // the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then
2112 // fail. This can be done later if necessary.
2113 }
2114 }
2115
2116 /**
2117 * Helper function to create new or reuse old CompileLog.
2118 */
2119 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
2120 if (!LogCompilation) return nullptr;
2121
2122 AbstractCompiler *compiler = ct->compiler();
2123 bool jvmci = JVMCI_ONLY( compiler->is_jvmci() ||) false;
2124 bool c1 = compiler->is_c1();
2125 jobject* compiler_objects = c1 ? _compiler1_objects : (_c3_count == 0 ? _compiler2_objects : (jvmci ? _compiler2_objects : _compiler3_objects));
2126 assert(compiler_objects != nullptr, "must be initialized at this point");
2127 CompileLog** logs = c1 ? _compiler1_logs : (_c3_count == 0 ? _compiler2_logs : (jvmci ? _compiler2_logs : _compiler3_logs));
2128 assert(logs != nullptr, "must be initialized at this point");
2129 int count = c1 ? _c1_count : (_c3_count == 0 ? _c2_count : (jvmci ? _c2_count : _c3_count));
2130
2131 if (ct->queue() == _ac1_compile_queue || ct->queue() == _ac2_compile_queue) {
2132 compiler_objects = _ac_objects;
2133 logs = _ac_logs;
2134 count = _ac_count;
2135 }
2136 // Find Compiler number by its threadObj.
2137 oop compiler_obj = ct->threadObj();
2138 int compiler_number = 0;
2139 bool found = false;
2140 for (; compiler_number < count; compiler_number++) {
2141 if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
2142 found = true;
2143 break;
2144 }
2145 }
2146 assert(found, "Compiler must exist at this point");
2147
2148 // Determine pointer for this thread's log.
2149 CompileLog** log_ptr = &logs[compiler_number];
2150
2151 // Return old one if it exists.
2152 CompileLog* log = *log_ptr;
2153 if (log != nullptr) {
2154 ct->init_log(log);
2155 return log;
2193 log->stamp();
2194 log->end_elem();
2195 }
2196
2197 // If compiler thread/runtime initialization fails, exit the compiler thread
2198 if (!init_compiler_runtime()) {
2199 return;
2200 }
2201
2202 thread->start_idle_timer();
2203
2204 // Poll for new compilation tasks as long as the JVM runs. Compilation
2205 // should only be disabled if something went wrong while initializing the
2206 // compiler runtimes. This, in turn, should not happen. The only known case
2207 // when compiler runtime initialization fails is if there is not enough free
2208 // space in the code cache to generate the necessary stubs, etc.
2209 while (!is_compilation_disabled_forever()) {
2210 // We need this HandleMark to avoid leaking VM handles.
2211 HandleMark hm(thread);
2212
2213 RecompilationPolicy::recompilation_step(AOTRecompilationWorkUnitSize, thread);
2214
2215 CompileTask* task = queue->get(thread);
2216 if (task == nullptr) {
2217 if (UseDynamicNumberOfCompilerThreads) {
2218 // Access compiler_count under lock to enforce consistency.
2219 MutexLocker only_one(CompileThread_lock);
2220 if (can_remove(thread, true)) {
2221 if (trace_compiler_threads()) {
2222 ResourceMark rm;
2223 stringStream msg;
2224 msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
2225 thread->name(), thread->idle_time_millis());
2226 print_compiler_threads(msg);
2227 }
2228
2229 // Notify compiler that the compiler thread is about to stop
2230 thread->compiler()->stopping_compiler_thread(thread);
2231
2232 free_buffer_blob_if_allocated(thread);
2233 return; // Stop this thread.
2234 }
2235 }
2236 } else {
2237 // Assign the task to the current thread. Mark this compilation
2238 // thread as active for the profiler.
2239 // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
2240 // occurs after fetching the compile task off the queue.
2241 CompileTaskWrapper ctw(task);
2242 methodHandle method(thread, task->method());
2243
2244 // Never compile a method if breakpoints are present in it
2245 if (method()->number_of_breakpoints() == 0) {
2246 // Compile the method.
2247 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
2248 invoke_compiler_on_method(task);
2249 thread->start_idle_timer();
2250 } else {
2251 // After compilation is disabled, remove remaining methods from queue
2252 method->clear_queued_for_compilation();
2253 method->set_pending_queue_processed(false);
2254 task->set_failure_reason("compilation is disabled");
2255 }
2256 } else {
2257 task->set_failure_reason("breakpoints are present");
2258 }
2259
2260 if (UseDynamicNumberOfCompilerThreads) {
2261 possibly_add_compiler_threads(thread);
2262 assert(!thread->has_pending_exception(), "should have been handled");
2263 }
2264 }
2265 }
2266
2267 // Shut down compiler runtime
2268 shutdown_compiler_runtime(thread->compiler(), thread);
2269 }
2270
2271 // ------------------------------------------------------------------
2272 // CompileBroker::init_compiler_thread_log
2273 //
2436
2437 // Acquires Compilation_lock and waits for it to be notified
2438 // as long as WhiteBox::compilation_locked is true.
2439 static void whitebox_lock_compilation() {
2440 MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2441 while (WhiteBox::compilation_locked) {
2442 locker.wait();
2443 }
2444 }
2445
2446 // ------------------------------------------------------------------
2447 // CompileBroker::invoke_compiler_on_method
2448 //
2449 // Compile a method.
2450 //
2451 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2452 task->print_ul();
2453 elapsedTimer time;
2454
2455 DirectiveSet* directive = task->directive();
2456
2457 CompilerThread* thread = CompilerThread::current();
2458 ResourceMark rm(thread);
2459
2460 if (CompilationLog::log() != nullptr) {
2461 CompilationLog::log()->log_compile(thread, task);
2462 }
2463
2464 // Common flags.
2465 int compile_id = task->compile_id();
2466 int osr_bci = task->osr_bci();
2467 bool is_osr = (osr_bci != standard_entry_bci);
2468 bool should_log = (thread->log() != nullptr);
2469 bool should_break = false;
2470 bool should_print_compilation = PrintCompilation || directive->PrintCompilationOption;
2471 const int task_level = task->comp_level();
2472 AbstractCompiler* comp = task->compiler();
2473 {
2474 // create the handle inside it's own block so it can't
2475 // accidentally be referenced once the thread transitions to
2476 // native. The NoHandleMark before the transition should catch
2477 // any cases where this occurs in the future.
2478 methodHandle method(thread, task->method());
2479
2480 assert(!method->is_native(), "no longer compile natives");
2481
2482 // Update compile information when using perfdata.
2483 if (UsePerfData) {
2484 update_compile_perf_data(thread, method, is_osr);
2485 }
2486
2487 DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2488 }
2489
2490 should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2595
2596 if (comp == nullptr) {
2597 ci_env.record_method_not_compilable("no compiler");
2598 } else if (!ci_env.failing()) {
2599 if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2600 whitebox_lock_compilation();
2601 }
2602 comp->compile_method(&ci_env, target, osr_bci, true, directive);
2603
2604 /* Repeat compilation without installing code for profiling purposes */
2605 int repeat_compilation_count = directive->RepeatCompilationOption;
2606 while (repeat_compilation_count > 0) {
2607 ResourceMark rm(thread);
2608 task->print_ul("NO CODE INSTALLED");
2609 comp->compile_method(&ci_env, target, osr_bci, false, directive);
2610 repeat_compilation_count--;
2611 }
2612 }
2613
2614
2615 if (!ci_env.failing() && !task->is_success() && !task->is_precompiled()) {
2616 assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2617 assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2618 // The compiler elected, without comment, not to register a result.
2619 // Do not attempt further compilations of this method.
2620 ci_env.record_method_not_compilable("compile failed");
2621 }
2622
2623 // Copy this bit to the enclosing block:
2624 compilable = ci_env.compilable();
2625
2626 if (ci_env.failing()) {
2627 // Duplicate the failure reason string, so that it outlives ciEnv
2628 failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2629 failure_reason_on_C_heap = true;
2630 retry_message = ci_env.retry_message();
2631 ci_env.report_failure(failure_reason);
2632 }
2633
2634 if (ci_env.failing()) {
2635 handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2636 }
2637 if (event.should_commit()) {
2638 post_compilation_event(event, task);
2639 }
2640 }
2641
2642 if (failure_reason != nullptr) {
2643 task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2644 if (CompilationLog::log() != nullptr) {
2645 CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2646 }
2647 if (PrintCompilation || directive->PrintCompilationOption) {
2648 FormatBufferResource msg = retry_message != nullptr ?
2649 FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2650 FormatBufferResource("COMPILE SKIPPED: %s", failure_reason);
2651 task->print(tty, msg);
2652 }
2653 }
2654
2655 task->mark_finished(os::elapsed_counter());
2656 DirectivesStack::release(directive);
2657
2658 methodHandle method(thread, task->method());
2659
2660 DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2661
2662 collect_statistics(thread, time, task);
2663
2664 if (PrintCompilation && PrintCompilation2) {
2665 tty->print("%7d ", (int) tty->time_stamp().milliseconds()); // print timestamp
2666 tty->print("%4d ", compile_id); // print compilation number
2667 tty->print("%s ", (is_osr ? "%" : (task->is_aot() ? "A" : " ")));
2668 if (task->is_success()) {
2669 tty->print("size: %d(%d) ", task->nm_total_size(), task->nm_insts_size());
2670 }
2671 tty->print_cr("time: %d inlined: %d bytes", (int)time.milliseconds(), task->num_inlined_bytecodes());
2672 }
2673
2674 Log(compilation, codecache) log;
2675 if (log.is_debug()) {
2676 LogStream ls(log.debug());
2677 codecache_print(&ls, /* detailed= */ false);
2678 }
2679 if (PrintCodeCacheOnCompilation) {
2680 codecache_print(/* detailed= */ false);
2681 }
2682 // Disable compilation, if required.
2683 switch (compilable) {
2684 case ciEnv::MethodCompilable_never:
2685 if (is_osr)
2686 method->set_not_osr_compilable_quietly("MethodCompilable_never");
2687 else
2688 method->set_not_compilable_quietly("MethodCompilable_never");
2689 break;
2690 case ciEnv::MethodCompilable_not_at_tier:
2691 if (is_osr)
2692 method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2693 else
2694 method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2695 break;
2696 }
2697
2698 // Note that the queued_for_compilation bits are cleared without
2699 // protection of a mutex. [They were set by the requester thread,
2700 // when adding the task to the compile queue -- at which time the
2701 // compile queue lock was held. Subsequently, we acquired the compile
2702 // queue lock to get this task off the compile queue; thus (to belabour
2703 // the point somewhat) our clearing of the bits must be occurring
2704 // only after the setting of the bits. See also 14012000 above.
2705 method->clear_queued_for_compilation();
2706 method->set_pending_queue_processed(false);
2707
2708 if (should_print_compilation) {
2709 ResourceMark rm;
2710 task->print_tty();
2711 }
2712 }
2713
2714 /**
2715 * The CodeCache is full. Print warning and disable compilation.
2716 * Schedule code cache cleaning so compilation can continue later.
2717 * This function needs to be called only from CodeCache::allocate(),
2718 * since we currently handle a full code cache uniformly.
2719 */
2720 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2721 UseInterpreter = true;
2722 if (UseCompiler || AlwaysCompileLoopMethods ) {
2723 if (xtty != nullptr) {
2724 stringStream s;
2725 // Dump code cache state into a buffer before locking the tty,
2726 // because log_state() will use locks causing lock conflicts.
2727 CodeCache::log_state(&s);
2728 // Lock to prevent tearing
2729 ttyLocker ttyl;
2730 xtty->begin_elem("code_cache_full");
2731 xtty->print("%s", s.freeze());
2804 // CompileBroker::collect_statistics
2805 //
2806 // Collect statistics about the compilation.
2807
2808 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2809 bool success = task->is_success();
2810 methodHandle method (thread, task->method());
2811 int compile_id = task->compile_id();
2812 bool is_osr = (task->osr_bci() != standard_entry_bci);
2813 const int comp_level = task->comp_level();
2814 CompilerCounters* counters = thread->counters();
2815
2816 MutexLocker locker(CompileStatistics_lock);
2817
2818 // _perf variables are production performance counters which are
2819 // updated regardless of the setting of the CITime and CITimeEach flags
2820 //
2821
2822 // account all time, including bailouts and failures in this counter;
2823 // C1 and C2 counters are counting both successful and unsuccessful compiles
2824 _t_total_compilation.add(&time);
2825
2826 // Update compilation times. Used by the implementation of JFR CompilerStatistics
2827 // and java.lang.management.CompilationMXBean.
2828 _perf_total_compilation->inc(time.ticks());
2829 _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2830
2831 if (!success) {
2832 _total_bailout_count++;
2833 if (UsePerfData) {
2834 _perf_last_failed_method->set_value(counters->current_method());
2835 _perf_last_failed_type->set_value(counters->compile_type());
2836 _perf_total_bailout_count->inc();
2837 }
2838 _t_bailedout_compilation.add(&time);
2839
2840 if (CITime || log_is_enabled(Info, init)) {
2841 CompilerStatistics* stats = nullptr;
2842 if (task->is_aot()) {
2843 int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2844 stats = &_aot_stats_per_level[level];
2845 } else {
2846 stats = &_stats_per_level[comp_level-1];
2847 }
2848 stats->_bailout.update(time, 0);
2849 }
2850 } else if (!task->is_success()) {
2851 if (UsePerfData) {
2852 _perf_last_invalidated_method->set_value(counters->current_method());
2853 _perf_last_invalidated_type->set_value(counters->compile_type());
2854 _perf_total_invalidated_count->inc();
2855 }
2856 _total_invalidated_count++;
2857 _t_invalidated_compilation.add(&time);
2858
2859 if (CITime || log_is_enabled(Info, init)) {
2860 CompilerStatistics* stats = nullptr;
2861 if (task->is_aot()) {
2862 int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2863 stats = &_aot_stats_per_level[level];
2864 } else {
2865 stats = &_stats_per_level[comp_level-1];
2866 }
2867 stats->_invalidated.update(time, 0);
2868 }
2869 } else {
2870 // Compilation succeeded
2871 if (CITime || log_is_enabled(Info, init)) {
2872 int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2873 if (is_osr) {
2874 _t_osr_compilation.add(&time);
2875 _sum_osr_bytes_compiled += bytes_compiled;
2876 } else {
2877 _t_standard_compilation.add(&time);
2878 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2879 }
2880
2881 // Collect statistic per compilation level
2882 if (task->is_aot()) {
2883 _aot_stats._standard.update(time, bytes_compiled);
2884 _aot_stats._nmethods_size += task->nm_total_size();
2885 _aot_stats._nmethods_code_size += task->nm_insts_size();
2886 int level = task->preload() ? CompLevel_full_optimization : (comp_level - 1);
2887 CompilerStatistics* stats = &_aot_stats_per_level[level];
2888 stats->_standard.update(time, bytes_compiled);
2889 stats->_nmethods_size += task->nm_total_size();
2890 stats->_nmethods_code_size += task->nm_insts_size();
2891 } else if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2892 CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2893 if (is_osr) {
2894 stats->_osr.update(time, bytes_compiled);
2895 } else {
2896 stats->_standard.update(time, bytes_compiled);
2897 }
2898 stats->_nmethods_size += task->nm_total_size();
2899 stats->_nmethods_code_size += task->nm_insts_size();
2900 } else {
2901 assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2902 }
2903
2904 // Collect statistic per compiler
2905 AbstractCompiler* comp = task->compiler();
2906 if (comp && !task->is_aot()) {
2907 CompilerStatistics* stats = comp->stats();
2908 if (is_osr) {
2909 stats->_osr.update(time, bytes_compiled);
2910 } else {
2911 stats->_standard.update(time, bytes_compiled);
2912 }
2913 stats->_nmethods_size += task->nm_total_size();
2914 stats->_nmethods_code_size += task->nm_insts_size();
2915 } else if (!task->is_aot()) { // if (!comp)
2916 assert(false, "Compiler object must exist");
2917 }
2918 }
2919
2920 if (UsePerfData) {
2921 // save the name of the last method compiled
2922 _perf_last_method->set_value(counters->current_method());
2923 _perf_last_compile_type->set_value(counters->compile_type());
2924 _perf_last_compile_size->set_value(method->code_size() +
2925 task->num_inlined_bytecodes());
2926 if (is_osr) {
2927 _perf_osr_compilation->inc(time.ticks());
2928 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2929 } else {
2930 _perf_standard_compilation->inc(time.ticks());
2931 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2932 }
2933 }
2934
2935 if (CITimeEach) {
2958 _total_standard_compile_count++;
2959 }
2960 }
2961 // set the current method for the thread to null
2962 if (UsePerfData) counters->set_current_method("");
2963 }
2964
2965 const char* CompileBroker::compiler_name(int comp_level) {
2966 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2967 if (comp == nullptr) {
2968 return "no compiler";
2969 } else {
2970 return (comp->name());
2971 }
2972 }
2973
2974 jlong CompileBroker::total_compilation_ticks() {
2975 return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2976 }
2977
2978 void CompileBroker::log_not_entrant(nmethod* nm) {
2979 _total_not_entrant_count++;
2980 if (CITime || log_is_enabled(Info, init)) {
2981 CompilerStatistics* stats = nullptr;
2982 int level = nm->comp_level();
2983 if (nm->is_aot()) {
2984 if (nm->preloaded()) {
2985 assert(level == CompLevel_full_optimization, "%d", level);
2986 level = CompLevel_full_optimization + 1;
2987 }
2988 stats = &_aot_stats_per_level[level - 1];
2989 } else {
2990 stats = &_stats_per_level[level - 1];
2991 }
2992 stats->_made_not_entrant._count++;
2993 }
2994 }
2995
2996 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2997 tty->print_cr(" %s {speed: %6.3f bytes/s; standard: %6.3f s, %u bytes, %u methods; osr: %6.3f s, %u bytes, %u methods; nmethods_size: %u bytes; nmethods_code_size: %u bytes}",
2998 name, stats->bytes_per_second(),
2999 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
3000 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
3001 stats->_nmethods_size, stats->_nmethods_code_size);
3002 }
3003
3004 static void print_helper(outputStream* st, const char* name, CompilerStatistics::Data data, bool print_time = true) {
3005 if (data._count > 0) {
3006 st->print("; %s: %4u methods", name, data._count);
3007 if (print_time) {
3008 st->print(" (in %.3fs)", data._time.seconds());
3009 }
3010 }
3011 }
3012
3013 static void print_tier_helper(outputStream* st, const char* prefix, int tier, CompilerStatistics* stats) {
3014 st->print(" %s%d: %5u methods", prefix, tier, stats->_standard._count);
3015 if (stats->_standard._count > 0) {
3016 st->print(" (in %.3fs)", stats->_standard._time.seconds());
3017 }
3018 print_helper(st, "osr", stats->_osr);
3019 print_helper(st, "bailout", stats->_bailout);
3020 print_helper(st, "invalid", stats->_invalidated);
3021 print_helper(st, "not_entrant", stats->_made_not_entrant, false);
3022 st->cr();
3023 }
3024
3025 static void print_queue_info(outputStream* st, CompileQueue* queue) {
3026 if (queue != nullptr) {
3027 MutexLocker ml(queue->lock());
3028
3029 uint total_cnt = 0;
3030 uint active_cnt = 0;
3031 for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3032 guarantee(jt != nullptr, "");
3033 if (jt->is_Compiler_thread()) {
3034 CompilerThread* ct = (CompilerThread*)jt;
3035
3036 guarantee(ct != nullptr, "");
3037 if (ct->queue() == queue) {
3038 ++total_cnt;
3039 CompileTask* task = ct->task();
3040 if (task != nullptr) {
3041 ++active_cnt;
3042 }
3043 }
3044 }
3045 }
3046
3047 st->print(" %s (%d active / %d total threads): %u tasks",
3048 queue->name(), active_cnt, total_cnt, queue->size());
3049 if (queue->size() > 0) {
3050 uint counts[] = {0, 0, 0, 0, 0}; // T1 ... T5
3051 for (CompileTask* task = queue->first(); task != nullptr; task = task->next()) {
3052 int tier = task->comp_level();
3053 if (task->is_aot() && task->preload()) {
3054 assert(tier == CompLevel_full_optimization, "%d", tier);
3055 tier = CompLevel_full_optimization + 1;
3056 }
3057 counts[tier-1]++;
3058 }
3059 st->print(":");
3060 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3061 uint cnt = counts[tier-1];
3062 if (cnt > 0) {
3063 st->print(" T%d: %u tasks;", tier, cnt);
3064 }
3065 }
3066 }
3067 st->cr();
3068
3069 // for (JavaThread* jt : *ThreadsSMRSupport::get_java_thread_list()) {
3070 // guarantee(jt != nullptr, "");
3071 // if (jt->is_Compiler_thread()) {
3072 // CompilerThread* ct = (CompilerThread*)jt;
3073 //
3074 // guarantee(ct != nullptr, "");
3075 // if (ct->queue() == queue) {
3076 // ResourceMark rm;
3077 // CompileTask* task = ct->task();
3078 // st->print(" %s: ", ct->name_raw());
3079 // if (task != nullptr) {
3080 // task->print(st, nullptr, true /*short_form*/, false /*cr*/);
3081 // }
3082 // st->cr();
3083 // }
3084 // }
3085 // }
3086 }
3087 }
3088 void CompileBroker::print_statistics_on(outputStream* st) {
3089 st->print_cr(" Total: %u methods; %u bailouts, %u invalidated, %u non_entrant",
3090 _total_compile_count, _total_bailout_count, _total_invalidated_count, _total_not_entrant_count);
3091 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3092 print_tier_helper(st, "Tier", tier, &_stats_per_level[tier-1]);
3093 }
3094 st->cr();
3095
3096 if (AOTCodeCaching) {
3097 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3098 if (tier != CompLevel_full_profile) {
3099 print_tier_helper(st, "AOT Code T", tier, &_aot_stats_per_level[tier - 1]);
3100 }
3101 }
3102 st->cr();
3103 }
3104
3105 print_queue_info(st, _c1_compile_queue);
3106 print_queue_info(st, _c2_compile_queue);
3107 print_queue_info(st, _c3_compile_queue);
3108 print_queue_info(st, _ac1_compile_queue);
3109 print_queue_info(st, _ac2_compile_queue);
3110 }
3111
3112 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
3113 if (per_compiler) {
3114 if (aggregate) {
3115 tty->cr();
3116 tty->print_cr("[%dms] Individual compiler times (for compiled methods only)", (int)tty->time_stamp().milliseconds());
3117 tty->print_cr("------------------------------------------------");
3118 tty->cr();
3119 }
3120 for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
3121 AbstractCompiler* comp = _compilers[i];
3122 if (comp != nullptr) {
3123 print_times(comp->name(), comp->stats());
3124 }
3125 }
3126 if (_aot_stats._standard._count > 0) {
3127 print_times("SC", &_aot_stats);
3128 }
3129 if (aggregate) {
3130 tty->cr();
3131 tty->print_cr("Individual compilation Tier times (for compiled methods only)");
3132 tty->print_cr("------------------------------------------------");
3133 tty->cr();
3134 }
3135 char tier_name[256];
3136 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
3137 CompilerStatistics* stats = &_stats_per_level[tier-1];
3138 os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
3139 print_times(tier_name, stats);
3140 }
3141 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level() + 1; tier++) {
3142 CompilerStatistics* stats = &_aot_stats_per_level[tier-1];
3143 if (stats->_standard._bytes > 0) {
3144 os::snprintf_checked(tier_name, sizeof(tier_name), "AOT Code T%d", tier);
3145 print_times(tier_name, stats);
3146 }
3147 }
3148 }
3149
3150 if (!aggregate) {
3151 return;
3152 }
3153
3154 elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
3155 elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
3156 elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
3157
3158 uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
3159 uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
3160
3161 uint standard_compile_count = CompileBroker::_total_standard_compile_count;
3162 uint osr_compile_count = CompileBroker::_total_osr_compile_count;
3163 uint total_compile_count = CompileBroker::_total_compile_count;
3164 uint total_bailout_count = CompileBroker::_total_bailout_count;
3165 uint total_invalidated_count = CompileBroker::_total_invalidated_count;
3166
3167 uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
3169
3170 tty->cr();
3171 tty->print_cr("Accumulated compiler times");
3172 tty->print_cr("----------------------------------------------------------");
3173 //0000000000111111111122222222223333333333444444444455555555556666666666
3174 //0123456789012345678901234567890123456789012345678901234567890123456789
3175 tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds());
3176 tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s",
3177 standard_compilation.seconds(),
3178 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
3179 tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s",
3180 CompileBroker::_t_bailedout_compilation.seconds(),
3181 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
3182 tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s",
3183 osr_compilation.seconds(),
3184 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
3185 tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s",
3186 CompileBroker::_t_invalidated_compilation.seconds(),
3187 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
3188
3189 if (AOTCodeCaching) { // Check flags because AOT code cache could be closed already
3190 tty->cr();
3191 AOTCodeCache::print_timers_on(tty);
3192 }
3193 AbstractCompiler *comp = compiler(CompLevel_simple);
3194 if (comp != nullptr) {
3195 tty->cr();
3196 comp->print_timers();
3197 }
3198 comp = compiler(CompLevel_full_optimization);
3199 if (comp != nullptr) {
3200 tty->cr();
3201 comp->print_timers();
3202 }
3203 comp = _compilers[2];
3204 if (comp != nullptr) {
3205 tty->cr();
3206 comp->print_timers();
3207 }
3208 #if INCLUDE_JVMCI
3209 if (EnableJVMCI) {
3210 JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
3211 if (jvmci_comp != nullptr && jvmci_comp != comp) {
3212 tty->cr();
3213 jvmci_comp->print_timers();
3214 }
3215 }
3216 #endif
3217
3218 tty->cr();
3219 tty->print_cr(" Total compiled methods : %8u methods", total_compile_count);
3220 tty->print_cr(" Standard compilation : %8u methods", standard_compile_count);
3221 tty->print_cr(" On stack replacement : %8u methods", osr_compile_count);
3222 uint tcb = osr_bytes_compiled + standard_bytes_compiled;
3223 tty->print_cr(" Total compiled bytecodes : %8u bytes", tcb);
3224 tty->print_cr(" Standard compilation : %8u bytes", standard_bytes_compiled);
3225 tty->print_cr(" On stack replacement : %8u bytes", osr_bytes_compiled);
3226 double tcs = total_compilation.seconds();
3227 uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
|