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