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