1 /*
  2  * Copyright (c) 1998, 2025, 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 "code/SCCache.hpp"
 26 #include "compiler/compilationPolicy.hpp"
 27 #include "compiler/compileBroker.hpp"
 28 #include "compiler/compileLog.hpp"
 29 #include "compiler/compilerDirectives.hpp"
 30 #include "compiler/compileTask.hpp"
 31 #include "logging/log.hpp"
 32 #include "logging/logStream.hpp"
 33 #include "memory/resourceArea.hpp"
 34 #include "oops/klass.inline.hpp"
 35 #include "oops/method.inline.hpp"
 36 #include "runtime/handles.inline.hpp"
 37 #include "runtime/jniHandles.hpp"
 38 #include "runtime/mutexLocker.hpp"
 39 
 40 CompileTask*  CompileTask::_task_free_list = nullptr;
 41 int CompileTask::_active_tasks = 0;
 42 
 43 /**
 44  * Allocate a CompileTask, from the free list if possible.
 45  */
 46 CompileTask* CompileTask::allocate() {
 47   MonitorLocker locker(CompileTaskAlloc_lock);
 48   CompileTask* task = nullptr;
 49 
 50   if (_task_free_list != nullptr) {
 51     task = _task_free_list;
 52     _task_free_list = task->next();
 53     task->set_next(nullptr);
 54   } else {
 55     task = new CompileTask();
 56     task->set_next(nullptr);
 57     task->set_is_free(true);
 58   }
 59   assert(task->is_free(), "Task must be free.");
 60   task->set_is_free(false);
 61   _active_tasks++;
 62   return task;
 63 }
 64 
 65 /**
 66 * Add a task to the free list.
 67 */
 68 void CompileTask::free(CompileTask* task) {
 69   MonitorLocker locker(CompileTaskAlloc_lock);
 70   if (!task->is_free()) {
 71     assert(!task->lock()->is_locked(), "Should not be locked when freed");
 72     if ((task->_method_holder != nullptr && JNIHandles::is_weak_global_handle(task->_method_holder)) ||
 73         (task->_hot_method_holder != nullptr && JNIHandles::is_weak_global_handle(task->_hot_method_holder))) {
 74       JNIHandles::destroy_weak_global(task->_method_holder);
 75       JNIHandles::destroy_weak_global(task->_hot_method_holder);
 76     } else {
 77       JNIHandles::destroy_global(task->_method_holder);
 78       JNIHandles::destroy_global(task->_hot_method_holder);
 79     }
 80     if (task->_failure_reason_on_C_heap && task->_failure_reason != nullptr) {
 81       os::free((void*) task->_failure_reason);
 82     }
 83     task->_failure_reason = nullptr;
 84     task->_failure_reason_on_C_heap = false;
 85 
 86     task->set_is_free(true);
 87     task->set_next(_task_free_list);
 88     _task_free_list = task;
 89     _active_tasks--;
 90     if (_active_tasks == 0) {
 91       locker.notify_all();
 92     }
 93   }
 94 }
 95 
 96 void CompileTask::wait_for_no_active_tasks() {
 97   MonitorLocker locker(CompileTaskAlloc_lock);
 98   while (_active_tasks > 0) {
 99     locker.wait();
100   }
101 }
102 
103 void CompileTask::initialize(int compile_id,
104                              const methodHandle& method,
105                              int osr_bci,
106                              int comp_level,
107                              const methodHandle& hot_method,
108                              int hot_count,
109                              SCCEntry* scc_entry,
110                              CompileTask::CompileReason compile_reason,
111                              CompileQueue* compile_queue,
112                              bool requires_online_compilation,
113                              bool is_blocking) {
114   assert(!_lock->is_locked(), "bad locking");
115 
116   Thread* thread = Thread::current();
117   _compile_id = compile_id;
118   _method = method();
119   _method_holder = JNIHandles::make_weak_global(Handle(thread, method->method_holder()->klass_holder()));
120   _osr_bci = osr_bci;
121   _requires_online_compilation = requires_online_compilation;
122   _is_blocking = is_blocking;
123   _comp_level = comp_level;
124   _num_inlined_bytecodes = 0;
125 
126   _waiting_count = 0;
127 
128   _is_complete = false;
129   _is_success = false;
130 
131   _next = nullptr;
132   _prev = nullptr;
133 
134   _hot_method = nullptr;
135   _hot_method_holder = nullptr;
136   _hot_count = hot_count;
137   _time_created = os::elapsed_counter();
138   _time_queued = 0;
139   _time_started = 0;
140   _time_finished = 0;
141   _aot_load_start = 0;
142   _aot_load_finish = 0;
143   _compile_reason = compile_reason;
144   _nm_content_size = 0;
145   _nm_insts_size = 0;
146   _nm_total_size = 0;
147   _failure_reason = nullptr;
148   _failure_reason_on_C_heap = false;
149   _training_data = nullptr;
150   _scc_entry = scc_entry;
151   _compile_queue = compile_queue;
152 
153   AbstractCompiler* comp = CompileBroker::compiler(comp_level);
154 #if INCLUDE_JVMCI
155   if (comp->is_jvmci() && CompileBroker::compiler3() != nullptr) {
156     assert(_method != nullptr, "sanity");
157     if (((JVMCICompiler*)comp)->force_comp_at_level_simple(method)) {
158       comp = CompileBroker::compiler3();
159     }
160   }
161 #endif
162   _compiler = comp;
163   _directive = DirectivesStack::getMatchingDirective(method, comp);
164 
165   JVMCI_ONLY(_has_waiter = comp->is_jvmci();)
166   JVMCI_ONLY(_blocking_jvmci_compile_state = nullptr;)
167   _arena_bytes = 0;
168 
169   if (LogCompilation) {
170     if (hot_method.not_null()) {
171       if (hot_method == method) {
172         _hot_method = _method;
173       } else {
174         _hot_method = hot_method();
175         // only add loader or mirror if different from _method_holder
176         _hot_method_holder = JNIHandles::make_weak_global(Handle(thread, hot_method->method_holder()->klass_holder()));
177       }
178     }
179   }
180 
181   _next = nullptr;
182 }
183 
184 /**
185  * Returns the compiler for this task.
186  */
187 AbstractCompiler* CompileTask::compiler() const {
188   assert(_compiler != nullptr, "should be set");
189   return _compiler;
190 }
191 
192 // Replace weak handles by strong handles to avoid unloading during compilation.
193 CompileTask* CompileTask::select_for_compilation() {
194   if (_compile_reason == Reason_Preload) {
195     return this;
196   }
197   if (is_unloaded()) {
198     // Guard against concurrent class unloading
199     return nullptr;
200   }
201   Thread* thread = Thread::current();
202   assert(_method->method_holder()->is_loader_alive(), "should be alive");
203   Handle method_holder(thread, _method->method_holder()->klass_holder());
204   JNIHandles::destroy_weak_global(_method_holder);
205   JNIHandles::destroy_weak_global(_hot_method_holder);
206   _method_holder = JNIHandles::make_global(method_holder);
207   if (_hot_method != nullptr) {
208     _hot_method_holder = JNIHandles::make_global(Handle(thread, _hot_method->method_holder()->klass_holder()));
209   }
210   return this;
211 }
212 
213 void CompileTask::mark_on_stack() {
214   if (is_unloaded()) {
215     return;
216   }
217   // Mark these methods as something redefine classes cannot remove.
218   _method->set_on_stack(true);
219   if (_hot_method != nullptr) {
220     _hot_method->set_on_stack(true);
221   }
222 }
223 
224 bool CompileTask::is_unloaded() const {
225   if (preload()) return false;
226   return _method_holder != nullptr && JNIHandles::is_weak_global_handle(_method_holder) && JNIHandles::is_weak_global_cleared(_method_holder);
227 }
228 
229 // RedefineClasses support
230 void CompileTask::metadata_do(MetadataClosure* f) {
231   if (is_unloaded()) {
232     return;
233   }
234   f->do_metadata(method());
235   if (hot_method() != nullptr && hot_method() != method()) {
236     f->do_metadata(hot_method());
237   }
238 }
239 
240 // ------------------------------------------------------------------
241 // CompileTask::print_line_on_error
242 //
243 // This function is called by fatal error handler when the thread
244 // causing troubles is a compiler thread.
245 //
246 // Do not grab any lock, do not allocate memory.
247 //
248 // Otherwise it's the same as CompileTask::print_line()
249 //
250 void CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) {
251   // print compiler name
252   st->print("%s:", compiler()->name());
253   print(st);
254 }
255 
256 // ------------------------------------------------------------------
257 // CompileTask::print_tty
258 void CompileTask::print_tty() {
259   ttyLocker ttyl;  // keep the following output all in one block
260   print(tty);
261 }
262 
263 // ------------------------------------------------------------------
264 // CompileTask::print_impl
265 void CompileTask::print_impl(outputStream* st, Method* method, int compile_id, int comp_level,
266                              bool is_osr_method, int osr_bci, bool is_blocking, bool is_scc, bool is_preload,
267                              const char* compiler_name,
268                              const char* msg, bool short_form, bool cr,
269                              jlong time_created, jlong time_queued, jlong time_started, jlong time_finished,
270                              jlong aot_load_start, jlong aot_load_finish) {
271   if (!short_form) {
272     {
273       stringStream ss;
274       ss.print(UINT64_FORMAT, (uint64_t) tty->time_stamp().milliseconds());
275       st->print("%7s ", ss.freeze());
276     }
277     { // Time waiting to be put on queue
278       stringStream ss;
279       if (time_created != 0 && time_queued != 0) {
280         ss.print("W%.1f", TimeHelper::counter_to_millis(time_queued - time_created));
281       }
282       st->print("%7s ", ss.freeze());
283     }
284     { // Time in queue
285       stringStream ss;
286       if (time_queued != 0 && time_started != 0) {
287         ss.print("Q%.1f", TimeHelper::counter_to_millis(time_started - time_queued));
288       }
289       st->print("%7s ", ss.freeze());
290     }
291     { // Time in compilation
292       stringStream ss;
293       if (time_started != 0 && time_finished != 0) {
294         ss.print("C%.1f", TimeHelper::counter_to_millis(time_finished - time_started));
295       }
296       st->print("%7s ", ss.freeze());
297     }
298     { // Time to load from AOT code cache
299       stringStream ss;
300       if (aot_load_start != 0 && aot_load_finish != 0) {
301         ss.print("A%.1f", TimeHelper::counter_to_millis(aot_load_finish - aot_load_start));
302       }
303       st->print("%7s ", ss.freeze());
304     }
305     st->print("  ");
306   }
307 
308   // print compiler name if requested
309   if (CIPrintCompilerName) {
310     st->print("%s:", compiler_name);
311   }
312   st->print("%4d ", compile_id);    // print compilation number
313 
314   bool is_synchronized = false;
315   bool has_exception_handler = false;
316   bool is_native = false;
317   if (method != nullptr) {
318     is_synchronized       = method->is_synchronized();
319     has_exception_handler = method->has_exception_handler();
320     is_native             = method->is_native();
321   }
322   // method attributes
323   const char compile_type   = is_osr_method                   ? '%' : ' ';
324   const char sync_char      = is_synchronized                 ? 's' : ' ';
325   const char exception_char = has_exception_handler           ? '!' : ' ';
326   const char blocking_char  = is_blocking                     ? 'b' : ' ';
327   const char native_char    = is_native                       ? 'n' : ' ';
328   const char scc_char       = is_scc                          ? 'A' : ' ';
329   const char preload_char   = is_preload                      ? 'P' : ' ';
330 
331   // print method attributes
332   st->print("%c%c%c%c%c%c%c ", compile_type, sync_char, exception_char, blocking_char, native_char, scc_char, preload_char);
333 
334   if (TieredCompilation) {
335     if (comp_level != -1)  st->print("%d ", comp_level);
336     else                   st->print("- ");
337   }
338   st->print("     ");  // more indent
339 
340   if (method == nullptr) {
341     st->print("(method)");
342   } else {
343     method->print_short_name(st);
344     if (is_osr_method) {
345       st->print(" @ %d", osr_bci);
346     }
347     if (method->is_native())
348       st->print(" (native)");
349     else
350       st->print(" (%d bytes)", method->code_size());
351   }
352 
353   if (msg != nullptr) {
354     st->print("   %s", msg);
355   }
356   if (cr) {
357     st->cr();
358   }
359 }
360 
361 // ------------------------------------------------------------------
362 // CompileTask::print_compilation
363 void CompileTask::print(outputStream* st, const char* msg, bool short_form, bool cr) {
364   bool is_osr_method = osr_bci() != InvocationEntryBci;
365   print_impl(st, is_unloaded() ? nullptr : method(), compile_id(), comp_level(), is_osr_method, osr_bci(), is_blocking(), is_scc(), preload(),
366              compiler()->name(), msg, short_form, cr, _time_created, _time_queued, _time_started, _time_finished, _aot_load_start, _aot_load_finish);
367 }
368 
369 // ------------------------------------------------------------------
370 // CompileTask::log_task
371 void CompileTask::log_task(xmlStream* log) {
372   Thread* thread = Thread::current();
373   methodHandle method(thread, this->method());
374   ResourceMark rm(thread);
375 
376   // <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'>
377   log->print(" compile_id='%d'", _compile_id);
378   if (_osr_bci != CompileBroker::standard_entry_bci) {
379     log->print(" compile_kind='osr'");  // same as nmethod::compile_kind
380   } // else compile_kind='c2c'
381   if (!method.is_null())  log->method(method());
382   if (_osr_bci != CompileBroker::standard_entry_bci) {
383     log->print(" osr_bci='%d'", _osr_bci);
384   }
385   if (_comp_level != CompilationPolicy::highest_compile_level()) {
386     log->print(" level='%d'", _comp_level);
387   }
388   if (_is_blocking) {
389     log->print(" blocking='1'");
390   }
391 }
392 
393 // ------------------------------------------------------------------
394 // CompileTask::log_task_queued
395 void CompileTask::log_task_queued() {
396   ttyLocker ttyl;
397   ResourceMark rm;
398   NoSafepointVerifier nsv;
399 
400   xtty->begin_elem("task_queued");
401   log_task(xtty);
402   assert(_compile_reason > CompileTask::Reason_None && _compile_reason < CompileTask::Reason_Count, "Valid values");
403   xtty->print(" comment='%s'", reason_name(_compile_reason));
404 
405   if (_hot_method != nullptr && _hot_method != _method) {
406     xtty->method(_hot_method, "hot_");
407   }
408   if (_hot_count != 0) {
409     xtty->print(" hot_count='%d'", _hot_count);
410   }
411   xtty->stamp();
412   xtty->end_elem();
413 }
414 
415 
416 // ------------------------------------------------------------------
417 // CompileTask::log_task_start
418 void CompileTask::log_task_start(CompileLog* log) {
419   log->begin_head("task");
420   log_task(log);
421   log->stamp();
422   log->end_head();
423 }
424 
425 
426 // ------------------------------------------------------------------
427 // CompileTask::log_task_done
428 void CompileTask::log_task_done(CompileLog* log) {
429   Thread* thread = Thread::current();
430   methodHandle method(thread, this->method());
431   ResourceMark rm(thread);
432 
433   if (!_is_success) {
434     assert(_failure_reason != nullptr, "missing");
435     const char* reason = _failure_reason != nullptr ? _failure_reason : "unknown";
436     log->begin_elem("failure reason='");
437     log->text("%s", reason);
438     log->print("'");
439     log->end_elem();
440   }
441 
442   // <task_done ... stamp='1.234'>  </task>
443   log->begin_elem("task_done success='%d' nmsize='%d' count='%d'",
444                   _is_success, _nm_content_size,
445                   method->invocation_count());
446   int bec = method->backedge_count();
447   if (bec != 0)  log->print(" backedge_count='%d'", bec);
448   // Note:  "_is_complete" is about to be set, but is not.
449   if (_num_inlined_bytecodes != 0) {
450     log->print(" inlined_bytes='%d'", _num_inlined_bytecodes);
451   }
452   log->stamp();
453   log->end_elem();
454   log->clear_identities();   // next task will have different CI
455   log->tail("task");
456   log->flush();
457   log->mark_file_end();
458 }
459 
460 // ------------------------------------------------------------------
461 // CompileTask::check_break_at_flags
462 bool CompileTask::check_break_at_flags() {
463   int compile_id = this->_compile_id;
464   bool is_osr = (_osr_bci != CompileBroker::standard_entry_bci);
465 
466   if (CICountOSR && is_osr && (compile_id == CIBreakAtOSR)) {
467     return true;
468   } else {
469     return (compile_id == CIBreakAt);
470   }
471 }
472 
473 // ------------------------------------------------------------------
474 // CompileTask::print_inlining
475 void CompileTask::print_inlining_inner(outputStream* st, ciMethod* method, int inline_level, int bci, InliningResult result, const char* msg) {
476   print_inlining_header(st, method, inline_level, bci);
477   print_inlining_inner_message(st, result, msg);
478   st->cr();
479 }
480 
481 void CompileTask::print_inlining_header(outputStream* st, ciMethod* method, int inline_level, int bci) {
482   //         1234567
483   st->print("        "); // print timestamp
484   //         1234
485   st->print("     "); // print compilation number
486 
487   // method attributes
488   if (method->is_loaded()) {
489     const char sync_char = method->is_synchronized() ? 's' : ' ';
490     const char exception_char = method->has_exception_handlers() ? '!' : ' ';
491     const char monitors_char = method->has_monitor_bytecodes() ? 'm' : ' ';
492 
493     // print method attributes
494     st->print(" %c%c%c  ", sync_char, exception_char, monitors_char);
495   } else {
496     //         %s!bn
497     st->print("      "); // print method attributes
498   }
499 
500   if (TieredCompilation) {
501     st->print("  ");
502   }
503   st->print("     "); // more indent
504   st->print("    ");  // initial inlining indent
505 
506   for (int i = 0; i < inline_level; i++) {
507     st->print("  ");
508   }
509 
510   st->print("@ %d  ", bci); // print bci
511   print_inline_inner_method_info(st, method);
512 }
513 
514 void CompileTask::print_inline_inner_method_info(outputStream* st, ciMethod* method) {
515   method->print_short_name(st);
516   if (method->is_loaded()) {
517     st->print(" (%d bytes)", method->code_size());
518   } else {
519     st->print(" (not loaded)");
520   }
521 }
522 
523 void CompileTask::print_inline_indent(int inline_level, outputStream* st) {
524   //         1234567
525   st->print("        "); // print timestamp
526   //         1234
527   st->print("     "); // print compilation number
528   //         %s!bn
529   st->print("      "); // print method attributes
530   if (TieredCompilation) {
531     st->print("  ");
532   }
533   st->print("     "); // more indent
534   st->print("    ");  // initial inlining indent
535   for (int i = 0; i < inline_level; i++) {
536     st->print("  ");
537   }
538 }
539 
540 void CompileTask::print_inlining_inner_message(outputStream* st, InliningResult result, const char* msg) {
541   if (msg != nullptr) {
542     st->print("   %s%s", result == InliningResult::SUCCESS ? "" : "failed to inline: ", msg);
543   } else if (result == InliningResult::FAILURE) {
544     st->print("   %s", "failed to inline");
545   }
546 }
547 
548 void CompileTask::print_ul(const char* msg){
549   LogTarget(Debug, jit, compilation) lt;
550   if (lt.is_enabled()) {
551     LogStream ls(lt);
552     print(&ls, msg, /* short form */ true, /* cr */ true);
553   }
554 }
555 
556 void CompileTask::print_ul(const nmethod* nm, const char* msg) {
557   LogTarget(Debug, jit, compilation) lt;
558   if (lt.is_enabled()) {
559     LogStream ls(lt);
560     print_impl(&ls, nm->method(), nm->compile_id(),
561                nm->comp_level(), nm->is_osr_method(),
562                nm->is_osr_method() ? nm->osr_entry_bci() : -1,
563                /*is_blocking*/ false, nm->scc_entry() != nullptr,
564                nm->preloaded(), nm->compiler_name(),
565                msg, /* short form */ true, /* cr */ true);
566   }
567 }
568 
569 void CompileTask::print_inlining_ul(ciMethod* method, int inline_level, int bci, InliningResult result, const char* msg) {
570   LogTarget(Debug, jit, inlining) lt;
571   if (lt.is_enabled()) {
572     LogStream ls(lt);
573     print_inlining_inner(&ls, method, inline_level, bci, result, msg);
574   }
575 }
576