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