1 /*
   2  * Copyright (c) 2010, 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 "cds/aotLinkedClassBulkLoader.hpp"
  26 #include "code/scopeDesc.hpp"
  27 #include "code/SCCache.hpp"
  28 #include "compiler/compilationPolicy.hpp"
  29 #include "compiler/compileBroker.hpp"
  30 #include "compiler/compilerDefinitions.inline.hpp"
  31 #include "compiler/compilerOracle.hpp"
  32 #include "compiler/recompilationPolicy.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "oops/methodData.hpp"
  35 #include "oops/method.inline.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "oops/trainingData.hpp"
  38 #include "prims/jvmtiExport.hpp"
  39 #include "runtime/arguments.hpp"
  40 #include "runtime/deoptimization.hpp"
  41 #include "runtime/frame.hpp"
  42 #include "runtime/frame.inline.hpp"
  43 #include "runtime/globals_extension.hpp"
  44 #include "runtime/handles.inline.hpp"
  45 #include "runtime/safepoint.hpp"
  46 #include "runtime/safepointVerifiers.hpp"
  47 #ifdef COMPILER1
  48 #include "c1/c1_Compiler.hpp"
  49 #endif
  50 #ifdef COMPILER2
  51 #include "opto/c2compiler.hpp"
  52 #endif
  53 #if INCLUDE_JVMCI
  54 #include "jvmci/jvmci.hpp"
  55 #endif
  56 
  57 int64_t CompilationPolicy::_start_time = 0;
  58 int CompilationPolicy::_c1_count = 0;
  59 int CompilationPolicy::_c2_count = 0;
  60 int CompilationPolicy::_c3_count = 0;
  61 int CompilationPolicy::_sc_count = 0;
  62 double CompilationPolicy::_increase_threshold_at_ratio = 0;
  63 
  64 CompilationPolicy::TrainingReplayQueue CompilationPolicy::_training_replay_queue;
  65 
  66 void compilationPolicy_init() {
  67   CompilationPolicy::initialize();
  68 }
  69 
  70 int CompilationPolicy::compiler_count(CompLevel comp_level) {
  71   if (is_c1_compile(comp_level)) {
  72     return c1_count();
  73   } else if (is_c2_compile(comp_level)) {
  74     return c2_count();
  75   }
  76   return 0;
  77 }
  78 
  79 // Returns true if m must be compiled before executing it
  80 // This is intended to force compiles for methods (usually for
  81 // debugging) that would otherwise be interpreted for some reason.
  82 bool CompilationPolicy::must_be_compiled(const methodHandle& m, int comp_level) {
  83   // Don't allow Xcomp to cause compiles in replay mode
  84   if (ReplayCompiles) return false;
  85 
  86   if (m->has_compiled_code()) return false;       // already compiled
  87   if (!can_be_compiled(m, comp_level)) return false;
  88 
  89   return !UseInterpreter ||                                                                        // must compile all methods
  90          (AlwaysCompileLoopMethods && m->has_loops() && CompileBroker::should_compile_new_jobs()); // eagerly compile loop methods
  91 }
  92 
  93 void CompilationPolicy::maybe_compile_early(const methodHandle& m, TRAPS) {
  94   if (m->method_holder()->is_not_initialized()) {
  95     // 'is_not_initialized' means not only '!is_initialized', but also that
  96     // initialization has not been started yet ('!being_initialized')
  97     // Do not force compilation of methods in uninitialized classes.
  98     return;
  99   }
 100   if (!m->is_native() && MethodTrainingData::have_data()) {
 101     MethodTrainingData* mtd = MethodTrainingData::find_fast(m);
 102     if (mtd == nullptr) {
 103       return;              // there is no training data recorded for m
 104     }
 105     bool recompile = m->code_has_clinit_barriers();
 106     CompLevel cur_level = static_cast<CompLevel>(m->highest_comp_level());
 107     CompLevel next_level = trained_transition(m, cur_level, mtd, THREAD);
 108     if ((next_level != cur_level || recompile) && can_be_compiled(m, next_level) && !CompileBroker::compilation_is_in_queue(m)) {
 109       bool requires_online_compilation = false;
 110       CompileTrainingData* ctd = mtd->last_toplevel_compile(next_level);
 111       if (ctd != nullptr) {
 112         requires_online_compilation = (ctd->init_deps_left() > 0);
 113       }
 114       if (requires_online_compilation && recompile) {
 115         return;
 116       }
 117       if (PrintTieredEvents) {
 118         print_event(FORCE_COMPILE, m(), m(), InvocationEntryBci, next_level);
 119       }
 120       CompileBroker::compile_method(m, InvocationEntryBci, next_level, methodHandle(), 0, requires_online_compilation, CompileTask::Reason_MustBeCompiled, THREAD);
 121       if (HAS_PENDING_EXCEPTION) {
 122         CLEAR_PENDING_EXCEPTION;
 123       }
 124     }
 125   }
 126 }
 127 
 128 void CompilationPolicy::maybe_compile_early_after_init(const methodHandle& m, TRAPS) {
 129   assert(m->method_holder()->is_initialized(), "Should be called after class initialization");
 130   maybe_compile_early(m, THREAD);
 131 }
 132 
 133 void CompilationPolicy::compile_if_required(const methodHandle& m, TRAPS) {
 134   if (!THREAD->can_call_java() || THREAD->is_Compiler_thread()) {
 135     // don't force compilation, resolve was on behalf of compiler
 136     return;
 137   }
 138   if (m->method_holder()->is_not_initialized()) {
 139     // 'is_not_initialized' means not only '!is_initialized', but also that
 140     // initialization has not been started yet ('!being_initialized')
 141     // Do not force compilation of methods in uninitialized classes.
 142     // Note that doing this would throw an assert later,
 143     // in CompileBroker::compile_method.
 144     // We sometimes use the link resolver to do reflective lookups
 145     // even before classes are initialized.
 146     return;
 147   }
 148 
 149   if (must_be_compiled(m)) {
 150     // This path is unusual, mostly used by the '-Xcomp' stress test mode.
 151     CompLevel level = initial_compile_level(m);
 152     if (PrintTieredEvents) {
 153       print_event(FORCE_COMPILE, m(), m(), InvocationEntryBci, level);
 154     }
 155     CompileBroker::compile_method(m, InvocationEntryBci, level, methodHandle(), 0, false, CompileTask::Reason_MustBeCompiled, THREAD);
 156   }
 157 }
 158 
 159 void CompilationPolicy::replay_training_at_init_impl(InstanceKlass* klass, TRAPS) {
 160   if (!klass->has_init_deps_processed()) {
 161     ResourceMark rm;
 162     log_debug(training)("Replay training: %s", klass->external_name());
 163 
 164     KlassTrainingData* ktd = KlassTrainingData::find(klass);
 165     if (ktd != nullptr) {
 166       guarantee(ktd->has_holder(), "");
 167       ktd->notice_fully_initialized(); // sets klass->has_init_deps_processed bit
 168       assert(klass->has_init_deps_processed(), "");
 169 
 170       ktd->iterate_all_comp_deps([&](CompileTrainingData* ctd) {
 171         if (ctd->init_deps_left() == 0) {
 172           MethodTrainingData* mtd = ctd->method();
 173           if (mtd->has_holder()) {
 174             const methodHandle mh(THREAD, const_cast<Method*>(mtd->holder()));
 175             CompilationPolicy::maybe_compile_early(mh, THREAD);
 176           }
 177         }
 178       });
 179     }
 180     Array<Method*>* methods = klass->methods();
 181     for (int i = 0; i < methods->length(); i++) {
 182       const methodHandle mh(THREAD, methods->at(i));
 183       CompilationPolicy::maybe_compile_early_after_init(mh, THREAD);
 184     }
 185   }
 186 }
 187 
 188 void CompilationPolicy::replay_training_at_init(bool is_on_shutdown, TRAPS) {
 189   // Drain pending queue when no concurrent processing thread is present.
 190   if (UseConcurrentTrainingReplay) {
 191     if (VerifyTrainingData) {
 192       MonitorLocker locker(THREAD, TrainingReplayQueue_lock);
 193       while (!_training_replay_queue.is_empty_unlocked()) {
 194         locker.wait(); // let the replay training thread drain the queue
 195       }
 196     }
 197   } else {
 198     do {
 199       InstanceKlass* pending = _training_replay_queue.try_pop(TrainingReplayQueue_lock, THREAD);
 200       if (pending == nullptr) {
 201         break; // drained the queue
 202       }
 203       if (is_on_shutdown) {
 204         LogStreamHandle(Warning, training) log;
 205         if (log.is_enabled()) {
 206           ResourceMark rm;
 207           log.print("pending training replay request: %s%s",
 208                     pending->external_name(), (pending->has_aot_initialized_mirror() ? " (preinitialized)" : ""));
 209         }
 210       }
 211       replay_training_at_init_impl(pending, THREAD);
 212     } while (true);
 213   }
 214 
 215   if (VerifyTrainingData) {
 216     TrainingData::verify();
 217   }
 218 }
 219 
 220 void CompilationPolicy::replay_training_at_init(InstanceKlass* klass, TRAPS) {
 221   assert(klass->is_initialized(), "");
 222   if (TrainingData::have_data() && klass->is_shared() &&
 223       (CompileBroker::replay_initialized() || !klass->has_aot_initialized_mirror())) { // ignore preloaded classes during early startup
 224     if (UseConcurrentTrainingReplay || !CompileBroker::replay_initialized()) {
 225       _training_replay_queue.push(klass, TrainingReplayQueue_lock, THREAD);
 226     } else {
 227       replay_training_at_init_impl(klass, THREAD);
 228     }
 229     assert(!HAS_PENDING_EXCEPTION, "");
 230   }
 231 }
 232 
 233 // For TrainingReplayQueue
 234 template<>
 235 void CompilationPolicyUtils::Queue<InstanceKlass>::print_on(outputStream* st) {
 236   int pos = 0;
 237   for (QueueNode* cur = _head; cur != nullptr; cur = cur->next()) {
 238     ResourceMark rm;
 239     InstanceKlass* ik = cur->value();
 240     st->print_cr("%3d: " INTPTR_FORMAT " %s", ++pos, p2i(ik), ik->external_name());
 241   }
 242 }
 243 
 244 void CompilationPolicy::replay_training_at_init_loop(TRAPS) {
 245   precond(UseConcurrentTrainingReplay);
 246 
 247   while (!CompileBroker::is_compilation_disabled_forever() || VerifyTrainingData) {
 248     InstanceKlass* ik = _training_replay_queue.pop(TrainingReplayQueue_lock, THREAD);
 249     replay_training_at_init_impl(ik, THREAD);
 250   }
 251 }
 252 
 253 static inline CompLevel adjust_level_for_compilability_query(CompLevel comp_level) {
 254   if (comp_level == CompLevel_any) {
 255      if (CompilerConfig::is_c1_only()) {
 256        comp_level = CompLevel_simple;
 257      } else if (CompilerConfig::is_c2_or_jvmci_compiler_only()) {
 258        comp_level = CompLevel_full_optimization;
 259      }
 260   }
 261   return comp_level;
 262 }
 263 
 264 // Returns true if m is allowed to be compiled
 265 bool CompilationPolicy::can_be_compiled(const methodHandle& m, int comp_level) {
 266   // allow any levels for WhiteBox
 267   assert(WhiteBoxAPI || comp_level == CompLevel_any || is_compile(comp_level), "illegal compilation level %d", comp_level);
 268 
 269   if (m->is_abstract()) return false;
 270   if (DontCompileHugeMethods && m->code_size() > HugeMethodLimit) return false;
 271 
 272   // Math intrinsics should never be compiled as this can lead to
 273   // monotonicity problems because the interpreter will prefer the
 274   // compiled code to the intrinsic version.  This can't happen in
 275   // production because the invocation counter can't be incremented
 276   // but we shouldn't expose the system to this problem in testing
 277   // modes.
 278   if (!AbstractInterpreter::can_be_compiled(m)) {
 279     return false;
 280   }
 281   comp_level = adjust_level_for_compilability_query((CompLevel) comp_level);
 282   if (comp_level == CompLevel_any || is_compile(comp_level)) {
 283     return !m->is_not_compilable(comp_level);
 284   }
 285   return false;
 286 }
 287 
 288 // Returns true if m is allowed to be osr compiled
 289 bool CompilationPolicy::can_be_osr_compiled(const methodHandle& m, int comp_level) {
 290   bool result = false;
 291   comp_level = adjust_level_for_compilability_query((CompLevel) comp_level);
 292   if (comp_level == CompLevel_any || is_compile(comp_level)) {
 293     result = !m->is_not_osr_compilable(comp_level);
 294   }
 295   return (result && can_be_compiled(m, comp_level));
 296 }
 297 
 298 bool CompilationPolicy::is_compilation_enabled() {
 299   // NOTE: CompileBroker::should_compile_new_jobs() checks for UseCompiler
 300   return CompileBroker::should_compile_new_jobs();
 301 }
 302 
 303 CompileTask* CompilationPolicy::select_task_helper(CompileQueue* compile_queue) {
 304   // Remove unloaded methods from the queue
 305   for (CompileTask* task = compile_queue->first(); task != nullptr; ) {
 306     CompileTask* next = task->next();
 307     if (task->is_unloaded()) {
 308       compile_queue->remove_and_mark_stale(task);
 309     }
 310     task = next;
 311   }
 312 #if INCLUDE_JVMCI
 313   if (UseJVMCICompiler && !BackgroundCompilation) {
 314     /*
 315      * In blocking compilation mode, the CompileBroker will make
 316      * compilations submitted by a JVMCI compiler thread non-blocking. These
 317      * compilations should be scheduled after all blocking compilations
 318      * to service non-compiler related compilations sooner and reduce the
 319      * chance of such compilations timing out.
 320      */
 321     for (CompileTask* task = compile_queue->first(); task != nullptr; task = task->next()) {
 322       if (task->is_blocking()) {
 323         return task;
 324       }
 325     }
 326   }
 327 #endif
 328   return compile_queue->first();
 329 }
 330 
 331 // Simple methods are as good being compiled with C1 as C2.
 332 // Determine if a given method is such a case.
 333 bool CompilationPolicy::is_trivial(const methodHandle& method) {
 334   if (method->is_accessor() ||
 335       method->is_constant_getter()) {
 336     return true;
 337   }
 338   return false;
 339 }
 340 
 341 bool CompilationPolicy::force_comp_at_level_simple(const methodHandle& method) {
 342   if (CompilationModeFlag::quick_internal()) {
 343 #if INCLUDE_JVMCI
 344     if (UseJVMCICompiler) {
 345       AbstractCompiler* comp = CompileBroker::compiler(CompLevel_full_optimization);
 346       if (comp != nullptr && comp->is_jvmci() && ((JVMCICompiler*) comp)->force_comp_at_level_simple(method)) {
 347         return !SCCache::is_C3_on();
 348       }
 349     }
 350 #endif
 351   }
 352   return false;
 353 }
 354 
 355 CompLevel CompilationPolicy::comp_level(Method* method) {
 356   nmethod *nm = method->code();
 357   if (nm != nullptr && nm->is_in_use()) {
 358     return (CompLevel)nm->comp_level();
 359   }
 360   return CompLevel_none;
 361 }
 362 
 363 // Call and loop predicates determine whether a transition to a higher
 364 // compilation level should be performed (pointers to predicate functions
 365 // are passed to common()).
 366 // Tier?LoadFeedback is basically a coefficient that determines of
 367 // how many methods per compiler thread can be in the queue before
 368 // the threshold values double.
 369 class LoopPredicate : AllStatic {
 370 public:
 371   static bool apply_scaled(const methodHandle& method, CompLevel cur_level, int i, int b, double scale) {
 372     double threshold_scaling;
 373     if (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, threshold_scaling)) {
 374       scale *= threshold_scaling;
 375     }
 376     switch(cur_level) {
 377     case CompLevel_none:
 378     case CompLevel_limited_profile:
 379       return b >= Tier3BackEdgeThreshold * scale;
 380     case CompLevel_full_profile:
 381       return b >= Tier4BackEdgeThreshold * scale;
 382     default:
 383       return true;
 384     }
 385   }
 386 
 387   static bool apply(const methodHandle& method, CompLevel cur_level, int i, int b) {
 388     double k = 1;
 389     switch(cur_level) {
 390     case CompLevel_none:
 391     // Fall through
 392     case CompLevel_limited_profile: {
 393       k = CompilationPolicy::threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
 394       break;
 395     }
 396     case CompLevel_full_profile: {
 397       k = CompilationPolicy::threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);
 398       break;
 399     }
 400     default:
 401       return true;
 402     }
 403     return apply_scaled(method, cur_level, i, b, k);
 404   }
 405 };
 406 
 407 class CallPredicate : AllStatic {
 408 public:
 409   static bool apply_scaled(const methodHandle& method, CompLevel cur_level, int i, int b, double scale) {
 410     double threshold_scaling;
 411     if (CompilerOracle::has_option_value(method, CompileCommandEnum::CompileThresholdScaling, threshold_scaling)) {
 412       scale *= threshold_scaling;
 413     }
 414     switch(cur_level) {
 415     case CompLevel_none:
 416     case CompLevel_limited_profile:
 417       return (i >= Tier3InvocationThreshold * scale) ||
 418              (i >= Tier3MinInvocationThreshold * scale && i + b >= Tier3CompileThreshold * scale);
 419     case CompLevel_full_profile:
 420       return (i >= Tier4InvocationThreshold * scale) ||
 421              (i >= Tier4MinInvocationThreshold * scale && i + b >= Tier4CompileThreshold * scale);
 422     default:
 423      return true;
 424     }
 425   }
 426 
 427   static bool apply(const methodHandle& method, CompLevel cur_level, int i, int b) {
 428     double k = 1;
 429     switch(cur_level) {
 430     case CompLevel_none:
 431     case CompLevel_limited_profile: {
 432       k = CompilationPolicy::threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
 433       break;
 434     }
 435     case CompLevel_full_profile: {
 436       k = CompilationPolicy::threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);
 437       break;
 438     }
 439     default:
 440       return true;
 441     }
 442     return apply_scaled(method, cur_level, i, b, k);
 443   }
 444 };
 445 
 446 double CompilationPolicy::threshold_scale(CompLevel level, int feedback_k) {
 447   int comp_count = compiler_count(level);
 448   if (comp_count > 0) {
 449     double queue_size = CompileBroker::queue_size(level);
 450     double k = (double)queue_size / ((double)feedback_k * (double)comp_count) + 1;
 451 
 452     // Increase C1 compile threshold when the code cache is filled more
 453     // than specified by IncreaseFirstTierCompileThresholdAt percentage.
 454     // The main intention is to keep enough free space for C2 compiled code
 455     // to achieve peak performance if the code cache is under stress.
 456     if (CompilerConfig::is_tiered() && !CompilationModeFlag::disable_intermediate() && is_c1_compile(level))  {
 457       double current_reverse_free_ratio = CodeCache::reverse_free_ratio();
 458       if (current_reverse_free_ratio > _increase_threshold_at_ratio) {
 459         k *= exp(current_reverse_free_ratio - _increase_threshold_at_ratio);
 460       }
 461     }
 462     return k;
 463   }
 464   return 1;
 465 }
 466 
 467 void CompilationPolicy::print_counters(const char* prefix, Method* m) {
 468   int invocation_count = m->invocation_count();
 469   int backedge_count = m->backedge_count();
 470   MethodData* mdh = m->method_data();
 471   int mdo_invocations = 0, mdo_backedges = 0;
 472   int mdo_invocations_start = 0, mdo_backedges_start = 0;
 473   if (mdh != nullptr) {
 474     mdo_invocations = mdh->invocation_count();
 475     mdo_backedges = mdh->backedge_count();
 476     mdo_invocations_start = mdh->invocation_count_start();
 477     mdo_backedges_start = mdh->backedge_count_start();
 478   }
 479   tty->print(" %stotal=%d,%d %smdo=%d(%d),%d(%d)", prefix,
 480       invocation_count, backedge_count, prefix,
 481       mdo_invocations, mdo_invocations_start,
 482       mdo_backedges, mdo_backedges_start);
 483   tty->print(" %smax levels=%d,%d", prefix,
 484       m->highest_comp_level(), m->highest_osr_comp_level());
 485 }
 486 
 487 void CompilationPolicy::print_training_data(const char* prefix, Method* method) {
 488   methodHandle m(Thread::current(), method);
 489   tty->print(" %smtd: ", prefix);
 490   MethodTrainingData* mtd = MethodTrainingData::find_fast(m);
 491   if (mtd == nullptr) {
 492     tty->print("null");
 493   } else {
 494     MethodData* md = mtd->final_profile();
 495     tty->print("mdo=");
 496     if (md == nullptr) {
 497       tty->print("null");
 498     } else {
 499       int mdo_invocations = md->invocation_count();
 500       int mdo_backedges = md->backedge_count();
 501       int mdo_invocations_start = md->invocation_count_start();
 502       int mdo_backedges_start = md->backedge_count_start();
 503       tty->print("%d(%d), %d(%d)", mdo_invocations, mdo_invocations_start, mdo_backedges, mdo_backedges_start);
 504     }
 505     CompileTrainingData* ctd = mtd->last_toplevel_compile(CompLevel_full_optimization);
 506     tty->print(", deps=");
 507     if (ctd == nullptr) {
 508       tty->print("null");
 509     } else {
 510       tty->print("%d", ctd->init_deps_left());
 511     }
 512   }
 513 }
 514 
 515 // Print an event.
 516 void CompilationPolicy::print_event(EventType type, Method* m, Method* im, int bci, CompLevel level) {
 517   bool inlinee_event = m != im;
 518 
 519   ttyLocker tty_lock;
 520   tty->print("%lf: [", os::elapsedTime());
 521 
 522   switch(type) {
 523   case CALL:
 524     tty->print("call");
 525     break;
 526   case LOOP:
 527     tty->print("loop");
 528     break;
 529   case COMPILE:
 530     tty->print("compile");
 531     break;
 532   case FORCE_COMPILE:
 533     tty->print("force-compile");
 534     break;
 535   case FORCE_RECOMPILE:
 536     tty->print("force-recompile");
 537     break;
 538   case REMOVE_FROM_QUEUE:
 539     tty->print("remove-from-queue");
 540     break;
 541   case UPDATE_IN_QUEUE:
 542     tty->print("update-in-queue");
 543     break;
 544   case REPROFILE:
 545     tty->print("reprofile");
 546     break;
 547   case MAKE_NOT_ENTRANT:
 548     tty->print("make-not-entrant");
 549     break;
 550   default:
 551     tty->print("unknown");
 552   }
 553 
 554   tty->print(" level=%d ", level);
 555 
 556   ResourceMark rm;
 557   char *method_name = m->name_and_sig_as_C_string();
 558   tty->print("[%s", method_name);
 559   if (inlinee_event) {
 560     char *inlinee_name = im->name_and_sig_as_C_string();
 561     tty->print(" [%s]] ", inlinee_name);
 562   }
 563   else tty->print("] ");
 564   tty->print("@%d queues=%d,%d", bci, CompileBroker::queue_size(CompLevel_full_profile),
 565                                       CompileBroker::queue_size(CompLevel_full_optimization));
 566 
 567   tty->print(" rate=");
 568   if (m->prev_time() == 0) tty->print("n/a");
 569   else tty->print("%f", m->rate());
 570 
 571   RecompilationPolicy::print_load_average();
 572 
 573   tty->print(" k=%.2lf,%.2lf", threshold_scale(CompLevel_full_profile, Tier3LoadFeedback),
 574                                threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback));
 575 
 576   if (type != COMPILE) {
 577     print_counters("", m);
 578     if (inlinee_event) {
 579       print_counters("inlinee ", im);
 580     }
 581     tty->print(" compilable=");
 582     bool need_comma = false;
 583     if (!m->is_not_compilable(CompLevel_full_profile)) {
 584       tty->print("c1");
 585       need_comma = true;
 586     }
 587     if (!m->is_not_osr_compilable(CompLevel_full_profile)) {
 588       if (need_comma) tty->print(",");
 589       tty->print("c1-osr");
 590       need_comma = true;
 591     }
 592     if (!m->is_not_compilable(CompLevel_full_optimization)) {
 593       if (need_comma) tty->print(",");
 594       tty->print("c2");
 595       need_comma = true;
 596     }
 597     if (!m->is_not_osr_compilable(CompLevel_full_optimization)) {
 598       if (need_comma) tty->print(",");
 599       tty->print("c2-osr");
 600     }
 601     tty->print(" status=");
 602     if (m->queued_for_compilation()) {
 603       tty->print("in-queue");
 604     } else tty->print("idle");
 605     print_training_data("", m);
 606     if (inlinee_event) {
 607       print_training_data("inlinee ", im);
 608     }
 609   }
 610   tty->print_cr("]");
 611 }
 612 
 613 void CompilationPolicy::initialize() {
 614   if (!CompilerConfig::is_interpreter_only()) {
 615     int count = CICompilerCount;
 616     bool c1_only = CompilerConfig::is_c1_only();
 617     bool c2_only = CompilerConfig::is_c2_or_jvmci_compiler_only();
 618 
 619 #ifdef _LP64
 620     // Turn on ergonomic compiler count selection
 621     if (FLAG_IS_DEFAULT(CICompilerCountPerCPU) && FLAG_IS_DEFAULT(CICompilerCount)) {
 622       FLAG_SET_DEFAULT(CICompilerCountPerCPU, true);
 623     }
 624     if (CICompilerCountPerCPU) {
 625       // Simple log n seems to grow too slowly for tiered, try something faster: log n * log log n
 626       int log_cpu = log2i(os::active_processor_count());
 627       int loglog_cpu = log2i(MAX2(log_cpu, 1));
 628       count = MAX2(log_cpu * loglog_cpu * 3 / 2, 2);
 629       // Make sure there is enough space in the code cache to hold all the compiler buffers
 630       size_t c1_size = 0;
 631 #ifdef COMPILER1
 632       c1_size = Compiler::code_buffer_size();
 633 #endif
 634       size_t c2_size = 0;
 635 #ifdef COMPILER2
 636       c2_size = C2Compiler::initial_code_buffer_size();
 637 #endif
 638       size_t buffer_size = c1_only ? c1_size : (c1_size/3 + 2*c2_size/3);
 639       int max_count = (ReservedCodeCacheSize - (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3))) / (int)buffer_size;
 640       if (count > max_count) {
 641         // Lower the compiler count such that all buffers fit into the code cache
 642         count = MAX2(max_count, c1_only ? 1 : 2);
 643       }
 644       FLAG_SET_ERGO(CICompilerCount, count);
 645     }
 646 #else
 647     // On 32-bit systems, the number of compiler threads is limited to 3.
 648     // On these systems, the virtual address space available to the JVM
 649     // is usually limited to 2-4 GB (the exact value depends on the platform).
 650     // As the compilers (especially C2) can consume a large amount of
 651     // memory, scaling the number of compiler threads with the number of
 652     // available cores can result in the exhaustion of the address space
 653     /// available to the VM and thus cause the VM to crash.
 654     if (FLAG_IS_DEFAULT(CICompilerCount)) {
 655       count = 3;
 656       FLAG_SET_ERGO(CICompilerCount, count);
 657     }
 658 #endif
 659 
 660     if (c1_only) {
 661       // No C2 compiler thread required
 662       set_c1_count(count);
 663     } else if (c2_only) {
 664       set_c2_count(count);
 665     } else {
 666 #if INCLUDE_JVMCI
 667       if (UseJVMCICompiler && UseJVMCINativeLibrary) {
 668         int libjvmci_count = MAX2((int) (count * JVMCINativeLibraryThreadFraction), 1);
 669         int c1_count = MAX2(count - libjvmci_count, 1);
 670         set_c2_count(libjvmci_count);
 671         set_c1_count(c1_count);
 672       } else if (SCCache::is_C3_on()) {
 673         set_c1_count(MAX2(count / 3, 1));
 674         set_c2_count(MAX2(count - c1_count(), 1));
 675         set_c3_count(1);
 676       } else
 677 #endif
 678       {
 679         set_c1_count(MAX2(count / 3, 1));
 680         set_c2_count(MAX2(count - c1_count(), 1));
 681       }
 682     }
 683     if (SCCache::is_code_load_thread_on()) {
 684       set_sc_count((c1_only || c2_only) ? 1 : 2); // At minimum we need 2 threads to load C1 and C2 cached code in parallel
 685     }
 686     assert(count == c1_count() + c2_count(), "inconsistent compiler thread count");
 687     set_increase_threshold_at_ratio();
 688   }
 689 
 690   set_start_time(nanos_to_millis(os::javaTimeNanos()));
 691 }
 692 
 693 
 694 
 695 
 696 #ifdef ASSERT
 697 bool CompilationPolicy::verify_level(CompLevel level) {
 698   if (TieredCompilation && level > TieredStopAtLevel) {
 699     return false;
 700   }
 701   // Check if there is a compiler to process the requested level
 702   if (!CompilerConfig::is_c1_enabled() && is_c1_compile(level)) {
 703     return false;
 704   }
 705   if (!CompilerConfig::is_c2_or_jvmci_compiler_enabled() && is_c2_compile(level)) {
 706     return false;
 707   }
 708 
 709   // Interpreter level is always valid.
 710   if (level == CompLevel_none) {
 711     return true;
 712   }
 713   if (CompilationModeFlag::normal()) {
 714     return true;
 715   } else if (CompilationModeFlag::quick_only()) {
 716     return level == CompLevel_simple;
 717   } else if (CompilationModeFlag::high_only()) {
 718     return level == CompLevel_full_optimization;
 719   } else if (CompilationModeFlag::high_only_quick_internal()) {
 720     return level == CompLevel_full_optimization || level == CompLevel_simple;
 721   }
 722   return false;
 723 }
 724 #endif
 725 
 726 
 727 CompLevel CompilationPolicy::highest_compile_level() {
 728   CompLevel level = CompLevel_none;
 729   // Setup the maximum level available for the current compiler configuration.
 730   if (!CompilerConfig::is_interpreter_only()) {
 731     if (CompilerConfig::is_c2_or_jvmci_compiler_enabled()) {
 732       level = CompLevel_full_optimization;
 733     } else if (CompilerConfig::is_c1_enabled()) {
 734       if (CompilerConfig::is_c1_simple_only()) {
 735         level = CompLevel_simple;
 736       } else {
 737         level = CompLevel_full_profile;
 738       }
 739     }
 740   }
 741   // Clamp the maximum level with TieredStopAtLevel.
 742   if (TieredCompilation) {
 743     level = MIN2(level, (CompLevel) TieredStopAtLevel);
 744   }
 745 
 746   // Fix it up if after the clamping it has become invalid.
 747   // Bring it monotonically down depending on the next available level for
 748   // the compilation mode.
 749   if (!CompilationModeFlag::normal()) {
 750     // a) quick_only - levels 2,3,4 are invalid; levels -1,0,1 are valid;
 751     // b) high_only - levels 1,2,3 are invalid; levels -1,0,4 are valid;
 752     // c) high_only_quick_internal - levels 2,3 are invalid; levels -1,0,1,4 are valid.
 753     if (CompilationModeFlag::quick_only()) {
 754       if (level == CompLevel_limited_profile || level == CompLevel_full_profile || level == CompLevel_full_optimization) {
 755         level = CompLevel_simple;
 756       }
 757     } else if (CompilationModeFlag::high_only()) {
 758       if (level == CompLevel_simple || level == CompLevel_limited_profile || level == CompLevel_full_profile) {
 759         level = CompLevel_none;
 760       }
 761     } else if (CompilationModeFlag::high_only_quick_internal()) {
 762       if (level == CompLevel_limited_profile || level == CompLevel_full_profile) {
 763         level = CompLevel_simple;
 764       }
 765     }
 766   }
 767 
 768   assert(verify_level(level), "Invalid highest compilation level: %d", level);
 769   return level;
 770 }
 771 
 772 CompLevel CompilationPolicy::limit_level(CompLevel level) {
 773   level = MIN2(level, highest_compile_level());
 774   assert(verify_level(level), "Invalid compilation level: %d", level);
 775   return level;
 776 }
 777 
 778 CompLevel CompilationPolicy::initial_compile_level(const methodHandle& method) {
 779   CompLevel level = CompLevel_any;
 780   if (CompilationModeFlag::normal()) {
 781     level = CompLevel_full_profile;
 782   } else if (CompilationModeFlag::quick_only()) {
 783     level = CompLevel_simple;
 784   } else if (CompilationModeFlag::high_only()) {
 785     level = CompLevel_full_optimization;
 786   } else if (CompilationModeFlag::high_only_quick_internal()) {
 787     if (force_comp_at_level_simple(method)) {
 788       level = CompLevel_simple;
 789     } else {
 790       level = CompLevel_full_optimization;
 791     }
 792   }
 793   assert(level != CompLevel_any, "Unhandled compilation mode");
 794   return limit_level(level);
 795 }
 796 
 797 // Set carry flags on the counters if necessary
 798 void CompilationPolicy::handle_counter_overflow(const methodHandle& method) {
 799   MethodCounters *mcs = method->method_counters();
 800   if (mcs != nullptr) {
 801     mcs->invocation_counter()->set_carry_on_overflow();
 802     mcs->backedge_counter()->set_carry_on_overflow();
 803   }
 804   MethodData* mdo = method->method_data();
 805   if (mdo != nullptr) {
 806     mdo->invocation_counter()->set_carry_on_overflow();
 807     mdo->backedge_counter()->set_carry_on_overflow();
 808   }
 809 }
 810 
 811 // Called with the queue locked and with at least one element
 812 CompileTask* CompilationPolicy::select_task(CompileQueue* compile_queue, JavaThread* THREAD) {
 813   CompileTask *max_blocking_task = nullptr;
 814   CompileTask *max_task = nullptr;
 815   Method* max_method = nullptr;
 816 
 817   int64_t t = nanos_to_millis(os::javaTimeNanos());
 818   // Iterate through the queue and find a method with a maximum rate.
 819   for (CompileTask* task = compile_queue->first(); task != nullptr;) {
 820     CompileTask* next_task = task->next();
 821     // If a method was unloaded or has been stale for some time, remove it from the queue.
 822     // Blocking tasks and tasks submitted from whitebox API don't become stale
 823     if (task->is_unloaded()) {
 824       compile_queue->remove_and_mark_stale(task);
 825       task = next_task;
 826       continue;
 827     }
 828     if (task->is_scc()) {
 829       // SCC tasks are on separate queue, and they should load fast. There is no need to walk
 830       // the rest of the queue, just take the task and go.
 831       return task;
 832     }
 833     Method* method = task->method();
 834     methodHandle mh(THREAD, method);
 835     if (task->can_become_stale() && is_stale(t, TieredCompileTaskTimeout, mh) && !is_old(mh)) {
 836       if (PrintTieredEvents) {
 837         print_event(REMOVE_FROM_QUEUE, method, method, task->osr_bci(), (CompLevel) task->comp_level());
 838       }
 839       method->clear_queued_for_compilation();
 840       method->set_pending_queue_processed(false);
 841       compile_queue->remove_and_mark_stale(task);
 842       task = next_task;
 843       continue;
 844     }
 845     update_rate(t, mh);
 846     if (max_task == nullptr || compare_methods(method, max_method) || compare_tasks(task, max_task)) {
 847       // Select a method with the highest rate
 848       max_task = task;
 849       max_method = method;
 850     }
 851 
 852     if (task->is_blocking()) {
 853       if (max_blocking_task == nullptr || compare_methods(method, max_blocking_task->method())) {
 854         max_blocking_task = task;
 855       }
 856     }
 857 
 858     task = next_task;
 859   }
 860 
 861   if (max_blocking_task != nullptr) {
 862     // In blocking compilation mode, the CompileBroker will make
 863     // compilations submitted by a JVMCI compiler thread non-blocking. These
 864     // compilations should be scheduled after all blocking compilations
 865     // to service non-compiler related compilations sooner and reduce the
 866     // chance of such compilations timing out.
 867     max_task = max_blocking_task;
 868     max_method = max_task->method();
 869   }
 870 
 871   methodHandle max_method_h(THREAD, max_method);
 872 
 873   if (max_task != nullptr && max_task->comp_level() == CompLevel_full_profile && TieredStopAtLevel > CompLevel_full_profile &&
 874       max_method != nullptr && is_method_profiled(max_method_h) && !Arguments::is_compiler_only()) {
 875     max_task->set_comp_level(CompLevel_limited_profile);
 876 
 877     if (CompileBroker::compilation_is_complete(max_method_h(), max_task->osr_bci(), CompLevel_limited_profile,
 878                                                false /* requires_online_compilation */,
 879                                                CompileTask::Reason_None)) {
 880       if (PrintTieredEvents) {
 881         print_event(REMOVE_FROM_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());
 882       }
 883       compile_queue->remove_and_mark_stale(max_task);
 884       max_method->clear_queued_for_compilation();
 885       return nullptr;
 886     }
 887 
 888     if (PrintTieredEvents) {
 889       print_event(UPDATE_IN_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());
 890     }
 891   }
 892   return max_task;
 893 }
 894 
 895 void CompilationPolicy::reprofile(ScopeDesc* trap_scope, bool is_osr) {
 896   for (ScopeDesc* sd = trap_scope;; sd = sd->sender()) {
 897     if (PrintTieredEvents) {
 898       print_event(REPROFILE, sd->method(), sd->method(), InvocationEntryBci, CompLevel_none);
 899     }
 900     MethodData* mdo = sd->method()->method_data();
 901     if (mdo != nullptr) {
 902       mdo->reset_start_counters();
 903     }
 904     if (sd->is_top()) break;
 905   }
 906 }
 907 
 908 nmethod* CompilationPolicy::event(const methodHandle& method, const methodHandle& inlinee,
 909                                       int branch_bci, int bci, CompLevel comp_level, nmethod* nm, TRAPS) {
 910   if (PrintTieredEvents) {
 911     print_event(bci == InvocationEntryBci ? CALL : LOOP, method(), inlinee(), bci, comp_level);
 912   }
 913 
 914 #if INCLUDE_JVMCI
 915   if (EnableJVMCI && UseJVMCICompiler &&
 916       comp_level == CompLevel_full_optimization && !AOTLinkedClassBulkLoader::class_preloading_finished()) {
 917     return nullptr;
 918   }
 919 #endif
 920 
 921   if (comp_level == CompLevel_none &&
 922       JvmtiExport::can_post_interpreter_events() &&
 923       THREAD->is_interp_only_mode()) {
 924     return nullptr;
 925   }
 926   if (ReplayCompiles) {
 927     // Don't trigger other compiles in testing mode
 928     return nullptr;
 929   }
 930 
 931   handle_counter_overflow(method);
 932   if (method() != inlinee()) {
 933     handle_counter_overflow(inlinee);
 934   }
 935 
 936   if (bci == InvocationEntryBci) {
 937     method_invocation_event(method, inlinee, comp_level, nm, THREAD);
 938   } else {
 939     // method == inlinee if the event originated in the main method
 940     method_back_branch_event(method, inlinee, bci, comp_level, nm, THREAD);
 941     // Check if event led to a higher level OSR compilation
 942     CompLevel expected_comp_level = MIN2(CompLevel_full_optimization, static_cast<CompLevel>(comp_level + 1));
 943     if (!CompilationModeFlag::disable_intermediate() && inlinee->is_not_osr_compilable(expected_comp_level)) {
 944       // It's not possible to reach the expected level so fall back to simple.
 945       expected_comp_level = CompLevel_simple;
 946     }
 947     CompLevel max_osr_level = static_cast<CompLevel>(inlinee->highest_osr_comp_level());
 948     if (max_osr_level >= expected_comp_level) { // fast check to avoid locking in a typical scenario
 949       nmethod* osr_nm = inlinee->lookup_osr_nmethod_for(bci, expected_comp_level, false);
 950       assert(osr_nm == nullptr || osr_nm->comp_level() >= expected_comp_level, "lookup_osr_nmethod_for is broken");
 951       if (osr_nm != nullptr && osr_nm->comp_level() != comp_level) {
 952         // Perform OSR with new nmethod
 953         return osr_nm;
 954       }
 955     }
 956   }
 957   return nullptr;
 958 }
 959 
 960 // Check if the method can be compiled, change level if necessary
 961 void CompilationPolicy::compile(const methodHandle& mh, int bci, CompLevel level, TRAPS) {
 962   assert(verify_level(level), "Invalid compilation level requested: %d", level);
 963 
 964   if (level == CompLevel_none) {
 965     if (mh->has_compiled_code()) {
 966       // Happens when we switch to interpreter to profile.
 967       MutexLocker ml(Compile_lock);
 968       NoSafepointVerifier nsv;
 969       if (mh->has_compiled_code()) {
 970         mh->code()->make_not_used();
 971       }
 972       // Deoptimize immediately (we don't have to wait for a compile).
 973       JavaThread* jt = THREAD;
 974       RegisterMap map(jt,
 975                       RegisterMap::UpdateMap::skip,
 976                       RegisterMap::ProcessFrames::include,
 977                       RegisterMap::WalkContinuation::skip);
 978       frame fr = jt->last_frame().sender(&map);
 979       Deoptimization::deoptimize_frame(jt, fr.id());
 980     }
 981     return;
 982   }
 983 
 984   if (!CompilationModeFlag::disable_intermediate()) {
 985     // Check if the method can be compiled. If it cannot be compiled with C1, continue profiling
 986     // in the interpreter and then compile with C2 (the transition function will request that,
 987     // see common() ). If the method cannot be compiled with C2 but still can with C1, compile it with
 988     // pure C1.
 989     if ((bci == InvocationEntryBci && !can_be_compiled(mh, level))) {
 990       if (level == CompLevel_full_optimization && can_be_compiled(mh, CompLevel_simple)) {
 991         compile(mh, bci, CompLevel_simple, THREAD);
 992       }
 993       return;
 994     }
 995     if ((bci != InvocationEntryBci && !can_be_osr_compiled(mh, level))) {
 996       if (level == CompLevel_full_optimization && can_be_osr_compiled(mh, CompLevel_simple)) {
 997         nmethod* osr_nm = mh->lookup_osr_nmethod_for(bci, CompLevel_simple, false);
 998         if (osr_nm != nullptr && osr_nm->comp_level() > CompLevel_simple) {
 999           // Invalidate the existing OSR nmethod so that a compile at CompLevel_simple is permitted.
1000           osr_nm->make_not_entrant();
1001         }
1002         compile(mh, bci, CompLevel_simple, THREAD);
1003       }
1004       return;
1005     }
1006   }
1007   if (bci != InvocationEntryBci && mh->is_not_osr_compilable(level)) {
1008     return;
1009   }
1010   if (!CompileBroker::compilation_is_in_queue(mh)) {
1011     if (PrintTieredEvents) {
1012       print_event(COMPILE, mh(), mh(), bci, level);
1013     }
1014     int hot_count = (bci == InvocationEntryBci) ? mh->invocation_count() : mh->backedge_count();
1015     update_rate(nanos_to_millis(os::javaTimeNanos()), mh);
1016     bool requires_online_compilation = false;
1017     if (TrainingData::have_data()) {
1018       MethodTrainingData* mtd = MethodTrainingData::find_fast(mh);
1019       if (mtd != nullptr) {
1020         CompileTrainingData* ctd = mtd->last_toplevel_compile(level);
1021         if (ctd != nullptr) {
1022           requires_online_compilation = (ctd->init_deps_left() > 0);
1023         }
1024       }
1025     }
1026     CompileBroker::compile_method(mh, bci, level, mh, hot_count, requires_online_compilation, CompileTask::Reason_Tiered, THREAD);
1027   }
1028 }
1029 
1030 // update_rate() is called from select_task() while holding a compile queue lock.
1031 void CompilationPolicy::update_rate(int64_t t, const methodHandle& method) {
1032   // Skip update if counters are absent.
1033   // Can't allocate them since we are holding compile queue lock.
1034   if (method->method_counters() == nullptr)  return;
1035 
1036   if (is_old(method)) {
1037     // We don't remove old methods from the queue,
1038     // so we can just zero the rate.
1039     method->set_rate(0);
1040     return;
1041   }
1042 
1043   // We don't update the rate if we've just came out of a safepoint.
1044   // delta_s is the time since last safepoint in milliseconds.
1045   int64_t delta_s = t - SafepointTracing::end_of_last_safepoint_ms();
1046   int64_t delta_t = t - (method->prev_time() != 0 ? method->prev_time() : start_time()); // milliseconds since the last measurement
1047   // How many events were there since the last time?
1048   int event_count = method->invocation_count() + method->backedge_count();
1049   int delta_e = event_count - method->prev_event_count();
1050 
1051   // We should be running for at least 1ms.
1052   if (delta_s >= TieredRateUpdateMinTime) {
1053     // And we must've taken the previous point at least 1ms before.
1054     if (delta_t >= TieredRateUpdateMinTime && delta_e > 0) {
1055       method->set_prev_time(t);
1056       method->set_prev_event_count(event_count);
1057       method->set_rate((float)delta_e / (float)delta_t); // Rate is events per millisecond
1058     } else {
1059       if (delta_t > TieredRateUpdateMaxTime && delta_e == 0) {
1060         // If nothing happened for 25ms, zero the rate. Don't modify prev values.
1061         method->set_rate(0);
1062       }
1063     }
1064   }
1065 }
1066 
1067 // Check if this method has been stale for a given number of milliseconds.
1068 // See select_task().
1069 bool CompilationPolicy::is_stale(int64_t t, int64_t timeout, const methodHandle& method) {
1070   int64_t delta_s = t - SafepointTracing::end_of_last_safepoint_ms();
1071   int64_t delta_t = t - method->prev_time();
1072   if (delta_t > timeout && delta_s > timeout) {
1073     int event_count = method->invocation_count() + method->backedge_count();
1074     int delta_e = event_count - method->prev_event_count();
1075     // Return true if there were no events.
1076     return delta_e == 0;
1077   }
1078   return false;
1079 }
1080 
1081 // We don't remove old methods from the compile queue even if they have
1082 // very low activity. See select_task().
1083 bool CompilationPolicy::is_old(const methodHandle& method) {
1084   int i = method->invocation_count();
1085   int b = method->backedge_count();
1086   double k = TieredOldPercentage / 100.0;
1087 
1088   return CallPredicate::apply_scaled(method, CompLevel_none, i, b, k) || LoopPredicate::apply_scaled(method, CompLevel_none, i, b, k);
1089 }
1090 
1091 double CompilationPolicy::weight(Method* method) {
1092   return (double)(method->rate() + 1) * (method->invocation_count() + 1) * (method->backedge_count() + 1);
1093 }
1094 
1095 // Apply heuristics and return true if x should be compiled before y
1096 bool CompilationPolicy::compare_methods(Method* x, Method* y) {
1097   if (x->highest_comp_level() > y->highest_comp_level()) {
1098     // recompilation after deopt
1099     return true;
1100   } else
1101     if (x->highest_comp_level() == y->highest_comp_level()) {
1102       if (weight(x) > weight(y)) {
1103         return true;
1104       }
1105     }
1106   return false;
1107 }
1108 
1109 bool CompilationPolicy::compare_tasks(CompileTask* x, CompileTask* y) {
1110   assert(!x->is_scc() && !y->is_scc(), "SC tasks are not expected here");
1111   if (x->compile_reason() != y->compile_reason() && y->compile_reason() == CompileTask::Reason_MustBeCompiled) {
1112     return true;
1113   }
1114   return false;
1115 }
1116 
1117 // Is method profiled enough?
1118 bool CompilationPolicy::is_method_profiled(const methodHandle& method) {
1119   MethodData* mdo = method->method_data();
1120   if (mdo != nullptr) {
1121     int i = mdo->invocation_count_delta();
1122     int b = mdo->backedge_count_delta();
1123     return CallPredicate::apply_scaled(method, CompLevel_full_profile, i, b, 1);
1124   }
1125   return false;
1126 }
1127 
1128 
1129 // Determine is a method is mature.
1130 bool CompilationPolicy::is_mature(MethodData* mdo) {
1131   if (Arguments::is_compiler_only()) {
1132     // Always report profiles as immature with -Xcomp
1133     return false;
1134   }
1135   methodHandle mh(Thread::current(), mdo->method());
1136   if (mdo != nullptr) {
1137     int i = mdo->invocation_count();
1138     int b = mdo->backedge_count();
1139     double k = ProfileMaturityPercentage / 100.0;
1140     return CallPredicate::apply_scaled(mh, CompLevel_full_profile, i, b, k) || LoopPredicate::apply_scaled(mh, CompLevel_full_profile, i, b, k);
1141   }
1142   return false;
1143 }
1144 
1145 // If a method is old enough and is still in the interpreter we would want to
1146 // start profiling without waiting for the compiled method to arrive.
1147 // We also take the load on compilers into the account.
1148 bool CompilationPolicy::should_create_mdo(const methodHandle& method, CompLevel cur_level) {
1149   if (cur_level != CompLevel_none || force_comp_at_level_simple(method) || CompilationModeFlag::quick_only() || !ProfileInterpreter) {
1150     return false;
1151   }
1152 
1153   if (TrainingData::have_data()) {
1154     MethodTrainingData* mtd = MethodTrainingData::find_fast(method);
1155     if (mtd != nullptr && mtd->saw_level(CompLevel_full_optimization)) {
1156       return true;
1157     }
1158     return false;
1159   }
1160 
1161   if (is_old(method)) {
1162     return true;
1163   }
1164 
1165   int i = method->invocation_count();
1166   int b = method->backedge_count();
1167   double k = Tier0ProfilingStartPercentage / 100.0;
1168 
1169   // If the top level compiler is not keeping up, delay profiling.
1170   if (CompileBroker::queue_size(CompLevel_full_optimization) <= Tier0Delay * compiler_count(CompLevel_full_optimization)) {
1171     return CallPredicate::apply_scaled(method, CompLevel_none, i, b, k) || LoopPredicate::apply_scaled(method, CompLevel_none, i, b, k);
1172   }
1173   return false;
1174 }
1175 
1176 // Inlining control: if we're compiling a profiled method with C1 and the callee
1177 // is known to have OSRed in a C2 version, don't inline it.
1178 bool CompilationPolicy::should_not_inline(ciEnv* env, ciMethod* callee) {
1179   CompLevel comp_level = (CompLevel)env->comp_level();
1180   if (comp_level == CompLevel_full_profile ||
1181       comp_level == CompLevel_limited_profile) {
1182     return callee->highest_osr_comp_level() == CompLevel_full_optimization;
1183   }
1184   return false;
1185 }
1186 
1187 // Create MDO if necessary.
1188 void CompilationPolicy::create_mdo(const methodHandle& mh, JavaThread* THREAD) {
1189   if (mh->is_native() ||
1190       mh->is_abstract() ||
1191       mh->is_accessor() ||
1192       mh->is_constant_getter()) {
1193     return;
1194   }
1195   if (mh->method_data() == nullptr) {
1196     Method::build_profiling_method_data(mh, CHECK_AND_CLEAR);
1197   }
1198   if (ProfileInterpreter && THREAD->has_last_Java_frame()) {
1199     MethodData* mdo = mh->method_data();
1200     if (mdo != nullptr) {
1201       frame last_frame = THREAD->last_frame();
1202       if (last_frame.is_interpreted_frame() && mh == last_frame.interpreter_frame_method()) {
1203         int bci = last_frame.interpreter_frame_bci();
1204         address dp = mdo->bci_to_dp(bci);
1205         last_frame.interpreter_frame_set_mdp(dp);
1206       }
1207     }
1208   }
1209 }
1210 
1211 CompLevel CompilationPolicy::trained_transition_from_none(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD) {
1212   precond(mtd != nullptr);
1213   precond(cur_level == CompLevel_none);
1214 
1215   if (mtd->only_inlined() && !mtd->saw_level(CompLevel_full_optimization)) {
1216     return CompLevel_none;
1217   }
1218 
1219   bool training_has_profile = (mtd->final_profile() != nullptr);
1220   if (mtd->saw_level(CompLevel_full_optimization) && !training_has_profile) {
1221     return CompLevel_full_profile;
1222   }
1223 
1224   CompLevel highest_training_level = static_cast<CompLevel>(mtd->highest_top_level());
1225   switch (highest_training_level) {
1226     case CompLevel_limited_profile:
1227     case CompLevel_full_profile:
1228       return CompLevel_limited_profile;
1229     case CompLevel_simple:
1230       return CompLevel_simple;
1231     case CompLevel_none:
1232       return CompLevel_none;
1233     default:
1234       break;
1235   }
1236 
1237   // Now handle the case of level 4.
1238   assert(highest_training_level == CompLevel_full_optimization, "Unexpected compilation level: %d", highest_training_level);
1239   if (!training_has_profile) {
1240     // The method was a part of a level 4 compile, but don't have a stored profile,
1241     // we need to profile it.
1242     return CompLevel_full_profile;
1243   }
1244   const bool deopt = (static_cast<CompLevel>(method->highest_comp_level()) == CompLevel_full_optimization);
1245   // If we deopted, then we reprofile
1246   if (deopt && !is_method_profiled(method)) {
1247     return CompLevel_full_profile;
1248   }
1249 
1250   CompileTrainingData* ctd = mtd->last_toplevel_compile(CompLevel_full_optimization);
1251   assert(ctd != nullptr, "Should have CTD for CompLevel_full_optimization");
1252   // With SkipTier2IfPossible and all deps satisfied, go to level 4 immediately
1253   if (SkipTier2IfPossible && ctd->init_deps_left() == 0) {
1254     if (method->method_data() == nullptr) {
1255       create_mdo(method, THREAD);
1256     }
1257     return CompLevel_full_optimization;
1258   }
1259 
1260   // Otherwise go to level 2
1261   return CompLevel_limited_profile;
1262 }
1263 
1264 
1265 CompLevel CompilationPolicy::trained_transition_from_limited_profile(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD) {
1266   precond(mtd != nullptr);
1267   precond(cur_level == CompLevel_limited_profile);
1268 
1269   // One of the main reasons that we can get here is that we're waiting for the stored C2 code to become ready.
1270 
1271   // But first, check if we have a saved profile
1272   bool training_has_profile = (mtd->final_profile() != nullptr);
1273   if (!training_has_profile) {
1274     return CompLevel_full_profile;
1275   }
1276 
1277 
1278   assert(training_has_profile, "Have to have a profile to be here");
1279   // Check if the method is ready
1280   CompileTrainingData* ctd = mtd->last_toplevel_compile(CompLevel_full_optimization);
1281   if (ctd != nullptr && ctd->init_deps_left() == 0) {
1282     if (method->method_data() == nullptr) {
1283       create_mdo(method, THREAD);
1284     }
1285     return CompLevel_full_optimization;
1286   }
1287 
1288   // Otherwise stay at the current level
1289   return CompLevel_limited_profile;
1290 }
1291 
1292 
1293 CompLevel CompilationPolicy::trained_transition_from_full_profile(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD) {
1294   precond(mtd != nullptr);
1295   precond(cur_level == CompLevel_full_profile);
1296 
1297   CompLevel highest_training_level = static_cast<CompLevel>(mtd->highest_top_level());
1298   // We have method at the full profile level and we also know that it's possibly an important method.
1299   if (highest_training_level == CompLevel_full_optimization && !mtd->only_inlined()) {
1300     // Check if it is adequately profiled
1301     if (is_method_profiled(method)) {
1302       return CompLevel_full_optimization;
1303     }
1304   }
1305 
1306   // Otherwise stay at the current level
1307   return CompLevel_full_profile;
1308 }
1309 
1310 CompLevel CompilationPolicy::trained_transition(const methodHandle& method, CompLevel cur_level, MethodTrainingData* mtd, JavaThread* THREAD) {
1311   precond(MethodTrainingData::have_data());
1312 
1313   // If there is no training data recorded for this method, bail out.
1314   if (mtd == nullptr) {
1315     return cur_level;
1316   }
1317 
1318   CompLevel next_level = cur_level;
1319   switch(cur_level) {
1320     default: break;
1321     case CompLevel_none:
1322       next_level = trained_transition_from_none(method, cur_level, mtd, THREAD);
1323       break;
1324     case CompLevel_limited_profile:
1325       next_level = trained_transition_from_limited_profile(method, cur_level, mtd, THREAD);
1326       break;
1327     case CompLevel_full_profile:
1328       next_level = trained_transition_from_full_profile(method, cur_level, mtd, THREAD);
1329       break;
1330   }
1331 
1332   // We don't have any special strategies for the C2-only compilation modes, so just fix up the levels for now.
1333   if (CompilationModeFlag::high_only_quick_internal() && CompLevel_simple < next_level && next_level < CompLevel_full_optimization) {
1334     return CompLevel_none;
1335   }
1336   if (CompilationModeFlag::high_only() && next_level < CompLevel_full_optimization) {
1337     return CompLevel_none;
1338   }
1339   return (cur_level != next_level) ? limit_level(next_level) : cur_level;
1340 }
1341 
1342 /*
1343  * Method states:
1344  *   0 - interpreter (CompLevel_none)
1345  *   1 - pure C1 (CompLevel_simple)
1346  *   2 - C1 with invocation and backedge counting (CompLevel_limited_profile)
1347  *   3 - C1 with full profiling (CompLevel_full_profile)
1348  *   4 - C2 or Graal (CompLevel_full_optimization)
1349  *
1350  * Common state transition patterns:
1351  * a. 0 -> 3 -> 4.
1352  *    The most common path. But note that even in this straightforward case
1353  *    profiling can start at level 0 and finish at level 3.
1354  *
1355  * b. 0 -> 2 -> 3 -> 4.
1356  *    This case occurs when the load on C2 is deemed too high. So, instead of transitioning
1357  *    into state 3 directly and over-profiling while a method is in the C2 queue we transition to
1358  *    level 2 and wait until the load on C2 decreases. This path is disabled for OSRs.
1359  *
1360  * c. 0 -> (3->2) -> 4.
1361  *    In this case we enqueue a method for compilation at level 3, but the C1 queue is long enough
1362  *    to enable the profiling to fully occur at level 0. In this case we change the compilation level
1363  *    of the method to 2 while the request is still in-queue, because it'll allow it to run much faster
1364  *    without full profiling while c2 is compiling.
1365  *
1366  * d. 0 -> 3 -> 1 or 0 -> 2 -> 1.
1367  *    After a method was once compiled with C1 it can be identified as trivial and be compiled to
1368  *    level 1. These transition can also occur if a method can't be compiled with C2 but can with C1.
1369  *
1370  * e. 0 -> 4.
1371  *    This can happen if a method fails C1 compilation (it will still be profiled in the interpreter)
1372  *    or because of a deopt that didn't require reprofiling (compilation won't happen in this case because
1373  *    the compiled version already exists).
1374  *
1375  * Note that since state 0 can be reached from any other state via deoptimization different loops
1376  * are possible.
1377  *
1378  */
1379 
1380 // Common transition function. Given a predicate determines if a method should transition to another level.
1381 template<typename Predicate>
1382 CompLevel CompilationPolicy::common(const methodHandle& method, CompLevel cur_level, JavaThread* THREAD, bool disable_feedback) {
1383   CompLevel next_level = cur_level;
1384   int i = method->invocation_count();
1385   int b = method->backedge_count();
1386 
1387   if (force_comp_at_level_simple(method)) {
1388     next_level = CompLevel_simple;
1389   } else {
1390     if (MethodTrainingData::have_data()) {
1391       MethodTrainingData* mtd = MethodTrainingData::find_fast(method);
1392       if (mtd == nullptr) {
1393         // We haven't see compilations of this method in training. It's either very cold or the behavior changed.
1394         // Feed it to the standard TF with no profiling delay.
1395         next_level = standard_transition<Predicate>(method, cur_level, false /*delay_profiling*/, disable_feedback);
1396       } else {
1397         next_level = trained_transition(method, cur_level, mtd, THREAD);
1398         if (cur_level == next_level) {
1399           // trained_transtion() is going to return the same level if no startup/warmup optimizations apply.
1400           // In order to catch possible pathologies due to behavior change we feed the event to the regular
1401           // TF but with profiling delay.
1402           next_level = standard_transition<Predicate>(method, cur_level, true /*delay_profiling*/, disable_feedback);
1403         }
1404       }
1405     } else if (is_trivial(method) || method->is_native()) {
1406       next_level = CompilationModeFlag::disable_intermediate() ? CompLevel_full_optimization : CompLevel_simple;
1407     } else {
1408       next_level = standard_transition<Predicate>(method, cur_level, false /*delay_profiling*/, disable_feedback);
1409     }
1410   }
1411   return (next_level != cur_level) ? limit_level(next_level) : next_level;
1412 }
1413 
1414 
1415 template<typename Predicate>
1416 CompLevel CompilationPolicy::standard_transition(const methodHandle& method, CompLevel cur_level, bool delay_profiling, bool disable_feedback) {
1417   CompLevel next_level = cur_level;
1418   switch(cur_level) {
1419   default: break;
1420   case CompLevel_none:
1421     next_level = transition_from_none<Predicate>(method, cur_level, delay_profiling, disable_feedback);
1422     break;
1423   case CompLevel_limited_profile:
1424     next_level = transition_from_limited_profile<Predicate>(method, cur_level, delay_profiling, disable_feedback);
1425     break;
1426   case CompLevel_full_profile:
1427     next_level = transition_from_full_profile<Predicate>(method, cur_level);
1428     break;
1429   }
1430   return next_level;
1431 }
1432 
1433 template<typename Predicate>
1434 CompLevel CompilationPolicy::transition_from_none(const methodHandle& method, CompLevel cur_level, bool delay_profiling, bool disable_feedback) {
1435   precond(cur_level == CompLevel_none);
1436   CompLevel next_level = cur_level;
1437   int i = method->invocation_count();
1438   int b = method->backedge_count();
1439   double scale = delay_profiling ? Tier0ProfileDelayFactor : 1.0;
1440   // If we were at full profile level, would we switch to full opt?
1441   if (transition_from_full_profile<Predicate>(method, CompLevel_full_profile) == CompLevel_full_optimization) {
1442     next_level = CompLevel_full_optimization;
1443   } else if (!CompilationModeFlag::disable_intermediate() && Predicate::apply_scaled(method, cur_level, i, b, scale)) {
1444     // C1-generated fully profiled code is about 30% slower than the limited profile
1445     // code that has only invocation and backedge counters. The observation is that
1446     // if C2 queue is large enough we can spend too much time in the fully profiled code
1447     // while waiting for C2 to pick the method from the queue. To alleviate this problem
1448     // we introduce a feedback on the C2 queue size. If the C2 queue is sufficiently long
1449     // we choose to compile a limited profiled version and then recompile with full profiling
1450     // when the load on C2 goes down.
1451     if (delay_profiling || (!disable_feedback && CompileBroker::queue_size(CompLevel_full_optimization) > Tier3DelayOn * compiler_count(CompLevel_full_optimization))) {
1452       next_level = CompLevel_limited_profile;
1453     } else {
1454       next_level = CompLevel_full_profile;
1455     }
1456   }
1457   return next_level;
1458 }
1459 
1460 template<typename Predicate>
1461 CompLevel CompilationPolicy::transition_from_full_profile(const methodHandle& method, CompLevel cur_level) {
1462   precond(cur_level == CompLevel_full_profile);
1463   CompLevel next_level = cur_level;
1464   MethodData* mdo = method->method_data();
1465   if (mdo != nullptr) {
1466     if (mdo->would_profile() || CompilationModeFlag::disable_intermediate()) {
1467       int mdo_i = mdo->invocation_count_delta();
1468       int mdo_b = mdo->backedge_count_delta();
1469       if (Predicate::apply(method, cur_level, mdo_i, mdo_b)) {
1470         next_level = CompLevel_full_optimization;
1471       }
1472     } else {
1473       next_level = CompLevel_full_optimization;
1474     }
1475   }
1476   return next_level;
1477 }
1478 
1479 template<typename Predicate>
1480 CompLevel CompilationPolicy::transition_from_limited_profile(const methodHandle& method, CompLevel cur_level, bool delay_profiling, bool disable_feedback) {
1481   precond(cur_level == CompLevel_limited_profile);
1482   CompLevel next_level = cur_level;
1483   int i = method->invocation_count();
1484   int b = method->backedge_count();
1485   double scale = delay_profiling ? Tier2ProfileDelayFactor : 1.0;
1486   MethodData* mdo = method->method_data();
1487   if (mdo != nullptr) {
1488     if (mdo->would_profile()) {
1489       if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
1490                               Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
1491                               Predicate::apply_scaled(method, cur_level, i, b, scale))) {
1492         next_level = CompLevel_full_profile;
1493       }
1494     } else {
1495       next_level = CompLevel_full_optimization;
1496     }
1497   } else {
1498     // If there is no MDO we need to profile
1499     if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
1500                             Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
1501                             Predicate::apply_scaled(method, cur_level, i, b, scale))) {
1502       next_level = CompLevel_full_profile;
1503     }
1504   }
1505   if (next_level == CompLevel_full_profile && is_method_profiled(method)) {
1506     next_level = CompLevel_full_optimization;
1507   }
1508   return next_level;
1509 }
1510 
1511 
1512 // Determine if a method should be compiled with a normal entry point at a different level.
1513 CompLevel CompilationPolicy::call_event(const methodHandle& method, CompLevel cur_level, JavaThread* THREAD) {
1514   CompLevel osr_level = MIN2((CompLevel) method->highest_osr_comp_level(), common<LoopPredicate>(method, cur_level, THREAD, true));
1515   CompLevel next_level = common<CallPredicate>(method, cur_level, THREAD, !TrainingData::have_data() && is_old(method));
1516 
1517   // If OSR method level is greater than the regular method level, the levels should be
1518   // equalized by raising the regular method level in order to avoid OSRs during each
1519   // invocation of the method.
1520   if (osr_level == CompLevel_full_optimization && cur_level == CompLevel_full_profile) {
1521     MethodData* mdo = method->method_data();
1522     guarantee(mdo != nullptr, "MDO should not be nullptr");
1523     if (mdo->invocation_count() >= 1) {
1524       next_level = CompLevel_full_optimization;
1525     }
1526   } else {
1527     next_level = MAX2(osr_level, next_level);
1528   }
1529 #if INCLUDE_JVMCI
1530   if (EnableJVMCI && UseJVMCICompiler &&
1531       next_level == CompLevel_full_optimization && !AOTLinkedClassBulkLoader::class_preloading_finished()) {
1532     next_level = cur_level;
1533   }
1534 #endif
1535   return next_level;
1536 }
1537 
1538 // Determine if we should do an OSR compilation of a given method.
1539 CompLevel CompilationPolicy::loop_event(const methodHandle& method, CompLevel cur_level, JavaThread* THREAD) {
1540   CompLevel next_level = common<LoopPredicate>(method, cur_level, THREAD, true);
1541   if (cur_level == CompLevel_none) {
1542     // If there is a live OSR method that means that we deopted to the interpreter
1543     // for the transition.
1544     CompLevel osr_level = MIN2((CompLevel)method->highest_osr_comp_level(), next_level);
1545     if (osr_level > CompLevel_none) {
1546       return osr_level;
1547     }
1548   }
1549   return next_level;
1550 }
1551 
1552 // Handle the invocation event.
1553 void CompilationPolicy::method_invocation_event(const methodHandle& mh, const methodHandle& imh,
1554                                                       CompLevel level, nmethod* nm, TRAPS) {
1555   if (should_create_mdo(mh, level)) {
1556     create_mdo(mh, THREAD);
1557   }
1558   CompLevel next_level = call_event(mh, level, THREAD);
1559   if (next_level != level) {
1560     if (is_compilation_enabled() && !CompileBroker::compilation_is_in_queue(mh)) {
1561       compile(mh, InvocationEntryBci, next_level, THREAD);
1562     }
1563   }
1564 }
1565 
1566 // Handle the back branch event. Notice that we can compile the method
1567 // with a regular entry from here.
1568 void CompilationPolicy::method_back_branch_event(const methodHandle& mh, const methodHandle& imh,
1569                                                      int bci, CompLevel level, nmethod* nm, TRAPS) {
1570   if (should_create_mdo(mh, level)) {
1571     create_mdo(mh, THREAD);
1572   }
1573   // Check if MDO should be created for the inlined method
1574   if (should_create_mdo(imh, level)) {
1575     create_mdo(imh, THREAD);
1576   }
1577 
1578   if (is_compilation_enabled()) {
1579     CompLevel next_osr_level = loop_event(imh, level, THREAD);
1580     CompLevel max_osr_level = (CompLevel)imh->highest_osr_comp_level();
1581     // At the very least compile the OSR version
1582     if (!CompileBroker::compilation_is_in_queue(imh) && (next_osr_level != level)) {
1583       compile(imh, bci, next_osr_level, CHECK);
1584     }
1585 
1586     // Use loop event as an opportunity to also check if there's been
1587     // enough calls.
1588     CompLevel cur_level, next_level;
1589     if (mh() != imh()) { // If there is an enclosing method
1590       {
1591         guarantee(nm != nullptr, "Should have nmethod here");
1592         cur_level = comp_level(mh());
1593         next_level = call_event(mh, cur_level, THREAD);
1594 
1595         if (max_osr_level == CompLevel_full_optimization) {
1596           // The inlinee OSRed to full opt, we need to modify the enclosing method to avoid deopts
1597           bool make_not_entrant = false;
1598           if (nm->is_osr_method()) {
1599             // This is an osr method, just make it not entrant and recompile later if needed
1600             make_not_entrant = true;
1601           } else {
1602             if (next_level != CompLevel_full_optimization) {
1603               // next_level is not full opt, so we need to recompile the
1604               // enclosing method without the inlinee
1605               cur_level = CompLevel_none;
1606               make_not_entrant = true;
1607             }
1608           }
1609           if (make_not_entrant) {
1610             if (PrintTieredEvents) {
1611               int osr_bci = nm->is_osr_method() ? nm->osr_entry_bci() : InvocationEntryBci;
1612               print_event(MAKE_NOT_ENTRANT, mh(), mh(), osr_bci, level);
1613             }
1614             nm->make_not_entrant();
1615           }
1616         }
1617         // Fix up next_level if necessary to avoid deopts
1618         if (next_level == CompLevel_limited_profile && max_osr_level == CompLevel_full_profile) {
1619           next_level = CompLevel_full_profile;
1620         }
1621         if (cur_level != next_level) {
1622           if (!CompileBroker::compilation_is_in_queue(mh)) {
1623             compile(mh, InvocationEntryBci, next_level, THREAD);
1624           }
1625         }
1626       }
1627     } else {
1628       cur_level = comp_level(mh());
1629       next_level = call_event(mh, cur_level, THREAD);
1630       if (next_level != cur_level) {
1631         if (!CompileBroker::compilation_is_in_queue(mh)) {
1632           compile(mh, InvocationEntryBci, next_level, THREAD);
1633         }
1634       }
1635     }
1636   }
1637 }
1638