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