Fri, 03 Sep 2010 17:51:07 -0700
6953144: Tiered compilation
Summary: Infrastructure for tiered compilation support (interpreter + c1 + c2) for 32 and 64 bit. Simple tiered policy implementation.
Reviewed-by: kvn, never, phh, twisti
1 /*
2 * Copyright (c) 2000, 2010, 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 */
25 # include "incls/_precompiled.incl"
26 # include "incls/_compilationPolicy.cpp.incl"
28 CompilationPolicy* CompilationPolicy::_policy;
29 elapsedTimer CompilationPolicy::_accumulated_time;
30 bool CompilationPolicy::_in_vm_startup;
32 // Determine compilation policy based on command line argument
33 void compilationPolicy_init() {
34 CompilationPolicy::set_in_vm_startup(DelayCompilationDuringStartup);
36 switch(CompilationPolicyChoice) {
37 case 0:
38 CompilationPolicy::set_policy(new SimpleCompPolicy());
39 break;
41 case 1:
42 #ifdef COMPILER2
43 CompilationPolicy::set_policy(new StackWalkCompPolicy());
44 #else
45 Unimplemented();
46 #endif
47 break;
48 case 2:
49 #ifdef TIERED
50 CompilationPolicy::set_policy(new SimpleThresholdPolicy());
51 #else
52 Unimplemented();
53 #endif
54 break;
55 default:
56 fatal("CompilationPolicyChoice must be in the range: [0-2]");
57 }
58 CompilationPolicy::policy()->initialize();
59 }
61 void CompilationPolicy::completed_vm_startup() {
62 if (TraceCompilationPolicy) {
63 tty->print("CompilationPolicy: completed vm startup.\n");
64 }
65 _in_vm_startup = false;
66 }
68 // Returns true if m must be compiled before executing it
69 // This is intended to force compiles for methods (usually for
70 // debugging) that would otherwise be interpreted for some reason.
71 bool CompilationPolicy::must_be_compiled(methodHandle m, int comp_level) {
72 if (m->has_compiled_code()) return false; // already compiled
73 if (!can_be_compiled(m, comp_level)) return false;
75 return !UseInterpreter || // must compile all methods
76 (UseCompiler && AlwaysCompileLoopMethods && m->has_loops() && CompileBroker::should_compile_new_jobs()); // eagerly compile loop methods
77 }
79 // Returns true if m is allowed to be compiled
80 bool CompilationPolicy::can_be_compiled(methodHandle m, int comp_level) {
81 if (m->is_abstract()) return false;
82 if (DontCompileHugeMethods && m->code_size() > HugeMethodLimit) return false;
84 // Math intrinsics should never be compiled as this can lead to
85 // monotonicity problems because the interpreter will prefer the
86 // compiled code to the intrinsic version. This can't happen in
87 // production because the invocation counter can't be incremented
88 // but we shouldn't expose the system to this problem in testing
89 // modes.
90 if (!AbstractInterpreter::can_be_compiled(m)) {
91 return false;
92 }
93 if (comp_level == CompLevel_all) {
94 return !m->is_not_compilable(CompLevel_simple) && !m->is_not_compilable(CompLevel_full_optimization);
95 } else {
96 return !m->is_not_compilable(comp_level);
97 }
98 }
100 bool CompilationPolicy::is_compilation_enabled() {
101 // NOTE: CompileBroker::should_compile_new_jobs() checks for UseCompiler
102 return !delay_compilation_during_startup() && CompileBroker::should_compile_new_jobs();
103 }
105 #ifndef PRODUCT
106 void CompilationPolicy::print_time() {
107 tty->print_cr ("Accumulated compilationPolicy times:");
108 tty->print_cr ("---------------------------");
109 tty->print_cr (" Total: %3.3f sec.", _accumulated_time.seconds());
110 }
112 void NonTieredCompPolicy::trace_osr_completion(nmethod* osr_nm) {
113 if (TraceOnStackReplacement) {
114 if (osr_nm == NULL) tty->print_cr("compilation failed");
115 else tty->print_cr("nmethod " INTPTR_FORMAT, osr_nm);
116 }
117 }
118 #endif // !PRODUCT
120 void NonTieredCompPolicy::initialize() {
121 // Setup the compiler thread numbers
122 if (CICompilerCountPerCPU) {
123 // Example: if CICompilerCountPerCPU is true, then we get
124 // max(log2(8)-1,1) = 2 compiler threads on an 8-way machine.
125 // May help big-app startup time.
126 _compiler_count = MAX2(log2_intptr(os::active_processor_count())-1,1);
127 } else {
128 _compiler_count = CICompilerCount;
129 }
130 }
132 int NonTieredCompPolicy::compiler_count(CompLevel comp_level) {
133 #ifdef COMPILER1
134 if (is_c1_compile(comp_level)) {
135 return _compiler_count;
136 }
137 #endif
139 #ifdef COMPILER2
140 if (is_c2_compile(comp_level)) {
141 return _compiler_count;
142 }
143 #endif
145 return 0;
146 }
148 void NonTieredCompPolicy::reset_counter_for_invocation_event(methodHandle m) {
149 // Make sure invocation and backedge counter doesn't overflow again right away
150 // as would be the case for native methods.
152 // BUT also make sure the method doesn't look like it was never executed.
153 // Set carry bit and reduce counter's value to min(count, CompileThreshold/2).
154 m->invocation_counter()->set_carry();
155 m->backedge_counter()->set_carry();
157 assert(!m->was_never_executed(), "don't reset to 0 -- could be mistaken for never-executed");
158 }
160 void NonTieredCompPolicy::reset_counter_for_back_branch_event(methodHandle m) {
161 // Delay next back-branch event but pump up invocation counter to triger
162 // whole method compilation.
163 InvocationCounter* i = m->invocation_counter();
164 InvocationCounter* b = m->backedge_counter();
166 // Don't set invocation_counter's value too low otherwise the method will
167 // look like immature (ic < ~5300) which prevents the inlining based on
168 // the type profiling.
169 i->set(i->state(), CompileThreshold);
170 // Don't reset counter too low - it is used to check if OSR method is ready.
171 b->set(b->state(), CompileThreshold / 2);
172 }
174 //
175 // CounterDecay
176 //
177 // Interates through invocation counters and decrements them. This
178 // is done at each safepoint.
179 //
180 class CounterDecay : public AllStatic {
181 static jlong _last_timestamp;
182 static void do_method(methodOop m) {
183 m->invocation_counter()->decay();
184 }
185 public:
186 static void decay();
187 static bool is_decay_needed() {
188 return (os::javaTimeMillis() - _last_timestamp) > CounterDecayMinIntervalLength;
189 }
190 };
192 jlong CounterDecay::_last_timestamp = 0;
194 void CounterDecay::decay() {
195 _last_timestamp = os::javaTimeMillis();
197 // This operation is going to be performed only at the end of a safepoint
198 // and hence GC's will not be going on, all Java mutators are suspended
199 // at this point and hence SystemDictionary_lock is also not needed.
200 assert(SafepointSynchronize::is_at_safepoint(), "can only be executed at a safepoint");
201 int nclasses = SystemDictionary::number_of_classes();
202 double classes_per_tick = nclasses * (CounterDecayMinIntervalLength * 1e-3 /
203 CounterHalfLifeTime);
204 for (int i = 0; i < classes_per_tick; i++) {
205 klassOop k = SystemDictionary::try_get_next_class();
206 if (k != NULL && k->klass_part()->oop_is_instance()) {
207 instanceKlass::cast(k)->methods_do(do_method);
208 }
209 }
210 }
212 // Called at the end of the safepoint
213 void NonTieredCompPolicy::do_safepoint_work() {
214 if(UseCounterDecay && CounterDecay::is_decay_needed()) {
215 CounterDecay::decay();
216 }
217 }
219 void NonTieredCompPolicy::reprofile(ScopeDesc* trap_scope, bool is_osr) {
220 ScopeDesc* sd = trap_scope;
221 for (; !sd->is_top(); sd = sd->sender()) {
222 // Reset ICs of inlined methods, since they can trigger compilations also.
223 sd->method()->invocation_counter()->reset();
224 }
225 InvocationCounter* c = sd->method()->invocation_counter();
226 if (is_osr) {
227 // It was an OSR method, so bump the count higher.
228 c->set(c->state(), CompileThreshold);
229 } else {
230 c->reset();
231 }
232 sd->method()->backedge_counter()->reset();
233 }
235 // This method can be called by any component of the runtime to notify the policy
236 // that it's recommended to delay the complation of this method.
237 void NonTieredCompPolicy::delay_compilation(methodOop method) {
238 method->invocation_counter()->decay();
239 method->backedge_counter()->decay();
240 }
242 void NonTieredCompPolicy::disable_compilation(methodOop method) {
243 method->invocation_counter()->set_state(InvocationCounter::wait_for_nothing);
244 method->backedge_counter()->set_state(InvocationCounter::wait_for_nothing);
245 }
247 CompileTask* NonTieredCompPolicy::select_task(CompileQueue* compile_queue) {
248 return compile_queue->first();
249 }
251 bool NonTieredCompPolicy::is_mature(methodOop method) {
252 methodDataOop mdo = method->method_data();
253 assert(mdo != NULL, "Should be");
254 uint current = mdo->mileage_of(method);
255 uint initial = mdo->creation_mileage();
256 if (current < initial)
257 return true; // some sort of overflow
258 uint target;
259 if (ProfileMaturityPercentage <= 0)
260 target = (uint) -ProfileMaturityPercentage; // absolute value
261 else
262 target = (uint)( (ProfileMaturityPercentage * CompileThreshold) / 100 );
263 return (current >= initial + target);
264 }
266 nmethod* NonTieredCompPolicy::event(methodHandle method, methodHandle inlinee, int branch_bci, int bci, CompLevel comp_level, TRAPS) {
267 assert(comp_level == CompLevel_none, "This should be only called from the interpreter");
268 NOT_PRODUCT(trace_frequency_counter_overflow(method, branch_bci, bci));
269 if (JvmtiExport::can_post_interpreter_events()) {
270 assert(THREAD->is_Java_thread(), "Wrong type of thread");
271 if (((JavaThread*)THREAD)->is_interp_only_mode()) {
272 // If certain JVMTI events (e.g. frame pop event) are requested then the
273 // thread is forced to remain in interpreted code. This is
274 // implemented partly by a check in the run_compiled_code
275 // section of the interpreter whether we should skip running
276 // compiled code, and partly by skipping OSR compiles for
277 // interpreted-only threads.
278 if (bci != InvocationEntryBci) {
279 reset_counter_for_back_branch_event(method);
280 return NULL;
281 }
282 }
283 }
284 if (bci == InvocationEntryBci) {
285 // when code cache is full, compilation gets switched off, UseCompiler
286 // is set to false
287 if (!method->has_compiled_code() && UseCompiler) {
288 method_invocation_event(method, CHECK_NULL);
289 } else {
290 // Force counter overflow on method entry, even if no compilation
291 // happened. (The method_invocation_event call does this also.)
292 reset_counter_for_invocation_event(method);
293 }
294 // compilation at an invocation overflow no longer goes and retries test for
295 // compiled method. We always run the loser of the race as interpreted.
296 // so return NULL
297 return NULL;
298 } else {
299 // counter overflow in a loop => try to do on-stack-replacement
300 nmethod* osr_nm = method->lookup_osr_nmethod_for(bci, CompLevel_highest_tier, true);
301 NOT_PRODUCT(trace_osr_request(method, osr_nm, bci));
302 // when code cache is full, we should not compile any more...
303 if (osr_nm == NULL && UseCompiler) {
304 method_back_branch_event(method, bci, CHECK_NULL);
305 osr_nm = method->lookup_osr_nmethod_for(bci, CompLevel_highest_tier, true);
306 }
307 if (osr_nm == NULL) {
308 reset_counter_for_back_branch_event(method);
309 return NULL;
310 }
311 return osr_nm;
312 }
313 return NULL;
314 }
316 #ifndef PRODUCT
317 void NonTieredCompPolicy::trace_frequency_counter_overflow(methodHandle m, int branch_bci, int bci) {
318 if (TraceInvocationCounterOverflow) {
319 InvocationCounter* ic = m->invocation_counter();
320 InvocationCounter* bc = m->backedge_counter();
321 ResourceMark rm;
322 const char* msg =
323 bci == InvocationEntryBci
324 ? "comp-policy cntr ovfl @ %d in entry of "
325 : "comp-policy cntr ovfl @ %d in loop of ";
326 tty->print(msg, bci);
327 m->print_value();
328 tty->cr();
329 ic->print();
330 bc->print();
331 if (ProfileInterpreter) {
332 if (bci != InvocationEntryBci) {
333 methodDataOop mdo = m->method_data();
334 if (mdo != NULL) {
335 int count = mdo->bci_to_data(branch_bci)->as_JumpData()->taken();
336 tty->print_cr("back branch count = %d", count);
337 }
338 }
339 }
340 }
341 }
343 void NonTieredCompPolicy::trace_osr_request(methodHandle method, nmethod* osr, int bci) {
344 if (TraceOnStackReplacement) {
345 ResourceMark rm;
346 tty->print(osr != NULL ? "Reused OSR entry for " : "Requesting OSR entry for ");
347 method->print_short_name(tty);
348 tty->print_cr(" at bci %d", bci);
349 }
350 }
351 #endif // !PRODUCT
353 // SimpleCompPolicy - compile current method
355 void SimpleCompPolicy::method_invocation_event( methodHandle m, TRAPS) {
356 assert(UseCompiler || CompileTheWorld, "UseCompiler should be set by now.");
358 int hot_count = m->invocation_count();
359 reset_counter_for_invocation_event(m);
360 const char* comment = "count";
362 if (is_compilation_enabled() && can_be_compiled(m)) {
363 nmethod* nm = m->code();
364 if (nm == NULL ) {
365 const char* comment = "count";
366 CompileBroker::compile_method(m, InvocationEntryBci, CompLevel_highest_tier,
367 m, hot_count, comment, CHECK);
368 }
369 }
370 }
372 void SimpleCompPolicy::method_back_branch_event(methodHandle m, int bci, TRAPS) {
373 assert(UseCompiler || CompileTheWorld, "UseCompiler should be set by now.");
375 int hot_count = m->backedge_count();
376 const char* comment = "backedge_count";
378 if (is_compilation_enabled() && !m->is_not_osr_compilable() && can_be_compiled(m)) {
379 CompileBroker::compile_method(m, bci, CompLevel_highest_tier,
380 m, hot_count, comment, CHECK);
381 NOT_PRODUCT(trace_osr_completion(m->lookup_osr_nmethod_for(bci, CompLevel_highest_tier, true));)
382 }
383 }
384 // StackWalkCompPolicy - walk up stack to find a suitable method to compile
386 #ifdef COMPILER2
387 const char* StackWalkCompPolicy::_msg = NULL;
390 // Consider m for compilation
391 void StackWalkCompPolicy::method_invocation_event(methodHandle m, TRAPS) {
392 assert(UseCompiler || CompileTheWorld, "UseCompiler should be set by now.");
394 int hot_count = m->invocation_count();
395 reset_counter_for_invocation_event(m);
396 const char* comment = "count";
398 if (is_compilation_enabled() && m->code() == NULL && can_be_compiled(m)) {
399 ResourceMark rm(THREAD);
400 JavaThread *thread = (JavaThread*)THREAD;
401 frame fr = thread->last_frame();
402 assert(fr.is_interpreted_frame(), "must be interpreted");
403 assert(fr.interpreter_frame_method() == m(), "bad method");
405 if (TraceCompilationPolicy) {
406 tty->print("method invocation trigger: ");
407 m->print_short_name(tty);
408 tty->print(" ( interpreted " INTPTR_FORMAT ", size=%d ) ", (address)m(), m->code_size());
409 }
410 RegisterMap reg_map(thread, false);
411 javaVFrame* triggerVF = thread->last_java_vframe(®_map);
412 // triggerVF is the frame that triggered its counter
413 RFrame* first = new InterpretedRFrame(triggerVF->fr(), thread, m);
415 if (first->top_method()->code() != NULL) {
416 // called obsolete method/nmethod -- no need to recompile
417 if (TraceCompilationPolicy) tty->print_cr(" --> " INTPTR_FORMAT, first->top_method()->code());
418 } else {
419 if (TimeCompilationPolicy) accumulated_time()->start();
420 GrowableArray<RFrame*>* stack = new GrowableArray<RFrame*>(50);
421 stack->push(first);
422 RFrame* top = findTopInlinableFrame(stack);
423 if (TimeCompilationPolicy) accumulated_time()->stop();
424 assert(top != NULL, "findTopInlinableFrame returned null");
425 if (TraceCompilationPolicy) top->print();
426 CompileBroker::compile_method(top->top_method(), InvocationEntryBci, CompLevel_highest_tier,
427 m, hot_count, comment, CHECK);
428 }
429 }
430 }
432 void StackWalkCompPolicy::method_back_branch_event(methodHandle m, int bci, TRAPS) {
433 assert(UseCompiler || CompileTheWorld, "UseCompiler should be set by now.");
435 int hot_count = m->backedge_count();
436 const char* comment = "backedge_count";
438 if (is_compilation_enabled() && !m->is_not_osr_compilable() && can_be_compiled(m)) {
439 CompileBroker::compile_method(m, bci, CompLevel_highest_tier, m, hot_count, comment, CHECK);
441 NOT_PRODUCT(trace_osr_completion(m->lookup_osr_nmethod_for(bci, CompLevel_highest_tier, true));)
442 }
443 }
445 RFrame* StackWalkCompPolicy::findTopInlinableFrame(GrowableArray<RFrame*>* stack) {
446 // go up the stack until finding a frame that (probably) won't be inlined
447 // into its caller
448 RFrame* current = stack->at(0); // current choice for stopping
449 assert( current && !current->is_compiled(), "" );
450 const char* msg = NULL;
452 while (1) {
454 // before going up the stack further, check if doing so would get us into
455 // compiled code
456 RFrame* next = senderOf(current, stack);
457 if( !next ) // No next frame up the stack?
458 break; // Then compile with current frame
460 methodHandle m = current->top_method();
461 methodHandle next_m = next->top_method();
463 if (TraceCompilationPolicy && Verbose) {
464 tty->print("[caller: ");
465 next_m->print_short_name(tty);
466 tty->print("] ");
467 }
469 if( !Inline ) { // Inlining turned off
470 msg = "Inlining turned off";
471 break;
472 }
473 if (next_m->is_not_compilable()) { // Did fail to compile this before/
474 msg = "caller not compilable";
475 break;
476 }
477 if (next->num() > MaxRecompilationSearchLength) {
478 // don't go up too high when searching for recompilees
479 msg = "don't go up any further: > MaxRecompilationSearchLength";
480 break;
481 }
482 if (next->distance() > MaxInterpretedSearchLength) {
483 // don't go up too high when searching for recompilees
484 msg = "don't go up any further: next > MaxInterpretedSearchLength";
485 break;
486 }
487 // Compiled frame above already decided not to inline;
488 // do not recompile him.
489 if (next->is_compiled()) {
490 msg = "not going up into optimized code";
491 break;
492 }
494 // Interpreted frame above us was already compiled. Do not force
495 // a recompile, although if the frame above us runs long enough an
496 // OSR might still happen.
497 if( current->is_interpreted() && next_m->has_compiled_code() ) {
498 msg = "not going up -- already compiled caller";
499 break;
500 }
502 // Compute how frequent this call site is. We have current method 'm'.
503 // We know next method 'next_m' is interpreted. Find the call site and
504 // check the various invocation counts.
505 int invcnt = 0; // Caller counts
506 if (ProfileInterpreter) {
507 invcnt = next_m->interpreter_invocation_count();
508 }
509 int cnt = 0; // Call site counts
510 if (ProfileInterpreter && next_m->method_data() != NULL) {
511 ResourceMark rm;
512 int bci = next->top_vframe()->bci();
513 ProfileData* data = next_m->method_data()->bci_to_data(bci);
514 if (data != NULL && data->is_CounterData())
515 cnt = data->as_CounterData()->count();
516 }
518 // Caller counts / call-site counts; i.e. is this call site
519 // a hot call site for method next_m?
520 int freq = (invcnt) ? cnt/invcnt : cnt;
522 // Check size and frequency limits
523 if ((msg = shouldInline(m, freq, cnt)) != NULL) {
524 break;
525 }
526 // Check inlining negative tests
527 if ((msg = shouldNotInline(m)) != NULL) {
528 break;
529 }
532 // If the caller method is too big or something then we do not want to
533 // compile it just to inline a method
534 if (!can_be_compiled(next_m)) {
535 msg = "caller cannot be compiled";
536 break;
537 }
539 if( next_m->name() == vmSymbols::class_initializer_name() ) {
540 msg = "do not compile class initializer (OSR ok)";
541 break;
542 }
544 if (TraceCompilationPolicy && Verbose) {
545 tty->print("\n\t check caller: ");
546 next_m->print_short_name(tty);
547 tty->print(" ( interpreted " INTPTR_FORMAT ", size=%d ) ", (address)next_m(), next_m->code_size());
548 }
550 current = next;
551 }
553 assert( !current || !current->is_compiled(), "" );
555 if (TraceCompilationPolicy && msg) tty->print("(%s)\n", msg);
557 return current;
558 }
560 RFrame* StackWalkCompPolicy::senderOf(RFrame* rf, GrowableArray<RFrame*>* stack) {
561 RFrame* sender = rf->caller();
562 if (sender && sender->num() == stack->length()) stack->push(sender);
563 return sender;
564 }
567 const char* StackWalkCompPolicy::shouldInline(methodHandle m, float freq, int cnt) {
568 // Allows targeted inlining
569 // positive filter: should send be inlined? returns NULL (--> yes)
570 // or rejection msg
571 int max_size = MaxInlineSize;
572 int cost = m->code_size();
574 // Check for too many throws (and not too huge)
575 if (m->interpreter_throwout_count() > InlineThrowCount && cost < InlineThrowMaxSize ) {
576 return NULL;
577 }
579 // bump the max size if the call is frequent
580 if ((freq >= InlineFrequencyRatio) || (cnt >= InlineFrequencyCount)) {
581 if (TraceFrequencyInlining) {
582 tty->print("(Inlined frequent method)\n");
583 m->print();
584 }
585 max_size = FreqInlineSize;
586 }
587 if (cost > max_size) {
588 return (_msg = "too big");
589 }
590 return NULL;
591 }
594 const char* StackWalkCompPolicy::shouldNotInline(methodHandle m) {
595 // negative filter: should send NOT be inlined? returns NULL (--> inline) or rejection msg
596 if (m->is_abstract()) return (_msg = "abstract method");
597 // note: we allow ik->is_abstract()
598 if (!instanceKlass::cast(m->method_holder())->is_initialized()) return (_msg = "method holder not initialized");
599 if (m->is_native()) return (_msg = "native method");
600 nmethod* m_code = m->code();
601 if (m_code != NULL && m_code->code_size() > InlineSmallCode)
602 return (_msg = "already compiled into a big method");
604 // use frequency-based objections only for non-trivial methods
605 if (m->code_size() <= MaxTrivialSize) return NULL;
606 if (UseInterpreter) { // don't use counts with -Xcomp
607 if ((m->code() == NULL) && m->was_never_executed()) return (_msg = "never executed");
608 if (!m->was_executed_more_than(MIN2(MinInliningThreshold, CompileThreshold >> 1))) return (_msg = "executed < MinInliningThreshold times");
609 }
610 if (methodOopDesc::has_unloaded_classes_in_signature(m, JavaThread::current())) return (_msg = "unloaded signature classes");
612 return NULL;
613 }
617 #endif // COMPILER2