1 /*
2 * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "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/atomicAccess.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(); \
98 HOTSPOT_METHOD_COMPILE_BEGIN( \
99 (char *) comp_name, strlen(comp_name), \
100 (char *) klass_name->bytes(), klass_name->utf8_length(), \
101 (char *) name->bytes(), name->utf8_length(), \
102 (char *) signature->bytes(), signature->utf8_length()); \
103 }
104
105 #define DTRACE_METHOD_COMPILE_END_PROBE(method, comp_name, success) \
106 { \
107 Symbol* klass_name = (method)->klass_name(); \
108 Symbol* name = (method)->name(); \
109 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 thread->timeout()->arm();
222 if (log != nullptr && !task->is_unloaded()) task->log_task_start(log);
223 }
224
225 CompileTaskWrapper::~CompileTaskWrapper() {
226 CompilerThread* thread = CompilerThread::current();
227
228 // First, disarm the timeout. This still relies on the underlying task.
229 thread->timeout()->disarm();
230
231 CompileTask* task = thread->task();
232 CompileLog* log = thread->log();
233 if (log != nullptr && !task->is_unloaded()) task->log_task_done(log);
234 thread->set_task(nullptr);
235 thread->set_env(nullptr);
236 if (task->is_blocking()) {
237 bool free_task = false;
238 {
239 MutexLocker notifier(thread, CompileTaskWait_lock);
240 task->mark_complete();
241 #if INCLUDE_JVMCI
242 if (CompileBroker::compiler(task->comp_level())->is_jvmci()) {
243 if (!task->has_waiter()) {
244 // The waiting thread timed out and thus did not delete the task.
245 free_task = true;
246 }
247 task->set_blocking_jvmci_compile_state(nullptr);
248 }
249 #endif
250 if (!free_task) {
251 // Notify the waiting thread that the compilation has completed
252 // so that it can free the task.
253 CompileTaskWait_lock->notify_all();
254 }
255 }
256 if (free_task) {
257 // The task can only be deleted once the task lock is released.
258 delete task;
259 }
260 } else {
261 task->mark_complete();
262
263 // By convention, the compiling thread is responsible for deleting
264 // a non-blocking CompileTask.
265 delete task;
266 }
267 }
268
269 /**
270 * Check if a CompilerThread can be removed and update count if requested.
271 */
272 bool CompileBroker::can_remove(CompilerThread *ct, bool do_it) {
273 assert(UseDynamicNumberOfCompilerThreads, "or shouldn't be here");
274 if (!ReduceNumberOfCompilerThreads) return false;
275
276 AbstractCompiler *compiler = ct->compiler();
277 int compiler_count = compiler->num_compiler_threads();
278 bool c1 = compiler->is_c1();
279
280 // Keep at least 1 compiler thread of each type.
281 if (compiler_count < 2) return false;
282
283 // Keep thread alive for at least some time.
284 if (ct->idle_time_millis() < (c1 ? 500 : 100)) return false;
285
286 #if INCLUDE_JVMCI
287 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
288 // Handles for JVMCI thread objects may get released concurrently.
289 if (do_it) {
290 assert(CompileThread_lock->owner() == ct, "must be holding lock");
291 } else {
292 // Skip check if it's the last thread and let caller check again.
293 return true;
294 }
295 }
296 #endif
297
298 // We only allow the last compiler thread of each type to get removed.
299 jobject last_compiler = c1 ? compiler1_object(compiler_count - 1)
300 : compiler2_object(compiler_count - 1);
301 if (ct->threadObj() == JNIHandles::resolve_non_null(last_compiler)) {
302 if (do_it) {
303 assert_locked_or_safepoint(CompileThread_lock); // Update must be consistent.
304 compiler->set_num_compiler_threads(compiler_count - 1);
305 #if INCLUDE_JVMCI
306 if (compiler->is_jvmci() && !UseJVMCINativeLibrary) {
307 // Old j.l.Thread object can die when no longer referenced elsewhere.
308 JNIHandles::destroy_global(compiler2_object(compiler_count - 1));
309 _compiler2_objects[compiler_count - 1] = nullptr;
310 }
311 #endif
312 }
313 return true;
314 }
315 return false;
316 }
317
318 /**
319 * Add a CompileTask to a CompileQueue.
320 */
321 void CompileQueue::add(CompileTask* task) {
322 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
323
324 task->set_next(nullptr);
325 task->set_prev(nullptr);
326
327 if (_last == nullptr) {
328 // The compile queue is empty.
329 assert(_first == nullptr, "queue is empty");
330 _first = task;
331 _last = task;
332 } else {
333 // Append the task to the queue.
334 assert(_last->next() == nullptr, "not last");
335 _last->set_next(task);
336 task->set_prev(_last);
337 _last = task;
338 }
339 ++_size;
340 ++_total_added;
341 if (_size > _peak_size) {
342 _peak_size = _size;
343 }
344
345 // Mark the method as being in the compile queue.
346 task->method()->set_queued_for_compilation();
347
348 task->mark_queued(os::elapsed_counter());
349
350 if (CIPrintCompileQueue) {
351 print_tty();
352 }
353
354 if (LogCompilation && xtty != nullptr) {
355 task->log_task_queued();
356 }
357
358 if (TrainingData::need_data() && !CDSConfig::is_dumping_final_static_archive()) {
359 CompileTrainingData* ctd = CompileTrainingData::make(task);
360 if (ctd != nullptr) {
361 task->set_training_data(ctd);
362 }
363 }
364
365 // Notify CompilerThreads that a task is available.
366 MethodCompileQueue_lock->notify_all();
367 }
368
369 /**
370 * Empties compilation queue by deleting all compilation tasks.
371 * Furthermore, the method wakes up all threads that are waiting
372 * on a compilation task to finish. This can happen if background
373 * compilation is disabled.
374 */
375 void CompileQueue::delete_all() {
376 MutexLocker mu(MethodCompileQueue_lock);
377 CompileTask* current = _first;
378
379 // Iterate over all tasks in the compile queue
380 while (current != nullptr) {
381 CompileTask* next = current->next();
382 if (!current->is_blocking()) {
383 // Non-blocking task. No one is waiting for it, delete it now.
384 delete current;
385 } else {
386 // Blocking task. By convention, it is the waiters responsibility
387 // to delete the task. We cannot delete it here, because we do not
388 // coordinate with waiters. We will notify the waiters later.
389 }
390 current = next;
391 }
392 _first = nullptr;
393 _last = nullptr;
394
395 // Wake up all blocking task waiters to deal with remaining blocking
396 // tasks. This is not a performance sensitive path, so we do this
397 // unconditionally to simplify coding/testing.
398 {
399 MonitorLocker ml(Thread::current(), CompileTaskWait_lock);
400 ml.notify_all();
401 }
402
403 // Wake up all threads that block on the queue.
404 MethodCompileQueue_lock->notify_all();
405 }
406
407 /**
408 * Get the next CompileTask from a CompileQueue
409 */
410 CompileTask* CompileQueue::get(CompilerThread* thread) {
411 // save methods from RedefineClasses across safepoint
412 // across MethodCompileQueue_lock below.
413 methodHandle save_method;
414
415 MonitorLocker locker(MethodCompileQueue_lock);
416 // If _first is null we have no more compile jobs. There are two reasons for
417 // having no compile jobs: First, we compiled everything we wanted. Second,
418 // we ran out of code cache so compilation has been disabled. In the latter
419 // case we perform code cache sweeps to free memory such that we can re-enable
420 // compilation.
421 while (_first == nullptr) {
422 // Exit loop if compilation is disabled forever
423 if (CompileBroker::is_compilation_disabled_forever()) {
424 return nullptr;
425 }
426
427 AbstractCompiler* compiler = thread->compiler();
428 guarantee(compiler != nullptr, "Compiler object must exist");
429 compiler->on_empty_queue(this, thread);
430 if (_first != nullptr) {
431 // The call to on_empty_queue may have temporarily unlocked the MCQ lock
432 // so check again whether any tasks were added to the queue.
433 break;
434 }
435
436 // If there are no compilation tasks and we can compile new jobs
437 // (i.e., there is enough free space in the code cache) there is
438 // no need to invoke the GC.
439 // We need a timed wait here, since compiler threads can exit if compilation
440 // is disabled forever. We use 5 seconds wait time; the exiting of compiler threads
441 // is not critical and we do not want idle compiler threads to wake up too often.
442 locker.wait(5*1000);
443
444 if (UseDynamicNumberOfCompilerThreads && _first == nullptr) {
445 // Still nothing to compile. Give caller a chance to stop this thread.
446 if (CompileBroker::can_remove(CompilerThread::current(), false)) return nullptr;
447 }
448 }
449
450 if (CompileBroker::is_compilation_disabled_forever()) {
451 return nullptr;
452 }
453
454 CompileTask* task;
455 {
456 NoSafepointVerifier nsv;
457 task = CompilationPolicy::select_task(this, thread);
458 if (task != nullptr) {
459 task = task->select_for_compilation();
460 }
461 }
462
463 if (task != nullptr) {
464 // Save method pointers across unlock safepoint. The task is removed from
465 // the compilation queue, which is walked during RedefineClasses.
466 Thread* thread = Thread::current();
467 save_method = methodHandle(thread, task->method());
468
469 remove(task);
470 }
471 purge_stale_tasks(); // may temporarily release MCQ lock
472 return task;
473 }
474
475 // Clean & deallocate stale compile tasks.
476 // Temporarily releases MethodCompileQueue lock.
477 void CompileQueue::purge_stale_tasks() {
478 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
479 if (_first_stale != nullptr) {
480 // Stale tasks are purged when MCQ lock is released,
481 // but _first_stale updates are protected by MCQ lock.
482 // Once task processing starts and MCQ lock is released,
483 // other compiler threads can reuse _first_stale.
484 CompileTask* head = _first_stale;
485 _first_stale = nullptr;
486 {
487 MutexUnlocker ul(MethodCompileQueue_lock);
488 for (CompileTask* task = head; task != nullptr; ) {
489 CompileTask* next_task = task->next();
490 task->set_next(nullptr);
491 CompileTaskWrapper ctw(task); // Frees the task
492 task->set_failure_reason("stale task");
493 task = next_task;
494 }
495 }
496 }
497 }
498
499 void CompileQueue::remove(CompileTask* task) {
500 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
501 if (task->prev() != nullptr) {
502 task->prev()->set_next(task->next());
503 } else {
504 // max is the first element
505 assert(task == _first, "Sanity");
506 _first = task->next();
507 }
508
509 if (task->next() != nullptr) {
510 task->next()->set_prev(task->prev());
511 } else {
512 // max is the last element
513 assert(task == _last, "Sanity");
514 _last = task->prev();
515 }
516 task->set_next(nullptr);
517 task->set_prev(nullptr);
518 --_size;
519 ++_total_removed;
520 }
521
522 void CompileQueue::remove_and_mark_stale(CompileTask* task) {
523 assert(MethodCompileQueue_lock->owned_by_self(), "must own lock");
524 remove(task);
525
526 // Enqueue the task for reclamation (should be done outside MCQ lock)
527 task->set_next(_first_stale);
528 task->set_prev(nullptr);
529 _first_stale = task;
530 }
531
532 // methods in the compile queue need to be marked as used on the stack
533 // so that they don't get reclaimed by Redefine Classes
534 void CompileQueue::mark_on_stack() {
535 CompileTask* task = _first;
536 while (task != nullptr) {
537 task->mark_on_stack();
538 task = task->next();
539 }
540 }
541
542
543 CompileQueue* CompileBroker::compile_queue(int comp_level) {
544 if (is_c2_compile(comp_level)) return _c2_compile_queue;
545 if (is_c1_compile(comp_level)) return _c1_compile_queue;
546 return nullptr;
547 }
548
549 CompileQueue* CompileBroker::c1_compile_queue() {
550 return _c1_compile_queue;
551 }
552
553 CompileQueue* CompileBroker::c2_compile_queue() {
554 return _c2_compile_queue;
555 }
556
557 void CompileBroker::print_compile_queues(outputStream* st) {
558 st->print_cr("Current compiles: ");
559
560 char buf[2000];
561 int buflen = sizeof(buf);
562 Threads::print_threads_compiling(st, buf, buflen, /* short_form = */ true);
563
564 st->cr();
565 if (_c1_compile_queue != nullptr) {
566 _c1_compile_queue->print(st);
567 }
568 if (_c2_compile_queue != nullptr) {
569 _c2_compile_queue->print(st);
570 }
571 }
572
573 void CompileQueue::print(outputStream* st) {
574 assert_locked_or_safepoint(MethodCompileQueue_lock);
575 st->print_cr("%s:", name());
576 CompileTask* task = _first;
577 if (task == nullptr) {
578 st->print_cr("Empty");
579 } else {
580 while (task != nullptr) {
581 task->print(st, nullptr, true, true);
582 task = task->next();
583 }
584 }
585 st->cr();
586 }
587
588 void CompileQueue::print_tty() {
589 stringStream ss;
590 // Dump the compile queue into a buffer before locking the tty
591 print(&ss);
592 {
593 ttyLocker ttyl;
594 tty->print("%s", ss.freeze());
595 }
596 }
597
598 CompilerCounters::CompilerCounters() {
599 _current_method[0] = '\0';
600 _compile_type = CompileBroker::no_compile;
601 }
602
603 #if INCLUDE_JFR && COMPILER2_OR_JVMCI
604 // It appends new compiler phase names to growable array phase_names(a new CompilerPhaseType mapping
605 // in compiler/compilerEvent.cpp) and registers it with its serializer.
606 //
607 // c2 uses explicit CompilerPhaseType idToPhase mapping in opto/phasetype.hpp,
608 // so if c2 is used, it should be always registered first.
609 // This function is called during vm initialization.
610 static void register_jfr_phasetype_serializer(CompilerType compiler_type) {
611 ResourceMark rm;
612 static bool first_registration = true;
613 if (compiler_type == compiler_jvmci) {
614 CompilerEvent::PhaseEvent::get_phase_id("NOT_A_PHASE_NAME", false, false, false);
615 first_registration = false;
616 #ifdef COMPILER2
617 } else if (compiler_type == compiler_c2) {
618 assert(first_registration, "invariant"); // c2 must be registered first.
619 for (int i = 0; i < PHASE_NUM_TYPES; i++) {
620 const char* phase_name = CompilerPhaseTypeHelper::to_description((CompilerPhaseType) i);
621 CompilerEvent::PhaseEvent::get_phase_id(phase_name, false, false, false);
622 }
623 first_registration = false;
624 #endif // COMPILER2
625 }
626 }
627 #endif // INCLUDE_JFR && COMPILER2_OR_JVMCI
628
629 // ------------------------------------------------------------------
630 // CompileBroker::compilation_init
631 //
632 // Initialize the Compilation object
633 void CompileBroker::compilation_init(JavaThread* THREAD) {
634 // No need to initialize compilation system if we do not use it.
635 if (!UseCompiler) {
636 return;
637 }
638 // Set the interface to the current compiler(s).
639 _c1_count = CompilationPolicy::c1_count();
640 _c2_count = CompilationPolicy::c2_count();
641
642 #if INCLUDE_JVMCI
643 if (EnableJVMCI) {
644 // This is creating a JVMCICompiler singleton.
645 JVMCICompiler* jvmci = new JVMCICompiler();
646
647 if (UseJVMCICompiler) {
648 _compilers[1] = jvmci;
649 if (FLAG_IS_DEFAULT(JVMCIThreads)) {
650 if (BootstrapJVMCI) {
651 // JVMCI will bootstrap so give it more threads
652 _c2_count = MIN2(32, os::active_processor_count());
653 }
654 } else {
655 _c2_count = JVMCIThreads;
656 }
657 if (FLAG_IS_DEFAULT(JVMCIHostThreads)) {
658 } else {
659 #ifdef COMPILER1
660 _c1_count = JVMCIHostThreads;
661 #endif // COMPILER1
662 }
663 }
664 }
665 #endif // INCLUDE_JVMCI
666
667 #ifdef COMPILER1
668 if (_c1_count > 0) {
669 _compilers[0] = new Compiler();
670 }
671 #endif // COMPILER1
672
673 #ifdef COMPILER2
674 if (true JVMCI_ONLY( && !UseJVMCICompiler)) {
675 if (_c2_count > 0) {
676 _compilers[1] = new C2Compiler();
677 // Register c2 first as c2 CompilerPhaseType idToPhase mapping is explicit.
678 // idToPhase mapping for c2 is in opto/phasetype.hpp
679 JFR_ONLY(register_jfr_phasetype_serializer(compiler_c2);)
680 }
681 }
682 #endif // COMPILER2
683
684 #if INCLUDE_JVMCI
685 // Register after c2 registration.
686 // JVMCI CompilerPhaseType idToPhase mapping is dynamic.
687 if (EnableJVMCI) {
688 JFR_ONLY(register_jfr_phasetype_serializer(compiler_jvmci);)
689 }
690 #endif // INCLUDE_JVMCI
691
692 if (CompilerOracle::should_collect_memstat()) {
693 CompilationMemoryStatistic::initialize();
694 }
695
696 // Start the compiler thread(s)
697 init_compiler_threads();
698 // totalTime performance counter is always created as it is required
699 // by the implementation of java.lang.management.CompilationMXBean.
700 {
701 // Ensure OOM leads to vm_exit_during_initialization.
702 EXCEPTION_MARK;
703 _perf_total_compilation =
704 PerfDataManager::create_counter(JAVA_CI, "totalTime",
705 PerfData::U_Ticks, CHECK);
706 }
707
708 if (UsePerfData) {
709
710 EXCEPTION_MARK;
711
712 // create the jvmstat performance counters
713 _perf_osr_compilation =
714 PerfDataManager::create_counter(SUN_CI, "osrTime",
715 PerfData::U_Ticks, CHECK);
716
717 _perf_standard_compilation =
718 PerfDataManager::create_counter(SUN_CI, "standardTime",
719 PerfData::U_Ticks, CHECK);
720
721 _perf_total_bailout_count =
722 PerfDataManager::create_counter(SUN_CI, "totalBailouts",
723 PerfData::U_Events, CHECK);
724
725 _perf_total_invalidated_count =
726 PerfDataManager::create_counter(SUN_CI, "totalInvalidates",
727 PerfData::U_Events, CHECK);
728
729 _perf_total_compile_count =
730 PerfDataManager::create_counter(SUN_CI, "totalCompiles",
731 PerfData::U_Events, CHECK);
732 _perf_total_osr_compile_count =
733 PerfDataManager::create_counter(SUN_CI, "osrCompiles",
734 PerfData::U_Events, CHECK);
735
736 _perf_total_standard_compile_count =
737 PerfDataManager::create_counter(SUN_CI, "standardCompiles",
738 PerfData::U_Events, CHECK);
739
740 _perf_sum_osr_bytes_compiled =
741 PerfDataManager::create_counter(SUN_CI, "osrBytes",
742 PerfData::U_Bytes, CHECK);
743
744 _perf_sum_standard_bytes_compiled =
745 PerfDataManager::create_counter(SUN_CI, "standardBytes",
746 PerfData::U_Bytes, CHECK);
747
748 _perf_sum_nmethod_size =
749 PerfDataManager::create_counter(SUN_CI, "nmethodSize",
750 PerfData::U_Bytes, CHECK);
751
752 _perf_sum_nmethod_code_size =
753 PerfDataManager::create_counter(SUN_CI, "nmethodCodeSize",
754 PerfData::U_Bytes, CHECK);
755
756 _perf_last_method =
757 PerfDataManager::create_string_variable(SUN_CI, "lastMethod",
758 CompilerCounters::cmname_buffer_length,
759 "", CHECK);
760
761 _perf_last_failed_method =
762 PerfDataManager::create_string_variable(SUN_CI, "lastFailedMethod",
763 CompilerCounters::cmname_buffer_length,
764 "", CHECK);
765
766 _perf_last_invalidated_method =
767 PerfDataManager::create_string_variable(SUN_CI, "lastInvalidatedMethod",
768 CompilerCounters::cmname_buffer_length,
769 "", CHECK);
770
771 _perf_last_compile_type =
772 PerfDataManager::create_variable(SUN_CI, "lastType",
773 PerfData::U_None,
774 (jlong)CompileBroker::no_compile,
775 CHECK);
776
777 _perf_last_compile_size =
778 PerfDataManager::create_variable(SUN_CI, "lastSize",
779 PerfData::U_Bytes,
780 (jlong)CompileBroker::no_compile,
781 CHECK);
782
783
784 _perf_last_failed_type =
785 PerfDataManager::create_variable(SUN_CI, "lastFailedType",
786 PerfData::U_None,
787 (jlong)CompileBroker::no_compile,
788 CHECK);
789
790 _perf_last_invalidated_type =
791 PerfDataManager::create_variable(SUN_CI, "lastInvalidatedType",
792 PerfData::U_None,
793 (jlong)CompileBroker::no_compile,
794 CHECK);
795 }
796
797 _initialized = true;
798 }
799
800 void TrainingReplayThread::training_replay_thread_entry(JavaThread* thread, TRAPS) {
801 CompilationPolicy::replay_training_at_init_loop(thread);
802 }
803
804 #if defined(ASSERT) && COMPILER2_OR_JVMCI
805 // Entry for DeoptimizeObjectsALotThread. The threads are started in
806 // CompileBroker::init_compiler_threads() iff DeoptimizeObjectsALot is enabled
807 void DeoptimizeObjectsALotThread::deopt_objs_alot_thread_entry(JavaThread* thread, TRAPS) {
808 DeoptimizeObjectsALotThread* dt = ((DeoptimizeObjectsALotThread*) thread);
809 bool enter_single_loop;
810 {
811 MonitorLocker ml(dt, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag);
812 static int single_thread_count = 0;
813 enter_single_loop = single_thread_count++ < DeoptimizeObjectsALotThreadCountSingle;
814 }
815 if (enter_single_loop) {
816 dt->deoptimize_objects_alot_loop_single();
817 } else {
818 dt->deoptimize_objects_alot_loop_all();
819 }
820 }
821
822 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
823 // barrier targets a single thread which is selected round robin.
824 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_single() {
825 HandleMark hm(this);
826 while (true) {
827 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *deoptee_thread = jtiwh.next(); ) {
828 { // Begin new scope for escape barrier
829 HandleMarkCleaner hmc(this);
830 ResourceMark rm(this);
831 EscapeBarrier eb(true, this, deoptee_thread);
832 eb.deoptimize_objects(100);
833 }
834 // Now sleep after the escape barriers destructor resumed deoptee_thread.
835 sleep(DeoptimizeObjectsALotInterval);
836 }
837 }
838 }
839
840 // Execute EscapeBarriers in an endless loop to revert optimizations based on escape analysis. Each
841 // barrier targets all java threads in the vm at once.
842 void DeoptimizeObjectsALotThread::deoptimize_objects_alot_loop_all() {
843 HandleMark hm(this);
844 while (true) {
845 { // Begin new scope for escape barrier
846 HandleMarkCleaner hmc(this);
847 ResourceMark rm(this);
848 EscapeBarrier eb(true, this);
849 eb.deoptimize_objects_all_threads();
850 }
851 // Now sleep after the escape barriers destructor resumed the java threads.
852 sleep(DeoptimizeObjectsALotInterval);
853 }
854 }
855 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
856
857
858 JavaThread* CompileBroker::make_thread(ThreadType type, jobject thread_handle, CompileQueue* queue, AbstractCompiler* comp, JavaThread* THREAD) {
859 Handle thread_oop(THREAD, JNIHandles::resolve_non_null(thread_handle));
860
861 if (java_lang_Thread::thread(thread_oop()) != nullptr) {
862 assert(type == compiler_t, "should only happen with reused compiler threads");
863 // The compiler thread hasn't actually exited yet so don't try to reuse it
864 return nullptr;
865 }
866
867 JavaThread* new_thread = nullptr;
868 switch (type) {
869 case compiler_t:
870 assert(comp != nullptr, "Compiler instance missing.");
871 if (!InjectCompilerCreationFailure || comp->num_compiler_threads() == 0) {
872 CompilerCounters* counters = new CompilerCounters();
873 new_thread = new CompilerThread(queue, counters);
874 }
875 break;
876 #if defined(ASSERT) && COMPILER2_OR_JVMCI
877 case deoptimizer_t:
878 new_thread = new DeoptimizeObjectsALotThread();
879 break;
880 #endif // ASSERT
881 case training_replay_t:
882 new_thread = new TrainingReplayThread();
883 break;
884 default:
885 ShouldNotReachHere();
886 }
887
888 // At this point the new CompilerThread data-races with this startup
889 // thread (which is the main thread and NOT the VM thread).
890 // This means Java bytecodes being executed at startup can
891 // queue compile jobs which will run at whatever default priority the
892 // newly created CompilerThread runs at.
893
894
895 // At this point it may be possible that no osthread was created for the
896 // JavaThread due to lack of resources. We will handle that failure below.
897 // Also check new_thread so that static analysis is happy.
898 if (new_thread != nullptr && new_thread->osthread() != nullptr) {
899
900 if (type == compiler_t) {
901 CompilerThread::cast(new_thread)->set_compiler(comp);
902 }
903
904 // Note that we cannot call os::set_priority because it expects Java
905 // priorities and we are *explicitly* using OS priorities so that it's
906 // possible to set the compiler thread priority higher than any Java
907 // thread.
908
909 int native_prio = CompilerThreadPriority;
910 if (native_prio == -1) {
911 if (UseCriticalCompilerThreadPriority) {
912 native_prio = os::java_to_os_priority[CriticalPriority];
913 } else {
914 native_prio = os::java_to_os_priority[NearMaxPriority];
915 }
916 }
917 os::set_native_priority(new_thread, native_prio);
918
919 // Note that this only sets the JavaThread _priority field, which by
920 // definition is limited to Java priorities and not OS priorities.
921 JavaThread::start_internal_daemon(THREAD, new_thread, thread_oop, NearMaxPriority);
922
923 } else { // osthread initialization failure
924 if (UseDynamicNumberOfCompilerThreads && type == compiler_t
925 && comp->num_compiler_threads() > 0) {
926 // The new thread is not known to Thread-SMR yet so we can just delete.
927 delete new_thread;
928 return nullptr;
929 } else {
930 vm_exit_during_initialization("java.lang.OutOfMemoryError",
931 os::native_thread_creation_failed_msg());
932 }
933 }
934
935 os::naked_yield(); // make sure that the compiler thread is started early (especially helpful on SOLARIS)
936
937 return new_thread;
938 }
939
940 static bool trace_compiler_threads() {
941 LogTarget(Debug, jit, thread) lt;
942 return TraceCompilerThreads || lt.is_enabled();
943 }
944
945 static jobject create_compiler_thread(AbstractCompiler* compiler, int i, TRAPS) {
946 char name_buffer[256];
947 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", compiler->name(), i);
948 Handle thread_oop = JavaThread::create_system_thread_object(name_buffer, CHECK_NULL);
949 return JNIHandles::make_global(thread_oop);
950 }
951
952 static void print_compiler_threads(stringStream& msg) {
953 if (TraceCompilerThreads) {
954 tty->print_cr("%7d %s", (int)tty->time_stamp().milliseconds(), msg.as_string());
955 }
956 LogTarget(Debug, jit, thread) lt;
957 if (lt.is_enabled()) {
958 LogStream ls(lt);
959 ls.print_cr("%s", msg.as_string());
960 }
961 }
962
963 void CompileBroker::init_compiler_threads() {
964 // Ensure any exceptions lead to vm_exit_during_initialization.
965 EXCEPTION_MARK;
966 #if !defined(ZERO)
967 assert(_c2_count > 0 || _c1_count > 0, "No compilers?");
968 #endif // !ZERO
969 // Initialize the compilation queue
970 if (_c2_count > 0) {
971 const char* name = JVMCI_ONLY(UseJVMCICompiler ? "JVMCI compile queue" :) "C2 compile queue";
972 _c2_compile_queue = new CompileQueue(name);
973 _compiler2_objects = NEW_C_HEAP_ARRAY(jobject, _c2_count, mtCompiler);
974 _compiler2_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c2_count, mtCompiler);
975 }
976 if (_c1_count > 0) {
977 _c1_compile_queue = new CompileQueue("C1 compile queue");
978 _compiler1_objects = NEW_C_HEAP_ARRAY(jobject, _c1_count, mtCompiler);
979 _compiler1_logs = NEW_C_HEAP_ARRAY(CompileLog*, _c1_count, mtCompiler);
980 }
981
982 for (int i = 0; i < _c2_count; i++) {
983 // Create a name for our thread.
984 jobject thread_handle = create_compiler_thread(_compilers[1], i, CHECK);
985 _compiler2_objects[i] = thread_handle;
986 _compiler2_logs[i] = nullptr;
987
988 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
989 JavaThread *ct = make_thread(compiler_t, thread_handle, _c2_compile_queue, _compilers[1], THREAD);
990 assert(ct != nullptr, "should have been handled for initial thread");
991 _compilers[1]->set_num_compiler_threads(i + 1);
992 if (trace_compiler_threads()) {
993 ResourceMark rm;
994 ThreadsListHandle tlh; // name() depends on the TLH.
995 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
996 stringStream msg;
997 msg.print("Added initial compiler thread %s", ct->name());
998 print_compiler_threads(msg);
999 }
1000 }
1001 }
1002
1003 for (int i = 0; i < _c1_count; i++) {
1004 // Create a name for our thread.
1005 jobject thread_handle = create_compiler_thread(_compilers[0], i, CHECK);
1006 _compiler1_objects[i] = thread_handle;
1007 _compiler1_logs[i] = nullptr;
1008
1009 if (!UseDynamicNumberOfCompilerThreads || i == 0) {
1010 JavaThread *ct = make_thread(compiler_t, thread_handle, _c1_compile_queue, _compilers[0], THREAD);
1011 assert(ct != nullptr, "should have been handled for initial thread");
1012 _compilers[0]->set_num_compiler_threads(i + 1);
1013 if (trace_compiler_threads()) {
1014 ResourceMark rm;
1015 ThreadsListHandle tlh; // name() depends on the TLH.
1016 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1017 stringStream msg;
1018 msg.print("Added initial compiler thread %s", ct->name());
1019 print_compiler_threads(msg);
1020 }
1021 }
1022 }
1023
1024 if (UsePerfData) {
1025 PerfDataManager::create_constant(SUN_CI, "threads", PerfData::U_Bytes, _c1_count + _c2_count, CHECK);
1026 }
1027
1028 #if defined(ASSERT) && COMPILER2_OR_JVMCI
1029 if (DeoptimizeObjectsALot) {
1030 // Initialize and start the object deoptimizer threads
1031 const int total_count = DeoptimizeObjectsALotThreadCountSingle + DeoptimizeObjectsALotThreadCountAll;
1032 for (int count = 0; count < total_count; count++) {
1033 Handle thread_oop = JavaThread::create_system_thread_object("Deoptimize objects a lot single mode", CHECK);
1034 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1035 make_thread(deoptimizer_t, thread_handle, nullptr, nullptr, THREAD);
1036 }
1037 }
1038 #endif // defined(ASSERT) && COMPILER2_OR_JVMCI
1039 }
1040
1041 void CompileBroker::init_training_replay() {
1042 // Ensure any exceptions lead to vm_exit_during_initialization.
1043 EXCEPTION_MARK;
1044 if (TrainingData::have_data()) {
1045 Handle thread_oop = JavaThread::create_system_thread_object("Training replay thread", CHECK);
1046 jobject thread_handle = JNIHandles::make_local(THREAD, thread_oop());
1047 make_thread(training_replay_t, thread_handle, nullptr, nullptr, THREAD);
1048 }
1049 }
1050
1051 void CompileBroker::possibly_add_compiler_threads(JavaThread* THREAD) {
1052
1053 int old_c2_count = 0, new_c2_count = 0, old_c1_count = 0, new_c1_count = 0;
1054 const int c2_tasks_per_thread = 2, c1_tasks_per_thread = 4;
1055
1056 // Quick check if we already have enough compiler threads without taking the lock.
1057 // Numbers may change concurrently, so we read them again after we have the lock.
1058 if (_c2_compile_queue != nullptr) {
1059 old_c2_count = get_c2_thread_count();
1060 new_c2_count = MIN2(_c2_count, _c2_compile_queue->size() / c2_tasks_per_thread);
1061 }
1062 if (_c1_compile_queue != nullptr) {
1063 old_c1_count = get_c1_thread_count();
1064 new_c1_count = MIN2(_c1_count, _c1_compile_queue->size() / c1_tasks_per_thread);
1065 }
1066 if (new_c2_count <= old_c2_count && new_c1_count <= old_c1_count) return;
1067
1068 // Now, we do the more expensive operations.
1069 physical_memory_size_type free_memory = 0;
1070 // Return value ignored - defaulting to 0 on failure.
1071 (void)os::free_memory(free_memory);
1072 // If SegmentedCodeCache is off, both values refer to the single heap (with type CodeBlobType::All).
1073 size_t available_cc_np = CodeCache::unallocated_capacity(CodeBlobType::MethodNonProfiled),
1074 available_cc_p = CodeCache::unallocated_capacity(CodeBlobType::MethodProfiled);
1075
1076 // Only attempt to start additional threads if the lock is free.
1077 if (!CompileThread_lock->try_lock()) return;
1078
1079 if (_c2_compile_queue != nullptr) {
1080 old_c2_count = get_c2_thread_count();
1081 new_c2_count = MIN4(_c2_count,
1082 _c2_compile_queue->size() / c2_tasks_per_thread,
1083 (int)(free_memory / (200*M)),
1084 (int)(available_cc_np / (128*K)));
1085
1086 for (int i = old_c2_count; i < new_c2_count; i++) {
1087 #if INCLUDE_JVMCI
1088 if (UseJVMCICompiler && !UseJVMCINativeLibrary && _compiler2_objects[i] == nullptr) {
1089 // Native compiler threads as used in C1/C2 can reuse the j.l.Thread objects as their
1090 // existence is completely hidden from the rest of the VM (and those compiler threads can't
1091 // call Java code to do the creation anyway).
1092 //
1093 // For pure Java JVMCI we have to create new j.l.Thread objects as they are visible and we
1094 // can see unexpected thread lifecycle transitions if we bind them to new JavaThreads. For
1095 // native library JVMCI it's preferred to use the C1/C2 strategy as this avoids unnecessary
1096 // coupling with Java.
1097 if (!THREAD->can_call_java()) break;
1098 char name_buffer[256];
1099 os::snprintf_checked(name_buffer, sizeof(name_buffer), "%s CompilerThread%d", _compilers[1]->name(), i);
1100 Handle thread_oop;
1101 {
1102 // We have to give up the lock temporarily for the Java calls.
1103 MutexUnlocker mu(CompileThread_lock);
1104 thread_oop = JavaThread::create_system_thread_object(name_buffer, THREAD);
1105 }
1106 if (HAS_PENDING_EXCEPTION) {
1107 if (trace_compiler_threads()) {
1108 ResourceMark rm;
1109 stringStream msg;
1110 msg.print_cr("JVMCI compiler thread creation failed:");
1111 PENDING_EXCEPTION->print_on(&msg);
1112 print_compiler_threads(msg);
1113 }
1114 CLEAR_PENDING_EXCEPTION;
1115 break;
1116 }
1117 // Check if another thread has beaten us during the Java calls.
1118 if (get_c2_thread_count() != i) break;
1119 jobject thread_handle = JNIHandles::make_global(thread_oop);
1120 assert(compiler2_object(i) == nullptr, "Old one must be released!");
1121 _compiler2_objects[i] = thread_handle;
1122 }
1123 #endif
1124 guarantee(compiler2_object(i) != nullptr, "Thread oop must exist");
1125 JavaThread *ct = make_thread(compiler_t, compiler2_object(i), _c2_compile_queue, _compilers[1], THREAD);
1126 if (ct == nullptr) break;
1127 _compilers[1]->set_num_compiler_threads(i + 1);
1128 if (trace_compiler_threads()) {
1129 ResourceMark rm;
1130 ThreadsListHandle tlh; // name() depends on the TLH.
1131 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1132 stringStream msg;
1133 msg.print("Added compiler thread %s (free memory: %dMB, available non-profiled code cache: %dMB)",
1134 ct->name(), (int)(free_memory/M), (int)(available_cc_np/M));
1135 print_compiler_threads(msg);
1136 }
1137 }
1138 }
1139
1140 if (_c1_compile_queue != nullptr) {
1141 old_c1_count = get_c1_thread_count();
1142 new_c1_count = MIN4(_c1_count,
1143 _c1_compile_queue->size() / c1_tasks_per_thread,
1144 (int)(free_memory / (100*M)),
1145 (int)(available_cc_p / (128*K)));
1146
1147 for (int i = old_c1_count; i < new_c1_count; i++) {
1148 JavaThread *ct = make_thread(compiler_t, compiler1_object(i), _c1_compile_queue, _compilers[0], THREAD);
1149 if (ct == nullptr) break;
1150 _compilers[0]->set_num_compiler_threads(i + 1);
1151 if (trace_compiler_threads()) {
1152 ResourceMark rm;
1153 ThreadsListHandle tlh; // name() depends on the TLH.
1154 assert(tlh.includes(ct), "ct=" INTPTR_FORMAT " exited unexpectedly.", p2i(ct));
1155 stringStream msg;
1156 msg.print("Added compiler thread %s (free memory: %dMB, available profiled code cache: %dMB)",
1157 ct->name(), (int)(free_memory/M), (int)(available_cc_p/M));
1158 print_compiler_threads(msg);
1159 }
1160 }
1161 }
1162
1163 CompileThread_lock->unlock();
1164 }
1165
1166
1167 /**
1168 * Set the methods on the stack as on_stack so that redefine classes doesn't
1169 * reclaim them. This method is executed at a safepoint.
1170 */
1171 void CompileBroker::mark_on_stack() {
1172 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
1173 // Since we are at a safepoint, we do not need a lock to access
1174 // the compile queues.
1175 if (_c2_compile_queue != nullptr) {
1176 _c2_compile_queue->mark_on_stack();
1177 }
1178 if (_c1_compile_queue != nullptr) {
1179 _c1_compile_queue->mark_on_stack();
1180 }
1181 }
1182
1183 // ------------------------------------------------------------------
1184 // CompileBroker::compile_method
1185 //
1186 // Request compilation of a method.
1187 void CompileBroker::compile_method_base(const methodHandle& method,
1188 int osr_bci,
1189 int comp_level,
1190 int hot_count,
1191 CompileTask::CompileReason compile_reason,
1192 bool blocking,
1193 Thread* thread) {
1194 guarantee(!method->is_abstract(), "cannot compile abstract methods");
1195 assert(method->method_holder()->is_instance_klass(),
1196 "sanity check");
1197 assert(!method->method_holder()->is_not_initialized(),
1198 "method holder must be initialized");
1199 assert(!method->is_method_handle_intrinsic(), "do not enqueue these guys");
1200
1201 if (CIPrintRequests) {
1202 tty->print("request: ");
1203 method->print_short_name(tty);
1204 if (osr_bci != InvocationEntryBci) {
1205 tty->print(" osr_bci: %d", osr_bci);
1206 }
1207 tty->print(" level: %d comment: %s count: %d", comp_level, CompileTask::reason_name(compile_reason), hot_count);
1208 if (hot_count > 0) {
1209 tty->print(" hot: yes");
1210 }
1211 tty->cr();
1212 }
1213
1214 // A request has been made for compilation. Before we do any
1215 // real work, check to see if the method has been compiled
1216 // in the meantime with a definitive result.
1217 if (compilation_is_complete(method, osr_bci, comp_level)) {
1218 return;
1219 }
1220
1221 #ifndef PRODUCT
1222 if (osr_bci != -1 && !FLAG_IS_DEFAULT(OSROnlyBCI)) {
1223 if ((OSROnlyBCI > 0) ? (OSROnlyBCI != osr_bci) : (-OSROnlyBCI == osr_bci)) {
1224 // Positive OSROnlyBCI means only compile that bci. Negative means don't compile that BCI.
1225 return;
1226 }
1227 }
1228 #endif
1229
1230 // If this method is already in the compile queue, then
1231 // we do not block the current thread.
1232 if (compilation_is_in_queue(method)) {
1233 // We may want to decay our counter a bit here to prevent
1234 // multiple denied requests for compilation. This is an
1235 // open compilation policy issue. Note: The other possibility,
1236 // in the case that this is a blocking compile request, is to have
1237 // all subsequent blocking requesters wait for completion of
1238 // ongoing compiles. Note that in this case we'll need a protocol
1239 // for freeing the associated compile tasks. [Or we could have
1240 // a single static monitor on which all these waiters sleep.]
1241 return;
1242 }
1243
1244 // Tiered policy requires MethodCounters to exist before adding a method to
1245 // the queue. Create if we don't have them yet.
1246 method->get_method_counters(thread);
1247
1248 // Outputs from the following MutexLocker block:
1249 CompileTask* task = nullptr;
1250 CompileQueue* queue = compile_queue(comp_level);
1251
1252 // Acquire our lock.
1253 {
1254 MutexLocker locker(thread, MethodCompileQueue_lock);
1255
1256 // Make sure the method has not slipped into the queues since
1257 // last we checked; note that those checks were "fast bail-outs".
1258 // Here we need to be more careful, see 14012000 below.
1259 if (compilation_is_in_queue(method)) {
1260 return;
1261 }
1262
1263 // We need to check again to see if the compilation has
1264 // completed. A previous compilation may have registered
1265 // some result.
1266 if (compilation_is_complete(method, osr_bci, comp_level)) {
1267 return;
1268 }
1269
1270 // We now know that this compilation is not pending, complete,
1271 // or prohibited. Assign a compile_id to this compilation
1272 // and check to see if it is in our [Start..Stop) range.
1273 int compile_id = assign_compile_id(method, osr_bci);
1274 if (compile_id == 0) {
1275 // The compilation falls outside the allowed range.
1276 return;
1277 }
1278
1279 #if INCLUDE_JVMCI
1280 if (UseJVMCICompiler && blocking) {
1281 // Don't allow blocking compiles for requests triggered by JVMCI.
1282 if (thread->is_Compiler_thread()) {
1283 blocking = false;
1284 }
1285
1286 // In libjvmci, JVMCI initialization should not deadlock with other threads
1287 if (!UseJVMCINativeLibrary) {
1288 // Don't allow blocking compiles if inside a class initializer or while performing class loading
1289 vframeStream vfst(JavaThread::cast(thread));
1290 for (; !vfst.at_end(); vfst.next()) {
1291 if (vfst.method()->is_class_initializer() ||
1292 (vfst.method()->method_holder()->is_subclass_of(vmClasses::ClassLoader_klass()) &&
1293 vfst.method()->name() == vmSymbols::loadClass_name())) {
1294 blocking = false;
1295 break;
1296 }
1297 }
1298
1299 // Don't allow blocking compilation requests to JVMCI
1300 // if JVMCI itself is not yet initialized
1301 if (!JVMCI::is_compiler_initialized() && compiler(comp_level)->is_jvmci()) {
1302 blocking = false;
1303 }
1304 }
1305
1306 // Don't allow blocking compilation requests if we are in JVMCIRuntime::shutdown
1307 // to avoid deadlock between compiler thread(s) and threads run at shutdown
1308 // such as the DestroyJavaVM thread.
1309 if (JVMCI::in_shutdown()) {
1310 blocking = false;
1311 }
1312 }
1313 #endif // INCLUDE_JVMCI
1314
1315 // We will enter the compilation in the queue.
1316 // 14012000: Note that this sets the queued_for_compile bits in
1317 // the target method. We can now reason that a method cannot be
1318 // queued for compilation more than once, as follows:
1319 // Before a thread queues a task for compilation, it first acquires
1320 // the compile queue lock, then checks if the method's queued bits
1321 // are set or it has already been compiled. Thus there can not be two
1322 // instances of a compilation task for the same method on the
1323 // compilation queue. Consider now the case where the compilation
1324 // thread has already removed a task for that method from the queue
1325 // and is in the midst of compiling it. In this case, the
1326 // queued_for_compile bits must be set in the method (and these
1327 // will be visible to the current thread, since the bits were set
1328 // under protection of the compile queue lock, which we hold now.
1329 // When the compilation completes, the compiler thread first sets
1330 // the compilation result and then clears the queued_for_compile
1331 // bits. Neither of these actions are protected by a barrier (or done
1332 // under the protection of a lock), so the only guarantee we have
1333 // (on machines with TSO (Total Store Order)) is that these values
1334 // will update in that order. As a result, the only combinations of
1335 // these bits that the current thread will see are, in temporal order:
1336 // <RESULT, QUEUE> :
1337 // <0, 1> : in compile queue, but not yet compiled
1338 // <1, 1> : compiled but queue bit not cleared
1339 // <1, 0> : compiled and queue bit cleared
1340 // Because we first check the queue bits then check the result bits,
1341 // we are assured that we cannot introduce a duplicate task.
1342 // Note that if we did the tests in the reverse order (i.e. check
1343 // result then check queued bit), we could get the result bit before
1344 // the compilation completed, and the queue bit after the compilation
1345 // completed, and end up introducing a "duplicate" (redundant) task.
1346 // In that case, the compiler thread should first check if a method
1347 // has already been compiled before trying to compile it.
1348 // NOTE: in the event that there are multiple compiler threads and
1349 // there is de-optimization/recompilation, things will get hairy,
1350 // and in that case it's best to protect both the testing (here) of
1351 // these bits, and their updating (here and elsewhere) under a
1352 // common lock.
1353 task = create_compile_task(queue,
1354 compile_id, method,
1355 osr_bci, comp_level,
1356 hot_count, compile_reason,
1357 blocking);
1358 }
1359
1360 if (blocking) {
1361 wait_for_completion(task);
1362 }
1363 }
1364
1365 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1366 int comp_level,
1367 int hot_count,
1368 CompileTask::CompileReason compile_reason,
1369 TRAPS) {
1370 // Do nothing if compilebroker is not initialized or compiles are submitted on level none
1371 if (!_initialized || comp_level == CompLevel_none) {
1372 return nullptr;
1373 }
1374
1375 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
1376 assert(comp != nullptr, "Ensure we have a compiler");
1377
1378 #if INCLUDE_JVMCI
1379 if (comp->is_jvmci() && !JVMCI::can_initialize_JVMCI()) {
1380 // JVMCI compilation is not yet initializable.
1381 return nullptr;
1382 }
1383 #endif
1384
1385 CompilerDirectiveMatcher matcher(method, comp_level);
1386 // CompileBroker::compile_method can trap and can have pending async exception.
1387 nmethod* nm = CompileBroker::compile_method(method, osr_bci, comp_level, hot_count, compile_reason, matcher.directive_set(), THREAD);
1388 return nm;
1389 }
1390
1391 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1392 int comp_level,
1393 int hot_count,
1394 CompileTask::CompileReason compile_reason,
1395 DirectiveSet* directive,
1396 TRAPS) {
1397
1398 // make sure arguments make sense
1399 assert(method->method_holder()->is_instance_klass(), "not an instance method");
1400 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1401 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1402 assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");
1403 // return quickly if possible
1404
1405 // lock, make sure that the compilation
1406 // isn't prohibited in a straightforward way.
1407 AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1408 if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1409 return nullptr;
1410 }
1411
1412 if (osr_bci == InvocationEntryBci) {
1413 // standard compilation
1414 nmethod* method_code = method->code();
1415 if (method_code != nullptr) {
1416 if (compilation_is_complete(method, osr_bci, comp_level)) {
1417 return method_code;
1418 }
1419 }
1420 if (method->is_not_compilable(comp_level)) {
1421 return nullptr;
1422 }
1423 } else {
1424 // osr compilation
1425 // We accept a higher level osr method
1426 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1427 if (nm != nullptr) return nm;
1428 if (method->is_not_osr_compilable(comp_level)) return nullptr;
1429 }
1430
1431 assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1432 // some prerequisites that are compiler specific
1433 if (comp->is_c2() || comp->is_jvmci()) {
1434 InternalOOMEMark iom(THREAD);
1435 method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1436 // Resolve all classes seen in the signature of the method
1437 // we are compiling.
1438 Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1439 }
1440
1441 // If the method is native, do the lookup in the thread requesting
1442 // the compilation. Native lookups can load code, which is not
1443 // permitted during compilation.
1444 //
1445 // Note: A native method implies non-osr compilation which is
1446 // checked with an assertion at the entry of this method.
1447 if (method->is_native() && !method->is_method_handle_intrinsic()) {
1448 address adr = NativeLookup::lookup(method, THREAD);
1449 if (HAS_PENDING_EXCEPTION) {
1450 // In case of an exception looking up the method, we just forget
1451 // about it. The interpreter will kick-in and throw the exception.
1452 method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1453 CLEAR_PENDING_EXCEPTION;
1454 return nullptr;
1455 }
1456 assert(method->has_native_function(), "must have native code by now");
1457 }
1458
1459 // RedefineClasses() has replaced this method; just return
1460 if (method->is_old()) {
1461 return nullptr;
1462 }
1463
1464 // JVMTI -- post_compile_event requires jmethod_id() that may require
1465 // a lock the compiling thread can not acquire. Prefetch it here.
1466 if (JvmtiExport::should_post_compiled_method_load()) {
1467 method->jmethod_id();
1468 }
1469
1470 // do the compilation
1471 if (method->is_native()) {
1472 if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1473 // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1474 // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1475 //
1476 // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1477 // in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls.
1478 AdapterHandlerLibrary::create_native_wrapper(method);
1479 } else {
1480 return nullptr;
1481 }
1482 } else {
1483 // If the compiler is shut off due to code cache getting full
1484 // fail out now so blocking compiles dont hang the java thread
1485 if (!should_compile_new_jobs()) {
1486 return nullptr;
1487 }
1488 bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;
1489 compile_method_base(method, osr_bci, comp_level, hot_count, compile_reason, is_blocking, THREAD);
1490 }
1491
1492 // return requested nmethod
1493 // We accept a higher level osr method
1494 if (osr_bci == InvocationEntryBci) {
1495 return method->code();
1496 }
1497 return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1498 }
1499
1500
1501 // ------------------------------------------------------------------
1502 // CompileBroker::compilation_is_complete
1503 //
1504 // See if compilation of this method is already complete.
1505 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1506 int osr_bci,
1507 int comp_level) {
1508 bool is_osr = (osr_bci != standard_entry_bci);
1509 if (is_osr) {
1510 if (method->is_not_osr_compilable(comp_level)) {
1511 return true;
1512 } else {
1513 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1514 return (result != nullptr);
1515 }
1516 } else {
1517 if (method->is_not_compilable(comp_level)) {
1518 return true;
1519 } else {
1520 nmethod* result = method->code();
1521 if (result == nullptr) return false;
1522 return comp_level == result->comp_level();
1523 }
1524 }
1525 }
1526
1527
1528 /**
1529 * See if this compilation is already requested.
1530 *
1531 * Implementation note: there is only a single "is in queue" bit
1532 * for each method. This means that the check below is overly
1533 * conservative in the sense that an osr compilation in the queue
1534 * will block a normal compilation from entering the queue (and vice
1535 * versa). This can be remedied by a full queue search to disambiguate
1536 * cases. If it is deemed profitable, this may be done.
1537 */
1538 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1539 return method->queued_for_compilation();
1540 }
1541
1542 // ------------------------------------------------------------------
1543 // CompileBroker::compilation_is_prohibited
1544 //
1545 // See if this compilation is not allowed.
1546 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) {
1547 bool is_native = method->is_native();
1548 // Some compilers may not support the compilation of natives.
1549 AbstractCompiler *comp = compiler(comp_level);
1550 if (is_native && (!CICompileNatives || comp == nullptr)) {
1551 method->set_not_compilable_quietly("native methods not supported", comp_level);
1552 return true;
1553 }
1554
1555 bool is_osr = (osr_bci != standard_entry_bci);
1556 // Some compilers may not support on stack replacement.
1557 if (is_osr && (!CICompileOSR || comp == nullptr)) {
1558 method->set_not_osr_compilable("OSR not supported", comp_level);
1559 return true;
1560 }
1561
1562 // The method may be explicitly excluded by the user.
1563 double scale;
1564 if (excluded || (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, scale) && scale == 0)) {
1565 bool quietly = CompilerOracle::be_quiet();
1566 if (PrintCompilation && !quietly) {
1567 // This does not happen quietly...
1568 ResourceMark rm;
1569 tty->print("### Excluding %s:%s",
1570 method->is_native() ? "generation of native wrapper" : "compile",
1571 (method->is_static() ? " static" : ""));
1572 method->print_short_name(tty);
1573 tty->cr();
1574 }
1575 method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly);
1576 }
1577
1578 return false;
1579 }
1580
1581 /**
1582 * Generate serialized IDs for compilation requests. If certain debugging flags are used
1583 * and the ID is not within the specified range, the method is not compiled and 0 is returned.
1584 * The function also allows to generate separate compilation IDs for OSR compilations.
1585 */
1586 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) {
1587 #ifdef ASSERT
1588 bool is_osr = (osr_bci != standard_entry_bci);
1589 int id;
1590 if (method->is_native()) {
1591 assert(!is_osr, "can't be osr");
1592 // Adapters, native wrappers and method handle intrinsics
1593 // should be generated always.
1594 return AtomicAccess::add(CICountNative ? &_native_compilation_id : &_compilation_id, 1);
1595 } else if (CICountOSR && is_osr) {
1596 id = AtomicAccess::add(&_osr_compilation_id, 1);
1597 if (CIStartOSR <= id && id < CIStopOSR) {
1598 return id;
1599 }
1600 } else {
1601 id = AtomicAccess::add(&_compilation_id, 1);
1602 if (CIStart <= id && id < CIStop) {
1603 return id;
1604 }
1605 }
1606
1607 // Method was not in the appropriate compilation range.
1608 method->set_not_compilable_quietly("Not in requested compile id range");
1609 return 0;
1610 #else
1611 // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1612 // only _compilation_id is incremented.
1613 return AtomicAccess::add(&_compilation_id, 1);
1614 #endif
1615 }
1616
1617 // ------------------------------------------------------------------
1618 // CompileBroker::assign_compile_id_unlocked
1619 //
1620 // Public wrapper for assign_compile_id that acquires the needed locks
1621 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1622 MutexLocker locker(thread, MethodCompileQueue_lock);
1623 return assign_compile_id(method, osr_bci);
1624 }
1625
1626 // ------------------------------------------------------------------
1627 // CompileBroker::create_compile_task
1628 //
1629 // Create a CompileTask object representing the current request for
1630 // compilation. Add this task to the queue.
1631 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1632 int compile_id,
1633 const methodHandle& method,
1634 int osr_bci,
1635 int comp_level,
1636 int hot_count,
1637 CompileTask::CompileReason compile_reason,
1638 bool blocking) {
1639 CompileTask* new_task = new CompileTask(compile_id, method, osr_bci, comp_level,
1640 hot_count, compile_reason, blocking);
1641 queue->add(new_task);
1642 return new_task;
1643 }
1644
1645 #if INCLUDE_JVMCI
1646 // The number of milliseconds to wait before checking if
1647 // JVMCI compilation has made progress.
1648 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1649
1650 // The number of JVMCI compilation progress checks that must fail
1651 // before unblocking a thread waiting for a blocking compilation.
1652 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1653
1654 /**
1655 * Waits for a JVMCI compiler to complete a given task. This thread
1656 * waits until either the task completes or it sees no JVMCI compilation
1657 * progress for N consecutive milliseconds where N is
1658 * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1659 * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1660 *
1661 * @return true if this thread needs to delete the task
1662 */
1663 bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) {
1664 assert(UseJVMCICompiler, "sanity");
1665 MonitorLocker ml(thread, CompileTaskWait_lock);
1666 int progress_wait_attempts = 0;
1667 jint thread_jvmci_compilation_ticks = 0;
1668 jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks();
1669 while (!task->is_complete() && !is_compilation_disabled_forever() &&
1670 ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) {
1671 JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state();
1672
1673 bool progress;
1674 if (jvmci_compile_state != nullptr) {
1675 jint ticks = jvmci_compile_state->compilation_ticks();
1676 progress = (ticks - thread_jvmci_compilation_ticks) != 0;
1677 JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks);
1678 thread_jvmci_compilation_ticks = ticks;
1679 } else {
1680 // Still waiting on JVMCI compiler queue. This thread may be holding a lock
1681 // that all JVMCI compiler threads are blocked on. We use the global JVMCI
1682 // compilation ticks to determine whether JVMCI compilation
1683 // is still making progress through the JVMCI compiler queue.
1684 jint ticks = jvmci->global_compilation_ticks();
1685 progress = (ticks - global_jvmci_compilation_ticks) != 0;
1686 JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks);
1687 global_jvmci_compilation_ticks = ticks;
1688 }
1689
1690 if (!progress) {
1691 if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) {
1692 if (PrintCompilation) {
1693 task->print(tty, "wait for blocking compilation timed out");
1694 }
1695 JVMCI_event_1("waiting on compilation %d timed out", task->compile_id());
1696 break;
1697 }
1698 } else {
1699 progress_wait_attempts = 0;
1700 }
1701 }
1702 task->clear_waiter();
1703 return task->is_complete();
1704 }
1705 #endif
1706
1707 /**
1708 * Wait for the compilation task to complete.
1709 */
1710 void CompileBroker::wait_for_completion(CompileTask* task) {
1711 if (CIPrintCompileQueue) {
1712 ttyLocker ttyl;
1713 tty->print_cr("BLOCKING FOR COMPILE");
1714 }
1715
1716 assert(task->is_blocking(), "can only wait on blocking task");
1717
1718 JavaThread* thread = JavaThread::current();
1719
1720 methodHandle method(thread, task->method());
1721 bool free_task;
1722 #if INCLUDE_JVMCI
1723 AbstractCompiler* comp = compiler(task->comp_level());
1724 if (!UseJVMCINativeLibrary && comp->is_jvmci() && !task->should_wait_for_compilation()) {
1725 // It may return before compilation is completed.
1726 // Note that libjvmci should not pre-emptively unblock
1727 // a thread waiting for a compilation as it does not call
1728 // Java code and so is not deadlock prone like jarjvmci.
1729 free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread);
1730 } else
1731 #endif
1732 {
1733 free_task = true;
1734 // Wait until the task is complete or compilation is shut down.
1735 MonitorLocker ml(thread, CompileTaskWait_lock);
1736 while (!task->is_complete() && !is_compilation_disabled_forever()) {
1737 ml.wait();
1738 }
1739 }
1740
1741 // It is harmless to check this status without the lock, because
1742 // completion is a stable property.
1743 if (!task->is_complete()) {
1744 // Task is not complete, likely because we are exiting for compilation
1745 // shutdown. The task can still be reached through the queue, or executed
1746 // by some compiler thread. There is no coordination with either MCQ lock
1747 // holders or compilers, therefore we cannot delete the task.
1748 //
1749 // This will leave task allocated, which leaks it. At this (degraded) point,
1750 // it is less risky to abandon the task, rather than attempting a more
1751 // complicated deletion protocol.
1752 free_task = false;
1753 }
1754
1755 if (free_task) {
1756 assert(task->is_complete(), "Compilation should have completed");
1757 assert(task->next() == nullptr && task->prev() == nullptr,
1758 "Completed task should not be in the queue");
1759
1760 // By convention, the waiter is responsible for deleting a
1761 // blocking CompileTask. Since there is only one waiter ever
1762 // waiting on a CompileTask, we know that no one else will
1763 // be using this CompileTask; we can delete it.
1764 delete task;
1765 }
1766 }
1767
1768 void CompileBroker::wait_for_no_active_tasks() {
1769 CompileTask::wait_for_no_active_tasks();
1770 }
1771
1772 /**
1773 * Initialize compiler thread(s) + compiler object(s). The postcondition
1774 * of this function is that the compiler runtimes are initialized and that
1775 * compiler threads can start compiling.
1776 */
1777 bool CompileBroker::init_compiler_runtime() {
1778 CompilerThread* thread = CompilerThread::current();
1779 AbstractCompiler* comp = thread->compiler();
1780 // Final sanity check - the compiler object must exist
1781 guarantee(comp != nullptr, "Compiler object must exist");
1782
1783 {
1784 // Must switch to native to allocate ci_env
1785 ThreadToNativeFromVM ttn(thread);
1786 ciEnv ci_env((CompileTask*)nullptr);
1787 // Cache Jvmti state
1788 ci_env.cache_jvmti_state();
1789 // Cache DTrace flags
1790 ci_env.cache_dtrace_flags();
1791
1792 // Switch back to VM state to do compiler initialization
1793 ThreadInVMfromNative tv(thread);
1794
1795 // Perform per-thread and global initializations
1796 comp->initialize();
1797 }
1798
1799 if (comp->is_failed()) {
1800 disable_compilation_forever();
1801 // If compiler initialization failed, no compiler thread that is specific to a
1802 // particular compiler runtime will ever start to compile methods.
1803 shutdown_compiler_runtime(comp, thread);
1804 return false;
1805 }
1806
1807 // C1 specific check
1808 if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
1809 warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1810 return false;
1811 }
1812
1813 return true;
1814 }
1815
1816 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
1817 BufferBlob* blob = thread->get_buffer_blob();
1818 if (blob != nullptr) {
1819 blob->purge();
1820 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1821 CodeCache::free(blob);
1822 }
1823 }
1824
1825 /**
1826 * If C1 and/or C2 initialization failed, we shut down all compilation.
1827 * We do this to keep things simple. This can be changed if it ever turns
1828 * out to be a problem.
1829 */
1830 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1831 free_buffer_blob_if_allocated(thread);
1832
1833 if (comp->should_perform_shutdown()) {
1834 // There are two reasons for shutting down the compiler
1835 // 1) compiler runtime initialization failed
1836 // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1837 warning("%s initialization failed. Shutting down all compilers", comp->name());
1838
1839 // Only one thread per compiler runtime object enters here
1840 // Set state to shut down
1841 comp->set_shut_down();
1842
1843 // Delete all queued compilation tasks to make compiler threads exit faster.
1844 if (_c1_compile_queue != nullptr) {
1845 _c1_compile_queue->delete_all();
1846 }
1847
1848 if (_c2_compile_queue != nullptr) {
1849 _c2_compile_queue->delete_all();
1850 }
1851
1852 // Set flags so that we continue execution with using interpreter only.
1853 UseCompiler = false;
1854 UseInterpreter = true;
1855
1856 // We could delete compiler runtimes also. However, there are references to
1857 // the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then
1858 // fail. This can be done later if necessary.
1859 }
1860 }
1861
1862 /**
1863 * Helper function to create new or reuse old CompileLog.
1864 */
1865 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
1866 if (!LogCompilation) return nullptr;
1867
1868 AbstractCompiler *compiler = ct->compiler();
1869 bool c1 = compiler->is_c1();
1870 jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
1871 assert(compiler_objects != nullptr, "must be initialized at this point");
1872 CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
1873 assert(logs != nullptr, "must be initialized at this point");
1874 int count = c1 ? _c1_count : _c2_count;
1875
1876 // Find Compiler number by its threadObj.
1877 oop compiler_obj = ct->threadObj();
1878 int compiler_number = 0;
1879 bool found = false;
1880 for (; compiler_number < count; compiler_number++) {
1881 if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
1882 found = true;
1883 break;
1884 }
1885 }
1886 assert(found, "Compiler must exist at this point");
1887
1888 // Determine pointer for this thread's log.
1889 CompileLog** log_ptr = &logs[compiler_number];
1890
1891 // Return old one if it exists.
1892 CompileLog* log = *log_ptr;
1893 if (log != nullptr) {
1894 ct->init_log(log);
1895 return log;
1896 }
1897
1898 // Create a new one and remember it.
1899 init_compiler_thread_log();
1900 log = ct->log();
1901 *log_ptr = log;
1902 return log;
1903 }
1904
1905 // ------------------------------------------------------------------
1906 // CompileBroker::compiler_thread_loop
1907 //
1908 // The main loop run by a CompilerThread.
1909 void CompileBroker::compiler_thread_loop() {
1910 CompilerThread* thread = CompilerThread::current();
1911 CompileQueue* queue = thread->queue();
1912 // For the thread that initializes the ciObjectFactory
1913 // this resource mark holds all the shared objects
1914 ResourceMark rm;
1915
1916 // First thread to get here will initialize the compiler interface
1917
1918 {
1919 ASSERT_IN_VM;
1920 MutexLocker only_one (thread, CompileThread_lock);
1921 if (!ciObjectFactory::is_initialized()) {
1922 ciObjectFactory::initialize();
1923 }
1924 }
1925
1926 // Open a log.
1927 CompileLog* log = get_log(thread);
1928 if (log != nullptr) {
1929 log->begin_elem("start_compile_thread name='%s' thread='%zu' process='%d'",
1930 thread->name(),
1931 os::current_thread_id(),
1932 os::current_process_id());
1933 log->stamp();
1934 log->end_elem();
1935 }
1936
1937 if (!thread->init_compilation_timeout()) {
1938 return;
1939 }
1940
1941 // If compiler thread/runtime initialization fails, exit the compiler thread
1942 if (!init_compiler_runtime()) {
1943 return;
1944 }
1945
1946 thread->start_idle_timer();
1947
1948 // Poll for new compilation tasks as long as the JVM runs. Compilation
1949 // should only be disabled if something went wrong while initializing the
1950 // compiler runtimes. This, in turn, should not happen. The only known case
1951 // when compiler runtime initialization fails is if there is not enough free
1952 // space in the code cache to generate the necessary stubs, etc.
1953 while (!is_compilation_disabled_forever()) {
1954 // We need this HandleMark to avoid leaking VM handles.
1955 HandleMark hm(thread);
1956
1957 CompileTask* task = queue->get(thread);
1958 if (task == nullptr) {
1959 if (UseDynamicNumberOfCompilerThreads) {
1960 // Access compiler_count under lock to enforce consistency.
1961 MutexLocker only_one(CompileThread_lock);
1962 if (can_remove(thread, true)) {
1963 if (trace_compiler_threads()) {
1964 ResourceMark rm;
1965 stringStream msg;
1966 msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
1967 thread->name(), thread->idle_time_millis());
1968 print_compiler_threads(msg);
1969 }
1970
1971 // Notify compiler that the compiler thread is about to stop
1972 thread->compiler()->stopping_compiler_thread(thread);
1973
1974 free_buffer_blob_if_allocated(thread);
1975 return; // Stop this thread.
1976 }
1977 }
1978 } else {
1979 // Assign the task to the current thread. Mark this compilation
1980 // thread as active for the profiler.
1981 // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
1982 // occurs after fetching the compile task off the queue.
1983 CompileTaskWrapper ctw(task);
1984 methodHandle method(thread, task->method());
1985
1986 // Never compile a method if breakpoints are present in it
1987 if (method()->number_of_breakpoints() == 0) {
1988 // Compile the method.
1989 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1990 invoke_compiler_on_method(task);
1991 thread->start_idle_timer();
1992 } else {
1993 // After compilation is disabled, remove remaining methods from queue
1994 method->clear_queued_for_compilation();
1995 task->set_failure_reason("compilation is disabled");
1996 }
1997 } else {
1998 task->set_failure_reason("breakpoints are present");
1999 }
2000
2001 if (UseDynamicNumberOfCompilerThreads) {
2002 possibly_add_compiler_threads(thread);
2003 assert(!thread->has_pending_exception(), "should have been handled");
2004 }
2005 }
2006 }
2007
2008 // Shut down compiler runtime
2009 shutdown_compiler_runtime(thread->compiler(), thread);
2010 }
2011
2012 // ------------------------------------------------------------------
2013 // CompileBroker::init_compiler_thread_log
2014 //
2015 // Set up state required by +LogCompilation.
2016 void CompileBroker::init_compiler_thread_log() {
2017 CompilerThread* thread = CompilerThread::current();
2018 char file_name[4*K];
2019 FILE* fp = nullptr;
2020 intx thread_id = os::current_thread_id();
2021 for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
2022 const char* dir = (try_temp_dir ? os::get_temp_directory() : nullptr);
2023 if (dir == nullptr) {
2024 jio_snprintf(file_name, sizeof(file_name), "hs_c%zu_pid%u.log",
2025 thread_id, os::current_process_id());
2026 } else {
2027 jio_snprintf(file_name, sizeof(file_name),
2028 "%s%shs_c%zu_pid%u.log", dir,
2029 os::file_separator(), thread_id, os::current_process_id());
2030 }
2031
2032 fp = os::fopen(file_name, "wt");
2033 if (fp != nullptr) {
2034 if (LogCompilation && Verbose) {
2035 tty->print_cr("Opening compilation log %s", file_name);
2036 }
2037 CompileLog* log = new(mtCompiler) CompileLog(file_name, fp, thread_id);
2038 if (log == nullptr) {
2039 fclose(fp);
2040 return;
2041 }
2042 thread->init_log(log);
2043
2044 if (xtty != nullptr) {
2045 ttyLocker ttyl;
2046 // Record any per thread log files
2047 xtty->elem("thread_logfile thread='%zd' filename='%s'", thread_id, file_name);
2048 }
2049 return;
2050 }
2051 }
2052 warning("Cannot open log file: %s", file_name);
2053 }
2054
2055 void CompileBroker::log_metaspace_failure() {
2056 const char* message = "some methods may not be compiled because metaspace "
2057 "is out of memory";
2058 if (CompilationLog::log() != nullptr) {
2059 CompilationLog::log()->log_metaspace_failure(message);
2060 }
2061 if (PrintCompilation) {
2062 tty->print_cr("COMPILE PROFILING SKIPPED: %s", message);
2063 }
2064 }
2065
2066
2067 // ------------------------------------------------------------------
2068 // CompileBroker::set_should_block
2069 //
2070 // Set _should_block.
2071 // Call this from the VM, with Threads_lock held and a safepoint requested.
2072 void CompileBroker::set_should_block() {
2073 assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2074 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
2075 #ifndef PRODUCT
2076 if (PrintCompilation && (Verbose || WizardMode))
2077 tty->print_cr("notifying compiler thread pool to block");
2078 #endif
2079 _should_block = true;
2080 }
2081
2082 // ------------------------------------------------------------------
2083 // CompileBroker::maybe_block
2084 //
2085 // Call this from the compiler at convenient points, to poll for _should_block.
2086 void CompileBroker::maybe_block() {
2087 if (_should_block) {
2088 #ifndef PRODUCT
2089 if (PrintCompilation && (Verbose || WizardMode))
2090 tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));
2091 #endif
2092 // If we are executing a task during the request to block, report the task
2093 // before disappearing.
2094 CompilerThread* thread = CompilerThread::current();
2095 if (thread != nullptr) {
2096 CompileTask* task = thread->task();
2097 if (task != nullptr) {
2098 if (PrintCompilation) {
2099 task->print(tty, "blocked");
2100 }
2101 task->print_ul("blocked");
2102 }
2103 }
2104 // Go to VM state and block for final VM shutdown safepoint.
2105 ThreadInVMfromNative tivfn(JavaThread::current());
2106 assert(false, "Should never unblock from TIVNM entry");
2107 }
2108 }
2109
2110 // wrapper for CodeCache::print_summary()
2111 static void codecache_print(bool detailed)
2112 {
2113 stringStream s;
2114 // Dump code cache into a buffer before locking the tty,
2115 {
2116 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2117 CodeCache::print_summary(&s, detailed);
2118 }
2119 ttyLocker ttyl;
2120 tty->print("%s", s.freeze());
2121 }
2122
2123 // wrapper for CodeCache::print_summary() using outputStream
2124 static void codecache_print(outputStream* out, bool detailed) {
2125 stringStream s;
2126
2127 // Dump code cache into a buffer
2128 {
2129 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2130 CodeCache::print_summary(&s, detailed);
2131 }
2132
2133 char* remaining_log = s.as_string();
2134 while (*remaining_log != '\0') {
2135 char* eol = strchr(remaining_log, '\n');
2136 if (eol == nullptr) {
2137 out->print_cr("%s", remaining_log);
2138 remaining_log = remaining_log + strlen(remaining_log);
2139 } else {
2140 *eol = '\0';
2141 out->print_cr("%s", remaining_log);
2142 remaining_log = eol + 1;
2143 }
2144 }
2145 }
2146
2147 void CompileBroker::handle_compile_error(CompilerThread* thread, CompileTask* task, ciEnv* ci_env,
2148 int compilable, const char* failure_reason) {
2149 if (!AbortVMOnCompilationFailure) {
2150 return;
2151 }
2152 if (compilable == ciEnv::MethodCompilable_not_at_tier) {
2153 fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason);
2154 }
2155 if (compilable == ciEnv::MethodCompilable_never) {
2156 fatal("Never compilable: %s", failure_reason);
2157 }
2158 }
2159
2160 static void post_compilation_event(EventCompilation& event, CompileTask* task) {
2161 assert(task != nullptr, "invariant");
2162 CompilerEvent::CompilationEvent::post(event,
2163 task->compile_id(),
2164 task->compiler()->type(),
2165 task->method(),
2166 task->comp_level(),
2167 task->is_success(),
2168 task->osr_bci() != CompileBroker::standard_entry_bci,
2169 task->nm_total_size(),
2170 task->num_inlined_bytecodes(),
2171 task->arena_bytes());
2172 }
2173
2174 int DirectivesStack::_depth = 0;
2175 CompilerDirectives* DirectivesStack::_top = nullptr;
2176 CompilerDirectives* DirectivesStack::_bottom = nullptr;
2177
2178 // Acquires Compilation_lock and waits for it to be notified
2179 // as long as WhiteBox::compilation_locked is true.
2180 static void whitebox_lock_compilation() {
2181 MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2182 while (WhiteBox::compilation_locked) {
2183 locker.wait();
2184 }
2185 }
2186
2187 // ------------------------------------------------------------------
2188 // CompileBroker::invoke_compiler_on_method
2189 //
2190 // Compile a method.
2191 //
2192 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2193 task->print_ul();
2194 elapsedTimer time;
2195
2196 DirectiveSet* directive = task->directive();
2197 if (directive->PrintCompilationOption) {
2198 ResourceMark rm;
2199 task->print_tty();
2200 }
2201
2202 CompilerThread* thread = CompilerThread::current();
2203 ResourceMark rm(thread);
2204
2205 if (CompilationLog::log() != nullptr) {
2206 CompilationLog::log()->log_compile(thread, task);
2207 }
2208
2209 // Common flags.
2210 int compile_id = task->compile_id();
2211 int osr_bci = task->osr_bci();
2212 bool is_osr = (osr_bci != standard_entry_bci);
2213 bool should_log = (thread->log() != nullptr);
2214 bool should_break = false;
2215 const int task_level = task->comp_level();
2216 AbstractCompiler* comp = task->compiler();
2217 {
2218 // create the handle inside it's own block so it can't
2219 // accidentally be referenced once the thread transitions to
2220 // native. The NoHandleMark before the transition should catch
2221 // any cases where this occurs in the future.
2222 methodHandle method(thread, task->method());
2223
2224 assert(!method->is_native(), "no longer compile natives");
2225
2226 // Update compile information when using perfdata.
2227 if (UsePerfData) {
2228 update_compile_perf_data(thread, method, is_osr);
2229 }
2230
2231 DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2232 }
2233
2234 should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2235 if (should_log && !directive->LogOption) {
2236 should_log = false;
2237 }
2238
2239 // Allocate a new set of JNI handles.
2240 JNIHandleMark jhm(thread);
2241 Method* target_handle = task->method();
2242 int compilable = ciEnv::MethodCompilable;
2243 const char* failure_reason = nullptr;
2244 bool failure_reason_on_C_heap = false;
2245 const char* retry_message = nullptr;
2246
2247 #if INCLUDE_JVMCI
2248 if (UseJVMCICompiler && comp != nullptr && comp->is_jvmci()) {
2249 JVMCICompiler* jvmci = (JVMCICompiler*) comp;
2250
2251 TraceTime t1("compilation", &time);
2252 EventCompilation event;
2253 JVMCICompileState compile_state(task, jvmci);
2254 JVMCIRuntime *runtime = nullptr;
2255
2256 if (JVMCI::in_shutdown()) {
2257 failure_reason = "in JVMCI shutdown";
2258 retry_message = "not retryable";
2259 compilable = ciEnv::MethodCompilable_never;
2260 } else if (compile_state.target_method_is_old()) {
2261 // Skip redefined methods
2262 failure_reason = "redefined method";
2263 retry_message = "not retryable";
2264 compilable = ciEnv::MethodCompilable_never;
2265 } else {
2266 JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__);
2267 if (env.init_error() != JNI_OK) {
2268 const char* msg = env.init_error_msg();
2269 failure_reason = os::strdup(err_msg("Error attaching to libjvmci (err: %d, %s)",
2270 env.init_error(), msg == nullptr ? "unknown" : msg), mtJVMCI);
2271 bool reason_on_C_heap = true;
2272 // In case of JNI_ENOMEM, there's a good chance a subsequent attempt to create libjvmci or attach to it
2273 // might succeed. Other errors most likely indicate a non-recoverable error in the JVMCI runtime.
2274 bool retryable = env.init_error() == JNI_ENOMEM;
2275 compile_state.set_failure(retryable, failure_reason, reason_on_C_heap);
2276 }
2277 if (failure_reason == nullptr) {
2278 if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2279 // Must switch to native to block
2280 ThreadToNativeFromVM ttn(thread);
2281 whitebox_lock_compilation();
2282 }
2283 methodHandle method(thread, target_handle);
2284 runtime = env.runtime();
2285 runtime->compile_method(&env, jvmci, method, osr_bci);
2286
2287 failure_reason = compile_state.failure_reason();
2288 failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap();
2289 if (!compile_state.retryable()) {
2290 retry_message = "not retryable";
2291 compilable = ciEnv::MethodCompilable_not_at_tier;
2292 }
2293 if (!task->is_success()) {
2294 assert(failure_reason != nullptr, "must specify failure_reason");
2295 }
2296 }
2297 }
2298 if (!task->is_success() && !JVMCI::in_shutdown()) {
2299 handle_compile_error(thread, task, nullptr, compilable, failure_reason);
2300 }
2301 if (event.should_commit()) {
2302 post_compilation_event(event, task);
2303 }
2304
2305 if (runtime != nullptr) {
2306 runtime->post_compile(thread);
2307 }
2308 } else
2309 #endif // INCLUDE_JVMCI
2310 {
2311 NoHandleMark nhm;
2312 ThreadToNativeFromVM ttn(thread);
2313
2314 ciEnv ci_env(task);
2315 if (should_break) {
2316 ci_env.set_break_at_compile(true);
2317 }
2318 if (should_log) {
2319 ci_env.set_log(thread->log());
2320 }
2321 assert(thread->env() == &ci_env, "set by ci_env");
2322 // The thread-env() field is cleared in ~CompileTaskWrapper.
2323
2324 // Cache Jvmti state
2325 bool method_is_old = ci_env.cache_jvmti_state();
2326
2327 // Skip redefined methods
2328 if (method_is_old) {
2329 ci_env.record_method_not_compilable("redefined method", true);
2330 }
2331
2332 // Cache DTrace flags
2333 ci_env.cache_dtrace_flags();
2334
2335 ciMethod* target = ci_env.get_method_from_handle(target_handle);
2336
2337 TraceTime t1("compilation", &time);
2338 EventCompilation event;
2339
2340 if (comp == nullptr) {
2341 ci_env.record_method_not_compilable("no compiler");
2342 } else if (!ci_env.failing()) {
2343 if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2344 whitebox_lock_compilation();
2345 }
2346 comp->compile_method(&ci_env, target, osr_bci, true, directive);
2347
2348 /* Repeat compilation without installing code for profiling purposes */
2349 int repeat_compilation_count = directive->RepeatCompilationOption;
2350 if (repeat_compilation_count > 0) {
2351 CHeapStringHolder failure_reason;
2352 failure_reason.set(ci_env._failure_reason.get());
2353 while (repeat_compilation_count > 0) {
2354 ResourceMark rm(thread);
2355 task->print_ul("NO CODE INSTALLED");
2356 thread->timeout()->reset();
2357 ci_env._failure_reason.clear();
2358 comp->compile_method(&ci_env, target, osr_bci, false, directive);
2359 repeat_compilation_count--;
2360 }
2361 ci_env._failure_reason.set(failure_reason.get());
2362 }
2363 }
2364
2365
2366 if (!ci_env.failing() && !task->is_success()) {
2367 const char* reason = task->failure_reason();
2368 assert(reason != nullptr, "compiler should always document failure");
2369 // Do not attempt further compilations of this method.
2370 ci_env.record_method_not_compilable(reason != nullptr ? reason : "compile failed: reason unknown");
2371 }
2372
2373 // Copy this bit to the enclosing block:
2374 compilable = ci_env.compilable();
2375
2376 if (ci_env.failing()) {
2377 // Duplicate the failure reason string, so that it outlives ciEnv
2378 failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2379 failure_reason_on_C_heap = true;
2380 retry_message = ci_env.retry_message();
2381 ci_env.report_failure(failure_reason);
2382 }
2383
2384 if (ci_env.failing()) {
2385 handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2386 }
2387 if (event.should_commit()) {
2388 post_compilation_event(event, task);
2389 }
2390 }
2391
2392 if (failure_reason != nullptr) {
2393 task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2394 if (CompilationLog::log() != nullptr) {
2395 CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2396 }
2397 if (PrintCompilation || directive->PrintCompilationOption) {
2398 FormatBufferResource msg = retry_message != nullptr ?
2399 FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2400 FormatBufferResource("COMPILE SKIPPED: %s", failure_reason);
2401 task->print(tty, msg);
2402 }
2403 }
2404
2405 task->mark_finished(os::elapsed_counter());
2406
2407 methodHandle method(thread, task->method());
2408
2409 DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2410
2411 collect_statistics(thread, time, task);
2412
2413 if (PrintCompilation2 || directive->PrintCompilation2Option) {
2414 ResourceMark rm;
2415 task->print_post(tty);
2416 }
2417
2418 Log(compilation, codecache) log;
2419 if (log.is_debug()) {
2420 LogStream ls(log.debug());
2421 codecache_print(&ls, /* detailed= */ false);
2422 }
2423 if (PrintCodeCacheOnCompilation) {
2424 codecache_print(/* detailed= */ false);
2425 }
2426 // Disable compilation, if required.
2427 switch (compilable) {
2428 case ciEnv::MethodCompilable_never:
2429 if (is_osr)
2430 method->set_not_osr_compilable_quietly("MethodCompilable_never");
2431 else
2432 method->set_not_compilable_quietly("MethodCompilable_never");
2433 break;
2434 case ciEnv::MethodCompilable_not_at_tier:
2435 if (is_osr)
2436 method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2437 else
2438 method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2439 break;
2440 }
2441
2442 // Note that the queued_for_compilation bits are cleared without
2443 // protection of a mutex. [They were set by the requester thread,
2444 // when adding the task to the compile queue -- at which time the
2445 // compile queue lock was held. Subsequently, we acquired the compile
2446 // queue lock to get this task off the compile queue; thus (to belabour
2447 // the point somewhat) our clearing of the bits must be occurring
2448 // only after the setting of the bits. See also 14012000 above.
2449 method->clear_queued_for_compilation();
2450 }
2451
2452 /**
2453 * The CodeCache is full. Print warning and disable compilation.
2454 * Schedule code cache cleaning so compilation can continue later.
2455 * This function needs to be called only from CodeCache::allocate(),
2456 * since we currently handle a full code cache uniformly.
2457 */
2458 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2459 UseInterpreter = true;
2460 if (UseCompiler || AlwaysCompileLoopMethods ) {
2461 if (xtty != nullptr) {
2462 stringStream s;
2463 // Dump code cache state into a buffer before locking the tty,
2464 // because log_state() will use locks causing lock conflicts.
2465 CodeCache::log_state(&s);
2466 // Lock to prevent tearing
2467 ttyLocker ttyl;
2468 xtty->begin_elem("code_cache_full");
2469 xtty->print("%s", s.freeze());
2470 xtty->stamp();
2471 xtty->end_elem();
2472 }
2473
2474 #ifndef PRODUCT
2475 if (ExitOnFullCodeCache) {
2476 codecache_print(/* detailed= */ true);
2477 before_exit(JavaThread::current());
2478 exit_globals(); // will delete tty
2479 vm_direct_exit(1);
2480 }
2481 #endif
2482 if (UseCodeCacheFlushing) {
2483 // Since code cache is full, immediately stop new compiles
2484 if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {
2485 log_info(codecache)("Code cache is full - disabling compilation");
2486 }
2487 } else {
2488 disable_compilation_forever();
2489 }
2490
2491 CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning());
2492 }
2493 }
2494
2495 // ------------------------------------------------------------------
2496 // CompileBroker::update_compile_perf_data
2497 //
2498 // Record this compilation for debugging purposes.
2499 void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) {
2500 ResourceMark rm;
2501 char* method_name = method->name()->as_C_string();
2502 char current_method[CompilerCounters::cmname_buffer_length];
2503 size_t maxLen = CompilerCounters::cmname_buffer_length;
2504
2505 const char* class_name = method->method_holder()->name()->as_C_string();
2506
2507 size_t s1len = strlen(class_name);
2508 size_t s2len = strlen(method_name);
2509
2510 // check if we need to truncate the string
2511 if (s1len + s2len + 2 > maxLen) {
2512
2513 // the strategy is to lop off the leading characters of the
2514 // class name and the trailing characters of the method name.
2515
2516 if (s2len + 2 > maxLen) {
2517 // lop of the entire class name string, let snprintf handle
2518 // truncation of the method name.
2519 class_name += s1len; // null string
2520 }
2521 else {
2522 // lop off the extra characters from the front of the class name
2523 class_name += ((s1len + s2len + 2) - maxLen);
2524 }
2525 }
2526
2527 jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
2528
2529 int last_compile_type = normal_compile;
2530 if (CICountOSR && is_osr) {
2531 last_compile_type = osr_compile;
2532 } else if (CICountNative && method->is_native()) {
2533 last_compile_type = native_compile;
2534 }
2535
2536 CompilerCounters* counters = thread->counters();
2537 counters->set_current_method(current_method);
2538 counters->set_compile_type((jlong) last_compile_type);
2539 }
2540
2541 // ------------------------------------------------------------------
2542 // CompileBroker::collect_statistics
2543 //
2544 // Collect statistics about the compilation.
2545
2546 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2547 bool success = task->is_success();
2548 methodHandle method (thread, task->method());
2549 int compile_id = task->compile_id();
2550 bool is_osr = (task->osr_bci() != standard_entry_bci);
2551 const int comp_level = task->comp_level();
2552 CompilerCounters* counters = thread->counters();
2553
2554 MutexLocker locker(CompileStatistics_lock);
2555
2556 // _perf variables are production performance counters which are
2557 // updated regardless of the setting of the CITime and CITimeEach flags
2558 //
2559
2560 // account all time, including bailouts and failures in this counter;
2561 // C1 and C2 counters are counting both successful and unsuccessful compiles
2562 _t_total_compilation.add(time);
2563
2564 // Update compilation times. Used by the implementation of JFR CompilerStatistics
2565 // and java.lang.management.CompilationMXBean.
2566 _perf_total_compilation->inc(time.ticks());
2567 _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2568
2569 if (!success) {
2570 _total_bailout_count++;
2571 if (UsePerfData) {
2572 _perf_last_failed_method->set_value(counters->current_method());
2573 _perf_last_failed_type->set_value(counters->compile_type());
2574 _perf_total_bailout_count->inc();
2575 }
2576 _t_bailedout_compilation.add(time);
2577 } else if (!task->is_success()) {
2578 if (UsePerfData) {
2579 _perf_last_invalidated_method->set_value(counters->current_method());
2580 _perf_last_invalidated_type->set_value(counters->compile_type());
2581 _perf_total_invalidated_count->inc();
2582 }
2583 _total_invalidated_count++;
2584 _t_invalidated_compilation.add(time);
2585 } else {
2586 // Compilation succeeded
2587 if (CITime) {
2588 int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2589 if (is_osr) {
2590 _t_osr_compilation.add(time);
2591 _sum_osr_bytes_compiled += bytes_compiled;
2592 } else {
2593 _t_standard_compilation.add(time);
2594 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2595 }
2596
2597 // Collect statistic per compilation level
2598 if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2599 CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2600 if (is_osr) {
2601 stats->_osr.update(time, bytes_compiled);
2602 } else {
2603 stats->_standard.update(time, bytes_compiled);
2604 }
2605 stats->_nmethods_size += task->nm_total_size();
2606 stats->_nmethods_code_size += task->nm_insts_size();
2607 } else {
2608 assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2609 }
2610
2611 // Collect statistic per compiler
2612 AbstractCompiler* comp = task->compiler();
2613 if (comp) {
2614 CompilerStatistics* stats = comp->stats();
2615 if (is_osr) {
2616 stats->_osr.update(time, bytes_compiled);
2617 } else {
2618 stats->_standard.update(time, bytes_compiled);
2619 }
2620 stats->_nmethods_size += task->nm_total_size();
2621 stats->_nmethods_code_size += task->nm_insts_size();
2622 } else { // if (!comp)
2623 assert(false, "Compiler object must exist");
2624 }
2625 }
2626
2627 if (UsePerfData) {
2628 // save the name of the last method compiled
2629 _perf_last_method->set_value(counters->current_method());
2630 _perf_last_compile_type->set_value(counters->compile_type());
2631 _perf_last_compile_size->set_value(method->code_size() +
2632 task->num_inlined_bytecodes());
2633 if (is_osr) {
2634 _perf_osr_compilation->inc(time.ticks());
2635 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2636 } else {
2637 _perf_standard_compilation->inc(time.ticks());
2638 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2639 }
2640 }
2641
2642 if (CITimeEach) {
2643 double compile_time = time.seconds();
2644 double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time;
2645 tty->print_cr("%3d seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)",
2646 compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
2647 }
2648
2649 // Collect counts of successful compilations
2650 _sum_nmethod_size += task->nm_total_size();
2651 _sum_nmethod_code_size += task->nm_insts_size();
2652 _total_compile_count++;
2653
2654 if (UsePerfData) {
2655 _perf_sum_nmethod_size->inc( task->nm_total_size());
2656 _perf_sum_nmethod_code_size->inc(task->nm_insts_size());
2657 _perf_total_compile_count->inc();
2658 }
2659
2660 if (is_osr) {
2661 if (UsePerfData) _perf_total_osr_compile_count->inc();
2662 _total_osr_compile_count++;
2663 } else {
2664 if (UsePerfData) _perf_total_standard_compile_count->inc();
2665 _total_standard_compile_count++;
2666 }
2667 }
2668 // set the current method for the thread to null
2669 if (UsePerfData) counters->set_current_method("");
2670 }
2671
2672 const char* CompileBroker::compiler_name(int comp_level) {
2673 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2674 if (comp == nullptr) {
2675 return "no compiler";
2676 } else {
2677 return (comp->name());
2678 }
2679 }
2680
2681 jlong CompileBroker::total_compilation_ticks() {
2682 return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2683 }
2684
2685 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2686 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}",
2687 name, stats->bytes_per_second(),
2688 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2689 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2690 stats->_nmethods_size, stats->_nmethods_code_size);
2691 }
2692
2693 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
2694 if (per_compiler) {
2695 if (aggregate) {
2696 tty->cr();
2697 tty->print_cr("Individual compiler times (for compiled methods only)");
2698 tty->print_cr("------------------------------------------------");
2699 tty->cr();
2700 }
2701 for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
2702 AbstractCompiler* comp = _compilers[i];
2703 if (comp != nullptr) {
2704 print_times(comp->name(), comp->stats());
2705 }
2706 }
2707 if (aggregate) {
2708 tty->cr();
2709 tty->print_cr("Individual compilation Tier times (for compiled methods only)");
2710 tty->print_cr("------------------------------------------------");
2711 tty->cr();
2712 }
2713 char tier_name[256];
2714 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
2715 CompilerStatistics* stats = &_stats_per_level[tier-1];
2716 os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
2717 print_times(tier_name, stats);
2718 }
2719 }
2720
2721 if (!aggregate) {
2722 return;
2723 }
2724
2725 elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
2726 elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
2727 elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
2728
2729 uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
2730 uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
2731
2732 uint standard_compile_count = CompileBroker::_total_standard_compile_count;
2733 uint osr_compile_count = CompileBroker::_total_osr_compile_count;
2734 uint total_compile_count = CompileBroker::_total_compile_count;
2735 uint total_bailout_count = CompileBroker::_total_bailout_count;
2736 uint total_invalidated_count = CompileBroker::_total_invalidated_count;
2737
2738 uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
2739 uint nmethods_size = CompileBroker::_sum_nmethod_size;
2740
2741 tty->cr();
2742 tty->print_cr("Accumulated compiler times");
2743 tty->print_cr("----------------------------------------------------------");
2744 //0000000000111111111122222222223333333333444444444455555555556666666666
2745 //0123456789012345678901234567890123456789012345678901234567890123456789
2746 tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds());
2747 tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s",
2748 standard_compilation.seconds(),
2749 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
2750 tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s",
2751 CompileBroker::_t_bailedout_compilation.seconds(),
2752 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
2753 tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s",
2754 osr_compilation.seconds(),
2755 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
2756 tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s",
2757 CompileBroker::_t_invalidated_compilation.seconds(),
2758 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
2759
2760 AbstractCompiler *comp = compiler(CompLevel_simple);
2761 if (comp != nullptr) {
2762 tty->cr();
2763 comp->print_timers();
2764 }
2765 comp = compiler(CompLevel_full_optimization);
2766 if (comp != nullptr) {
2767 tty->cr();
2768 comp->print_timers();
2769 }
2770 #if INCLUDE_JVMCI
2771 if (EnableJVMCI) {
2772 JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
2773 if (jvmci_comp != nullptr && jvmci_comp != comp) {
2774 tty->cr();
2775 jvmci_comp->print_timers();
2776 }
2777 }
2778 #endif
2779
2780 tty->cr();
2781 tty->print_cr(" Total compiled methods : %8u methods", total_compile_count);
2782 tty->print_cr(" Standard compilation : %8u methods", standard_compile_count);
2783 tty->print_cr(" On stack replacement : %8u methods", osr_compile_count);
2784 uint tcb = osr_bytes_compiled + standard_bytes_compiled;
2785 tty->print_cr(" Total compiled bytecodes : %8u bytes", tcb);
2786 tty->print_cr(" Standard compilation : %8u bytes", standard_bytes_compiled);
2787 tty->print_cr(" On stack replacement : %8u bytes", osr_bytes_compiled);
2788 double tcs = total_compilation.seconds();
2789 uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
2790 tty->print_cr(" Average compilation speed : %8u bytes/s", bps);
2791 tty->cr();
2792 tty->print_cr(" nmethod code size : %8u bytes", nmethods_code_size);
2793 tty->print_cr(" nmethod total size : %8u bytes", nmethods_size);
2794 }
2795
2796 // Print general/accumulated JIT information.
2797 void CompileBroker::print_info(outputStream *out) {
2798 if (out == nullptr) out = tty;
2799 out->cr();
2800 out->print_cr("======================");
2801 out->print_cr(" General JIT info ");
2802 out->print_cr("======================");
2803 out->cr();
2804 out->print_cr(" JIT is : %7s", should_compile_new_jobs() ? "on" : "off");
2805 out->print_cr(" Compiler threads : %7d", (int)CICompilerCount);
2806 out->cr();
2807 out->print_cr("CodeCache overview");
2808 out->print_cr("--------------------------------------------------------");
2809 out->cr();
2810 out->print_cr(" Reserved size : %7zu KB", CodeCache::max_capacity() / K);
2811 out->print_cr(" Committed size : %7zu KB", CodeCache::capacity() / K);
2812 out->print_cr(" Unallocated capacity : %7zu KB", CodeCache::unallocated_capacity() / K);
2813 out->cr();
2814 }
2815
2816 // Note: tty_lock must not be held upon entry to this function.
2817 // Print functions called from herein do "micro-locking" on tty_lock.
2818 // That's a tradeoff which keeps together important blocks of output.
2819 // At the same time, continuous tty_lock hold time is kept in check,
2820 // preventing concurrently printing threads from stalling a long time.
2821 void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) {
2822 TimeStamp ts_total;
2823 TimeStamp ts_global;
2824 TimeStamp ts;
2825
2826 bool allFun = !strcmp(function, "all");
2827 bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun;
2828 bool usedSpace = !strcmp(function, "UsedSpace") || allFun;
2829 bool freeSpace = !strcmp(function, "FreeSpace") || allFun;
2830 bool methodCount = !strcmp(function, "MethodCount") || allFun;
2831 bool methodSpace = !strcmp(function, "MethodSpace") || allFun;
2832 bool methodAge = !strcmp(function, "MethodAge") || allFun;
2833 bool methodNames = !strcmp(function, "MethodNames") || allFun;
2834 bool discard = !strcmp(function, "discard") || allFun;
2835
2836 if (out == nullptr) {
2837 out = tty;
2838 }
2839
2840 if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) {
2841 out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function);
2842 out->cr();
2843 return;
2844 }
2845
2846 ts_total.update(); // record starting point
2847
2848 if (aggregate) {
2849 print_info(out);
2850 }
2851
2852 // We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function.
2853 // That prevents other threads from destroying (making inconsistent) our view on the CodeHeap.
2854 // When we request individual parts of the analysis via the jcmd interface, it is possible
2855 // that in between another thread (another jcmd user or the vm running into CodeCache OOM)
2856 // updated the aggregated data. We will then see a modified, but again consistent, view
2857 // on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold
2858 // a lock across user interaction.
2859
2860 // We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock.
2861 // CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time,
2862 // leading to an unnecessarily long hold time of the other locks we acquired before.
2863 ts.update(); // record starting point
2864 MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag);
2865 out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds());
2866
2867 // Holding the CodeCache_lock protects from concurrent alterations of the CodeCache.
2868 // Unfortunately, such protection is not sufficient:
2869 // When a new nmethod is created via ciEnv::register_method(), the
2870 // Compile_lock is taken first. After some initializations,
2871 // nmethod::new_nmethod() takes over, grabbing the CodeCache_lock
2872 // immediately (after finalizing the oop references). To lock out concurrent
2873 // modifiers, we have to grab both locks as well in the described sequence.
2874 //
2875 // If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock
2876 // for the entire duration of aggregation and printing. That makes sure we see
2877 // a consistent picture and do not run into issues caused by concurrent alterations.
2878 bool should_take_Compile_lock = !SafepointSynchronize::is_at_safepoint() &&
2879 !Compile_lock->owned_by_self();
2880 bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() &&
2881 !CodeCache_lock->owned_by_self();
2882 bool take_global_lock_1 = allFun && should_take_Compile_lock;
2883 bool take_global_lock_2 = allFun && should_take_CodeCache_lock;
2884 bool take_function_lock_1 = !allFun && should_take_Compile_lock;
2885 bool take_function_lock_2 = !allFun && should_take_CodeCache_lock;
2886 bool take_global_locks = take_global_lock_1 || take_global_lock_2;
2887 bool take_function_locks = take_function_lock_1 || take_function_lock_2;
2888
2889 ts_global.update(); // record starting point
2890
2891 ConditionalMutexLocker mu1(Compile_lock, take_global_lock_1, Mutex::_safepoint_check_flag);
2892 ConditionalMutexLocker mu2(CodeCache_lock, take_global_lock_2, Mutex::_no_safepoint_check_flag);
2893 if (take_global_locks) {
2894 out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds());
2895 ts_global.update(); // record starting point
2896 }
2897
2898 if (aggregate) {
2899 ts.update(); // record starting point
2900 ConditionalMutexLocker mu11(Compile_lock, take_function_lock_1, Mutex::_safepoint_check_flag);
2901 ConditionalMutexLocker mu22(CodeCache_lock, take_function_lock_2, Mutex::_no_safepoint_check_flag);
2902 if (take_function_locks) {
2903 out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds());
2904 }
2905
2906 ts.update(); // record starting point
2907 CodeCache::aggregate(out, granularity);
2908 if (take_function_locks) {
2909 out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds());
2910 }
2911 }
2912
2913 if (usedSpace) CodeCache::print_usedSpace(out);
2914 if (freeSpace) CodeCache::print_freeSpace(out);
2915 if (methodCount) CodeCache::print_count(out);
2916 if (methodSpace) CodeCache::print_space(out);
2917 if (methodAge) CodeCache::print_age(out);
2918 if (methodNames) {
2919 if (allFun) {
2920 // print_names() can only be used safely if the locks have been continuously held
2921 // since aggregation begin. That is true only for function "all".
2922 CodeCache::print_names(out);
2923 } else {
2924 out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'");
2925 }
2926 }
2927 if (discard) CodeCache::discard(out);
2928
2929 if (take_global_locks) {
2930 out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds());
2931 }
2932 out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds());
2933 }