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