1 /*
2 * Copyright (c) 2010, 2018, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "precompiled.hpp"
26 #include "compiler/compileBroker.hpp"
27 #include "compiler/compilerOracle.hpp"
28 #include "memory/resourceArea.hpp"
29 #include "runtime/arguments.hpp"
30 #include "runtime/handles.inline.hpp"
31 #include "runtime/safepointVerifiers.hpp"
32 #include "runtime/tieredThresholdPolicy.hpp"
33 #include "code/scopeDesc.hpp"
34 #include "oops/method.inline.hpp"
35 #if INCLUDE_JVMCI
36 #include "jvmci/jvmciRuntime.hpp"
37 #endif
38
39 #ifdef TIERED
40
41 #include "c1/c1_Compiler.hpp"
42 #include "opto/c2compiler.hpp"
43
44 template<CompLevel level>
call_predicate_helper(int i,int b,double scale,Method * method)45 bool TieredThresholdPolicy::call_predicate_helper(int i, int b, double scale, Method* method) {
46 double threshold_scaling;
47 if (CompilerOracle::has_option_value(method, "CompileThresholdScaling", threshold_scaling)) {
48 scale *= threshold_scaling;
49 }
50 switch(level) {
51 case CompLevel_aot:
52 return (i >= Tier3AOTInvocationThreshold * scale) ||
53 (i >= Tier3AOTMinInvocationThreshold * scale && i + b >= Tier3AOTCompileThreshold * scale);
54 case CompLevel_none:
55 case CompLevel_limited_profile:
56 return (i >= Tier3InvocationThreshold * scale) ||
57 (i >= Tier3MinInvocationThreshold * scale && i + b >= Tier3CompileThreshold * scale);
58 case CompLevel_full_profile:
59 return (i >= Tier4InvocationThreshold * scale) ||
60 (i >= Tier4MinInvocationThreshold * scale && i + b >= Tier4CompileThreshold * scale);
61 }
62 return true;
63 }
64
65 template<CompLevel level>
loop_predicate_helper(int i,int b,double scale,Method * method)66 bool TieredThresholdPolicy::loop_predicate_helper(int i, int b, double scale, Method* method) {
67 double threshold_scaling;
68 if (CompilerOracle::has_option_value(method, "CompileThresholdScaling", threshold_scaling)) {
69 scale *= threshold_scaling;
70 }
71 switch(level) {
72 case CompLevel_aot:
73 return b >= Tier3AOTBackEdgeThreshold * scale;
74 case CompLevel_none:
75 case CompLevel_limited_profile:
76 return b >= Tier3BackEdgeThreshold * scale;
77 case CompLevel_full_profile:
78 return b >= Tier4BackEdgeThreshold * scale;
79 }
80 return true;
81 }
82
83 // Simple methods are as good being compiled with C1 as C2.
84 // Determine if a given method is such a case.
is_trivial(Method * method)85 bool TieredThresholdPolicy::is_trivial(Method* method) {
86 if (method->is_accessor() ||
87 method->is_constant_getter()) {
88 return true;
89 }
90 return false;
91 }
92
comp_level(Method * method)93 inline CompLevel TieredThresholdPolicy::comp_level(Method* method) {
94 CompiledMethod *nm = method->code();
95 if (nm != NULL && nm->is_in_use()) {
96 return (CompLevel)nm->comp_level();
97 }
98 return CompLevel_none;
99 }
100
print_counters(const char * prefix,const methodHandle & mh)101 void TieredThresholdPolicy::print_counters(const char* prefix, const methodHandle& mh) {
102 int invocation_count = mh->invocation_count();
103 int backedge_count = mh->backedge_count();
104 MethodData* mdh = mh->method_data();
105 int mdo_invocations = 0, mdo_backedges = 0;
106 int mdo_invocations_start = 0, mdo_backedges_start = 0;
107 if (mdh != NULL) {
108 mdo_invocations = mdh->invocation_count();
109 mdo_backedges = mdh->backedge_count();
110 mdo_invocations_start = mdh->invocation_count_start();
111 mdo_backedges_start = mdh->backedge_count_start();
112 }
113 tty->print(" %stotal=%d,%d %smdo=%d(%d),%d(%d)", prefix,
114 invocation_count, backedge_count, prefix,
115 mdo_invocations, mdo_invocations_start,
116 mdo_backedges, mdo_backedges_start);
117 tty->print(" %smax levels=%d,%d", prefix,
118 mh->highest_comp_level(), mh->highest_osr_comp_level());
119 }
120
121 // Print an event.
print_event(EventType type,const methodHandle & mh,const methodHandle & imh,int bci,CompLevel level)122 void TieredThresholdPolicy::print_event(EventType type, const methodHandle& mh, const methodHandle& imh,
123 int bci, CompLevel level) {
124 bool inlinee_event = mh() != imh();
125
126 ttyLocker tty_lock;
127 tty->print("%lf: [", os::elapsedTime());
128
129 switch(type) {
130 case CALL:
131 tty->print("call");
132 break;
133 case LOOP:
134 tty->print("loop");
135 break;
136 case COMPILE:
137 tty->print("compile");
138 break;
139 case REMOVE_FROM_QUEUE:
140 tty->print("remove-from-queue");
141 break;
142 case UPDATE_IN_QUEUE:
143 tty->print("update-in-queue");
144 break;
145 case REPROFILE:
146 tty->print("reprofile");
147 break;
148 case MAKE_NOT_ENTRANT:
149 tty->print("make-not-entrant");
150 break;
151 default:
152 tty->print("unknown");
153 }
154
155 tty->print(" level=%d ", level);
156
157 ResourceMark rm;
158 char *method_name = mh->name_and_sig_as_C_string();
159 tty->print("[%s", method_name);
160 if (inlinee_event) {
161 char *inlinee_name = imh->name_and_sig_as_C_string();
162 tty->print(" [%s]] ", inlinee_name);
163 }
164 else tty->print("] ");
165 tty->print("@%d queues=%d,%d", bci, CompileBroker::queue_size(CompLevel_full_profile),
166 CompileBroker::queue_size(CompLevel_full_optimization));
167
168 print_specific(type, mh, imh, bci, level);
169
170 if (type != COMPILE) {
171 print_counters("", mh);
172 if (inlinee_event) {
173 print_counters("inlinee ", imh);
174 }
175 tty->print(" compilable=");
176 bool need_comma = false;
177 if (!mh->is_not_compilable(CompLevel_full_profile)) {
178 tty->print("c1");
179 need_comma = true;
180 }
181 if (!mh->is_not_osr_compilable(CompLevel_full_profile)) {
182 if (need_comma) tty->print(",");
183 tty->print("c1-osr");
184 need_comma = true;
185 }
186 if (!mh->is_not_compilable(CompLevel_full_optimization)) {
187 if (need_comma) tty->print(",");
188 tty->print("c2");
189 need_comma = true;
190 }
191 if (!mh->is_not_osr_compilable(CompLevel_full_optimization)) {
192 if (need_comma) tty->print(",");
193 tty->print("c2-osr");
194 }
195 tty->print(" status=");
196 if (mh->queued_for_compilation()) {
197 tty->print("in-queue");
198 } else tty->print("idle");
199 }
200 tty->print_cr("]");
201 }
202
initialize()203 void TieredThresholdPolicy::initialize() {
204 int count = CICompilerCount;
205 bool c1_only = TieredStopAtLevel < CompLevel_full_optimization;
206 #ifdef _LP64
207 // Turn on ergonomic compiler count selection
208 if (FLAG_IS_DEFAULT(CICompilerCountPerCPU) && FLAG_IS_DEFAULT(CICompilerCount)) {
209 FLAG_SET_DEFAULT(CICompilerCountPerCPU, true);
210 }
211 if (CICompilerCountPerCPU) {
212 // Simple log n seems to grow too slowly for tiered, try something faster: log n * log log n
213 int log_cpu = log2_int(os::active_processor_count());
214 int loglog_cpu = log2_int(MAX2(log_cpu, 1));
215 count = MAX2(log_cpu * loglog_cpu * 3 / 2, 2);
216 // Make sure there is enough space in the code cache to hold all the compiler buffers
217 size_t c1_size = Compiler::code_buffer_size();
218 size_t c2_size = C2Compiler::initial_code_buffer_size();
219 size_t buffer_size = c1_only ? c1_size : (c1_size/3 + 2*c2_size/3);
220 int max_count = (ReservedCodeCacheSize - (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3))) / (int)buffer_size;
221 if (count > max_count) {
222 // Lower the compiler count such that all buffers fit into the code cache
223 count = MAX2(max_count, c1_only ? 1 : 2);
224 }
225 FLAG_SET_ERGO(intx, CICompilerCount, count);
226 }
227 #else
228 // On 32-bit systems, the number of compiler threads is limited to 3.
229 // On these systems, the virtual address space available to the JVM
230 // is usually limited to 2-4 GB (the exact value depends on the platform).
231 // As the compilers (especially C2) can consume a large amount of
232 // memory, scaling the number of compiler threads with the number of
233 // available cores can result in the exhaustion of the address space
234 /// available to the VM and thus cause the VM to crash.
235 if (FLAG_IS_DEFAULT(CICompilerCount)) {
236 count = 3;
237 FLAG_SET_ERGO(intx, CICompilerCount, count);
238 }
239 #endif
240
241 if (c1_only) {
242 // No C2 compiler thread required
243 set_c1_count(count);
244 } else {
245 set_c1_count(MAX2(count / 3, 1));
246 set_c2_count(MAX2(count - c1_count(), 1));
247 }
248 assert(count == c1_count() + c2_count(), "inconsistent compiler thread count");
249
250 // Some inlining tuning
251 #ifdef X86
252 if (FLAG_IS_DEFAULT(InlineSmallCode)) {
253 FLAG_SET_DEFAULT(InlineSmallCode, 2000);
254 }
255 #endif
256
257 #if defined SPARC || defined AARCH64
258 if (FLAG_IS_DEFAULT(InlineSmallCode)) {
259 FLAG_SET_DEFAULT(InlineSmallCode, 2500);
260 }
261 #endif
262
263 set_increase_threshold_at_ratio();
264 set_start_time(os::javaTimeMillis());
265 }
266
set_carry_if_necessary(InvocationCounter * counter)267 void TieredThresholdPolicy::set_carry_if_necessary(InvocationCounter *counter) {
268 if (!counter->carry() && counter->count() > InvocationCounter::count_limit / 2) {
269 counter->set_carry_flag();
270 }
271 }
272
273 // Set carry flags on the counters if necessary
handle_counter_overflow(Method * method)274 void TieredThresholdPolicy::handle_counter_overflow(Method* method) {
275 MethodCounters *mcs = method->method_counters();
276 if (mcs != NULL) {
277 set_carry_if_necessary(mcs->invocation_counter());
278 set_carry_if_necessary(mcs->backedge_counter());
279 }
280 MethodData* mdo = method->method_data();
281 if (mdo != NULL) {
282 set_carry_if_necessary(mdo->invocation_counter());
283 set_carry_if_necessary(mdo->backedge_counter());
284 }
285 }
286
287 // Called with the queue locked and with at least one element
select_task(CompileQueue * compile_queue)288 CompileTask* TieredThresholdPolicy::select_task(CompileQueue* compile_queue) {
289 CompileTask *max_blocking_task = NULL;
290 CompileTask *max_task = NULL;
291 Method* max_method = NULL;
292 jlong t = os::javaTimeMillis();
293 // Iterate through the queue and find a method with a maximum rate.
294 for (CompileTask* task = compile_queue->first(); task != NULL;) {
295 CompileTask* next_task = task->next();
296 Method* method = task->method();
297 // If a method was unloaded or has been stale for some time, remove it from the queue.
298 // Blocking tasks and tasks submitted from whitebox API don't become stale
299 if (task->is_unloaded() || (task->can_become_stale() && is_stale(t, TieredCompileTaskTimeout, method) && !is_old(method))) {
300 if (!task->is_unloaded()) {
301 if (PrintTieredEvents) {
302 print_event(REMOVE_FROM_QUEUE, method, method, task->osr_bci(), (CompLevel) task->comp_level());
303 }
304 method->clear_queued_for_compilation();
305 }
306 compile_queue->remove_and_mark_stale(task);
307 task = next_task;
308 continue;
309 }
310 update_rate(t, method);
311 if (max_task == NULL || compare_methods(method, max_method)) {
312 // Select a method with the highest rate
313 max_task = task;
314 max_method = method;
315 }
316
317 if (task->is_blocking()) {
318 if (max_blocking_task == NULL || compare_methods(method, max_blocking_task->method())) {
319 max_blocking_task = task;
320 }
321 }
322
323 task = next_task;
324 }
325
326 if (max_blocking_task != NULL) {
327 // In blocking compilation mode, the CompileBroker will make
328 // compilations submitted by a JVMCI compiler thread non-blocking. These
329 // compilations should be scheduled after all blocking compilations
330 // to service non-compiler related compilations sooner and reduce the
331 // chance of such compilations timing out.
332 max_task = max_blocking_task;
333 max_method = max_task->method();
334 }
335
336 if (max_task != NULL && max_task->comp_level() == CompLevel_full_profile &&
337 TieredStopAtLevel > CompLevel_full_profile &&
338 max_method != NULL && is_method_profiled(max_method)) {
339 max_task->set_comp_level(CompLevel_limited_profile);
340
341 if (CompileBroker::compilation_is_complete(max_method, max_task->osr_bci(), CompLevel_limited_profile)) {
342 if (PrintTieredEvents) {
343 print_event(REMOVE_FROM_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());
344 }
345 compile_queue->remove_and_mark_stale(max_task);
346 max_method->clear_queued_for_compilation();
347 return NULL;
348 }
349
350 if (PrintTieredEvents) {
351 print_event(UPDATE_IN_QUEUE, max_method, max_method, max_task->osr_bci(), (CompLevel)max_task->comp_level());
352 }
353 }
354
355 return max_task;
356 }
357
reprofile(ScopeDesc * trap_scope,bool is_osr)358 void TieredThresholdPolicy::reprofile(ScopeDesc* trap_scope, bool is_osr) {
359 for (ScopeDesc* sd = trap_scope;; sd = sd->sender()) {
360 if (PrintTieredEvents) {
361 methodHandle mh(sd->method());
362 print_event(REPROFILE, mh, mh, InvocationEntryBci, CompLevel_none);
363 }
364 MethodData* mdo = sd->method()->method_data();
365 if (mdo != NULL) {
366 mdo->reset_start_counters();
367 }
368 if (sd->is_top()) break;
369 }
370 }
371
event(const methodHandle & method,const methodHandle & inlinee,int branch_bci,int bci,CompLevel comp_level,CompiledMethod * nm,JavaThread * thread)372 nmethod* TieredThresholdPolicy::event(const methodHandle& method, const methodHandle& inlinee,
373 int branch_bci, int bci, CompLevel comp_level, CompiledMethod* nm, JavaThread* thread) {
374 if (comp_level == CompLevel_none &&
375 JvmtiExport::can_post_interpreter_events() &&
376 thread->is_interp_only_mode()) {
377 return NULL;
378 }
379 if (CompileTheWorld || ReplayCompiles) {
380 // Don't trigger other compiles in testing mode
381 return NULL;
382 }
383
384 handle_counter_overflow(method());
385 if (method() != inlinee()) {
386 handle_counter_overflow(inlinee());
387 }
388
389 if (PrintTieredEvents) {
390 print_event(bci == InvocationEntryBci ? CALL : LOOP, method, inlinee, bci, comp_level);
391 }
392
393 if (bci == InvocationEntryBci) {
394 method_invocation_event(method, inlinee, comp_level, nm, thread);
395 } else {
396 // method == inlinee if the event originated in the main method
397 method_back_branch_event(method, inlinee, bci, comp_level, nm, thread);
398 // Check if event led to a higher level OSR compilation
399 nmethod* osr_nm = inlinee->lookup_osr_nmethod_for(bci, comp_level, false);
400 if (osr_nm != NULL && osr_nm->comp_level() > comp_level) {
401 // Perform OSR with new nmethod
402 return osr_nm;
403 }
404 }
405 return NULL;
406 }
407
408 // Check if the method can be compiled, change level if necessary
compile(const methodHandle & mh,int bci,CompLevel level,JavaThread * thread)409 void TieredThresholdPolicy::compile(const methodHandle& mh, int bci, CompLevel level, JavaThread* thread) {
410 assert(level <= TieredStopAtLevel, "Invalid compilation level");
411 if (level == CompLevel_none) {
412 return;
413 }
414 if (level == CompLevel_aot) {
415 if (mh->has_aot_code()) {
416 if (PrintTieredEvents) {
417 print_event(COMPILE, mh, mh, bci, level);
418 }
419 MutexLocker ml(Compile_lock);
420 NoSafepointVerifier nsv;
421 if (mh->has_aot_code() && mh->code() != mh->aot_code()) {
422 mh->aot_code()->make_entrant();
423 if (mh->has_compiled_code()) {
424 mh->code()->make_not_entrant();
425 }
426 Method::set_code(mh, mh->aot_code());
427 }
428 }
429 return;
430 }
431
432 // Check if the method can be compiled. If it cannot be compiled with C1, continue profiling
433 // in the interpreter and then compile with C2 (the transition function will request that,
434 // see common() ). If the method cannot be compiled with C2 but still can with C1, compile it with
435 // pure C1.
436 if (!can_be_compiled(mh, level)) {
437 if (level == CompLevel_full_optimization && can_be_compiled(mh, CompLevel_simple)) {
438 compile(mh, bci, CompLevel_simple, thread);
439 }
440 return;
441 }
442 if (bci != InvocationEntryBci && mh->is_not_osr_compilable(level)) {
443 return;
444 }
445 if (!CompileBroker::compilation_is_in_queue(mh)) {
446 if (PrintTieredEvents) {
447 print_event(COMPILE, mh, mh, bci, level);
448 }
449 submit_compile(mh, bci, level, thread);
450 }
451 }
452
453 // Update the rate and submit compile
submit_compile(const methodHandle & mh,int bci,CompLevel level,JavaThread * thread)454 void TieredThresholdPolicy::submit_compile(const methodHandle& mh, int bci, CompLevel level, JavaThread* thread) {
455 int hot_count = (bci == InvocationEntryBci) ? mh->invocation_count() : mh->backedge_count();
456 update_rate(os::javaTimeMillis(), mh());
457 CompileBroker::compile_method(mh, bci, level, mh, hot_count, CompileTask::Reason_Tiered, thread);
458 }
459
460 // Print an event.
print_specific(EventType type,const methodHandle & mh,const methodHandle & imh,int bci,CompLevel level)461 void TieredThresholdPolicy::print_specific(EventType type, const methodHandle& mh, const methodHandle& imh,
462 int bci, CompLevel level) {
463 tty->print(" rate=");
464 if (mh->prev_time() == 0) tty->print("n/a");
465 else tty->print("%f", mh->rate());
466
467 tty->print(" k=%.2lf,%.2lf", threshold_scale(CompLevel_full_profile, Tier3LoadFeedback),
468 threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback));
469
470 }
471
472 // update_rate() is called from select_task() while holding a compile queue lock.
update_rate(jlong t,Method * m)473 void TieredThresholdPolicy::update_rate(jlong t, Method* m) {
474 // Skip update if counters are absent.
475 // Can't allocate them since we are holding compile queue lock.
476 if (m->method_counters() == NULL) return;
477
478 if (is_old(m)) {
479 // We don't remove old methods from the queue,
480 // so we can just zero the rate.
481 m->set_rate(0);
482 return;
483 }
484
485 // We don't update the rate if we've just came out of a safepoint.
486 // delta_s is the time since last safepoint in milliseconds.
487 jlong delta_s = t - SafepointSynchronize::end_of_last_safepoint();
488 jlong delta_t = t - (m->prev_time() != 0 ? m->prev_time() : start_time()); // milliseconds since the last measurement
489 // How many events were there since the last time?
490 int event_count = m->invocation_count() + m->backedge_count();
491 int delta_e = event_count - m->prev_event_count();
492
493 // We should be running for at least 1ms.
494 if (delta_s >= TieredRateUpdateMinTime) {
495 // And we must've taken the previous point at least 1ms before.
496 if (delta_t >= TieredRateUpdateMinTime && delta_e > 0) {
497 m->set_prev_time(t);
498 m->set_prev_event_count(event_count);
499 m->set_rate((float)delta_e / (float)delta_t); // Rate is events per millisecond
500 } else {
501 if (delta_t > TieredRateUpdateMaxTime && delta_e == 0) {
502 // If nothing happened for 25ms, zero the rate. Don't modify prev values.
503 m->set_rate(0);
504 }
505 }
506 }
507 }
508
509 // Check if this method has been stale for a given number of milliseconds.
510 // See select_task().
is_stale(jlong t,jlong timeout,Method * m)511 bool TieredThresholdPolicy::is_stale(jlong t, jlong timeout, Method* m) {
512 jlong delta_s = t - SafepointSynchronize::end_of_last_safepoint();
513 jlong delta_t = t - m->prev_time();
514 if (delta_t > timeout && delta_s > timeout) {
515 int event_count = m->invocation_count() + m->backedge_count();
516 int delta_e = event_count - m->prev_event_count();
517 // Return true if there were no events.
518 return delta_e == 0;
519 }
520 return false;
521 }
522
523 // We don't remove old methods from the compile queue even if they have
524 // very low activity. See select_task().
is_old(Method * method)525 bool TieredThresholdPolicy::is_old(Method* method) {
526 return method->invocation_count() > 50000 || method->backedge_count() > 500000;
527 }
528
weight(Method * method)529 double TieredThresholdPolicy::weight(Method* method) {
530 return (double)(method->rate() + 1) *
531 (method->invocation_count() + 1) * (method->backedge_count() + 1);
532 }
533
534 // Apply heuristics and return true if x should be compiled before y
compare_methods(Method * x,Method * y)535 bool TieredThresholdPolicy::compare_methods(Method* x, Method* y) {
536 if (x->highest_comp_level() > y->highest_comp_level()) {
537 // recompilation after deopt
538 return true;
539 } else
540 if (x->highest_comp_level() == y->highest_comp_level()) {
541 if (weight(x) > weight(y)) {
542 return true;
543 }
544 }
545 return false;
546 }
547
548 // Is method profiled enough?
is_method_profiled(Method * method)549 bool TieredThresholdPolicy::is_method_profiled(Method* method) {
550 MethodData* mdo = method->method_data();
551 if (mdo != NULL) {
552 int i = mdo->invocation_count_delta();
553 int b = mdo->backedge_count_delta();
554 return call_predicate_helper<CompLevel_full_profile>(i, b, 1, method);
555 }
556 return false;
557 }
558
threshold_scale(CompLevel level,int feedback_k)559 double TieredThresholdPolicy::threshold_scale(CompLevel level, int feedback_k) {
560 double queue_size = CompileBroker::queue_size(level);
561 int comp_count = compiler_count(level);
562 double k = queue_size / (feedback_k * comp_count) + 1;
563
564 // Increase C1 compile threshold when the code cache is filled more
565 // than specified by IncreaseFirstTierCompileThresholdAt percentage.
566 // The main intention is to keep enough free space for C2 compiled code
567 // to achieve peak performance if the code cache is under stress.
568 if ((TieredStopAtLevel == CompLevel_full_optimization) && (level != CompLevel_full_optimization)) {
569 double current_reverse_free_ratio = CodeCache::reverse_free_ratio(CodeCache::get_code_blob_type(level));
570 if (current_reverse_free_ratio > _increase_threshold_at_ratio) {
571 k *= exp(current_reverse_free_ratio - _increase_threshold_at_ratio);
572 }
573 }
574 return k;
575 }
576
577 // Call and loop predicates determine whether a transition to a higher
578 // compilation level should be performed (pointers to predicate functions
579 // are passed to common()).
580 // Tier?LoadFeedback is basically a coefficient that determines of
581 // how many methods per compiler thread can be in the queue before
582 // the threshold values double.
loop_predicate(int i,int b,CompLevel cur_level,Method * method)583 bool TieredThresholdPolicy::loop_predicate(int i, int b, CompLevel cur_level, Method* method) {
584 switch(cur_level) {
585 case CompLevel_aot: {
586 double k = threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
587 return loop_predicate_helper<CompLevel_aot>(i, b, k, method);
588 }
589 case CompLevel_none:
590 case CompLevel_limited_profile: {
591 double k = threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
592 return loop_predicate_helper<CompLevel_none>(i, b, k, method);
593 }
594 case CompLevel_full_profile: {
595 double k = threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);
596 return loop_predicate_helper<CompLevel_full_profile>(i, b, k, method);
597 }
598 default:
599 return true;
600 }
601 }
602
call_predicate(int i,int b,CompLevel cur_level,Method * method)603 bool TieredThresholdPolicy::call_predicate(int i, int b, CompLevel cur_level, Method* method) {
604 switch(cur_level) {
605 case CompLevel_aot: {
606 double k = threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
607 return call_predicate_helper<CompLevel_aot>(i, b, k, method);
608 }
609 case CompLevel_none:
610 case CompLevel_limited_profile: {
611 double k = threshold_scale(CompLevel_full_profile, Tier3LoadFeedback);
612 return call_predicate_helper<CompLevel_none>(i, b, k, method);
613 }
614 case CompLevel_full_profile: {
615 double k = threshold_scale(CompLevel_full_optimization, Tier4LoadFeedback);
616 return call_predicate_helper<CompLevel_full_profile>(i, b, k, method);
617 }
618 default:
619 return true;
620 }
621 }
622
623 // Determine is a method is mature.
is_mature(Method * method)624 bool TieredThresholdPolicy::is_mature(Method* method) {
625 if (is_trivial(method)) return true;
626 MethodData* mdo = method->method_data();
627 if (mdo != NULL) {
628 int i = mdo->invocation_count();
629 int b = mdo->backedge_count();
630 double k = ProfileMaturityPercentage / 100.0;
631 return call_predicate_helper<CompLevel_full_profile>(i, b, k, method) ||
632 loop_predicate_helper<CompLevel_full_profile>(i, b, k, method);
633 }
634 return false;
635 }
636
637 // If a method is old enough and is still in the interpreter we would want to
638 // start profiling without waiting for the compiled method to arrive.
639 // We also take the load on compilers into the account.
should_create_mdo(Method * method,CompLevel cur_level)640 bool TieredThresholdPolicy::should_create_mdo(Method* method, CompLevel cur_level) {
641 if (cur_level == CompLevel_none &&
642 CompileBroker::queue_size(CompLevel_full_optimization) <=
643 Tier3DelayOn * compiler_count(CompLevel_full_optimization)) {
644 int i = method->invocation_count();
645 int b = method->backedge_count();
646 double k = Tier0ProfilingStartPercentage / 100.0;
647 return call_predicate_helper<CompLevel_none>(i, b, k, method) || loop_predicate_helper<CompLevel_none>(i, b, k, method);
648 }
649 return false;
650 }
651
652 // Inlining control: if we're compiling a profiled method with C1 and the callee
653 // is known to have OSRed in a C2 version, don't inline it.
should_not_inline(ciEnv * env,ciMethod * callee)654 bool TieredThresholdPolicy::should_not_inline(ciEnv* env, ciMethod* callee) {
655 CompLevel comp_level = (CompLevel)env->comp_level();
656 if (comp_level == CompLevel_full_profile ||
657 comp_level == CompLevel_limited_profile) {
658 return callee->highest_osr_comp_level() == CompLevel_full_optimization;
659 }
660 return false;
661 }
662
663 // Create MDO if necessary.
create_mdo(const methodHandle & mh,JavaThread * THREAD)664 void TieredThresholdPolicy::create_mdo(const methodHandle& mh, JavaThread* THREAD) {
665 if (mh->is_native() ||
666 mh->is_abstract() ||
667 mh->is_accessor() ||
668 mh->is_constant_getter()) {
669 return;
670 }
671 if (mh->method_data() == NULL) {
672 Method::build_interpreter_method_data(mh, CHECK_AND_CLEAR);
673 }
674 }
675
676
677 /*
678 * Method states:
679 * 0 - interpreter (CompLevel_none)
680 * 1 - pure C1 (CompLevel_simple)
681 * 2 - C1 with invocation and backedge counting (CompLevel_limited_profile)
682 * 3 - C1 with full profiling (CompLevel_full_profile)
683 * 4 - C2 (CompLevel_full_optimization)
684 *
685 * Common state transition patterns:
686 * a. 0 -> 3 -> 4.
687 * The most common path. But note that even in this straightforward case
688 * profiling can start at level 0 and finish at level 3.
689 *
690 * b. 0 -> 2 -> 3 -> 4.
691 * This case occurs when the load on C2 is deemed too high. So, instead of transitioning
692 * into state 3 directly and over-profiling while a method is in the C2 queue we transition to
693 * level 2 and wait until the load on C2 decreases. This path is disabled for OSRs.
694 *
695 * c. 0 -> (3->2) -> 4.
696 * In this case we enqueue a method for compilation at level 3, but the C1 queue is long enough
697 * to enable the profiling to fully occur at level 0. In this case we change the compilation level
698 * of the method to 2 while the request is still in-queue, because it'll allow it to run much faster
699 * without full profiling while c2 is compiling.
700 *
701 * d. 0 -> 3 -> 1 or 0 -> 2 -> 1.
702 * After a method was once compiled with C1 it can be identified as trivial and be compiled to
703 * level 1. These transition can also occur if a method can't be compiled with C2 but can with C1.
704 *
705 * e. 0 -> 4.
706 * This can happen if a method fails C1 compilation (it will still be profiled in the interpreter)
707 * or because of a deopt that didn't require reprofiling (compilation won't happen in this case because
708 * the compiled version already exists).
709 *
710 * Note that since state 0 can be reached from any other state via deoptimization different loops
711 * are possible.
712 *
713 */
714
715 // Common transition function. Given a predicate determines if a method should transition to another level.
common(Predicate p,Method * method,CompLevel cur_level,bool disable_feedback)716 CompLevel TieredThresholdPolicy::common(Predicate p, Method* method, CompLevel cur_level, bool disable_feedback) {
717 CompLevel next_level = cur_level;
718 int i = method->invocation_count();
719 int b = method->backedge_count();
720
721 if (is_trivial(method)) {
722 next_level = CompLevel_simple;
723 } else {
724 switch(cur_level) {
725 default: break;
726 case CompLevel_aot: {
727 // If we were at full profile level, would we switch to full opt?
728 if (common(p, method, CompLevel_full_profile, disable_feedback) == CompLevel_full_optimization) {
729 next_level = CompLevel_full_optimization;
730 } else if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
731 Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
732 (this->*p)(i, b, cur_level, method))) {
733 next_level = CompLevel_full_profile;
734 }
735 }
736 break;
737 case CompLevel_none:
738 // If we were at full profile level, would we switch to full opt?
739 if (common(p, method, CompLevel_full_profile, disable_feedback) == CompLevel_full_optimization) {
740 next_level = CompLevel_full_optimization;
741 } else if ((this->*p)(i, b, cur_level, method)) {
742 #if INCLUDE_JVMCI
743 if (EnableJVMCI && UseJVMCICompiler) {
744 // Since JVMCI takes a while to warm up, its queue inevitably backs up during
745 // early VM execution. As of 2014-06-13, JVMCI's inliner assumes that the root
746 // compilation method and all potential inlinees have mature profiles (which
747 // includes type profiling). If it sees immature profiles, JVMCI's inliner
748 // can perform pathologically bad (e.g., causing OutOfMemoryErrors due to
749 // exploring/inlining too many graphs). Since a rewrite of the inliner is
750 // in progress, we simply disable the dialing back heuristic for now and will
751 // revisit this decision once the new inliner is completed.
752 next_level = CompLevel_full_profile;
753 } else
754 #endif
755 {
756 // C1-generated fully profiled code is about 30% slower than the limited profile
757 // code that has only invocation and backedge counters. The observation is that
758 // if C2 queue is large enough we can spend too much time in the fully profiled code
759 // while waiting for C2 to pick the method from the queue. To alleviate this problem
760 // we introduce a feedback on the C2 queue size. If the C2 queue is sufficiently long
761 // we choose to compile a limited profiled version and then recompile with full profiling
762 // when the load on C2 goes down.
763 if (!disable_feedback && CompileBroker::queue_size(CompLevel_full_optimization) >
764 Tier3DelayOn * compiler_count(CompLevel_full_optimization)) {
765 next_level = CompLevel_limited_profile;
766 } else {
767 next_level = CompLevel_full_profile;
768 }
769 }
770 }
771 break;
772 case CompLevel_limited_profile:
773 if (is_method_profiled(method)) {
774 // Special case: we got here because this method was fully profiled in the interpreter.
775 next_level = CompLevel_full_optimization;
776 } else {
777 MethodData* mdo = method->method_data();
778 if (mdo != NULL) {
779 if (mdo->would_profile()) {
780 if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
781 Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
782 (this->*p)(i, b, cur_level, method))) {
783 next_level = CompLevel_full_profile;
784 }
785 } else {
786 next_level = CompLevel_full_optimization;
787 }
788 } else {
789 // If there is no MDO we need to profile
790 if (disable_feedback || (CompileBroker::queue_size(CompLevel_full_optimization) <=
791 Tier3DelayOff * compiler_count(CompLevel_full_optimization) &&
792 (this->*p)(i, b, cur_level, method))) {
793 next_level = CompLevel_full_profile;
794 }
795 }
796 }
797 break;
798 case CompLevel_full_profile:
799 {
800 MethodData* mdo = method->method_data();
801 if (mdo != NULL) {
802 if (mdo->would_profile()) {
803 int mdo_i = mdo->invocation_count_delta();
804 int mdo_b = mdo->backedge_count_delta();
805 if ((this->*p)(mdo_i, mdo_b, cur_level, method)) {
806 next_level = CompLevel_full_optimization;
807 }
808 } else {
809 next_level = CompLevel_full_optimization;
810 }
811 }
812 }
813 break;
814 }
815 }
816 return MIN2(next_level, (CompLevel)TieredStopAtLevel);
817 }
818
819 // Determine if a method should be compiled with a normal entry point at a different level.
call_event(Method * method,CompLevel cur_level,JavaThread * thread)820 CompLevel TieredThresholdPolicy::call_event(Method* method, CompLevel cur_level, JavaThread * thread) {
821 CompLevel osr_level = MIN2((CompLevel) method->highest_osr_comp_level(),
822 common(&TieredThresholdPolicy::loop_predicate, method, cur_level, true));
823 CompLevel next_level = common(&TieredThresholdPolicy::call_predicate, method, cur_level);
824
825 // If OSR method level is greater than the regular method level, the levels should be
826 // equalized by raising the regular method level in order to avoid OSRs during each
827 // invocation of the method.
828 if (osr_level == CompLevel_full_optimization && cur_level == CompLevel_full_profile) {
829 MethodData* mdo = method->method_data();
830 guarantee(mdo != NULL, "MDO should not be NULL");
831 if (mdo->invocation_count() >= 1) {
832 next_level = CompLevel_full_optimization;
833 }
834 } else {
835 next_level = MAX2(osr_level, next_level);
836 }
837 #if INCLUDE_JVMCI
838 if (UseJVMCICompiler) {
839 next_level = JVMCIRuntime::adjust_comp_level(method, false, next_level, thread);
840 }
841 #endif
842 return next_level;
843 }
844
845 // Determine if we should do an OSR compilation of a given method.
loop_event(Method * method,CompLevel cur_level,JavaThread * thread)846 CompLevel TieredThresholdPolicy::loop_event(Method* method, CompLevel cur_level, JavaThread* thread) {
847 CompLevel next_level = common(&TieredThresholdPolicy::loop_predicate, method, cur_level, true);
848 if (cur_level == CompLevel_none) {
849 // If there is a live OSR method that means that we deopted to the interpreter
850 // for the transition.
851 CompLevel osr_level = MIN2((CompLevel)method->highest_osr_comp_level(), next_level);
852 if (osr_level > CompLevel_none) {
853 return osr_level;
854 }
855 }
856 #if INCLUDE_JVMCI
857 if (UseJVMCICompiler) {
858 next_level = JVMCIRuntime::adjust_comp_level(method, true, next_level, thread);
859 }
860 #endif
861 return next_level;
862 }
863
maybe_switch_to_aot(const methodHandle & mh,CompLevel cur_level,CompLevel next_level,JavaThread * thread)864 bool TieredThresholdPolicy::maybe_switch_to_aot(const methodHandle& mh, CompLevel cur_level, CompLevel next_level, JavaThread* thread) {
865 if (UseAOT && !delay_compilation_during_startup()) {
866 if (cur_level == CompLevel_full_profile || cur_level == CompLevel_none) {
867 // If the current level is full profile or interpreter and we're switching to any other level,
868 // activate the AOT code back first so that we won't waste time overprofiling.
869 compile(mh, InvocationEntryBci, CompLevel_aot, thread);
870 // Fall through for JIT compilation.
871 }
872 if (next_level == CompLevel_limited_profile && cur_level != CompLevel_aot && mh->has_aot_code()) {
873 // If the next level is limited profile, use the aot code (if there is any),
874 // since it's essentially the same thing.
875 compile(mh, InvocationEntryBci, CompLevel_aot, thread);
876 // Not need to JIT, we're done.
877 return true;
878 }
879 }
880 return false;
881 }
882
883
884 // Handle the invocation event.
method_invocation_event(const methodHandle & mh,const methodHandle & imh,CompLevel level,CompiledMethod * nm,JavaThread * thread)885 void TieredThresholdPolicy::method_invocation_event(const methodHandle& mh, const methodHandle& imh,
886 CompLevel level, CompiledMethod* nm, JavaThread* thread) {
887 if (should_create_mdo(mh(), level)) {
888 create_mdo(mh, thread);
889 }
890 CompLevel next_level = call_event(mh(), level, thread);
891 if (next_level != level) {
892 if (maybe_switch_to_aot(mh, level, next_level, thread)) {
893 // No JITting necessary
894 return;
895 }
896 if (is_compilation_enabled() && !CompileBroker::compilation_is_in_queue(mh)) {
897 compile(mh, InvocationEntryBci, next_level, thread);
898 }
899 }
900 }
901
902 // Handle the back branch event. Notice that we can compile the method
903 // with a regular entry from here.
method_back_branch_event(const methodHandle & mh,const methodHandle & imh,int bci,CompLevel level,CompiledMethod * nm,JavaThread * thread)904 void TieredThresholdPolicy::method_back_branch_event(const methodHandle& mh, const methodHandle& imh,
905 int bci, CompLevel level, CompiledMethod* nm, JavaThread* thread) {
906 if (should_create_mdo(mh(), level)) {
907 create_mdo(mh, thread);
908 }
909 // Check if MDO should be created for the inlined method
910 if (should_create_mdo(imh(), level)) {
911 create_mdo(imh, thread);
912 }
913
914 if (is_compilation_enabled()) {
915 CompLevel next_osr_level = loop_event(imh(), level, thread);
916 CompLevel max_osr_level = (CompLevel)imh->highest_osr_comp_level();
917 // At the very least compile the OSR version
918 if (!CompileBroker::compilation_is_in_queue(imh) && (next_osr_level != level)) {
919 compile(imh, bci, next_osr_level, thread);
920 }
921
922 // Use loop event as an opportunity to also check if there's been
923 // enough calls.
924 CompLevel cur_level, next_level;
925 if (mh() != imh()) { // If there is an enclosing method
926 if (level == CompLevel_aot) {
927 // Recompile the enclosing method to prevent infinite OSRs. Stay at AOT level while it's compiling.
928 if (max_osr_level != CompLevel_none && !CompileBroker::compilation_is_in_queue(mh)) {
929 compile(mh, InvocationEntryBci, MIN2((CompLevel)TieredStopAtLevel, CompLevel_full_profile), thread);
930 }
931 } else {
932 // Current loop event level is not AOT
933 guarantee(nm != NULL, "Should have nmethod here");
934 cur_level = comp_level(mh());
935 next_level = call_event(mh(), cur_level, thread);
936
937 if (max_osr_level == CompLevel_full_optimization) {
938 // The inlinee OSRed to full opt, we need to modify the enclosing method to avoid deopts
939 bool make_not_entrant = false;
940 if (nm->is_osr_method()) {
941 // This is an osr method, just make it not entrant and recompile later if needed
942 make_not_entrant = true;
943 } else {
944 if (next_level != CompLevel_full_optimization) {
945 // next_level is not full opt, so we need to recompile the
946 // enclosing method without the inlinee
947 cur_level = CompLevel_none;
948 make_not_entrant = true;
949 }
950 }
951 if (make_not_entrant) {
952 if (PrintTieredEvents) {
953 int osr_bci = nm->is_osr_method() ? nm->osr_entry_bci() : InvocationEntryBci;
954 print_event(MAKE_NOT_ENTRANT, mh(), mh(), osr_bci, level);
955 }
956 nm->make_not_entrant();
957 }
958 }
959 // Fix up next_level if necessary to avoid deopts
960 if (next_level == CompLevel_limited_profile && max_osr_level == CompLevel_full_profile) {
961 next_level = CompLevel_full_profile;
962 }
963 if (cur_level != next_level) {
964 if (!maybe_switch_to_aot(mh, cur_level, next_level, thread) && !CompileBroker::compilation_is_in_queue(mh)) {
965 compile(mh, InvocationEntryBci, next_level, thread);
966 }
967 }
968 }
969 } else {
970 cur_level = comp_level(mh());
971 next_level = call_event(mh(), cur_level, thread);
972 if (next_level != cur_level) {
973 if (!maybe_switch_to_aot(mh, cur_level, next_level, thread) && !CompileBroker::compilation_is_in_queue(mh)) {
974 compile(mh, InvocationEntryBci, next_level, thread);
975 }
976 }
977 }
978 }
979 }
980
981 #endif
982