Path: blob/master/src/hotspot/share/compiler/compilationPolicy.cpp
40930 views
/*1* Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "code/scopeDesc.hpp"26#include "compiler/compilationPolicy.hpp"27#include "compiler/compileBroker.hpp"28#include "compiler/compilerOracle.hpp"29#include "memory/resourceArea.hpp"30#include "oops/methodData.hpp"31#include "oops/method.inline.hpp"32#include "oops/oop.inline.hpp"33#include "prims/jvmtiExport.hpp"34#include "runtime/arguments.hpp"35#include "runtime/deoptimization.hpp"36#include "runtime/frame.hpp"37#include "runtime/frame.inline.hpp"38#include "runtime/globals_extension.hpp"39#include "runtime/handles.inline.hpp"40#include "runtime/safepoint.hpp"41#include "runtime/safepointVerifiers.hpp"4243#if INCLUDE_JVMCI44#include "jvmci/jvmci.hpp"45#endif4647#ifdef COMPILER148#include "c1/c1_Compiler.hpp"49#endif5051#ifdef COMPILER252#include "opto/c2compiler.hpp"53#endif5455jlong CompilationPolicy::_start_time = 0;56int CompilationPolicy::_c1_count = 0;57int CompilationPolicy::_c2_count = 0;58double CompilationPolicy::_increase_threshold_at_ratio = 0;5960void compilationPolicy_init() {61CompilationPolicy::initialize();62}6364int CompilationPolicy::compiler_count(CompLevel comp_level) {65if (is_c1_compile(comp_level)) {66return c1_count();67} else if (is_c2_compile(comp_level)) {68return c2_count();69}70return 0;71}7273// Returns true if m must be compiled before executing it74// This is intended to force compiles for methods (usually for75// debugging) that would otherwise be interpreted for some reason.76bool CompilationPolicy::must_be_compiled(const methodHandle& m, int comp_level) {77// Don't allow Xcomp to cause compiles in replay mode78if (ReplayCompiles) return false;7980if (m->has_compiled_code()) return false; // already compiled81if (!can_be_compiled(m, comp_level)) return false;8283return !UseInterpreter || // must compile all methods84(UseCompiler && AlwaysCompileLoopMethods && m->has_loops() && CompileBroker::should_compile_new_jobs()); // eagerly compile loop methods85}8687void CompilationPolicy::compile_if_required(const methodHandle& m, TRAPS) {88if (must_be_compiled(m)) {89// This path is unusual, mostly used by the '-Xcomp' stress test mode.9091if (!THREAD->can_call_java() || THREAD->is_Compiler_thread()) {92// don't force compilation, resolve was on behalf of compiler93return;94}95if (m->method_holder()->is_not_initialized()) {96// 'is_not_initialized' means not only '!is_initialized', but also that97// initialization has not been started yet ('!being_initialized')98// Do not force compilation of methods in uninitialized classes.99// Note that doing this would throw an assert later,100// in CompileBroker::compile_method.101// We sometimes use the link resolver to do reflective lookups102// even before classes are initialized.103return;104}105CompLevel level = initial_compile_level(m);106if (PrintTieredEvents) {107print_event(COMPILE, m(), m(), InvocationEntryBci, level);108}109CompileBroker::compile_method(m, InvocationEntryBci, level, methodHandle(), 0, CompileTask::Reason_MustBeCompiled, THREAD);110}111}112113static inline CompLevel adjust_level_for_compilability_query(CompLevel comp_level) {114if (comp_level == CompLevel_any) {115if (CompilerConfig::is_c1_only()) {116comp_level = CompLevel_simple;117} else if (CompilerConfig::is_c2_or_jvmci_compiler_only()) {118comp_level = CompLevel_full_optimization;119}120}121return comp_level;122}123124// Returns true if m is allowed to be compiled125bool CompilationPolicy::can_be_compiled(const methodHandle& m, int comp_level) {126// allow any levels for WhiteBox127assert(WhiteBoxAPI || comp_level == CompLevel_any || is_compile(comp_level), "illegal compilation level");128129if (m->is_abstract()) return false;130if (DontCompileHugeMethods && m->code_size() > HugeMethodLimit) return false;131132// Math intrinsics should never be compiled as this can lead to133// monotonicity problems because the interpreter will prefer the134// compiled code to the intrinsic version. This can't happen in135// production because the invocation counter can't be incremented136// but we shouldn't expose the system to this problem in testing137// modes.138if (!AbstractInterpreter::can_be_compiled(m)) {139return false;140}141comp_level = adjust_level_for_compilability_query((CompLevel) comp_level);142if (comp_level == CompLevel_any || is_compile(comp_level)) {143return !m->is_not_compilable(comp_level);144}145return false;146}147148// Returns true if m is allowed to be osr compiled149bool CompilationPolicy::can_be_osr_compiled(const methodHandle& m, int comp_level) {150bool result = false;151comp_level = adjust_level_for_compilability_query((CompLevel) comp_level);152if (comp_level == CompLevel_any || is_compile(comp_level)) {153result = !m->is_not_osr_compilable(comp_level);154}155return (result && can_be_compiled(m, comp_level));156}157158bool CompilationPolicy::is_compilation_enabled() {159// NOTE: CompileBroker::should_compile_new_jobs() checks for UseCompiler160return CompileBroker::should_compile_new_jobs();161}162163CompileTask* CompilationPolicy::select_task_helper(CompileQueue* compile_queue) {164// Remove unloaded methods from the queue165for (CompileTask* task = compile_queue->first(); task != NULL; ) {166CompileTask* next = task->next();167if (task->is_unloaded()) {168compile_queue->remove_and_mark_stale(task);169}170task = next;171}172#if INCLUDE_JVMCI173if (UseJVMCICompiler && !BackgroundCompilation) {174/*175* In blocking compilation mode, the CompileBroker will make176* compilations submitted by a JVMCI compiler thread non-blocking. These177* compilations should be scheduled after all blocking compilations178* to service non-compiler related compilations sooner and reduce the179* chance of such compilations timing out.180*/181for (CompileTask* task = compile_queue->first(); task != NULL; task = task->next()) {182if (task->is_blocking()) {183return task;184}185}186}187#endif188return compile_queue->first();189}190191// Simple methods are as good being compiled with C1 as C2.192// Determine if a given method is such a case.193bool CompilationPolicy::is_trivial(Method* method) {194if (method->is_accessor() ||195method->is_constant_getter()) {196return true;197}198return false;199}200201bool CompilationPolicy::force_comp_at_level_simple(const methodHandle& method) {202if (CompilationModeFlag::quick_internal()) {203#if INCLUDE_JVMCI204if (UseJVMCICompiler) {205AbstractCompiler* comp = CompileBroker::compiler(CompLevel_full_optimization);206if (comp != NULL && comp->is_jvmci() && ((JVMCICompiler*) comp)->force_comp_at_level_simple(method)) {207return true;208}209}210#endif211}212return false;213}214215CompLevel CompilationPolicy::comp_level(Method* method) {216CompiledMethod *nm = method->code();217if (nm != NULL && nm->is_in_use()) {218return (CompLevel)nm->comp_level();219}220return CompLevel_none;221}222223// Call and loop predicates determine whether a transition to a higher224// compilation level should be performed (pointers to predicate functions225// are passed to common()).226// Tier?LoadFeedback is basically a coefficient that determines of227// how many methods per compiler thread can be in the queue before228// the threshold values double.229class LoopPredicate : AllStatic {230public:231static bool apply_scaled(const methodHandle& method, CompLevel cur_level, int i, int b, double scale) {232double threshold_scaling;233if (CompilerOracle::has_option_value(method, CompileCommand::CompileThresholdScaling, threshold_scaling)) {234scale *= threshold_scaling;235}236switch(cur_level) {237case CompLevel_none:238case CompLevel_limited_profile:239return b >= Tier3BackEdgeThreshold * scale;240case CompLevel_full_profile:241return b >= Tier4BackEdgeThreshold * scale;242default:243return true;244}245}246247static bool apply(int i, int b, CompLevel cur_level, const methodHandle& method) {248double k = 1;249switch(cur_level) {250case CompLevel_none:251// Fall through252case CompLevel_limited_profile: {253k = CompilationPolicy::threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);254break;255}256case CompLevel_full_profile: {257k = CompilationPolicy::threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);258break;259}260default:261return true;262}263return apply_scaled(method, cur_level, i, b, k);264}265};266267class CallPredicate : AllStatic {268public:269static bool apply_scaled(const methodHandle& method, CompLevel cur_level, int i, int b, double scale) {270double threshold_scaling;271if (CompilerOracle::has_option_value(method, CompileCommand::CompileThresholdScaling, threshold_scaling)) {272scale *= threshold_scaling;273}274switch(cur_level) {275case CompLevel_none:276case CompLevel_limited_profile:277return (i >= Tier3InvocationThreshold * scale) ||278(i >= Tier3MinInvocationThreshold * scale && i + b >= Tier3CompileThreshold * scale);279case CompLevel_full_profile:280return (i >= Tier4InvocationThreshold * scale) ||281(i >= Tier4MinInvocationThreshold * scale && i + b >= Tier4CompileThreshold * scale);282default:283return true;284}285}286287static bool apply(int i, int b, CompLevel cur_level, const methodHandle& method) {288double k = 1;289switch(cur_level) {290case CompLevel_none:291case CompLevel_limited_profile: {292k = CompilationPolicy::threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);293break;294}295case CompLevel_full_profile: {296k = CompilationPolicy::threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);297break;298}299default:300return true;301}302return apply_scaled(method, cur_level, i, b, k);303}304};305306double CompilationPolicy::threshold_scale(CompLevel level, int feedback_k) {307int comp_count = compiler_count(level);308if (comp_count > 0) {309double queue_size = CompileBroker::queue_size(level);310double k = queue_size / (feedback_k * comp_count) + 1;311312// Increase C1 compile threshold when the code cache is filled more313// than specified by IncreaseFirstTierCompileThresholdAt percentage.314// The main intention is to keep enough free space for C2 compiled code315// to achieve peak performance if the code cache is under stress.316if (CompilerConfig::is_tiered() && !CompilationModeFlag::disable_intermediate() && is_c1_compile(level)) {317double current_reverse_free_ratio = CodeCache::reverse_free_ratio(CodeCache::get_code_blob_type(level));318if (current_reverse_free_ratio > _increase_threshold_at_ratio) {319k *= exp(current_reverse_free_ratio - _increase_threshold_at_ratio);320}321}322return k;323}324return 1;325}326327void CompilationPolicy::print_counters(const char* prefix, const Method* m) {328int invocation_count = m->invocation_count();329int backedge_count = m->backedge_count();330MethodData* mdh = m->method_data();331int mdo_invocations = 0, mdo_backedges = 0;332int mdo_invocations_start = 0, mdo_backedges_start = 0;333if (mdh != NULL) {334mdo_invocations = mdh->invocation_count();335mdo_backedges = mdh->backedge_count();336mdo_invocations_start = mdh->invocation_count_start();337mdo_backedges_start = mdh->backedge_count_start();338}339tty->print(" %stotal=%d,%d %smdo=%d(%d),%d(%d)", prefix,340invocation_count, backedge_count, prefix,341mdo_invocations, mdo_invocations_start,342mdo_backedges, mdo_backedges_start);343tty->print(" %smax levels=%d,%d", prefix,344m->highest_comp_level(), m->highest_osr_comp_level());345}346347// Print an event.348void CompilationPolicy::print_event(EventType type, const Method* m, const Method* im, int bci, CompLevel level) {349bool inlinee_event = m != im;350351ttyLocker tty_lock;352tty->print("%lf: [", os::elapsedTime());353354switch(type) {355case CALL:356tty->print("call");357break;358case LOOP:359tty->print("loop");360break;361case COMPILE:362tty->print("compile");363break;364case REMOVE_FROM_QUEUE:365tty->print("remove-from-queue");366break;367case UPDATE_IN_QUEUE:368tty->print("update-in-queue");369break;370case REPROFILE:371tty->print("reprofile");372break;373case MAKE_NOT_ENTRANT:374tty->print("make-not-entrant");375break;376default:377tty->print("unknown");378}379380tty->print(" level=%d ", level);381382ResourceMark rm;383char *method_name = m->name_and_sig_as_C_string();384tty->print("[%s", method_name);385if (inlinee_event) {386char *inlinee_name = im->name_and_sig_as_C_string();387tty->print(" [%s]] ", inlinee_name);388}389else tty->print("] ");390tty->print("@%d queues=%d,%d", bci, CompileBroker::queue_size(CompLevel_full_profile),391CompileBroker::queue_size(CompLevel_full_optimization));392393tty->print(" rate=");394if (m->prev_time() == 0) tty->print("n/a");395else tty->print("%f", m->rate());396397tty->print(" k=%.2lf,%.2lf", threshold_scale(CompLevel_full_profile, Tier3LoadFeedback),398threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback));399400if (type != COMPILE) {401print_counters("", m);402if (inlinee_event) {403print_counters("inlinee ", im);404}405tty->print(" compilable=");406bool need_comma = false;407if (!m->is_not_compilable(CompLevel_full_profile)) {408tty->print("c1");409need_comma = true;410}411if (!m->is_not_osr_compilable(CompLevel_full_profile)) {412if (need_comma) tty->print(",");413tty->print("c1-osr");414need_comma = true;415}416if (!m->is_not_compilable(CompLevel_full_optimization)) {417if (need_comma) tty->print(",");418tty->print("c2");419need_comma = true;420}421if (!m->is_not_osr_compilable(CompLevel_full_optimization)) {422if (need_comma) tty->print(",");423tty->print("c2-osr");424}425tty->print(" status=");426if (m->queued_for_compilation()) {427tty->print("in-queue");428} else tty->print("idle");429}430tty->print_cr("]");431}432433void CompilationPolicy::initialize() {434if (!CompilerConfig::is_interpreter_only()) {435int count = CICompilerCount;436bool c1_only = CompilerConfig::is_c1_only();437bool c2_only = CompilerConfig::is_c2_or_jvmci_compiler_only();438439#ifdef _LP64440// Turn on ergonomic compiler count selection441if (FLAG_IS_DEFAULT(CICompilerCountPerCPU) && FLAG_IS_DEFAULT(CICompilerCount)) {442FLAG_SET_DEFAULT(CICompilerCountPerCPU, true);443}444if (CICompilerCountPerCPU) {445// Simple log n seems to grow too slowly for tiered, try something faster: log n * log log n446int log_cpu = log2i(os::active_processor_count());447int loglog_cpu = log2i(MAX2(log_cpu, 1));448count = MAX2(log_cpu * loglog_cpu * 3 / 2, 2);449// Make sure there is enough space in the code cache to hold all the compiler buffers450size_t c1_size = 0;451#ifdef COMPILER1452c1_size = Compiler::code_buffer_size();453#endif454size_t c2_size = 0;455#ifdef COMPILER2456c2_size = C2Compiler::initial_code_buffer_size();457#endif458size_t buffer_size = c1_only ? c1_size : (c1_size/3 + 2*c2_size/3);459int max_count = (ReservedCodeCacheSize - (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3))) / (int)buffer_size;460if (count > max_count) {461// Lower the compiler count such that all buffers fit into the code cache462count = MAX2(max_count, c1_only ? 1 : 2);463}464FLAG_SET_ERGO(CICompilerCount, count);465}466#else467// On 32-bit systems, the number of compiler threads is limited to 3.468// On these systems, the virtual address space available to the JVM469// is usually limited to 2-4 GB (the exact value depends on the platform).470// As the compilers (especially C2) can consume a large amount of471// memory, scaling the number of compiler threads with the number of472// available cores can result in the exhaustion of the address space473/// available to the VM and thus cause the VM to crash.474if (FLAG_IS_DEFAULT(CICompilerCount)) {475count = 3;476FLAG_SET_ERGO(CICompilerCount, count);477}478#endif479480if (c1_only) {481// No C2 compiler thread required482set_c1_count(count);483} else if (c2_only) {484set_c2_count(count);485} else {486set_c1_count(MAX2(count / 3, 1));487set_c2_count(MAX2(count - c1_count(), 1));488}489assert(count == c1_count() + c2_count(), "inconsistent compiler thread count");490set_increase_threshold_at_ratio();491}492set_start_time(nanos_to_millis(os::javaTimeNanos()));493}494495496#ifdef ASSERT497bool CompilationPolicy::verify_level(CompLevel level) {498if (TieredCompilation && level > TieredStopAtLevel) {499return false;500}501// Check if there is a compiler to process the requested level502if (!CompilerConfig::is_c1_enabled() && is_c1_compile(level)) {503return false;504}505if (!CompilerConfig::is_c2_or_jvmci_compiler_enabled() && is_c2_compile(level)) {506return false;507}508509// Interpreter level is always valid.510if (level == CompLevel_none) {511return true;512}513if (CompilationModeFlag::normal()) {514return true;515} else if (CompilationModeFlag::quick_only()) {516return level == CompLevel_simple;517} else if (CompilationModeFlag::high_only()) {518return level == CompLevel_full_optimization;519} else if (CompilationModeFlag::high_only_quick_internal()) {520return level == CompLevel_full_optimization || level == CompLevel_simple;521}522return false;523}524#endif525526527CompLevel CompilationPolicy::highest_compile_level() {528CompLevel level = CompLevel_none;529// Setup the maximum level availible for the current compiler configuration.530if (!CompilerConfig::is_interpreter_only()) {531if (CompilerConfig::is_c2_or_jvmci_compiler_enabled()) {532level = CompLevel_full_optimization;533} else if (CompilerConfig::is_c1_enabled()) {534if (CompilerConfig::is_c1_simple_only()) {535level = CompLevel_simple;536} else {537level = CompLevel_full_profile;538}539}540}541// Clamp the maximum level with TieredStopAtLevel.542if (TieredCompilation) {543level = MIN2(level, (CompLevel) TieredStopAtLevel);544}545546// Fix it up if after the clamping it has become invalid.547// Bring it monotonically down depending on the next available level for548// the compilation mode.549if (!CompilationModeFlag::normal()) {550// a) quick_only - levels 2,3,4 are invalid; levels -1,0,1 are valid;551// b) high_only - levels 1,2,3 are invalid; levels -1,0,4 are valid;552// c) high_only_quick_internal - levels 2,3 are invalid; levels -1,0,1,4 are valid.553if (CompilationModeFlag::quick_only()) {554if (level == CompLevel_limited_profile || level == CompLevel_full_profile || level == CompLevel_full_optimization) {555level = CompLevel_simple;556}557} else if (CompilationModeFlag::high_only()) {558if (level == CompLevel_simple || level == CompLevel_limited_profile || level == CompLevel_full_profile) {559level = CompLevel_none;560}561} else if (CompilationModeFlag::high_only_quick_internal()) {562if (level == CompLevel_limited_profile || level == CompLevel_full_profile) {563level = CompLevel_simple;564}565}566}567568assert(verify_level(level), "Invalid highest compilation level: %d", level);569return level;570}571572CompLevel CompilationPolicy::limit_level(CompLevel level) {573level = MIN2(level, highest_compile_level());574assert(verify_level(level), "Invalid compilation level: %d", level);575return level;576}577578CompLevel CompilationPolicy::initial_compile_level(const methodHandle& method) {579CompLevel level = CompLevel_any;580if (CompilationModeFlag::normal()) {581level = CompLevel_full_profile;582} else if (CompilationModeFlag::quick_only()) {583level = CompLevel_simple;584} else if (CompilationModeFlag::high_only()) {585level = CompLevel_full_optimization;586} else if (CompilationModeFlag::high_only_quick_internal()) {587if (force_comp_at_level_simple(method)) {588level = CompLevel_simple;589} else {590level = CompLevel_full_optimization;591}592}593assert(level != CompLevel_any, "Unhandled compilation mode");594return limit_level(level);595}596597// Set carry flags on the counters if necessary598void CompilationPolicy::handle_counter_overflow(Method* method) {599MethodCounters *mcs = method->method_counters();600if (mcs != NULL) {601mcs->invocation_counter()->set_carry_on_overflow();602mcs->backedge_counter()->set_carry_on_overflow();603}604MethodData* mdo = method->method_data();605if (mdo != NULL) {606mdo->invocation_counter()->set_carry_on_overflow();607mdo->backedge_counter()->set_carry_on_overflow();608}609}610611// Called with the queue locked and with at least one element612CompileTask* CompilationPolicy::select_task(CompileQueue* compile_queue) {613CompileTask *max_blocking_task = NULL;614CompileTask *max_task = NULL;615Method* max_method = NULL;616617jlong t = nanos_to_millis(os::javaTimeNanos());618// Iterate through the queue and find a method with a maximum rate.619for (CompileTask* task = compile_queue->first(); task != NULL;) {620CompileTask* next_task = task->next();621Method* method = task->method();622// If a method was unloaded or has been stale for some time, remove it from the queue.623// Blocking tasks and tasks submitted from whitebox API don't become stale624if (task->is_unloaded() || (task->can_become_stale() && is_stale(t, TieredCompileTaskTimeout, method) && !is_old(method))) {625if (!task->is_unloaded()) {626if (PrintTieredEvents) {627print_event(REMOVE_FROM_QUEUE, method, method, task->osr_bci(), (CompLevel) task->comp_level());628}629method->clear_queued_for_compilation();630}631compile_queue->remove_and_mark_stale(task);632task = next_task;633continue;634}635update_rate(t, method);636if (max_task == NULL || compare_methods(method, max_method)) {637// Select a method with the highest rate638max_task = task;639max_method = method;640}641642if (task->is_blocking()) {643if (max_blocking_task == NULL || compare_methods(method, max_blocking_task->method())) {644max_blocking_task = task;645}646}647648task = next_task;649}650651if (max_blocking_task != NULL) {652// In blocking compilation mode, the CompileBroker will make653// compilations submitted by a JVMCI compiler thread non-blocking. These654// compilations should be scheduled after all blocking compilations655// to service non-compiler related compilations sooner and reduce the656// chance of such compilations timing out.657max_task = max_blocking_task;658max_method = max_task->method();659}660661methodHandle max_method_h(Thread::current(), max_method);662663if (max_task != NULL && max_task->comp_level() == CompLevel_full_profile && TieredStopAtLevel > CompLevel_full_profile &&664max_method != NULL && is_method_profiled(max_method_h) && !Arguments::is_compiler_only()) {665max_task->set_comp_level(CompLevel_limited_profile);666667if (CompileBroker::compilation_is_complete(max_method_h, max_task->osr_bci(), CompLevel_limited_profile)) {668if (PrintTieredEvents) {669print_event(REMOVE_FROM_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());670}671compile_queue->remove_and_mark_stale(max_task);672max_method->clear_queued_for_compilation();673return NULL;674}675676if (PrintTieredEvents) {677print_event(UPDATE_IN_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());678}679}680681return max_task;682}683684void CompilationPolicy::reprofile(ScopeDesc* trap_scope, bool is_osr) {685for (ScopeDesc* sd = trap_scope;; sd = sd->sender()) {686if (PrintTieredEvents) {687print_event(REPROFILE, sd->method(), sd->method(), InvocationEntryBci, CompLevel_none);688}689MethodData* mdo = sd->method()->method_data();690if (mdo != NULL) {691mdo->reset_start_counters();692}693if (sd->is_top()) break;694}695}696697nmethod* CompilationPolicy::event(const methodHandle& method, const methodHandle& inlinee,698int branch_bci, int bci, CompLevel comp_level, CompiledMethod* nm, TRAPS) {699if (PrintTieredEvents) {700print_event(bci == InvocationEntryBci ? CALL : LOOP, method(), inlinee(), bci, comp_level);701}702703if (comp_level == CompLevel_none &&704JvmtiExport::can_post_interpreter_events() &&705THREAD->is_interp_only_mode()) {706return NULL;707}708if (ReplayCompiles) {709// Don't trigger other compiles in testing mode710return NULL;711}712713handle_counter_overflow(method());714if (method() != inlinee()) {715handle_counter_overflow(inlinee());716}717718if (bci == InvocationEntryBci) {719method_invocation_event(method, inlinee, comp_level, nm, THREAD);720} else {721// method == inlinee if the event originated in the main method722method_back_branch_event(method, inlinee, bci, comp_level, nm, THREAD);723// Check if event led to a higher level OSR compilation724CompLevel expected_comp_level = MIN2(CompLevel_full_optimization, static_cast<CompLevel>(comp_level + 1));725if (!CompilationModeFlag::disable_intermediate() && inlinee->is_not_osr_compilable(expected_comp_level)) {726// It's not possble to reach the expected level so fall back to simple.727expected_comp_level = CompLevel_simple;728}729CompLevel max_osr_level = static_cast<CompLevel>(inlinee->highest_osr_comp_level());730if (max_osr_level >= expected_comp_level) { // fast check to avoid locking in a typical scenario731nmethod* osr_nm = inlinee->lookup_osr_nmethod_for(bci, expected_comp_level, false);732assert(osr_nm == NULL || osr_nm->comp_level() >= expected_comp_level, "lookup_osr_nmethod_for is broken");733if (osr_nm != NULL && osr_nm->comp_level() != comp_level) {734// Perform OSR with new nmethod735return osr_nm;736}737}738}739return NULL;740}741742// Check if the method can be compiled, change level if necessary743void CompilationPolicy::compile(const methodHandle& mh, int bci, CompLevel level, TRAPS) {744assert(verify_level(level), "Invalid compilation level requested: %d", level);745746if (level == CompLevel_none) {747if (mh->has_compiled_code()) {748// Happens when we switch to interpreter to profile.749MutexLocker ml(Compile_lock);750NoSafepointVerifier nsv;751if (mh->has_compiled_code()) {752mh->code()->make_not_used();753}754// Deoptimize immediately (we don't have to wait for a compile).755JavaThread* jt = THREAD;756RegisterMap map(jt, false);757frame fr = jt->last_frame().sender(&map);758Deoptimization::deoptimize_frame(jt, fr.id());759}760return;761}762763if (!CompilationModeFlag::disable_intermediate()) {764// Check if the method can be compiled. If it cannot be compiled with C1, continue profiling765// in the interpreter and then compile with C2 (the transition function will request that,766// see common() ). If the method cannot be compiled with C2 but still can with C1, compile it with767// pure C1.768if ((bci == InvocationEntryBci && !can_be_compiled(mh, level))) {769if (level == CompLevel_full_optimization && can_be_compiled(mh, CompLevel_simple)) {770compile(mh, bci, CompLevel_simple, THREAD);771}772return;773}774if ((bci != InvocationEntryBci && !can_be_osr_compiled(mh, level))) {775if (level == CompLevel_full_optimization && can_be_osr_compiled(mh, CompLevel_simple)) {776nmethod* osr_nm = mh->lookup_osr_nmethod_for(bci, CompLevel_simple, false);777if (osr_nm != NULL && osr_nm->comp_level() > CompLevel_simple) {778// Invalidate the existing OSR nmethod so that a compile at CompLevel_simple is permitted.779osr_nm->make_not_entrant();780}781compile(mh, bci, CompLevel_simple, THREAD);782}783return;784}785}786if (bci != InvocationEntryBci && mh->is_not_osr_compilable(level)) {787return;788}789if (!CompileBroker::compilation_is_in_queue(mh)) {790if (PrintTieredEvents) {791print_event(COMPILE, mh(), mh(), bci, level);792}793int hot_count = (bci == InvocationEntryBci) ? mh->invocation_count() : mh->backedge_count();794update_rate(nanos_to_millis(os::javaTimeNanos()), mh());795CompileBroker::compile_method(mh, bci, level, mh, hot_count, CompileTask::Reason_Tiered, THREAD);796}797}798799// update_rate() is called from select_task() while holding a compile queue lock.800void CompilationPolicy::update_rate(jlong t, Method* m) {801// Skip update if counters are absent.802// Can't allocate them since we are holding compile queue lock.803if (m->method_counters() == NULL) return;804805if (is_old(m)) {806// We don't remove old methods from the queue,807// so we can just zero the rate.808m->set_rate(0);809return;810}811812// We don't update the rate if we've just came out of a safepoint.813// delta_s is the time since last safepoint in milliseconds.814jlong delta_s = t - SafepointTracing::end_of_last_safepoint_ms();815jlong delta_t = t - (m->prev_time() != 0 ? m->prev_time() : start_time()); // milliseconds since the last measurement816// How many events were there since the last time?817int event_count = m->invocation_count() + m->backedge_count();818int delta_e = event_count - m->prev_event_count();819820// We should be running for at least 1ms.821if (delta_s >= TieredRateUpdateMinTime) {822// And we must've taken the previous point at least 1ms before.823if (delta_t >= TieredRateUpdateMinTime && delta_e > 0) {824m->set_prev_time(t);825m->set_prev_event_count(event_count);826m->set_rate((float)delta_e / (float)delta_t); // Rate is events per millisecond827} else {828if (delta_t > TieredRateUpdateMaxTime && delta_e == 0) {829// If nothing happened for 25ms, zero the rate. Don't modify prev values.830m->set_rate(0);831}832}833}834}835836// Check if this method has been stale for a given number of milliseconds.837// See select_task().838bool CompilationPolicy::is_stale(jlong t, jlong timeout, Method* m) {839jlong delta_s = t - SafepointTracing::end_of_last_safepoint_ms();840jlong delta_t = t - m->prev_time();841if (delta_t > timeout && delta_s > timeout) {842int event_count = m->invocation_count() + m->backedge_count();843int delta_e = event_count - m->prev_event_count();844// Return true if there were no events.845return delta_e == 0;846}847return false;848}849850// We don't remove old methods from the compile queue even if they have851// very low activity. See select_task().852bool CompilationPolicy::is_old(Method* method) {853return method->invocation_count() > 50000 || method->backedge_count() > 500000;854}855856double CompilationPolicy::weight(Method* method) {857return (double)(method->rate() + 1) *858(method->invocation_count() + 1) * (method->backedge_count() + 1);859}860861// Apply heuristics and return true if x should be compiled before y862bool CompilationPolicy::compare_methods(Method* x, Method* y) {863if (x->highest_comp_level() > y->highest_comp_level()) {864// recompilation after deopt865return true;866} else867if (x->highest_comp_level() == y->highest_comp_level()) {868if (weight(x) > weight(y)) {869return true;870}871}872return false;873}874875// Is method profiled enough?876bool CompilationPolicy::is_method_profiled(const methodHandle& method) {877MethodData* mdo = method->method_data();878if (mdo != NULL) {879int i = mdo->invocation_count_delta();880int b = mdo->backedge_count_delta();881return CallPredicate::apply_scaled(method, CompLevel_full_profile, i, b, 1);882}883return false;884}885886887// Determine is a method is mature.888bool CompilationPolicy::is_mature(Method* method) {889methodHandle mh(Thread::current(), method);890MethodData* mdo = method->method_data();891if (mdo != NULL) {892int i = mdo->invocation_count();893int b = mdo->backedge_count();894double k = ProfileMaturityPercentage / 100.0;895return CallPredicate::apply_scaled(mh, CompLevel_full_profile, i, b, k) || LoopPredicate::apply_scaled(mh, CompLevel_full_profile, i, b, k);896}897return false;898}899900// If a method is old enough and is still in the interpreter we would want to901// start profiling without waiting for the compiled method to arrive.902// We also take the load on compilers into the account.903bool CompilationPolicy::should_create_mdo(const methodHandle& method, CompLevel cur_level) {904if (cur_level != CompLevel_none || force_comp_at_level_simple(method) || CompilationModeFlag::quick_only() || !ProfileInterpreter) {905return false;906}907int i = method->invocation_count();908int b = method->backedge_count();909double k = Tier0ProfilingStartPercentage / 100.0;910911// If the top level compiler is not keeping up, delay profiling.912if (CompileBroker::queue_size(CompLevel_full_optimization) <= Tier0Delay * compiler_count(CompLevel_full_optimization)) {913return CallPredicate::apply_scaled(method, CompLevel_full_profile, i, b, k) || LoopPredicate::apply_scaled(method, CompLevel_full_profile, i, b, k);914}915return false;916}917918// Inlining control: if we're compiling a profiled method with C1 and the callee919// is known to have OSRed in a C2 version, don't inline it.920bool CompilationPolicy::should_not_inline(ciEnv* env, ciMethod* callee) {921CompLevel comp_level = (CompLevel)env->comp_level();922if (comp_level == CompLevel_full_profile ||923comp_level == CompLevel_limited_profile) {924return callee->highest_osr_comp_level() == CompLevel_full_optimization;925}926return false;927}928929// Create MDO if necessary.930void CompilationPolicy::create_mdo(const methodHandle& mh, JavaThread* THREAD) {931if (mh->is_native() ||932mh->is_abstract() ||933mh->is_accessor() ||934mh->is_constant_getter()) {935return;936}937if (mh->method_data() == NULL) {938Method::build_interpreter_method_data(mh, CHECK_AND_CLEAR);939}940if (ProfileInterpreter) {941MethodData* mdo = mh->method_data();942if (mdo != NULL) {943frame last_frame = THREAD->last_frame();944if (last_frame.is_interpreted_frame() && mh == last_frame.interpreter_frame_method()) {945int bci = last_frame.interpreter_frame_bci();946address dp = mdo->bci_to_dp(bci);947last_frame.interpreter_frame_set_mdp(dp);948}949}950}951}952953954955/*956* Method states:957* 0 - interpreter (CompLevel_none)958* 1 - pure C1 (CompLevel_simple)959* 2 - C1 with invocation and backedge counting (CompLevel_limited_profile)960* 3 - C1 with full profiling (CompLevel_full_profile)961* 4 - C2 or Graal (CompLevel_full_optimization)962*963* Common state transition patterns:964* a. 0 -> 3 -> 4.965* The most common path. But note that even in this straightforward case966* profiling can start at level 0 and finish at level 3.967*968* b. 0 -> 2 -> 3 -> 4.969* This case occurs when the load on C2 is deemed too high. So, instead of transitioning970* into state 3 directly and over-profiling while a method is in the C2 queue we transition to971* level 2 and wait until the load on C2 decreases. This path is disabled for OSRs.972*973* c. 0 -> (3->2) -> 4.974* In this case we enqueue a method for compilation at level 3, but the C1 queue is long enough975* to enable the profiling to fully occur at level 0. In this case we change the compilation level976* of the method to 2 while the request is still in-queue, because it'll allow it to run much faster977* without full profiling while c2 is compiling.978*979* d. 0 -> 3 -> 1 or 0 -> 2 -> 1.980* After a method was once compiled with C1 it can be identified as trivial and be compiled to981* level 1. These transition can also occur if a method can't be compiled with C2 but can with C1.982*983* e. 0 -> 4.984* This can happen if a method fails C1 compilation (it will still be profiled in the interpreter)985* or because of a deopt that didn't require reprofiling (compilation won't happen in this case because986* the compiled version already exists).987*988* Note that since state 0 can be reached from any other state via deoptimization different loops989* are possible.990*991*/992993// Common transition function. Given a predicate determines if a method should transition to another level.994template<typename Predicate>995CompLevel CompilationPolicy::common(const methodHandle& method, CompLevel cur_level, bool disable_feedback) {996CompLevel next_level = cur_level;997int i = method->invocation_count();998int b = method->backedge_count();9991000if (force_comp_at_level_simple(method)) {1001next_level = CompLevel_simple;1002} else {1003if (is_trivial(method())) {1004next_level = CompilationModeFlag::disable_intermediate() ? CompLevel_full_optimization : CompLevel_simple;1005} else {1006switch(cur_level) {1007default: break;1008case CompLevel_none:1009// If we were at full profile level, would we switch to full opt?1010if (common<Predicate>(method, CompLevel_full_profile, disable_feedback) == CompLevel_full_optimization) {1011next_level = CompLevel_full_optimization;1012} else if (!CompilationModeFlag::disable_intermediate() && Predicate::apply(i, b, cur_level, method)) {1013// C1-generated fully profiled code is about 30% slower than the limited profile1014// code that has only invocation and backedge counters. The observation is that1015// if C2 queue is large enough we can spend too much time in the fully profiled code1016// while waiting for C2 to pick the method from the queue. To alleviate this problem1017// we introduce a feedback on the C2 queue size. If the C2 queue is sufficiently long1018// we choose to compile a limited profiled version and then recompile with full profiling1019// when the load on C2 goes down.1020if (!disable_feedback && CompileBroker::queue_size(CompLevel_full_optimization) >1021Tier3DelayOn * compiler_count(CompLevel_full_optimization)) {1022next_level = CompLevel_limited_profile;1023} else {1024next_level = CompLevel_full_profile;1025}1026}1027break;1028case CompLevel_limited_profile:1029if (is_method_profiled(method)) {1030// Special case: we got here because this method was fully profiled in the interpreter.1031next_level = CompLevel_full_optimization;1032} else {1033MethodData* mdo = method->method_data();1034if (mdo != NULL) {1035if (mdo->would_profile()) {1036if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=1037Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&1038Predicate::apply(i, b, cur_level, method))) {1039next_level = CompLevel_full_profile;1040}1041} else {1042next_level = CompLevel_full_optimization;1043}1044} else {1045// If there is no MDO we need to profile1046if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=1047Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&1048Predicate::apply(i, b, cur_level, method))) {1049next_level = CompLevel_full_profile;1050}1051}1052}1053break;1054case CompLevel_full_profile:1055{1056MethodData* mdo = method->method_data();1057if (mdo != NULL) {1058if (mdo->would_profile() || CompilationModeFlag::disable_intermediate()) {1059int mdo_i = mdo->invocation_count_delta();1060int mdo_b = mdo->backedge_count_delta();1061if (Predicate::apply(mdo_i, mdo_b, cur_level, method)) {1062next_level = CompLevel_full_optimization;1063}1064} else {1065next_level = CompLevel_full_optimization;1066}1067}1068}1069break;1070}1071}1072}1073return (next_level != cur_level) ? limit_level(next_level) : next_level;1074}1075107610771078// Determine if a method should be compiled with a normal entry point at a different level.1079CompLevel CompilationPolicy::call_event(const methodHandle& method, CompLevel cur_level, Thread* thread) {1080CompLevel osr_level = MIN2((CompLevel) method->highest_osr_comp_level(), common<LoopPredicate>(method, cur_level, true));1081CompLevel next_level = common<CallPredicate>(method, cur_level);10821083// If OSR method level is greater than the regular method level, the levels should be1084// equalized by raising the regular method level in order to avoid OSRs during each1085// invocation of the method.1086if (osr_level == CompLevel_full_optimization && cur_level == CompLevel_full_profile) {1087MethodData* mdo = method->method_data();1088guarantee(mdo != NULL, "MDO should not be NULL");1089if (mdo->invocation_count() >= 1) {1090next_level = CompLevel_full_optimization;1091}1092} else {1093next_level = MAX2(osr_level, next_level);1094}1095return next_level;1096}10971098// Determine if we should do an OSR compilation of a given method.1099CompLevel CompilationPolicy::loop_event(const methodHandle& method, CompLevel cur_level, Thread* thread) {1100CompLevel next_level = common<LoopPredicate>(method, cur_level, true);1101if (cur_level == CompLevel_none) {1102// If there is a live OSR method that means that we deopted to the interpreter1103// for the transition.1104CompLevel osr_level = MIN2((CompLevel)method->highest_osr_comp_level(), next_level);1105if (osr_level > CompLevel_none) {1106return osr_level;1107}1108}1109return next_level;1110}11111112// Handle the invocation event.1113void CompilationPolicy::method_invocation_event(const methodHandle& mh, const methodHandle& imh,1114CompLevel level, CompiledMethod* nm, TRAPS) {1115if (should_create_mdo(mh, level)) {1116create_mdo(mh, THREAD);1117}1118CompLevel next_level = call_event(mh, level, THREAD);1119if (next_level != level) {1120if (is_compilation_enabled() && !CompileBroker::compilation_is_in_queue(mh)) {1121compile(mh, InvocationEntryBci, next_level, THREAD);1122}1123}1124}11251126// Handle the back branch event. Notice that we can compile the method1127// with a regular entry from here.1128void CompilationPolicy::method_back_branch_event(const methodHandle& mh, const methodHandle& imh,1129int bci, CompLevel level, CompiledMethod* nm, TRAPS) {1130if (should_create_mdo(mh, level)) {1131create_mdo(mh, THREAD);1132}1133// Check if MDO should be created for the inlined method1134if (should_create_mdo(imh, level)) {1135create_mdo(imh, THREAD);1136}11371138if (is_compilation_enabled()) {1139CompLevel next_osr_level = loop_event(imh, level, THREAD);1140CompLevel max_osr_level = (CompLevel)imh->highest_osr_comp_level();1141// At the very least compile the OSR version1142if (!CompileBroker::compilation_is_in_queue(imh) && (next_osr_level != level)) {1143compile(imh, bci, next_osr_level, CHECK);1144}11451146// Use loop event as an opportunity to also check if there's been1147// enough calls.1148CompLevel cur_level, next_level;1149if (mh() != imh()) { // If there is an enclosing method1150{1151guarantee(nm != NULL, "Should have nmethod here");1152cur_level = comp_level(mh());1153next_level = call_event(mh, cur_level, THREAD);11541155if (max_osr_level == CompLevel_full_optimization) {1156// The inlinee OSRed to full opt, we need to modify the enclosing method to avoid deopts1157bool make_not_entrant = false;1158if (nm->is_osr_method()) {1159// This is an osr method, just make it not entrant and recompile later if needed1160make_not_entrant = true;1161} else {1162if (next_level != CompLevel_full_optimization) {1163// next_level is not full opt, so we need to recompile the1164// enclosing method without the inlinee1165cur_level = CompLevel_none;1166make_not_entrant = true;1167}1168}1169if (make_not_entrant) {1170if (PrintTieredEvents) {1171int osr_bci = nm->is_osr_method() ? nm->osr_entry_bci() : InvocationEntryBci;1172print_event(MAKE_NOT_ENTRANT, mh(), mh(), osr_bci, level);1173}1174nm->make_not_entrant();1175}1176}1177// Fix up next_level if necessary to avoid deopts1178if (next_level == CompLevel_limited_profile && max_osr_level == CompLevel_full_profile) {1179next_level = CompLevel_full_profile;1180}1181if (cur_level != next_level) {1182if (!CompileBroker::compilation_is_in_queue(mh)) {1183compile(mh, InvocationEntryBci, next_level, THREAD);1184}1185}1186}1187} else {1188cur_level = comp_level(mh());1189next_level = call_event(mh, cur_level, THREAD);1190if (next_level != cur_level) {1191if (!CompileBroker::compilation_is_in_queue(mh)) {1192compile(mh, InvocationEntryBci, next_level, THREAD);1193}1194}1195}1196}1197}1198119912001201