c1_Compilation.cpp revision 9111:a41fe5ffa839
1/*
2 * Copyright (c) 1999, 2015, 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 "c1/c1_CFGPrinter.hpp"
27#include "c1/c1_Compilation.hpp"
28#include "c1/c1_IR.hpp"
29#include "c1/c1_LIRAssembler.hpp"
30#include "c1/c1_LinearScan.hpp"
31#include "c1/c1_MacroAssembler.hpp"
32#include "c1/c1_RangeCheckElimination.hpp"
33#include "c1/c1_ValueMap.hpp"
34#include "c1/c1_ValueStack.hpp"
35#include "code/debugInfoRec.hpp"
36#include "compiler/compileLog.hpp"
37#include "runtime/sharedRuntime.hpp"
38
39typedef enum {
40  _t_compile,
41    _t_setup,
42    _t_buildIR,
43      _t_hir_parse,
44      _t_gvn,
45      _t_optimize_blocks,
46      _t_optimize_null_checks,
47      _t_rangeCheckElimination,
48    _t_emit_lir,
49      _t_linearScan,
50      _t_lirGeneration,
51    _t_codeemit,
52    _t_codeinstall,
53  max_phase_timers
54} TimerName;
55
56static const char * timer_name[] = {
57  "compile",
58  "setup",
59  "buildIR",
60  "parse_hir",
61  "gvn",
62  "optimize_blocks",
63  "optimize_null_checks",
64  "rangeCheckElimination",
65  "emit_lir",
66  "linearScan",
67  "lirGeneration",
68  "codeemit",
69  "codeinstall"
70};
71
72static elapsedTimer timers[max_phase_timers];
73static int totalInstructionNodes = 0;
74
75class PhaseTraceTime: public TraceTime {
76 private:
77  JavaThread* _thread;
78  CompileLog* _log;
79  TimerName _timer;
80
81 public:
82  PhaseTraceTime(TimerName timer)
83  : TraceTime("", &timers[timer], CITime || CITimeEach, Verbose),
84    _log(NULL), _timer(timer)
85  {
86    if (Compilation::current() != NULL) {
87      _log = Compilation::current()->log();
88    }
89
90    if (_log != NULL) {
91      _log->begin_head("phase name='%s'", timer_name[_timer]);
92      _log->stamp();
93      _log->end_head();
94    }
95  }
96
97  ~PhaseTraceTime() {
98    if (_log != NULL)
99      _log->done("phase name='%s'", timer_name[_timer]);
100  }
101};
102
103// Implementation of Compilation
104
105
106#ifndef PRODUCT
107
108void Compilation::maybe_print_current_instruction() {
109  if (_current_instruction != NULL && _last_instruction_printed != _current_instruction) {
110    _last_instruction_printed = _current_instruction;
111    _current_instruction->print_line();
112  }
113}
114#endif // PRODUCT
115
116
117DebugInformationRecorder* Compilation::debug_info_recorder() const {
118  return _env->debug_info();
119}
120
121
122Dependencies* Compilation::dependency_recorder() const {
123  return _env->dependencies();
124}
125
126
127void Compilation::initialize() {
128  // Use an oop recorder bound to the CI environment.
129  // (The default oop recorder is ignorant of the CI.)
130  OopRecorder* ooprec = new OopRecorder(_env->arena());
131  _env->set_oop_recorder(ooprec);
132  _env->set_debug_info(new DebugInformationRecorder(ooprec));
133  debug_info_recorder()->set_oopmaps(new OopMapSet());
134  _env->set_dependencies(new Dependencies(_env));
135}
136
137
138void Compilation::build_hir() {
139  CHECK_BAILOUT();
140
141  // setup ir
142  CompileLog* log = this->log();
143  if (log != NULL) {
144    log->begin_head("parse method='%d' ",
145                    log->identify(_method));
146    log->stamp();
147    log->end_head();
148  }
149  {
150    PhaseTraceTime timeit(_t_hir_parse);
151    _hir = new IR(this, method(), osr_bci());
152  }
153  if (log)  log->done("parse");
154  if (!_hir->is_valid()) {
155    bailout("invalid parsing");
156    return;
157  }
158
159#ifndef PRODUCT
160  if (PrintCFGToFile) {
161    CFGPrinter::print_cfg(_hir, "After Generation of HIR", true, false);
162  }
163#endif
164
165#ifndef PRODUCT
166  if (PrintCFG || PrintCFG0) { tty->print_cr("CFG after parsing"); _hir->print(true); }
167  if (PrintIR  || PrintIR0 ) { tty->print_cr("IR after parsing"); _hir->print(false); }
168#endif
169
170  _hir->verify();
171
172  if (UseC1Optimizations) {
173    NEEDS_CLEANUP
174    // optimization
175    PhaseTraceTime timeit(_t_optimize_blocks);
176
177    _hir->optimize_blocks();
178  }
179
180  _hir->verify();
181
182  _hir->split_critical_edges();
183
184#ifndef PRODUCT
185  if (PrintCFG || PrintCFG1) { tty->print_cr("CFG after optimizations"); _hir->print(true); }
186  if (PrintIR  || PrintIR1 ) { tty->print_cr("IR after optimizations"); _hir->print(false); }
187#endif
188
189  _hir->verify();
190
191  // compute block ordering for code generation
192  // the control flow must not be changed from here on
193  _hir->compute_code();
194
195  if (UseGlobalValueNumbering) {
196    // No resource mark here! LoopInvariantCodeMotion can allocate ValueStack objects.
197    PhaseTraceTime timeit(_t_gvn);
198    int instructions = Instruction::number_of_instructions();
199    GlobalValueNumbering gvn(_hir);
200    assert(instructions == Instruction::number_of_instructions(),
201           "shouldn't have created an instructions");
202  }
203
204  _hir->verify();
205
206#ifndef PRODUCT
207  if (PrintCFGToFile) {
208    CFGPrinter::print_cfg(_hir, "Before RangeCheckElimination", true, false);
209  }
210#endif
211
212  if (RangeCheckElimination) {
213    if (_hir->osr_entry() == NULL) {
214      PhaseTraceTime timeit(_t_rangeCheckElimination);
215      RangeCheckElimination::eliminate(_hir);
216    }
217  }
218
219#ifndef PRODUCT
220  if (PrintCFGToFile) {
221    CFGPrinter::print_cfg(_hir, "After RangeCheckElimination", true, false);
222  }
223#endif
224
225  if (UseC1Optimizations) {
226    // loop invariant code motion reorders instructions and range
227    // check elimination adds new instructions so do null check
228    // elimination after.
229    NEEDS_CLEANUP
230    // optimization
231    PhaseTraceTime timeit(_t_optimize_null_checks);
232
233    _hir->eliminate_null_checks();
234  }
235
236  _hir->verify();
237
238  // compute use counts after global value numbering
239  _hir->compute_use_counts();
240
241#ifndef PRODUCT
242  if (PrintCFG || PrintCFG2) { tty->print_cr("CFG before code generation"); _hir->code()->print(true); }
243  if (PrintIR  || PrintIR2 ) { tty->print_cr("IR before code generation"); _hir->code()->print(false, true); }
244#endif
245
246  _hir->verify();
247}
248
249
250void Compilation::emit_lir() {
251  CHECK_BAILOUT();
252
253  LIRGenerator gen(this, method());
254  {
255    PhaseTraceTime timeit(_t_lirGeneration);
256    hir()->iterate_linear_scan_order(&gen);
257  }
258
259  CHECK_BAILOUT();
260
261  {
262    PhaseTraceTime timeit(_t_linearScan);
263
264    LinearScan* allocator = new LinearScan(hir(), &gen, frame_map());
265    set_allocator(allocator);
266    // Assign physical registers to LIR operands using a linear scan algorithm.
267    allocator->do_linear_scan();
268    CHECK_BAILOUT();
269
270    _max_spills = allocator->max_spills();
271  }
272
273  if (BailoutAfterLIR) {
274    if (PrintLIR && !bailed_out()) {
275      print_LIR(hir()->code());
276    }
277    bailout("Bailing out because of -XX:+BailoutAfterLIR");
278  }
279}
280
281
282void Compilation::emit_code_epilog(LIR_Assembler* assembler) {
283  CHECK_BAILOUT();
284
285  CodeOffsets* code_offsets = assembler->offsets();
286
287  // generate code or slow cases
288  assembler->emit_slow_case_stubs();
289  CHECK_BAILOUT();
290
291  // generate exception adapters
292  assembler->emit_exception_entries(exception_info_list());
293  CHECK_BAILOUT();
294
295  // Generate code for exception handler.
296  code_offsets->set_value(CodeOffsets::Exceptions, assembler->emit_exception_handler());
297  CHECK_BAILOUT();
298
299  // Generate code for deopt handler.
300  code_offsets->set_value(CodeOffsets::Deopt, assembler->emit_deopt_handler());
301  CHECK_BAILOUT();
302
303  // Emit the MethodHandle deopt handler code (if required).
304  if (has_method_handle_invokes()) {
305    // We can use the same code as for the normal deopt handler, we
306    // just need a different entry point address.
307    code_offsets->set_value(CodeOffsets::DeoptMH, assembler->emit_deopt_handler());
308    CHECK_BAILOUT();
309  }
310
311  // Emit the handler to remove the activation from the stack and
312  // dispatch to the caller.
313  offsets()->set_value(CodeOffsets::UnwindHandler, assembler->emit_unwind_handler());
314
315  // done
316  masm()->flush();
317}
318
319
320bool Compilation::setup_code_buffer(CodeBuffer* code, int call_stub_estimate) {
321  // Preinitialize the consts section to some large size:
322  int locs_buffer_size = 20 * (relocInfo::length_limit + sizeof(relocInfo));
323  char* locs_buffer = NEW_RESOURCE_ARRAY(char, locs_buffer_size);
324  code->insts()->initialize_shared_locs((relocInfo*)locs_buffer,
325                                        locs_buffer_size / sizeof(relocInfo));
326  code->initialize_consts_size(Compilation::desired_max_constant_size());
327  // Call stubs + two deopt handlers (regular and MH) + exception handler
328  int call_stub_size = LIR_Assembler::call_stub_size;
329  int stub_size = (call_stub_estimate * call_stub_size) +
330                   LIR_Assembler::exception_handler_size +
331                   (2 * LIR_Assembler::deopt_handler_size);
332  if (stub_size >= code->insts_capacity()) return false;
333  code->initialize_stubs_size(stub_size);
334  return true;
335}
336
337
338int Compilation::emit_code_body() {
339  // emit code
340  if (!setup_code_buffer(code(), allocator()->num_calls())) {
341    BAILOUT_("size requested greater than avail code buffer size", 0);
342  }
343  code()->initialize_oop_recorder(env()->oop_recorder());
344
345  _masm = new C1_MacroAssembler(code());
346  _masm->set_oop_recorder(env()->oop_recorder());
347
348  LIR_Assembler lir_asm(this);
349
350  lir_asm.emit_code(hir()->code());
351  CHECK_BAILOUT_(0);
352
353  emit_code_epilog(&lir_asm);
354  CHECK_BAILOUT_(0);
355
356  generate_exception_handler_table();
357
358#ifndef PRODUCT
359  if (PrintExceptionHandlers && Verbose) {
360    exception_handler_table()->print();
361  }
362#endif /* PRODUCT */
363
364  return frame_map()->framesize();
365}
366
367
368int Compilation::compile_java_method() {
369  assert(!method()->is_native(), "should not reach here");
370
371  if (BailoutOnExceptionHandlers) {
372    if (method()->has_exception_handlers()) {
373      bailout("linear scan can't handle exception handlers");
374    }
375  }
376
377  CHECK_BAILOUT_(no_frame_size);
378
379  if (is_profiling() && !method()->ensure_method_data()) {
380    BAILOUT_("mdo allocation failed", no_frame_size);
381  }
382
383  {
384    PhaseTraceTime timeit(_t_buildIR);
385    build_hir();
386  }
387  if (BailoutAfterHIR) {
388    BAILOUT_("Bailing out because of -XX:+BailoutAfterHIR", no_frame_size);
389  }
390
391
392  {
393    PhaseTraceTime timeit(_t_emit_lir);
394
395    _frame_map = new FrameMap(method(), hir()->number_of_locks(), MAX2(4, hir()->max_stack()));
396    emit_lir();
397  }
398  CHECK_BAILOUT_(no_frame_size);
399
400  {
401    PhaseTraceTime timeit(_t_codeemit);
402    return emit_code_body();
403  }
404}
405
406void Compilation::install_code(int frame_size) {
407  // frame_size is in 32-bit words so adjust it intptr_t words
408  assert(frame_size == frame_map()->framesize(), "must match");
409  assert(in_bytes(frame_map()->framesize_in_bytes()) % sizeof(intptr_t) == 0, "must be at least pointer aligned");
410  _env->register_method(
411    method(),
412    osr_bci(),
413    &_offsets,
414    in_bytes(_frame_map->sp_offset_for_orig_pc()),
415    code(),
416    in_bytes(frame_map()->framesize_in_bytes()) / sizeof(intptr_t),
417    debug_info_recorder()->_oopmaps,
418    exception_handler_table(),
419    implicit_exception_table(),
420    compiler(),
421    _env->comp_level(),
422    has_unsafe_access(),
423    SharedRuntime::is_wide_vector(max_vector_size())
424  );
425}
426
427
428void Compilation::compile_method() {
429  {
430    PhaseTraceTime timeit(_t_setup);
431
432    // setup compilation
433    initialize();
434  }
435
436  if (!method()->can_be_compiled()) {
437    // Prevent race condition 6328518.
438    // This can happen if the method is obsolete or breakpointed.
439    bailout("Bailing out because method is not compilable");
440    return;
441  }
442
443  if (_env->jvmti_can_hotswap_or_post_breakpoint()) {
444    // We can assert evol_method because method->can_be_compiled is true.
445    dependency_recorder()->assert_evol_method(method());
446  }
447
448  if (method()->break_at_execute()) {
449    BREAKPOINT;
450  }
451
452#ifndef PRODUCT
453  if (PrintCFGToFile) {
454    CFGPrinter::print_compilation(this);
455  }
456#endif
457
458  // compile method
459  int frame_size = compile_java_method();
460
461  // bailout if method couldn't be compiled
462  // Note: make sure we mark the method as not compilable!
463  CHECK_BAILOUT();
464
465  if (InstallMethods) {
466    // install code
467    PhaseTraceTime timeit(_t_codeinstall);
468    install_code(frame_size);
469  }
470
471  if (log() != NULL) // Print code cache state into compiler log
472    log()->code_cache_state();
473
474  totalInstructionNodes += Instruction::number_of_instructions();
475}
476
477
478void Compilation::generate_exception_handler_table() {
479  // Generate an ExceptionHandlerTable from the exception handler
480  // information accumulated during the compilation.
481  ExceptionInfoList* info_list = exception_info_list();
482
483  if (info_list->length() == 0) {
484    return;
485  }
486
487  // allocate some arrays for use by the collection code.
488  const int num_handlers = 5;
489  GrowableArray<intptr_t>* bcis = new GrowableArray<intptr_t>(num_handlers);
490  GrowableArray<intptr_t>* scope_depths = new GrowableArray<intptr_t>(num_handlers);
491  GrowableArray<intptr_t>* pcos = new GrowableArray<intptr_t>(num_handlers);
492
493  for (int i = 0; i < info_list->length(); i++) {
494    ExceptionInfo* info = info_list->at(i);
495    XHandlers* handlers = info->exception_handlers();
496
497    // empty the arrays
498    bcis->trunc_to(0);
499    scope_depths->trunc_to(0);
500    pcos->trunc_to(0);
501
502    for (int i = 0; i < handlers->length(); i++) {
503      XHandler* handler = handlers->handler_at(i);
504      assert(handler->entry_pco() != -1, "must have been generated");
505
506      int e = bcis->find(handler->handler_bci());
507      if (e >= 0 && scope_depths->at(e) == handler->scope_count()) {
508        // two different handlers are declared to dispatch to the same
509        // catch bci.  During parsing we created edges for each
510        // handler but we really only need one.  The exception handler
511        // table will also get unhappy if we try to declare both since
512        // it's nonsensical.  Just skip this handler.
513        continue;
514      }
515
516      bcis->append(handler->handler_bci());
517      if (handler->handler_bci() == -1) {
518        // insert a wildcard handler at scope depth 0 so that the
519        // exception lookup logic with find it.
520        scope_depths->append(0);
521      } else {
522        scope_depths->append(handler->scope_count());
523    }
524      pcos->append(handler->entry_pco());
525
526      // stop processing once we hit a catch any
527      if (handler->is_catch_all()) {
528        assert(i == handlers->length() - 1, "catch all must be last handler");
529  }
530    }
531    exception_handler_table()->add_subtable(info->pco(), bcis, scope_depths, pcos);
532  }
533}
534
535
536Compilation::Compilation(AbstractCompiler* compiler, ciEnv* env, ciMethod* method,
537                         int osr_bci, BufferBlob* buffer_blob)
538: _compiler(compiler)
539, _env(env)
540, _log(env->log())
541, _method(method)
542, _osr_bci(osr_bci)
543, _hir(NULL)
544, _max_spills(-1)
545, _frame_map(NULL)
546, _masm(NULL)
547, _has_exception_handlers(false)
548, _has_fpu_code(true)   // pessimistic assumption
549, _would_profile(false)
550, _has_unsafe_access(false)
551, _has_method_handle_invokes(false)
552, _bailout_msg(NULL)
553, _exception_info_list(NULL)
554, _allocator(NULL)
555, _next_id(0)
556, _next_block_id(0)
557, _code(buffer_blob)
558, _has_access_indexed(false)
559, _current_instruction(NULL)
560, _interpreter_frame_size(0)
561#ifndef PRODUCT
562, _last_instruction_printed(NULL)
563#endif // PRODUCT
564{
565  PhaseTraceTime timeit(_t_compile);
566  _arena = Thread::current()->resource_area();
567  _env->set_compiler_data(this);
568  _exception_info_list = new ExceptionInfoList();
569  _implicit_exception_table.set_size(0);
570  compile_method();
571  if (bailed_out()) {
572    _env->record_method_not_compilable(bailout_msg(), !TieredCompilation);
573    if (is_profiling()) {
574      // Compilation failed, create MDO, which would signal the interpreter
575      // to start profiling on its own.
576      _method->ensure_method_data();
577    }
578  } else if (is_profiling()) {
579    ciMethodData *md = method->method_data_or_null();
580    if (md != NULL) {
581      md->set_would_profile(_would_profile);
582    }
583  }
584}
585
586Compilation::~Compilation() {
587  _env->set_compiler_data(NULL);
588}
589
590
591void Compilation::add_exception_handlers_for_pco(int pco, XHandlers* exception_handlers) {
592#ifndef PRODUCT
593  if (PrintExceptionHandlers && Verbose) {
594    tty->print_cr("  added exception scope for pco %d", pco);
595  }
596#endif
597  // Note: we do not have program counters for these exception handlers yet
598  exception_info_list()->push(new ExceptionInfo(pco, exception_handlers));
599}
600
601
602void Compilation::notice_inlined_method(ciMethod* method) {
603  _env->notice_inlined_method(method);
604}
605
606
607void Compilation::bailout(const char* msg) {
608  assert(msg != NULL, "bailout message must exist");
609  if (!bailed_out()) {
610    // keep first bailout message
611    if (PrintCompilation || PrintBailouts) tty->print_cr("compilation bailout: %s", msg);
612    _bailout_msg = msg;
613  }
614}
615
616ciKlass* Compilation::cha_exact_type(ciType* type) {
617  if (type != NULL && type->is_loaded() && type->is_instance_klass()) {
618    ciInstanceKlass* ik = type->as_instance_klass();
619    assert(ik->exact_klass() == NULL, "no cha for final klass");
620    if (DeoptC1 && UseCHA && !(ik->has_subklass() || ik->is_interface())) {
621      dependency_recorder()->assert_leaf_type(ik);
622      return ik;
623    }
624  }
625  return NULL;
626}
627
628void Compilation::print_timers() {
629  tty->print_cr("    C1 Compile Time:      %7.3f s",      timers[_t_compile].seconds());
630  tty->print_cr("       Setup time:          %7.3f s",    timers[_t_setup].seconds());
631
632  {
633    tty->print_cr("       Build HIR:           %7.3f s",    timers[_t_buildIR].seconds());
634    tty->print_cr("         Parse:               %7.3f s", timers[_t_hir_parse].seconds());
635    tty->print_cr("         Optimize blocks:     %7.3f s", timers[_t_optimize_blocks].seconds());
636    tty->print_cr("         GVN:                 %7.3f s", timers[_t_gvn].seconds());
637    tty->print_cr("         Null checks elim:    %7.3f s", timers[_t_optimize_null_checks].seconds());
638    tty->print_cr("         Range checks elim:   %7.3f s", timers[_t_rangeCheckElimination].seconds());
639
640    double other = timers[_t_buildIR].seconds() -
641      (timers[_t_hir_parse].seconds() +
642       timers[_t_optimize_blocks].seconds() +
643       timers[_t_gvn].seconds() +
644       timers[_t_optimize_null_checks].seconds() +
645       timers[_t_rangeCheckElimination].seconds());
646    if (other > 0) {
647      tty->print_cr("         Other:               %7.3f s", other);
648    }
649  }
650
651  {
652    tty->print_cr("       Emit LIR:            %7.3f s",    timers[_t_emit_lir].seconds());
653    tty->print_cr("         LIR Gen:             %7.3f s",   timers[_t_lirGeneration].seconds());
654    tty->print_cr("         Linear Scan:         %7.3f s",   timers[_t_linearScan].seconds());
655    NOT_PRODUCT(LinearScan::print_timers(timers[_t_linearScan].seconds()));
656
657    double other = timers[_t_emit_lir].seconds() -
658      (timers[_t_lirGeneration].seconds() +
659       timers[_t_linearScan].seconds());
660    if (other > 0) {
661      tty->print_cr("         Other:               %7.3f s", other);
662    }
663  }
664
665  tty->print_cr("       Code Emission:       %7.3f s",    timers[_t_codeemit].seconds());
666  tty->print_cr("       Code Installation:   %7.3f s",    timers[_t_codeinstall].seconds());
667
668  double other = timers[_t_compile].seconds() -
669      (timers[_t_setup].seconds() +
670       timers[_t_buildIR].seconds() +
671       timers[_t_emit_lir].seconds() +
672       timers[_t_codeemit].seconds() +
673       timers[_t_codeinstall].seconds());
674  if (other > 0) {
675    tty->print_cr("       Other:               %7.3f s", other);
676  }
677
678  NOT_PRODUCT(LinearScan::print_statistics());
679}
680
681
682#ifndef PRODUCT
683void Compilation::compile_only_this_method() {
684  ResourceMark rm;
685  fileStream stream(fopen("c1_compile_only", "wt"));
686  stream.print_cr("# c1 compile only directives");
687  compile_only_this_scope(&stream, hir()->top_scope());
688}
689
690
691void Compilation::compile_only_this_scope(outputStream* st, IRScope* scope) {
692  st->print("CompileOnly=");
693  scope->method()->holder()->name()->print_symbol_on(st);
694  st->print(".");
695  scope->method()->name()->print_symbol_on(st);
696  st->cr();
697}
698
699
700void Compilation::exclude_this_method() {
701  fileStream stream(fopen(".hotspot_compiler", "at"));
702  stream.print("exclude ");
703  method()->holder()->name()->print_symbol_on(&stream);
704  stream.print(" ");
705  method()->name()->print_symbol_on(&stream);
706  stream.cr();
707  stream.cr();
708}
709#endif
710