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 DirectiveSet* directive = DirectivesStack::getMatchingDirective(method, comp);
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, directive, THREAD);
1388 DirectivesStack::release(directive);
1389 return nm;
1390 }
1391
1392 nmethod* CompileBroker::compile_method(const methodHandle& method, int osr_bci,
1393 int comp_level,
1394 int hot_count,
1395 CompileTask::CompileReason compile_reason,
1396 DirectiveSet* directive,
1397 TRAPS) {
1398
1399 // make sure arguments make sense
1400 assert(method->method_holder()->is_instance_klass(), "not an instance method");
1401 assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
1402 assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
1403 assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");
1404 // return quickly if possible
1405
1406 // lock, make sure that the compilation
1407 // isn't prohibited in a straightforward way.
1408 AbstractCompiler* comp = CompileBroker::compiler(comp_level);
1409 if (comp == nullptr || compilation_is_prohibited(method, osr_bci, comp_level, directive->ExcludeOption)) {
1410 return nullptr;
1411 }
1412
1413 if (osr_bci == InvocationEntryBci) {
1414 // standard compilation
1415 nmethod* method_code = method->code();
1416 if (method_code != nullptr) {
1417 if (compilation_is_complete(method, osr_bci, comp_level)) {
1418 return method_code;
1419 }
1420 }
1421 if (method->is_not_compilable(comp_level)) {
1422 return nullptr;
1423 }
1424 } else {
1425 // osr compilation
1426 // We accept a higher level osr method
1427 nmethod* nm = method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1428 if (nm != nullptr) return nm;
1429 if (method->is_not_osr_compilable(comp_level)) return nullptr;
1430 }
1431
1432 assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
1433 // some prerequisites that are compiler specific
1434 if (comp->is_c2() || comp->is_jvmci()) {
1435 InternalOOMEMark iom(THREAD);
1436 method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NONASYNC_NULL);
1437 // Resolve all classes seen in the signature of the method
1438 // we are compiling.
1439 Method::load_signature_classes(method, CHECK_AND_CLEAR_NONASYNC_NULL);
1440 }
1441
1442 // If the method is native, do the lookup in the thread requesting
1443 // the compilation. Native lookups can load code, which is not
1444 // permitted during compilation.
1445 //
1446 // Note: A native method implies non-osr compilation which is
1447 // checked with an assertion at the entry of this method.
1448 if (method->is_native() && !method->is_method_handle_intrinsic()) {
1449 address adr = NativeLookup::lookup(method, THREAD);
1450 if (HAS_PENDING_EXCEPTION) {
1451 // In case of an exception looking up the method, we just forget
1452 // about it. The interpreter will kick-in and throw the exception.
1453 method->set_not_compilable("NativeLookup::lookup failed"); // implies is_not_osr_compilable()
1454 CLEAR_PENDING_EXCEPTION;
1455 return nullptr;
1456 }
1457 assert(method->has_native_function(), "must have native code by now");
1458 }
1459
1460 // RedefineClasses() has replaced this method; just return
1461 if (method->is_old()) {
1462 return nullptr;
1463 }
1464
1465 // JVMTI -- post_compile_event requires jmethod_id() that may require
1466 // a lock the compiling thread can not acquire. Prefetch it here.
1467 if (JvmtiExport::should_post_compiled_method_load()) {
1468 method->jmethod_id();
1469 }
1470
1471 // do the compilation
1472 if (method->is_native()) {
1473 if (!PreferInterpreterNativeStubs || method->is_method_handle_intrinsic()) {
1474 // To properly handle the appendix argument for out-of-line calls we are using a small trampoline that
1475 // pops off the appendix argument and jumps to the target (see gen_special_dispatch in SharedRuntime).
1476 //
1477 // Since normal compiled-to-compiled calls are not able to handle such a thing we MUST generate an adapter
1478 // in this case. If we can't generate one and use it we can not execute the out-of-line method handle calls.
1479 AdapterHandlerLibrary::create_native_wrapper(method);
1480 } else {
1481 return nullptr;
1482 }
1483 } else {
1484 // If the compiler is shut off due to code cache getting full
1485 // fail out now so blocking compiles dont hang the java thread
1486 if (!should_compile_new_jobs()) {
1487 return nullptr;
1488 }
1489 bool is_blocking = !directive->BackgroundCompilationOption || ReplayCompiles;
1490 compile_method_base(method, osr_bci, comp_level, hot_count, compile_reason, is_blocking, THREAD);
1491 }
1492
1493 // return requested nmethod
1494 // We accept a higher level osr method
1495 if (osr_bci == InvocationEntryBci) {
1496 return method->code();
1497 }
1498 return method->lookup_osr_nmethod_for(osr_bci, comp_level, false);
1499 }
1500
1501
1502 // ------------------------------------------------------------------
1503 // CompileBroker::compilation_is_complete
1504 //
1505 // See if compilation of this method is already complete.
1506 bool CompileBroker::compilation_is_complete(const methodHandle& method,
1507 int osr_bci,
1508 int comp_level) {
1509 bool is_osr = (osr_bci != standard_entry_bci);
1510 if (is_osr) {
1511 if (method->is_not_osr_compilable(comp_level)) {
1512 return true;
1513 } else {
1514 nmethod* result = method->lookup_osr_nmethod_for(osr_bci, comp_level, true);
1515 return (result != nullptr);
1516 }
1517 } else {
1518 if (method->is_not_compilable(comp_level)) {
1519 return true;
1520 } else {
1521 nmethod* result = method->code();
1522 if (result == nullptr) return false;
1523 return comp_level == result->comp_level();
1524 }
1525 }
1526 }
1527
1528
1529 /**
1530 * See if this compilation is already requested.
1531 *
1532 * Implementation note: there is only a single "is in queue" bit
1533 * for each method. This means that the check below is overly
1534 * conservative in the sense that an osr compilation in the queue
1535 * will block a normal compilation from entering the queue (and vice
1536 * versa). This can be remedied by a full queue search to disambiguate
1537 * cases. If it is deemed profitable, this may be done.
1538 */
1539 bool CompileBroker::compilation_is_in_queue(const methodHandle& method) {
1540 return method->queued_for_compilation();
1541 }
1542
1543 // ------------------------------------------------------------------
1544 // CompileBroker::compilation_is_prohibited
1545 //
1546 // See if this compilation is not allowed.
1547 bool CompileBroker::compilation_is_prohibited(const methodHandle& method, int osr_bci, int comp_level, bool excluded) {
1548 bool is_native = method->is_native();
1549 // Some compilers may not support the compilation of natives.
1550 AbstractCompiler *comp = compiler(comp_level);
1551 if (is_native && (!CICompileNatives || comp == nullptr)) {
1552 method->set_not_compilable_quietly("native methods not supported", comp_level);
1553 return true;
1554 }
1555
1556 bool is_osr = (osr_bci != standard_entry_bci);
1557 // Some compilers may not support on stack replacement.
1558 if (is_osr && (!CICompileOSR || comp == nullptr)) {
1559 method->set_not_osr_compilable("OSR not supported", comp_level);
1560 return true;
1561 }
1562
1563 // The method may be explicitly excluded by the user.
1564 double scale;
1565 if (excluded || (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, scale) && scale == 0)) {
1566 bool quietly = CompilerOracle::be_quiet();
1567 if (PrintCompilation && !quietly) {
1568 // This does not happen quietly...
1569 ResourceMark rm;
1570 tty->print("### Excluding %s:%s",
1571 method->is_native() ? "generation of native wrapper" : "compile",
1572 (method->is_static() ? " static" : ""));
1573 method->print_short_name(tty);
1574 tty->cr();
1575 }
1576 method->set_not_compilable("excluded by CompileCommand", comp_level, !quietly);
1577 }
1578
1579 return false;
1580 }
1581
1582 /**
1583 * Generate serialized IDs for compilation requests. If certain debugging flags are used
1584 * and the ID is not within the specified range, the method is not compiled and 0 is returned.
1585 * The function also allows to generate separate compilation IDs for OSR compilations.
1586 */
1587 int CompileBroker::assign_compile_id(const methodHandle& method, int osr_bci) {
1588 #ifdef ASSERT
1589 bool is_osr = (osr_bci != standard_entry_bci);
1590 int id;
1591 if (method->is_native()) {
1592 assert(!is_osr, "can't be osr");
1593 // Adapters, native wrappers and method handle intrinsics
1594 // should be generated always.
1595 return AtomicAccess::add(CICountNative ? &_native_compilation_id : &_compilation_id, 1);
1596 } else if (CICountOSR && is_osr) {
1597 id = AtomicAccess::add(&_osr_compilation_id, 1);
1598 if (CIStartOSR <= id && id < CIStopOSR) {
1599 return id;
1600 }
1601 } else {
1602 id = AtomicAccess::add(&_compilation_id, 1);
1603 if (CIStart <= id && id < CIStop) {
1604 return id;
1605 }
1606 }
1607
1608 // Method was not in the appropriate compilation range.
1609 method->set_not_compilable_quietly("Not in requested compile id range");
1610 return 0;
1611 #else
1612 // CICountOSR is a develop flag and set to 'false' by default. In a product built,
1613 // only _compilation_id is incremented.
1614 return AtomicAccess::add(&_compilation_id, 1);
1615 #endif
1616 }
1617
1618 // ------------------------------------------------------------------
1619 // CompileBroker::assign_compile_id_unlocked
1620 //
1621 // Public wrapper for assign_compile_id that acquires the needed locks
1622 int CompileBroker::assign_compile_id_unlocked(Thread* thread, const methodHandle& method, int osr_bci) {
1623 MutexLocker locker(thread, MethodCompileQueue_lock);
1624 return assign_compile_id(method, osr_bci);
1625 }
1626
1627 // ------------------------------------------------------------------
1628 // CompileBroker::create_compile_task
1629 //
1630 // Create a CompileTask object representing the current request for
1631 // compilation. Add this task to the queue.
1632 CompileTask* CompileBroker::create_compile_task(CompileQueue* queue,
1633 int compile_id,
1634 const methodHandle& method,
1635 int osr_bci,
1636 int comp_level,
1637 int hot_count,
1638 CompileTask::CompileReason compile_reason,
1639 bool blocking) {
1640 CompileTask* new_task = new CompileTask(compile_id, method, osr_bci, comp_level,
1641 hot_count, compile_reason, blocking);
1642 queue->add(new_task);
1643 return new_task;
1644 }
1645
1646 #if INCLUDE_JVMCI
1647 // The number of milliseconds to wait before checking if
1648 // JVMCI compilation has made progress.
1649 static const long JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE = 1000;
1650
1651 // The number of JVMCI compilation progress checks that must fail
1652 // before unblocking a thread waiting for a blocking compilation.
1653 static const int JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS = 10;
1654
1655 /**
1656 * Waits for a JVMCI compiler to complete a given task. This thread
1657 * waits until either the task completes or it sees no JVMCI compilation
1658 * progress for N consecutive milliseconds where N is
1659 * JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE *
1660 * JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS.
1661 *
1662 * @return true if this thread needs to delete the task
1663 */
1664 bool CompileBroker::wait_for_jvmci_completion(JVMCICompiler* jvmci, CompileTask* task, JavaThread* thread) {
1665 assert(UseJVMCICompiler, "sanity");
1666 MonitorLocker ml(thread, CompileTaskWait_lock);
1667 int progress_wait_attempts = 0;
1668 jint thread_jvmci_compilation_ticks = 0;
1669 jint global_jvmci_compilation_ticks = jvmci->global_compilation_ticks();
1670 while (!task->is_complete() && !is_compilation_disabled_forever() &&
1671 ml.wait(JVMCI_COMPILATION_PROGRESS_WAIT_TIMESLICE)) {
1672 JVMCICompileState* jvmci_compile_state = task->blocking_jvmci_compile_state();
1673
1674 bool progress;
1675 if (jvmci_compile_state != nullptr) {
1676 jint ticks = jvmci_compile_state->compilation_ticks();
1677 progress = (ticks - thread_jvmci_compilation_ticks) != 0;
1678 JVMCI_event_1("waiting on compilation %d [ticks=%d]", task->compile_id(), ticks);
1679 thread_jvmci_compilation_ticks = ticks;
1680 } else {
1681 // Still waiting on JVMCI compiler queue. This thread may be holding a lock
1682 // that all JVMCI compiler threads are blocked on. We use the global JVMCI
1683 // compilation ticks to determine whether JVMCI compilation
1684 // is still making progress through the JVMCI compiler queue.
1685 jint ticks = jvmci->global_compilation_ticks();
1686 progress = (ticks - global_jvmci_compilation_ticks) != 0;
1687 JVMCI_event_1("waiting on compilation %d to be queued [ticks=%d]", task->compile_id(), ticks);
1688 global_jvmci_compilation_ticks = ticks;
1689 }
1690
1691 if (!progress) {
1692 if (++progress_wait_attempts == JVMCI_COMPILATION_PROGRESS_WAIT_ATTEMPTS) {
1693 if (PrintCompilation) {
1694 task->print(tty, "wait for blocking compilation timed out");
1695 }
1696 JVMCI_event_1("waiting on compilation %d timed out", task->compile_id());
1697 break;
1698 }
1699 } else {
1700 progress_wait_attempts = 0;
1701 }
1702 }
1703 task->clear_waiter();
1704 return task->is_complete();
1705 }
1706 #endif
1707
1708 /**
1709 * Wait for the compilation task to complete.
1710 */
1711 void CompileBroker::wait_for_completion(CompileTask* task) {
1712 if (CIPrintCompileQueue) {
1713 ttyLocker ttyl;
1714 tty->print_cr("BLOCKING FOR COMPILE");
1715 }
1716
1717 assert(task->is_blocking(), "can only wait on blocking task");
1718
1719 JavaThread* thread = JavaThread::current();
1720
1721 methodHandle method(thread, task->method());
1722 bool free_task;
1723 #if INCLUDE_JVMCI
1724 AbstractCompiler* comp = compiler(task->comp_level());
1725 if (!UseJVMCINativeLibrary && comp->is_jvmci() && !task->should_wait_for_compilation()) {
1726 // It may return before compilation is completed.
1727 // Note that libjvmci should not pre-emptively unblock
1728 // a thread waiting for a compilation as it does not call
1729 // Java code and so is not deadlock prone like jarjvmci.
1730 free_task = wait_for_jvmci_completion((JVMCICompiler*) comp, task, thread);
1731 } else
1732 #endif
1733 {
1734 free_task = true;
1735 // Wait until the task is complete or compilation is shut down.
1736 MonitorLocker ml(thread, CompileTaskWait_lock);
1737 while (!task->is_complete() && !is_compilation_disabled_forever()) {
1738 ml.wait();
1739 }
1740 }
1741
1742 // It is harmless to check this status without the lock, because
1743 // completion is a stable property.
1744 if (!task->is_complete()) {
1745 // Task is not complete, likely because we are exiting for compilation
1746 // shutdown. The task can still be reached through the queue, or executed
1747 // by some compiler thread. There is no coordination with either MCQ lock
1748 // holders or compilers, therefore we cannot delete the task.
1749 //
1750 // This will leave task allocated, which leaks it. At this (degraded) point,
1751 // it is less risky to abandon the task, rather than attempting a more
1752 // complicated deletion protocol.
1753 free_task = false;
1754 }
1755
1756 if (free_task) {
1757 assert(task->is_complete(), "Compilation should have completed");
1758 assert(task->next() == nullptr && task->prev() == nullptr,
1759 "Completed task should not be in the queue");
1760
1761 // By convention, the waiter is responsible for deleting a
1762 // blocking CompileTask. Since there is only one waiter ever
1763 // waiting on a CompileTask, we know that no one else will
1764 // be using this CompileTask; we can delete it.
1765 delete task;
1766 }
1767 }
1768
1769 void CompileBroker::wait_for_no_active_tasks() {
1770 CompileTask::wait_for_no_active_tasks();
1771 }
1772
1773 /**
1774 * Initialize compiler thread(s) + compiler object(s). The postcondition
1775 * of this function is that the compiler runtimes are initialized and that
1776 * compiler threads can start compiling.
1777 */
1778 bool CompileBroker::init_compiler_runtime() {
1779 CompilerThread* thread = CompilerThread::current();
1780 AbstractCompiler* comp = thread->compiler();
1781 // Final sanity check - the compiler object must exist
1782 guarantee(comp != nullptr, "Compiler object must exist");
1783
1784 {
1785 // Must switch to native to allocate ci_env
1786 ThreadToNativeFromVM ttn(thread);
1787 ciEnv ci_env((CompileTask*)nullptr);
1788 // Cache Jvmti state
1789 ci_env.cache_jvmti_state();
1790 // Cache DTrace flags
1791 ci_env.cache_dtrace_flags();
1792
1793 // Switch back to VM state to do compiler initialization
1794 ThreadInVMfromNative tv(thread);
1795
1796 // Perform per-thread and global initializations
1797 comp->initialize();
1798 }
1799
1800 if (comp->is_failed()) {
1801 disable_compilation_forever();
1802 // If compiler initialization failed, no compiler thread that is specific to a
1803 // particular compiler runtime will ever start to compile methods.
1804 shutdown_compiler_runtime(comp, thread);
1805 return false;
1806 }
1807
1808 // C1 specific check
1809 if (comp->is_c1() && (thread->get_buffer_blob() == nullptr)) {
1810 warning("Initialization of %s thread failed (no space to run compilers)", thread->name());
1811 return false;
1812 }
1813
1814 return true;
1815 }
1816
1817 void CompileBroker::free_buffer_blob_if_allocated(CompilerThread* thread) {
1818 BufferBlob* blob = thread->get_buffer_blob();
1819 if (blob != nullptr) {
1820 blob->purge();
1821 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1822 CodeCache::free(blob);
1823 }
1824 }
1825
1826 /**
1827 * If C1 and/or C2 initialization failed, we shut down all compilation.
1828 * We do this to keep things simple. This can be changed if it ever turns
1829 * out to be a problem.
1830 */
1831 void CompileBroker::shutdown_compiler_runtime(AbstractCompiler* comp, CompilerThread* thread) {
1832 free_buffer_blob_if_allocated(thread);
1833
1834 if (comp->should_perform_shutdown()) {
1835 // There are two reasons for shutting down the compiler
1836 // 1) compiler runtime initialization failed
1837 // 2) The code cache is full and the following flag is set: -XX:-UseCodeCacheFlushing
1838 warning("%s initialization failed. Shutting down all compilers", comp->name());
1839
1840 // Only one thread per compiler runtime object enters here
1841 // Set state to shut down
1842 comp->set_shut_down();
1843
1844 // Delete all queued compilation tasks to make compiler threads exit faster.
1845 if (_c1_compile_queue != nullptr) {
1846 _c1_compile_queue->delete_all();
1847 }
1848
1849 if (_c2_compile_queue != nullptr) {
1850 _c2_compile_queue->delete_all();
1851 }
1852
1853 // Set flags so that we continue execution with using interpreter only.
1854 UseCompiler = false;
1855 UseInterpreter = true;
1856
1857 // We could delete compiler runtimes also. However, there are references to
1858 // the compiler runtime(s) (e.g., nmethod::is_compiled_by_c1()) which then
1859 // fail. This can be done later if necessary.
1860 }
1861 }
1862
1863 /**
1864 * Helper function to create new or reuse old CompileLog.
1865 */
1866 CompileLog* CompileBroker::get_log(CompilerThread* ct) {
1867 if (!LogCompilation) return nullptr;
1868
1869 AbstractCompiler *compiler = ct->compiler();
1870 bool c1 = compiler->is_c1();
1871 jobject* compiler_objects = c1 ? _compiler1_objects : _compiler2_objects;
1872 assert(compiler_objects != nullptr, "must be initialized at this point");
1873 CompileLog** logs = c1 ? _compiler1_logs : _compiler2_logs;
1874 assert(logs != nullptr, "must be initialized at this point");
1875 int count = c1 ? _c1_count : _c2_count;
1876
1877 // Find Compiler number by its threadObj.
1878 oop compiler_obj = ct->threadObj();
1879 int compiler_number = 0;
1880 bool found = false;
1881 for (; compiler_number < count; compiler_number++) {
1882 if (JNIHandles::resolve_non_null(compiler_objects[compiler_number]) == compiler_obj) {
1883 found = true;
1884 break;
1885 }
1886 }
1887 assert(found, "Compiler must exist at this point");
1888
1889 // Determine pointer for this thread's log.
1890 CompileLog** log_ptr = &logs[compiler_number];
1891
1892 // Return old one if it exists.
1893 CompileLog* log = *log_ptr;
1894 if (log != nullptr) {
1895 ct->init_log(log);
1896 return log;
1897 }
1898
1899 // Create a new one and remember it.
1900 init_compiler_thread_log();
1901 log = ct->log();
1902 *log_ptr = log;
1903 return log;
1904 }
1905
1906 // ------------------------------------------------------------------
1907 // CompileBroker::compiler_thread_loop
1908 //
1909 // The main loop run by a CompilerThread.
1910 void CompileBroker::compiler_thread_loop() {
1911 CompilerThread* thread = CompilerThread::current();
1912 CompileQueue* queue = thread->queue();
1913 // For the thread that initializes the ciObjectFactory
1914 // this resource mark holds all the shared objects
1915 ResourceMark rm;
1916
1917 // First thread to get here will initialize the compiler interface
1918
1919 {
1920 ASSERT_IN_VM;
1921 MutexLocker only_one (thread, CompileThread_lock);
1922 if (!ciObjectFactory::is_initialized()) {
1923 ciObjectFactory::initialize();
1924 }
1925 }
1926
1927 // Open a log.
1928 CompileLog* log = get_log(thread);
1929 if (log != nullptr) {
1930 log->begin_elem("start_compile_thread name='%s' thread='%zu' process='%d'",
1931 thread->name(),
1932 os::current_thread_id(),
1933 os::current_process_id());
1934 log->stamp();
1935 log->end_elem();
1936 }
1937
1938 if (!thread->init_compilation_timeout()) {
1939 return;
1940 }
1941
1942 // If compiler thread/runtime initialization fails, exit the compiler thread
1943 if (!init_compiler_runtime()) {
1944 return;
1945 }
1946
1947 thread->start_idle_timer();
1948
1949 // Poll for new compilation tasks as long as the JVM runs. Compilation
1950 // should only be disabled if something went wrong while initializing the
1951 // compiler runtimes. This, in turn, should not happen. The only known case
1952 // when compiler runtime initialization fails is if there is not enough free
1953 // space in the code cache to generate the necessary stubs, etc.
1954 while (!is_compilation_disabled_forever()) {
1955 // We need this HandleMark to avoid leaking VM handles.
1956 HandleMark hm(thread);
1957
1958 CompileTask* task = queue->get(thread);
1959 if (task == nullptr) {
1960 if (UseDynamicNumberOfCompilerThreads) {
1961 // Access compiler_count under lock to enforce consistency.
1962 MutexLocker only_one(CompileThread_lock);
1963 if (can_remove(thread, true)) {
1964 if (trace_compiler_threads()) {
1965 ResourceMark rm;
1966 stringStream msg;
1967 msg.print("Removing compiler thread %s after " JLONG_FORMAT " ms idle time",
1968 thread->name(), thread->idle_time_millis());
1969 print_compiler_threads(msg);
1970 }
1971
1972 // Notify compiler that the compiler thread is about to stop
1973 thread->compiler()->stopping_compiler_thread(thread);
1974
1975 free_buffer_blob_if_allocated(thread);
1976 return; // Stop this thread.
1977 }
1978 }
1979 } else {
1980 // Assign the task to the current thread. Mark this compilation
1981 // thread as active for the profiler.
1982 // CompileTaskWrapper also keeps the Method* from being deallocated if redefinition
1983 // occurs after fetching the compile task off the queue.
1984 CompileTaskWrapper ctw(task);
1985 methodHandle method(thread, task->method());
1986
1987 // Never compile a method if breakpoints are present in it
1988 if (method()->number_of_breakpoints() == 0) {
1989 // Compile the method.
1990 if ((UseCompiler || AlwaysCompileLoopMethods) && CompileBroker::should_compile_new_jobs()) {
1991 invoke_compiler_on_method(task);
1992 thread->start_idle_timer();
1993 } else {
1994 // After compilation is disabled, remove remaining methods from queue
1995 method->clear_queued_for_compilation();
1996 task->set_failure_reason("compilation is disabled");
1997 }
1998 } else {
1999 task->set_failure_reason("breakpoints are present");
2000 }
2001
2002 if (UseDynamicNumberOfCompilerThreads) {
2003 possibly_add_compiler_threads(thread);
2004 assert(!thread->has_pending_exception(), "should have been handled");
2005 }
2006 }
2007 }
2008
2009 // Shut down compiler runtime
2010 shutdown_compiler_runtime(thread->compiler(), thread);
2011 }
2012
2013 // ------------------------------------------------------------------
2014 // CompileBroker::init_compiler_thread_log
2015 //
2016 // Set up state required by +LogCompilation.
2017 void CompileBroker::init_compiler_thread_log() {
2018 CompilerThread* thread = CompilerThread::current();
2019 char file_name[4*K];
2020 FILE* fp = nullptr;
2021 intx thread_id = os::current_thread_id();
2022 for (int try_temp_dir = 1; try_temp_dir >= 0; try_temp_dir--) {
2023 const char* dir = (try_temp_dir ? os::get_temp_directory() : nullptr);
2024 if (dir == nullptr) {
2025 jio_snprintf(file_name, sizeof(file_name), "hs_c%zu_pid%u.log",
2026 thread_id, os::current_process_id());
2027 } else {
2028 jio_snprintf(file_name, sizeof(file_name),
2029 "%s%shs_c%zu_pid%u.log", dir,
2030 os::file_separator(), thread_id, os::current_process_id());
2031 }
2032
2033 fp = os::fopen(file_name, "wt");
2034 if (fp != nullptr) {
2035 if (LogCompilation && Verbose) {
2036 tty->print_cr("Opening compilation log %s", file_name);
2037 }
2038 CompileLog* log = new(mtCompiler) CompileLog(file_name, fp, thread_id);
2039 if (log == nullptr) {
2040 fclose(fp);
2041 return;
2042 }
2043 thread->init_log(log);
2044
2045 if (xtty != nullptr) {
2046 ttyLocker ttyl;
2047 // Record any per thread log files
2048 xtty->elem("thread_logfile thread='%zd' filename='%s'", thread_id, file_name);
2049 }
2050 return;
2051 }
2052 }
2053 warning("Cannot open log file: %s", file_name);
2054 }
2055
2056 void CompileBroker::log_metaspace_failure() {
2057 const char* message = "some methods may not be compiled because metaspace "
2058 "is out of memory";
2059 if (CompilationLog::log() != nullptr) {
2060 CompilationLog::log()->log_metaspace_failure(message);
2061 }
2062 if (PrintCompilation) {
2063 tty->print_cr("COMPILE PROFILING SKIPPED: %s", message);
2064 }
2065 }
2066
2067
2068 // ------------------------------------------------------------------
2069 // CompileBroker::set_should_block
2070 //
2071 // Set _should_block.
2072 // Call this from the VM, with Threads_lock held and a safepoint requested.
2073 void CompileBroker::set_should_block() {
2074 assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2075 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint already");
2076 #ifndef PRODUCT
2077 if (PrintCompilation && (Verbose || WizardMode))
2078 tty->print_cr("notifying compiler thread pool to block");
2079 #endif
2080 _should_block = true;
2081 }
2082
2083 // ------------------------------------------------------------------
2084 // CompileBroker::maybe_block
2085 //
2086 // Call this from the compiler at convenient points, to poll for _should_block.
2087 void CompileBroker::maybe_block() {
2088 if (_should_block) {
2089 #ifndef PRODUCT
2090 if (PrintCompilation && (Verbose || WizardMode))
2091 tty->print_cr("compiler thread " INTPTR_FORMAT " poll detects block request", p2i(Thread::current()));
2092 #endif
2093 // If we are executing a task during the request to block, report the task
2094 // before disappearing.
2095 CompilerThread* thread = CompilerThread::current();
2096 if (thread != nullptr) {
2097 CompileTask* task = thread->task();
2098 if (task != nullptr) {
2099 if (PrintCompilation) {
2100 task->print(tty, "blocked");
2101 }
2102 task->print_ul("blocked");
2103 }
2104 }
2105 // Go to VM state and block for final VM shutdown safepoint.
2106 ThreadInVMfromNative tivfn(JavaThread::current());
2107 assert(false, "Should never unblock from TIVNM entry");
2108 }
2109 }
2110
2111 // wrapper for CodeCache::print_summary()
2112 static void codecache_print(bool detailed)
2113 {
2114 stringStream s;
2115 // Dump code cache into a buffer before locking the tty,
2116 {
2117 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2118 CodeCache::print_summary(&s, detailed);
2119 }
2120 ttyLocker ttyl;
2121 tty->print("%s", s.freeze());
2122 }
2123
2124 // wrapper for CodeCache::print_summary() using outputStream
2125 static void codecache_print(outputStream* out, bool detailed) {
2126 stringStream s;
2127
2128 // Dump code cache into a buffer
2129 {
2130 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2131 CodeCache::print_summary(&s, detailed);
2132 }
2133
2134 char* remaining_log = s.as_string();
2135 while (*remaining_log != '\0') {
2136 char* eol = strchr(remaining_log, '\n');
2137 if (eol == nullptr) {
2138 out->print_cr("%s", remaining_log);
2139 remaining_log = remaining_log + strlen(remaining_log);
2140 } else {
2141 *eol = '\0';
2142 out->print_cr("%s", remaining_log);
2143 remaining_log = eol + 1;
2144 }
2145 }
2146 }
2147
2148 void CompileBroker::handle_compile_error(CompilerThread* thread, CompileTask* task, ciEnv* ci_env,
2149 int compilable, const char* failure_reason) {
2150 if (!AbortVMOnCompilationFailure) {
2151 return;
2152 }
2153 if (compilable == ciEnv::MethodCompilable_not_at_tier) {
2154 fatal("Not compilable at tier %d: %s", task->comp_level(), failure_reason);
2155 }
2156 if (compilable == ciEnv::MethodCompilable_never) {
2157 fatal("Never compilable: %s", failure_reason);
2158 }
2159 }
2160
2161 static void post_compilation_event(EventCompilation& event, CompileTask* task) {
2162 assert(task != nullptr, "invariant");
2163 CompilerEvent::CompilationEvent::post(event,
2164 task->compile_id(),
2165 task->compiler()->type(),
2166 task->method(),
2167 task->comp_level(),
2168 task->is_success(),
2169 task->osr_bci() != CompileBroker::standard_entry_bci,
2170 task->nm_total_size(),
2171 task->num_inlined_bytecodes(),
2172 task->arena_bytes());
2173 }
2174
2175 int DirectivesStack::_depth = 0;
2176 CompilerDirectives* DirectivesStack::_top = nullptr;
2177 CompilerDirectives* DirectivesStack::_bottom = nullptr;
2178
2179 // Acquires Compilation_lock and waits for it to be notified
2180 // as long as WhiteBox::compilation_locked is true.
2181 static void whitebox_lock_compilation() {
2182 MonitorLocker locker(Compilation_lock, Mutex::_no_safepoint_check_flag);
2183 while (WhiteBox::compilation_locked) {
2184 locker.wait();
2185 }
2186 }
2187
2188 // ------------------------------------------------------------------
2189 // CompileBroker::invoke_compiler_on_method
2190 //
2191 // Compile a method.
2192 //
2193 void CompileBroker::invoke_compiler_on_method(CompileTask* task) {
2194 task->print_ul();
2195 elapsedTimer time;
2196
2197 DirectiveSet* directive = task->directive();
2198 if (directive->PrintCompilationOption) {
2199 ResourceMark rm;
2200 task->print_tty();
2201 }
2202
2203 CompilerThread* thread = CompilerThread::current();
2204 ResourceMark rm(thread);
2205
2206 if (CompilationLog::log() != nullptr) {
2207 CompilationLog::log()->log_compile(thread, task);
2208 }
2209
2210 // Common flags.
2211 int compile_id = task->compile_id();
2212 int osr_bci = task->osr_bci();
2213 bool is_osr = (osr_bci != standard_entry_bci);
2214 bool should_log = (thread->log() != nullptr);
2215 bool should_break = false;
2216 const int task_level = task->comp_level();
2217 AbstractCompiler* comp = task->compiler();
2218 {
2219 // create the handle inside it's own block so it can't
2220 // accidentally be referenced once the thread transitions to
2221 // native. The NoHandleMark before the transition should catch
2222 // any cases where this occurs in the future.
2223 methodHandle method(thread, task->method());
2224
2225 assert(!method->is_native(), "no longer compile natives");
2226
2227 // Update compile information when using perfdata.
2228 if (UsePerfData) {
2229 update_compile_perf_data(thread, method, is_osr);
2230 }
2231
2232 DTRACE_METHOD_COMPILE_BEGIN_PROBE(method, compiler_name(task_level));
2233 }
2234
2235 should_break = directive->BreakAtCompileOption || task->check_break_at_flags();
2236 if (should_log && !directive->LogOption) {
2237 should_log = false;
2238 }
2239
2240 // Allocate a new set of JNI handles.
2241 JNIHandleMark jhm(thread);
2242 Method* target_handle = task->method();
2243 int compilable = ciEnv::MethodCompilable;
2244 const char* failure_reason = nullptr;
2245 bool failure_reason_on_C_heap = false;
2246 const char* retry_message = nullptr;
2247
2248 #if INCLUDE_JVMCI
2249 if (UseJVMCICompiler && comp != nullptr && comp->is_jvmci()) {
2250 JVMCICompiler* jvmci = (JVMCICompiler*) comp;
2251
2252 TraceTime t1("compilation", &time);
2253 EventCompilation event;
2254 JVMCICompileState compile_state(task, jvmci);
2255 JVMCIRuntime *runtime = nullptr;
2256
2257 if (JVMCI::in_shutdown()) {
2258 failure_reason = "in JVMCI shutdown";
2259 retry_message = "not retryable";
2260 compilable = ciEnv::MethodCompilable_never;
2261 } else if (compile_state.target_method_is_old()) {
2262 // Skip redefined methods
2263 failure_reason = "redefined method";
2264 retry_message = "not retryable";
2265 compilable = ciEnv::MethodCompilable_never;
2266 } else {
2267 JVMCIEnv env(thread, &compile_state, __FILE__, __LINE__);
2268 if (env.init_error() != JNI_OK) {
2269 const char* msg = env.init_error_msg();
2270 failure_reason = os::strdup(err_msg("Error attaching to libjvmci (err: %d, %s)",
2271 env.init_error(), msg == nullptr ? "unknown" : msg), mtJVMCI);
2272 bool reason_on_C_heap = true;
2273 // In case of JNI_ENOMEM, there's a good chance a subsequent attempt to create libjvmci or attach to it
2274 // might succeed. Other errors most likely indicate a non-recoverable error in the JVMCI runtime.
2275 bool retryable = env.init_error() == JNI_ENOMEM;
2276 compile_state.set_failure(retryable, failure_reason, reason_on_C_heap);
2277 }
2278 if (failure_reason == nullptr) {
2279 if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2280 // Must switch to native to block
2281 ThreadToNativeFromVM ttn(thread);
2282 whitebox_lock_compilation();
2283 }
2284 methodHandle method(thread, target_handle);
2285 runtime = env.runtime();
2286 runtime->compile_method(&env, jvmci, method, osr_bci);
2287
2288 failure_reason = compile_state.failure_reason();
2289 failure_reason_on_C_heap = compile_state.failure_reason_on_C_heap();
2290 if (!compile_state.retryable()) {
2291 retry_message = "not retryable";
2292 compilable = ciEnv::MethodCompilable_not_at_tier;
2293 }
2294 if (!task->is_success()) {
2295 assert(failure_reason != nullptr, "must specify failure_reason");
2296 }
2297 }
2298 }
2299 if (!task->is_success() && !JVMCI::in_shutdown()) {
2300 handle_compile_error(thread, task, nullptr, compilable, failure_reason);
2301 }
2302 if (event.should_commit()) {
2303 post_compilation_event(event, task);
2304 }
2305
2306 if (runtime != nullptr) {
2307 runtime->post_compile(thread);
2308 }
2309 } else
2310 #endif // INCLUDE_JVMCI
2311 {
2312 NoHandleMark nhm;
2313 ThreadToNativeFromVM ttn(thread);
2314
2315 ciEnv ci_env(task);
2316 if (should_break) {
2317 ci_env.set_break_at_compile(true);
2318 }
2319 if (should_log) {
2320 ci_env.set_log(thread->log());
2321 }
2322 assert(thread->env() == &ci_env, "set by ci_env");
2323 // The thread-env() field is cleared in ~CompileTaskWrapper.
2324
2325 // Cache Jvmti state
2326 bool method_is_old = ci_env.cache_jvmti_state();
2327
2328 // Skip redefined methods
2329 if (method_is_old) {
2330 ci_env.record_method_not_compilable("redefined method", true);
2331 }
2332
2333 // Cache DTrace flags
2334 ci_env.cache_dtrace_flags();
2335
2336 ciMethod* target = ci_env.get_method_from_handle(target_handle);
2337
2338 TraceTime t1("compilation", &time);
2339 EventCompilation event;
2340
2341 if (comp == nullptr) {
2342 ci_env.record_method_not_compilable("no compiler");
2343 } else if (!ci_env.failing()) {
2344 if (WhiteBoxAPI && WhiteBox::compilation_locked) {
2345 whitebox_lock_compilation();
2346 }
2347 comp->compile_method(&ci_env, target, osr_bci, true, directive);
2348
2349 /* Repeat compilation without installing code for profiling purposes */
2350 int repeat_compilation_count = directive->RepeatCompilationOption;
2351 if (repeat_compilation_count > 0) {
2352 CHeapStringHolder failure_reason;
2353 failure_reason.set(ci_env._failure_reason.get());
2354 while (repeat_compilation_count > 0) {
2355 ResourceMark rm(thread);
2356 task->print_ul("NO CODE INSTALLED");
2357 thread->timeout()->reset();
2358 ci_env._failure_reason.clear();
2359 comp->compile_method(&ci_env, target, osr_bci, false, directive);
2360 repeat_compilation_count--;
2361 }
2362 ci_env._failure_reason.set(failure_reason.get());
2363 }
2364 }
2365
2366
2367 if (!ci_env.failing() && !task->is_success()) {
2368 assert(ci_env.failure_reason() != nullptr, "expect failure reason");
2369 assert(false, "compiler should always document failure: %s", ci_env.failure_reason());
2370 // The compiler elected, without comment, not to register a result.
2371 // Do not attempt further compilations of this method.
2372 ci_env.record_method_not_compilable("compile failed");
2373 }
2374
2375 // Copy this bit to the enclosing block:
2376 compilable = ci_env.compilable();
2377
2378 if (ci_env.failing()) {
2379 // Duplicate the failure reason string, so that it outlives ciEnv
2380 failure_reason = os::strdup(ci_env.failure_reason(), mtCompiler);
2381 failure_reason_on_C_heap = true;
2382 retry_message = ci_env.retry_message();
2383 ci_env.report_failure(failure_reason);
2384 }
2385
2386 if (ci_env.failing()) {
2387 handle_compile_error(thread, task, &ci_env, compilable, failure_reason);
2388 }
2389 if (event.should_commit()) {
2390 post_compilation_event(event, task);
2391 }
2392 }
2393
2394 if (failure_reason != nullptr) {
2395 task->set_failure_reason(failure_reason, failure_reason_on_C_heap);
2396 if (CompilationLog::log() != nullptr) {
2397 CompilationLog::log()->log_failure(thread, task, failure_reason, retry_message);
2398 }
2399 if (PrintCompilation || directive->PrintCompilationOption) {
2400 FormatBufferResource msg = retry_message != nullptr ?
2401 FormatBufferResource("COMPILE SKIPPED: %s (%s)", failure_reason, retry_message) :
2402 FormatBufferResource("COMPILE SKIPPED: %s", failure_reason);
2403 task->print(tty, msg);
2404 }
2405 }
2406
2407 task->mark_finished(os::elapsed_counter());
2408
2409 methodHandle method(thread, task->method());
2410
2411 DTRACE_METHOD_COMPILE_END_PROBE(method, compiler_name(task_level), task->is_success());
2412
2413 collect_statistics(thread, time, task);
2414
2415 if (PrintCompilation2 || directive->PrintCompilation2Option) {
2416 ResourceMark rm;
2417 task->print_post(tty);
2418 }
2419 DirectivesStack::release(directive);
2420
2421 Log(compilation, codecache) log;
2422 if (log.is_debug()) {
2423 LogStream ls(log.debug());
2424 codecache_print(&ls, /* detailed= */ false);
2425 }
2426 if (PrintCodeCacheOnCompilation) {
2427 codecache_print(/* detailed= */ false);
2428 }
2429 // Disable compilation, if required.
2430 switch (compilable) {
2431 case ciEnv::MethodCompilable_never:
2432 if (is_osr)
2433 method->set_not_osr_compilable_quietly("MethodCompilable_never");
2434 else
2435 method->set_not_compilable_quietly("MethodCompilable_never");
2436 break;
2437 case ciEnv::MethodCompilable_not_at_tier:
2438 if (is_osr)
2439 method->set_not_osr_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2440 else
2441 method->set_not_compilable_quietly("MethodCompilable_not_at_tier", task_level);
2442 break;
2443 }
2444
2445 // Note that the queued_for_compilation bits are cleared without
2446 // protection of a mutex. [They were set by the requester thread,
2447 // when adding the task to the compile queue -- at which time the
2448 // compile queue lock was held. Subsequently, we acquired the compile
2449 // queue lock to get this task off the compile queue; thus (to belabour
2450 // the point somewhat) our clearing of the bits must be occurring
2451 // only after the setting of the bits. See also 14012000 above.
2452 method->clear_queued_for_compilation();
2453 }
2454
2455 /**
2456 * The CodeCache is full. Print warning and disable compilation.
2457 * Schedule code cache cleaning so compilation can continue later.
2458 * This function needs to be called only from CodeCache::allocate(),
2459 * since we currently handle a full code cache uniformly.
2460 */
2461 void CompileBroker::handle_full_code_cache(CodeBlobType code_blob_type) {
2462 UseInterpreter = true;
2463 if (UseCompiler || AlwaysCompileLoopMethods ) {
2464 if (xtty != nullptr) {
2465 stringStream s;
2466 // Dump code cache state into a buffer before locking the tty,
2467 // because log_state() will use locks causing lock conflicts.
2468 CodeCache::log_state(&s);
2469 // Lock to prevent tearing
2470 ttyLocker ttyl;
2471 xtty->begin_elem("code_cache_full");
2472 xtty->print("%s", s.freeze());
2473 xtty->stamp();
2474 xtty->end_elem();
2475 }
2476
2477 #ifndef PRODUCT
2478 if (ExitOnFullCodeCache) {
2479 codecache_print(/* detailed= */ true);
2480 before_exit(JavaThread::current());
2481 exit_globals(); // will delete tty
2482 vm_direct_exit(1);
2483 }
2484 #endif
2485 if (UseCodeCacheFlushing) {
2486 // Since code cache is full, immediately stop new compiles
2487 if (CompileBroker::set_should_compile_new_jobs(CompileBroker::stop_compilation)) {
2488 log_info(codecache)("Code cache is full - disabling compilation");
2489 }
2490 } else {
2491 disable_compilation_forever();
2492 }
2493
2494 CodeCache::report_codemem_full(code_blob_type, should_print_compiler_warning());
2495 }
2496 }
2497
2498 // ------------------------------------------------------------------
2499 // CompileBroker::update_compile_perf_data
2500 //
2501 // Record this compilation for debugging purposes.
2502 void CompileBroker::update_compile_perf_data(CompilerThread* thread, const methodHandle& method, bool is_osr) {
2503 ResourceMark rm;
2504 char* method_name = method->name()->as_C_string();
2505 char current_method[CompilerCounters::cmname_buffer_length];
2506 size_t maxLen = CompilerCounters::cmname_buffer_length;
2507
2508 const char* class_name = method->method_holder()->name()->as_C_string();
2509
2510 size_t s1len = strlen(class_name);
2511 size_t s2len = strlen(method_name);
2512
2513 // check if we need to truncate the string
2514 if (s1len + s2len + 2 > maxLen) {
2515
2516 // the strategy is to lop off the leading characters of the
2517 // class name and the trailing characters of the method name.
2518
2519 if (s2len + 2 > maxLen) {
2520 // lop of the entire class name string, let snprintf handle
2521 // truncation of the method name.
2522 class_name += s1len; // null string
2523 }
2524 else {
2525 // lop off the extra characters from the front of the class name
2526 class_name += ((s1len + s2len + 2) - maxLen);
2527 }
2528 }
2529
2530 jio_snprintf(current_method, maxLen, "%s %s", class_name, method_name);
2531
2532 int last_compile_type = normal_compile;
2533 if (CICountOSR && is_osr) {
2534 last_compile_type = osr_compile;
2535 } else if (CICountNative && method->is_native()) {
2536 last_compile_type = native_compile;
2537 }
2538
2539 CompilerCounters* counters = thread->counters();
2540 counters->set_current_method(current_method);
2541 counters->set_compile_type((jlong) last_compile_type);
2542 }
2543
2544 // ------------------------------------------------------------------
2545 // CompileBroker::collect_statistics
2546 //
2547 // Collect statistics about the compilation.
2548
2549 void CompileBroker::collect_statistics(CompilerThread* thread, elapsedTimer time, CompileTask* task) {
2550 bool success = task->is_success();
2551 methodHandle method (thread, task->method());
2552 int compile_id = task->compile_id();
2553 bool is_osr = (task->osr_bci() != standard_entry_bci);
2554 const int comp_level = task->comp_level();
2555 CompilerCounters* counters = thread->counters();
2556
2557 MutexLocker locker(CompileStatistics_lock);
2558
2559 // _perf variables are production performance counters which are
2560 // updated regardless of the setting of the CITime and CITimeEach flags
2561 //
2562
2563 // account all time, including bailouts and failures in this counter;
2564 // C1 and C2 counters are counting both successful and unsuccessful compiles
2565 _t_total_compilation.add(time);
2566
2567 // Update compilation times. Used by the implementation of JFR CompilerStatistics
2568 // and java.lang.management.CompilationMXBean.
2569 _perf_total_compilation->inc(time.ticks());
2570 _peak_compilation_time = MAX2(time.milliseconds(), _peak_compilation_time);
2571
2572 if (!success) {
2573 _total_bailout_count++;
2574 if (UsePerfData) {
2575 _perf_last_failed_method->set_value(counters->current_method());
2576 _perf_last_failed_type->set_value(counters->compile_type());
2577 _perf_total_bailout_count->inc();
2578 }
2579 _t_bailedout_compilation.add(time);
2580 } else if (!task->is_success()) {
2581 if (UsePerfData) {
2582 _perf_last_invalidated_method->set_value(counters->current_method());
2583 _perf_last_invalidated_type->set_value(counters->compile_type());
2584 _perf_total_invalidated_count->inc();
2585 }
2586 _total_invalidated_count++;
2587 _t_invalidated_compilation.add(time);
2588 } else {
2589 // Compilation succeeded
2590 if (CITime) {
2591 int bytes_compiled = method->code_size() + task->num_inlined_bytecodes();
2592 if (is_osr) {
2593 _t_osr_compilation.add(time);
2594 _sum_osr_bytes_compiled += bytes_compiled;
2595 } else {
2596 _t_standard_compilation.add(time);
2597 _sum_standard_bytes_compiled += method->code_size() + task->num_inlined_bytecodes();
2598 }
2599
2600 // Collect statistic per compilation level
2601 if (comp_level > CompLevel_none && comp_level <= CompLevel_full_optimization) {
2602 CompilerStatistics* stats = &_stats_per_level[comp_level-1];
2603 if (is_osr) {
2604 stats->_osr.update(time, bytes_compiled);
2605 } else {
2606 stats->_standard.update(time, bytes_compiled);
2607 }
2608 stats->_nmethods_size += task->nm_total_size();
2609 stats->_nmethods_code_size += task->nm_insts_size();
2610 } else {
2611 assert(false, "CompilerStatistics object does not exist for compilation level %d", comp_level);
2612 }
2613
2614 // Collect statistic per compiler
2615 AbstractCompiler* comp = task->compiler();
2616 if (comp) {
2617 CompilerStatistics* stats = comp->stats();
2618 if (is_osr) {
2619 stats->_osr.update(time, bytes_compiled);
2620 } else {
2621 stats->_standard.update(time, bytes_compiled);
2622 }
2623 stats->_nmethods_size += task->nm_total_size();
2624 stats->_nmethods_code_size += task->nm_insts_size();
2625 } else { // if (!comp)
2626 assert(false, "Compiler object must exist");
2627 }
2628 }
2629
2630 if (UsePerfData) {
2631 // save the name of the last method compiled
2632 _perf_last_method->set_value(counters->current_method());
2633 _perf_last_compile_type->set_value(counters->compile_type());
2634 _perf_last_compile_size->set_value(method->code_size() +
2635 task->num_inlined_bytecodes());
2636 if (is_osr) {
2637 _perf_osr_compilation->inc(time.ticks());
2638 _perf_sum_osr_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2639 } else {
2640 _perf_standard_compilation->inc(time.ticks());
2641 _perf_sum_standard_bytes_compiled->inc(method->code_size() + task->num_inlined_bytecodes());
2642 }
2643 }
2644
2645 if (CITimeEach) {
2646 double compile_time = time.seconds();
2647 double bytes_per_sec = compile_time == 0.0 ? 0.0 : (double)(method->code_size() + task->num_inlined_bytecodes()) / compile_time;
2648 tty->print_cr("%3d seconds: %6.3f bytes/sec : %f (bytes %d + %d inlined)",
2649 compile_id, compile_time, bytes_per_sec, method->code_size(), task->num_inlined_bytecodes());
2650 }
2651
2652 // Collect counts of successful compilations
2653 _sum_nmethod_size += task->nm_total_size();
2654 _sum_nmethod_code_size += task->nm_insts_size();
2655 _total_compile_count++;
2656
2657 if (UsePerfData) {
2658 _perf_sum_nmethod_size->inc( task->nm_total_size());
2659 _perf_sum_nmethod_code_size->inc(task->nm_insts_size());
2660 _perf_total_compile_count->inc();
2661 }
2662
2663 if (is_osr) {
2664 if (UsePerfData) _perf_total_osr_compile_count->inc();
2665 _total_osr_compile_count++;
2666 } else {
2667 if (UsePerfData) _perf_total_standard_compile_count->inc();
2668 _total_standard_compile_count++;
2669 }
2670 }
2671 // set the current method for the thread to null
2672 if (UsePerfData) counters->set_current_method("");
2673 }
2674
2675 const char* CompileBroker::compiler_name(int comp_level) {
2676 AbstractCompiler *comp = CompileBroker::compiler(comp_level);
2677 if (comp == nullptr) {
2678 return "no compiler";
2679 } else {
2680 return (comp->name());
2681 }
2682 }
2683
2684 jlong CompileBroker::total_compilation_ticks() {
2685 return _perf_total_compilation != nullptr ? _perf_total_compilation->get_value() : 0;
2686 }
2687
2688 void CompileBroker::print_times(const char* name, CompilerStatistics* stats) {
2689 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}",
2690 name, stats->bytes_per_second(),
2691 stats->_standard._time.seconds(), stats->_standard._bytes, stats->_standard._count,
2692 stats->_osr._time.seconds(), stats->_osr._bytes, stats->_osr._count,
2693 stats->_nmethods_size, stats->_nmethods_code_size);
2694 }
2695
2696 void CompileBroker::print_times(bool per_compiler, bool aggregate) {
2697 if (per_compiler) {
2698 if (aggregate) {
2699 tty->cr();
2700 tty->print_cr("Individual compiler times (for compiled methods only)");
2701 tty->print_cr("------------------------------------------------");
2702 tty->cr();
2703 }
2704 for (unsigned int i = 0; i < sizeof(_compilers) / sizeof(AbstractCompiler*); i++) {
2705 AbstractCompiler* comp = _compilers[i];
2706 if (comp != nullptr) {
2707 print_times(comp->name(), comp->stats());
2708 }
2709 }
2710 if (aggregate) {
2711 tty->cr();
2712 tty->print_cr("Individual compilation Tier times (for compiled methods only)");
2713 tty->print_cr("------------------------------------------------");
2714 tty->cr();
2715 }
2716 char tier_name[256];
2717 for (int tier = CompLevel_simple; tier <= CompilationPolicy::highest_compile_level(); tier++) {
2718 CompilerStatistics* stats = &_stats_per_level[tier-1];
2719 os::snprintf_checked(tier_name, sizeof(tier_name), "Tier%d", tier);
2720 print_times(tier_name, stats);
2721 }
2722 }
2723
2724 if (!aggregate) {
2725 return;
2726 }
2727
2728 elapsedTimer standard_compilation = CompileBroker::_t_standard_compilation;
2729 elapsedTimer osr_compilation = CompileBroker::_t_osr_compilation;
2730 elapsedTimer total_compilation = CompileBroker::_t_total_compilation;
2731
2732 uint standard_bytes_compiled = CompileBroker::_sum_standard_bytes_compiled;
2733 uint osr_bytes_compiled = CompileBroker::_sum_osr_bytes_compiled;
2734
2735 uint standard_compile_count = CompileBroker::_total_standard_compile_count;
2736 uint osr_compile_count = CompileBroker::_total_osr_compile_count;
2737 uint total_compile_count = CompileBroker::_total_compile_count;
2738 uint total_bailout_count = CompileBroker::_total_bailout_count;
2739 uint total_invalidated_count = CompileBroker::_total_invalidated_count;
2740
2741 uint nmethods_code_size = CompileBroker::_sum_nmethod_code_size;
2742 uint nmethods_size = CompileBroker::_sum_nmethod_size;
2743
2744 tty->cr();
2745 tty->print_cr("Accumulated compiler times");
2746 tty->print_cr("----------------------------------------------------------");
2747 //0000000000111111111122222222223333333333444444444455555555556666666666
2748 //0123456789012345678901234567890123456789012345678901234567890123456789
2749 tty->print_cr(" Total compilation time : %7.3f s", total_compilation.seconds());
2750 tty->print_cr(" Standard compilation : %7.3f s, Average : %2.3f s",
2751 standard_compilation.seconds(),
2752 standard_compile_count == 0 ? 0.0 : standard_compilation.seconds() / standard_compile_count);
2753 tty->print_cr(" Bailed out compilation : %7.3f s, Average : %2.3f s",
2754 CompileBroker::_t_bailedout_compilation.seconds(),
2755 total_bailout_count == 0 ? 0.0 : CompileBroker::_t_bailedout_compilation.seconds() / total_bailout_count);
2756 tty->print_cr(" On stack replacement : %7.3f s, Average : %2.3f s",
2757 osr_compilation.seconds(),
2758 osr_compile_count == 0 ? 0.0 : osr_compilation.seconds() / osr_compile_count);
2759 tty->print_cr(" Invalidated : %7.3f s, Average : %2.3f s",
2760 CompileBroker::_t_invalidated_compilation.seconds(),
2761 total_invalidated_count == 0 ? 0.0 : CompileBroker::_t_invalidated_compilation.seconds() / total_invalidated_count);
2762
2763 AbstractCompiler *comp = compiler(CompLevel_simple);
2764 if (comp != nullptr) {
2765 tty->cr();
2766 comp->print_timers();
2767 }
2768 comp = compiler(CompLevel_full_optimization);
2769 if (comp != nullptr) {
2770 tty->cr();
2771 comp->print_timers();
2772 }
2773 #if INCLUDE_JVMCI
2774 if (EnableJVMCI) {
2775 JVMCICompiler *jvmci_comp = JVMCICompiler::instance(false, JavaThread::current_or_null());
2776 if (jvmci_comp != nullptr && jvmci_comp != comp) {
2777 tty->cr();
2778 jvmci_comp->print_timers();
2779 }
2780 }
2781 #endif
2782
2783 tty->cr();
2784 tty->print_cr(" Total compiled methods : %8u methods", total_compile_count);
2785 tty->print_cr(" Standard compilation : %8u methods", standard_compile_count);
2786 tty->print_cr(" On stack replacement : %8u methods", osr_compile_count);
2787 uint tcb = osr_bytes_compiled + standard_bytes_compiled;
2788 tty->print_cr(" Total compiled bytecodes : %8u bytes", tcb);
2789 tty->print_cr(" Standard compilation : %8u bytes", standard_bytes_compiled);
2790 tty->print_cr(" On stack replacement : %8u bytes", osr_bytes_compiled);
2791 double tcs = total_compilation.seconds();
2792 uint bps = tcs == 0.0 ? 0 : (uint)(tcb / tcs);
2793 tty->print_cr(" Average compilation speed : %8u bytes/s", bps);
2794 tty->cr();
2795 tty->print_cr(" nmethod code size : %8u bytes", nmethods_code_size);
2796 tty->print_cr(" nmethod total size : %8u bytes", nmethods_size);
2797 }
2798
2799 // Print general/accumulated JIT information.
2800 void CompileBroker::print_info(outputStream *out) {
2801 if (out == nullptr) out = tty;
2802 out->cr();
2803 out->print_cr("======================");
2804 out->print_cr(" General JIT info ");
2805 out->print_cr("======================");
2806 out->cr();
2807 out->print_cr(" JIT is : %7s", should_compile_new_jobs() ? "on" : "off");
2808 out->print_cr(" Compiler threads : %7d", (int)CICompilerCount);
2809 out->cr();
2810 out->print_cr("CodeCache overview");
2811 out->print_cr("--------------------------------------------------------");
2812 out->cr();
2813 out->print_cr(" Reserved size : %7zu KB", CodeCache::max_capacity() / K);
2814 out->print_cr(" Committed size : %7zu KB", CodeCache::capacity() / K);
2815 out->print_cr(" Unallocated capacity : %7zu KB", CodeCache::unallocated_capacity() / K);
2816 out->cr();
2817 }
2818
2819 // Note: tty_lock must not be held upon entry to this function.
2820 // Print functions called from herein do "micro-locking" on tty_lock.
2821 // That's a tradeoff which keeps together important blocks of output.
2822 // At the same time, continuous tty_lock hold time is kept in check,
2823 // preventing concurrently printing threads from stalling a long time.
2824 void CompileBroker::print_heapinfo(outputStream* out, const char* function, size_t granularity) {
2825 TimeStamp ts_total;
2826 TimeStamp ts_global;
2827 TimeStamp ts;
2828
2829 bool allFun = !strcmp(function, "all");
2830 bool aggregate = !strcmp(function, "aggregate") || !strcmp(function, "analyze") || allFun;
2831 bool usedSpace = !strcmp(function, "UsedSpace") || allFun;
2832 bool freeSpace = !strcmp(function, "FreeSpace") || allFun;
2833 bool methodCount = !strcmp(function, "MethodCount") || allFun;
2834 bool methodSpace = !strcmp(function, "MethodSpace") || allFun;
2835 bool methodAge = !strcmp(function, "MethodAge") || allFun;
2836 bool methodNames = !strcmp(function, "MethodNames") || allFun;
2837 bool discard = !strcmp(function, "discard") || allFun;
2838
2839 if (out == nullptr) {
2840 out = tty;
2841 }
2842
2843 if (!(aggregate || usedSpace || freeSpace || methodCount || methodSpace || methodAge || methodNames || discard)) {
2844 out->print_cr("\n__ CodeHeapStateAnalytics: Function %s is not supported", function);
2845 out->cr();
2846 return;
2847 }
2848
2849 ts_total.update(); // record starting point
2850
2851 if (aggregate) {
2852 print_info(out);
2853 }
2854
2855 // We hold the CodeHeapStateAnalytics_lock all the time, from here until we leave this function.
2856 // That prevents other threads from destroying (making inconsistent) our view on the CodeHeap.
2857 // When we request individual parts of the analysis via the jcmd interface, it is possible
2858 // that in between another thread (another jcmd user or the vm running into CodeCache OOM)
2859 // updated the aggregated data. We will then see a modified, but again consistent, view
2860 // on the CodeHeap. That's a tolerable tradeoff we have to accept because we can't hold
2861 // a lock across user interaction.
2862
2863 // We should definitely acquire this lock before acquiring Compile_lock and CodeCache_lock.
2864 // CodeHeapStateAnalytics_lock may be held by a concurrent thread for a long time,
2865 // leading to an unnecessarily long hold time of the other locks we acquired before.
2866 ts.update(); // record starting point
2867 MutexLocker mu0(CodeHeapStateAnalytics_lock, Mutex::_safepoint_check_flag);
2868 out->print_cr("\n__ CodeHeapStateAnalytics lock wait took %10.3f seconds _________\n", ts.seconds());
2869
2870 // Holding the CodeCache_lock protects from concurrent alterations of the CodeCache.
2871 // Unfortunately, such protection is not sufficient:
2872 // When a new nmethod is created via ciEnv::register_method(), the
2873 // Compile_lock is taken first. After some initializations,
2874 // nmethod::new_nmethod() takes over, grabbing the CodeCache_lock
2875 // immediately (after finalizing the oop references). To lock out concurrent
2876 // modifiers, we have to grab both locks as well in the described sequence.
2877 //
2878 // If we serve an "allFun" call, it is beneficial to hold CodeCache_lock and Compile_lock
2879 // for the entire duration of aggregation and printing. That makes sure we see
2880 // a consistent picture and do not run into issues caused by concurrent alterations.
2881 bool should_take_Compile_lock = !SafepointSynchronize::is_at_safepoint() &&
2882 !Compile_lock->owned_by_self();
2883 bool should_take_CodeCache_lock = !SafepointSynchronize::is_at_safepoint() &&
2884 !CodeCache_lock->owned_by_self();
2885 bool take_global_lock_1 = allFun && should_take_Compile_lock;
2886 bool take_global_lock_2 = allFun && should_take_CodeCache_lock;
2887 bool take_function_lock_1 = !allFun && should_take_Compile_lock;
2888 bool take_function_lock_2 = !allFun && should_take_CodeCache_lock;
2889 bool take_global_locks = take_global_lock_1 || take_global_lock_2;
2890 bool take_function_locks = take_function_lock_1 || take_function_lock_2;
2891
2892 ts_global.update(); // record starting point
2893
2894 ConditionalMutexLocker mu1(Compile_lock, take_global_lock_1, Mutex::_safepoint_check_flag);
2895 ConditionalMutexLocker mu2(CodeCache_lock, take_global_lock_2, Mutex::_no_safepoint_check_flag);
2896 if (take_global_locks) {
2897 out->print_cr("\n__ Compile & CodeCache (global) lock wait took %10.3f seconds _________\n", ts_global.seconds());
2898 ts_global.update(); // record starting point
2899 }
2900
2901 if (aggregate) {
2902 ts.update(); // record starting point
2903 ConditionalMutexLocker mu11(Compile_lock, take_function_lock_1, Mutex::_safepoint_check_flag);
2904 ConditionalMutexLocker mu22(CodeCache_lock, take_function_lock_2, Mutex::_no_safepoint_check_flag);
2905 if (take_function_locks) {
2906 out->print_cr("\n__ Compile & CodeCache (function) lock wait took %10.3f seconds _________\n", ts.seconds());
2907 }
2908
2909 ts.update(); // record starting point
2910 CodeCache::aggregate(out, granularity);
2911 if (take_function_locks) {
2912 out->print_cr("\n__ Compile & CodeCache (function) lock hold took %10.3f seconds _________\n", ts.seconds());
2913 }
2914 }
2915
2916 if (usedSpace) CodeCache::print_usedSpace(out);
2917 if (freeSpace) CodeCache::print_freeSpace(out);
2918 if (methodCount) CodeCache::print_count(out);
2919 if (methodSpace) CodeCache::print_space(out);
2920 if (methodAge) CodeCache::print_age(out);
2921 if (methodNames) {
2922 if (allFun) {
2923 // print_names() can only be used safely if the locks have been continuously held
2924 // since aggregation begin. That is true only for function "all".
2925 CodeCache::print_names(out);
2926 } else {
2927 out->print_cr("\nCodeHeapStateAnalytics: Function 'MethodNames' is only available as part of function 'all'");
2928 }
2929 }
2930 if (discard) CodeCache::discard(out);
2931
2932 if (take_global_locks) {
2933 out->print_cr("\n__ Compile & CodeCache (global) lock hold took %10.3f seconds _________\n", ts_global.seconds());
2934 }
2935 out->print_cr("\n__ CodeHeapStateAnalytics total duration %10.3f seconds _________\n", ts_total.seconds());
2936 }