Path: blob/master/src/hotspot/share/c1/c1_Compilation.cpp
40931 views
/*1* Copyright (c) 1999, 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 "c1/c1_CFGPrinter.hpp"26#include "c1/c1_Compilation.hpp"27#include "c1/c1_IR.hpp"28#include "c1/c1_LIRAssembler.hpp"29#include "c1/c1_LinearScan.hpp"30#include "c1/c1_MacroAssembler.hpp"31#include "c1/c1_RangeCheckElimination.hpp"32#include "c1/c1_ValueMap.hpp"33#include "c1/c1_ValueStack.hpp"34#include "code/debugInfoRec.hpp"35#include "compiler/compileLog.hpp"36#include "compiler/compilerDirectives.hpp"37#include "memory/resourceArea.hpp"38#include "runtime/sharedRuntime.hpp"39#include "runtime/timerTrace.hpp"4041typedef enum {42_t_compile,43_t_setup,44_t_buildIR,45_t_hir_parse,46_t_gvn,47_t_optimize_blocks,48_t_optimize_null_checks,49_t_rangeCheckElimination,50_t_emit_lir,51_t_linearScan,52_t_lirGeneration,53_t_codeemit,54_t_codeinstall,55max_phase_timers56} TimerName;5758static const char * timer_name[] = {59"compile",60"setup",61"buildIR",62"parse_hir",63"gvn",64"optimize_blocks",65"optimize_null_checks",66"rangeCheckElimination",67"emit_lir",68"linearScan",69"lirGeneration",70"codeemit",71"codeinstall"72};7374static elapsedTimer timers[max_phase_timers];75static int totalInstructionNodes = 0;7677class PhaseTraceTime: public TraceTime {78private:79JavaThread* _thread;80CompileLog* _log;81TimerName _timer;8283public:84PhaseTraceTime(TimerName timer)85: TraceTime("", &timers[timer], CITime || CITimeEach, Verbose),86_log(NULL), _timer(timer)87{88if (Compilation::current() != NULL) {89_log = Compilation::current()->log();90}9192if (_log != NULL) {93_log->begin_head("phase name='%s'", timer_name[_timer]);94_log->stamp();95_log->end_head();96}97}9899~PhaseTraceTime() {100if (_log != NULL)101_log->done("phase name='%s'", timer_name[_timer]);102}103};104105// Implementation of Compilation106107108#ifndef PRODUCT109110void Compilation::maybe_print_current_instruction() {111if (_current_instruction != NULL && _last_instruction_printed != _current_instruction) {112_last_instruction_printed = _current_instruction;113_current_instruction->print_line();114}115}116#endif // PRODUCT117118119DebugInformationRecorder* Compilation::debug_info_recorder() const {120return _env->debug_info();121}122123124Dependencies* Compilation::dependency_recorder() const {125return _env->dependencies();126}127128129void Compilation::initialize() {130// Use an oop recorder bound to the CI environment.131// (The default oop recorder is ignorant of the CI.)132OopRecorder* ooprec = new OopRecorder(_env->arena());133_env->set_oop_recorder(ooprec);134_env->set_debug_info(new DebugInformationRecorder(ooprec));135debug_info_recorder()->set_oopmaps(new OopMapSet());136_env->set_dependencies(new Dependencies(_env));137}138139140void Compilation::build_hir() {141CHECK_BAILOUT();142143// setup ir144CompileLog* log = this->log();145if (log != NULL) {146log->begin_head("parse method='%d' ",147log->identify(_method));148log->stamp();149log->end_head();150}151{152PhaseTraceTime timeit(_t_hir_parse);153_hir = new IR(this, method(), osr_bci());154}155if (log) log->done("parse");156if (!_hir->is_valid()) {157bailout("invalid parsing");158return;159}160161#ifndef PRODUCT162if (PrintCFGToFile) {163CFGPrinter::print_cfg(_hir, "After Generation of HIR", true, false);164}165#endif166167#ifndef PRODUCT168if (PrintCFG || PrintCFG0) { tty->print_cr("CFG after parsing"); _hir->print(true); }169if (PrintIR || PrintIR0 ) { tty->print_cr("IR after parsing"); _hir->print(false); }170#endif171172_hir->verify();173174if (UseC1Optimizations) {175NEEDS_CLEANUP176// optimization177PhaseTraceTime timeit(_t_optimize_blocks);178179_hir->optimize_blocks();180}181182_hir->verify();183184_hir->split_critical_edges();185186#ifndef PRODUCT187if (PrintCFG || PrintCFG1) { tty->print_cr("CFG after optimizations"); _hir->print(true); }188if (PrintIR || PrintIR1 ) { tty->print_cr("IR after optimizations"); _hir->print(false); }189#endif190191_hir->verify();192193// compute block ordering for code generation194// the control flow must not be changed from here on195_hir->compute_code();196197if (UseGlobalValueNumbering) {198// No resource mark here! LoopInvariantCodeMotion can allocate ValueStack objects.199PhaseTraceTime timeit(_t_gvn);200int instructions = Instruction::number_of_instructions();201GlobalValueNumbering gvn(_hir);202assert(instructions == Instruction::number_of_instructions(),203"shouldn't have created an instructions");204}205206_hir->verify();207208#ifndef PRODUCT209if (PrintCFGToFile) {210CFGPrinter::print_cfg(_hir, "Before RangeCheckElimination", true, false);211}212#endif213214if (RangeCheckElimination) {215if (_hir->osr_entry() == NULL) {216PhaseTraceTime timeit(_t_rangeCheckElimination);217RangeCheckElimination::eliminate(_hir);218}219}220221#ifndef PRODUCT222if (PrintCFGToFile) {223CFGPrinter::print_cfg(_hir, "After RangeCheckElimination", true, false);224}225#endif226227if (UseC1Optimizations) {228// loop invariant code motion reorders instructions and range229// check elimination adds new instructions so do null check230// elimination after.231NEEDS_CLEANUP232// optimization233PhaseTraceTime timeit(_t_optimize_null_checks);234235_hir->eliminate_null_checks();236}237238_hir->verify();239240// compute use counts after global value numbering241_hir->compute_use_counts();242243#ifndef PRODUCT244if (PrintCFG || PrintCFG2) { tty->print_cr("CFG before code generation"); _hir->code()->print(true); }245if (PrintIR || PrintIR2 ) { tty->print_cr("IR before code generation"); _hir->code()->print(false, true); }246#endif247248_hir->verify();249}250251252void Compilation::emit_lir() {253CHECK_BAILOUT();254255LIRGenerator gen(this, method());256{257PhaseTraceTime timeit(_t_lirGeneration);258hir()->iterate_linear_scan_order(&gen);259}260261CHECK_BAILOUT();262263{264PhaseTraceTime timeit(_t_linearScan);265266LinearScan* allocator = new LinearScan(hir(), &gen, frame_map());267set_allocator(allocator);268// Assign physical registers to LIR operands using a linear scan algorithm.269allocator->do_linear_scan();270CHECK_BAILOUT();271272_max_spills = allocator->max_spills();273}274275if (BailoutAfterLIR) {276if (PrintLIR && !bailed_out()) {277print_LIR(hir()->code());278}279bailout("Bailing out because of -XX:+BailoutAfterLIR");280}281}282283284void Compilation::emit_code_epilog(LIR_Assembler* assembler) {285CHECK_BAILOUT();286287CodeOffsets* code_offsets = assembler->offsets();288289// generate code or slow cases290assembler->emit_slow_case_stubs();291CHECK_BAILOUT();292293// generate exception adapters294assembler->emit_exception_entries(exception_info_list());295CHECK_BAILOUT();296297// Generate code for exception handler.298code_offsets->set_value(CodeOffsets::Exceptions, assembler->emit_exception_handler());299CHECK_BAILOUT();300301// Generate code for deopt handler.302code_offsets->set_value(CodeOffsets::Deopt, assembler->emit_deopt_handler());303CHECK_BAILOUT();304305// Emit the MethodHandle deopt handler code (if required).306if (has_method_handle_invokes()) {307// We can use the same code as for the normal deopt handler, we308// just need a different entry point address.309code_offsets->set_value(CodeOffsets::DeoptMH, assembler->emit_deopt_handler());310CHECK_BAILOUT();311}312313// Emit the handler to remove the activation from the stack and314// dispatch to the caller.315offsets()->set_value(CodeOffsets::UnwindHandler, assembler->emit_unwind_handler());316317// done318masm()->flush();319}320321322bool Compilation::setup_code_buffer(CodeBuffer* code, int call_stub_estimate) {323// Preinitialize the consts section to some large size:324int locs_buffer_size = 20 * (relocInfo::length_limit + sizeof(relocInfo));325char* locs_buffer = NEW_RESOURCE_ARRAY(char, locs_buffer_size);326code->insts()->initialize_shared_locs((relocInfo*)locs_buffer,327locs_buffer_size / sizeof(relocInfo));328code->initialize_consts_size(Compilation::desired_max_constant_size());329// Call stubs + two deopt handlers (regular and MH) + exception handler330int stub_size = (call_stub_estimate * LIR_Assembler::call_stub_size()) +331LIR_Assembler::exception_handler_size() +332(2 * LIR_Assembler::deopt_handler_size());333if (stub_size >= code->insts_capacity()) return false;334code->initialize_stubs_size(stub_size);335return true;336}337338339int Compilation::emit_code_body() {340// emit code341if (!setup_code_buffer(code(), allocator()->num_calls())) {342BAILOUT_("size requested greater than avail code buffer size", 0);343}344code()->initialize_oop_recorder(env()->oop_recorder());345346_masm = new C1_MacroAssembler(code());347_masm->set_oop_recorder(env()->oop_recorder());348349LIR_Assembler lir_asm(this);350351lir_asm.emit_code(hir()->code());352CHECK_BAILOUT_(0);353354emit_code_epilog(&lir_asm);355CHECK_BAILOUT_(0);356357generate_exception_handler_table();358359#ifndef PRODUCT360if (PrintExceptionHandlers && Verbose) {361exception_handler_table()->print();362}363#endif /* PRODUCT */364365return frame_map()->framesize();366}367368369int Compilation::compile_java_method() {370assert(!method()->is_native(), "should not reach here");371372if (BailoutOnExceptionHandlers) {373if (method()->has_exception_handlers()) {374bailout("linear scan can't handle exception handlers");375}376}377378CHECK_BAILOUT_(no_frame_size);379380if (is_profiling() && !method()->ensure_method_data()) {381BAILOUT_("mdo allocation failed", no_frame_size);382}383384{385PhaseTraceTime timeit(_t_buildIR);386build_hir();387}388if (BailoutAfterHIR) {389BAILOUT_("Bailing out because of -XX:+BailoutAfterHIR", no_frame_size);390}391392393{394PhaseTraceTime timeit(_t_emit_lir);395396_frame_map = new FrameMap(method(), hir()->number_of_locks(), MAX2(4, hir()->max_stack()));397emit_lir();398}399CHECK_BAILOUT_(no_frame_size);400401{402PhaseTraceTime timeit(_t_codeemit);403return emit_code_body();404}405}406407void Compilation::install_code(int frame_size) {408// frame_size is in 32-bit words so adjust it intptr_t words409assert(frame_size == frame_map()->framesize(), "must match");410assert(in_bytes(frame_map()->framesize_in_bytes()) % sizeof(intptr_t) == 0, "must be at least pointer aligned");411_env->register_method(412method(),413osr_bci(),414&_offsets,415in_bytes(_frame_map->sp_offset_for_orig_pc()),416code(),417in_bytes(frame_map()->framesize_in_bytes()) / sizeof(intptr_t),418debug_info_recorder()->_oopmaps,419exception_handler_table(),420implicit_exception_table(),421compiler(),422has_unsafe_access(),423SharedRuntime::is_wide_vector(max_vector_size())424);425}426427428void Compilation::compile_method() {429{430PhaseTraceTime timeit(_t_setup);431432// setup compilation433initialize();434}435436if (!method()->can_be_compiled()) {437// Prevent race condition 6328518.438// This can happen if the method is obsolete or breakpointed.439bailout("Bailing out because method is not compilable");440return;441}442443if (_env->jvmti_can_hotswap_or_post_breakpoint()) {444// We can assert evol_method because method->can_be_compiled is true.445dependency_recorder()->assert_evol_method(method());446}447448if (env()->break_at_compile()) {449BREAKPOINT;450}451452#ifndef PRODUCT453if (PrintCFGToFile) {454CFGPrinter::print_compilation(this);455}456#endif457458// compile method459int frame_size = compile_java_method();460461// bailout if method couldn't be compiled462// Note: make sure we mark the method as not compilable!463CHECK_BAILOUT();464465if (should_install_code()) {466// install code467PhaseTraceTime timeit(_t_codeinstall);468install_code(frame_size);469}470471if (log() != NULL) // Print code cache state into compiler log472log()->code_cache_state();473474totalInstructionNodes += Instruction::number_of_instructions();475}476477478void Compilation::generate_exception_handler_table() {479// Generate an ExceptionHandlerTable from the exception handler480// information accumulated during the compilation.481ExceptionInfoList* info_list = exception_info_list();482483if (info_list->length() == 0) {484return;485}486487// allocate some arrays for use by the collection code.488const int num_handlers = 5;489GrowableArray<intptr_t>* bcis = new GrowableArray<intptr_t>(num_handlers);490GrowableArray<intptr_t>* scope_depths = new GrowableArray<intptr_t>(num_handlers);491GrowableArray<intptr_t>* pcos = new GrowableArray<intptr_t>(num_handlers);492493for (int i = 0; i < info_list->length(); i++) {494ExceptionInfo* info = info_list->at(i);495XHandlers* handlers = info->exception_handlers();496497// empty the arrays498bcis->trunc_to(0);499scope_depths->trunc_to(0);500pcos->trunc_to(0);501502int prev_scope = 0;503for (int i = 0; i < handlers->length(); i++) {504XHandler* handler = handlers->handler_at(i);505assert(handler->entry_pco() != -1, "must have been generated");506assert(handler->scope_count() >= prev_scope, "handlers should be sorted by scope");507508if (handler->scope_count() == prev_scope) {509int e = bcis->find_from_end(handler->handler_bci());510if (e >= 0 && scope_depths->at(e) == handler->scope_count()) {511// two different handlers are declared to dispatch to the same512// catch bci. During parsing we created edges for each513// handler but we really only need one. The exception handler514// table will also get unhappy if we try to declare both since515// it's nonsensical. Just skip this handler.516continue;517}518}519520bcis->append(handler->handler_bci());521if (handler->handler_bci() == -1) {522// insert a wildcard handler at scope depth 0 so that the523// exception lookup logic with find it.524scope_depths->append(0);525} else {526scope_depths->append(handler->scope_count());527}528pcos->append(handler->entry_pco());529530// stop processing once we hit a catch any531if (handler->is_catch_all()) {532assert(i == handlers->length() - 1, "catch all must be last handler");533}534prev_scope = handler->scope_count();535}536exception_handler_table()->add_subtable(info->pco(), bcis, scope_depths, pcos);537}538}539540Compilation::Compilation(AbstractCompiler* compiler, ciEnv* env, ciMethod* method,541int osr_bci, BufferBlob* buffer_blob, bool install_code, DirectiveSet* directive)542: _next_id(0)543, _next_block_id(0)544, _compiler(compiler)545, _directive(directive)546, _env(env)547, _log(env->log())548, _method(method)549, _osr_bci(osr_bci)550, _hir(NULL)551, _max_spills(-1)552, _frame_map(NULL)553, _masm(NULL)554, _has_exception_handlers(false)555, _has_fpu_code(true) // pessimistic assumption556, _has_unsafe_access(false)557, _would_profile(false)558, _has_method_handle_invokes(false)559, _has_reserved_stack_access(method->has_reserved_stack_access())560, _install_code(install_code)561, _bailout_msg(NULL)562, _exception_info_list(NULL)563, _allocator(NULL)564, _code(buffer_blob)565, _has_access_indexed(false)566, _interpreter_frame_size(0)567, _current_instruction(NULL)568#ifndef PRODUCT569, _last_instruction_printed(NULL)570, _cfg_printer_output(NULL)571#endif // PRODUCT572{573PhaseTraceTime timeit(_t_compile);574_arena = Thread::current()->resource_area();575_env->set_compiler_data(this);576_exception_info_list = new ExceptionInfoList();577_implicit_exception_table.set_size(0);578#ifndef PRODUCT579if (PrintCFGToFile) {580_cfg_printer_output = new CFGPrinterOutput(this);581}582#endif583compile_method();584if (bailed_out()) {585_env->record_method_not_compilable(bailout_msg());586if (is_profiling()) {587// Compilation failed, create MDO, which would signal the interpreter588// to start profiling on its own.589_method->ensure_method_data();590}591} else if (is_profiling()) {592ciMethodData *md = method->method_data_or_null();593if (md != NULL) {594md->set_would_profile(_would_profile);595}596}597}598599Compilation::~Compilation() {600_env->set_compiler_data(NULL);601}602603void Compilation::add_exception_handlers_for_pco(int pco, XHandlers* exception_handlers) {604#ifndef PRODUCT605if (PrintExceptionHandlers && Verbose) {606tty->print_cr(" added exception scope for pco %d", pco);607}608#endif609// Note: we do not have program counters for these exception handlers yet610exception_info_list()->push(new ExceptionInfo(pco, exception_handlers));611}612613614void Compilation::notice_inlined_method(ciMethod* method) {615_env->notice_inlined_method(method);616}617618619void Compilation::bailout(const char* msg) {620assert(msg != NULL, "bailout message must exist");621if (!bailed_out()) {622// keep first bailout message623if (PrintCompilation || PrintBailouts) tty->print_cr("compilation bailout: %s", msg);624_bailout_msg = msg;625}626}627628ciKlass* Compilation::cha_exact_type(ciType* type) {629if (type != NULL && type->is_loaded() && type->is_instance_klass()) {630ciInstanceKlass* ik = type->as_instance_klass();631assert(ik->exact_klass() == NULL, "no cha for final klass");632if (DeoptC1 && UseCHA && !(ik->has_subklass() || ik->is_interface())) {633dependency_recorder()->assert_leaf_type(ik);634return ik;635}636}637return NULL;638}639640void Compilation::print_timers() {641tty->print_cr(" C1 Compile Time: %7.3f s", timers[_t_compile].seconds());642tty->print_cr(" Setup time: %7.3f s", timers[_t_setup].seconds());643644{645tty->print_cr(" Build HIR: %7.3f s", timers[_t_buildIR].seconds());646tty->print_cr(" Parse: %7.3f s", timers[_t_hir_parse].seconds());647tty->print_cr(" Optimize blocks: %7.3f s", timers[_t_optimize_blocks].seconds());648tty->print_cr(" GVN: %7.3f s", timers[_t_gvn].seconds());649tty->print_cr(" Null checks elim: %7.3f s", timers[_t_optimize_null_checks].seconds());650tty->print_cr(" Range checks elim: %7.3f s", timers[_t_rangeCheckElimination].seconds());651652double other = timers[_t_buildIR].seconds() -653(timers[_t_hir_parse].seconds() +654timers[_t_optimize_blocks].seconds() +655timers[_t_gvn].seconds() +656timers[_t_optimize_null_checks].seconds() +657timers[_t_rangeCheckElimination].seconds());658if (other > 0) {659tty->print_cr(" Other: %7.3f s", other);660}661}662663{664tty->print_cr(" Emit LIR: %7.3f s", timers[_t_emit_lir].seconds());665tty->print_cr(" LIR Gen: %7.3f s", timers[_t_lirGeneration].seconds());666tty->print_cr(" Linear Scan: %7.3f s", timers[_t_linearScan].seconds());667NOT_PRODUCT(LinearScan::print_timers(timers[_t_linearScan].seconds()));668669double other = timers[_t_emit_lir].seconds() -670(timers[_t_lirGeneration].seconds() +671timers[_t_linearScan].seconds());672if (other > 0) {673tty->print_cr(" Other: %7.3f s", other);674}675}676677tty->print_cr(" Code Emission: %7.3f s", timers[_t_codeemit].seconds());678tty->print_cr(" Code Installation: %7.3f s", timers[_t_codeinstall].seconds());679680double other = timers[_t_compile].seconds() -681(timers[_t_setup].seconds() +682timers[_t_buildIR].seconds() +683timers[_t_emit_lir].seconds() +684timers[_t_codeemit].seconds() +685timers[_t_codeinstall].seconds());686if (other > 0) {687tty->print_cr(" Other: %7.3f s", other);688}689690NOT_PRODUCT(LinearScan::print_statistics());691}692693694#ifndef PRODUCT695void Compilation::compile_only_this_method() {696ResourceMark rm;697fileStream stream(fopen("c1_compile_only", "wt"));698stream.print_cr("# c1 compile only directives");699compile_only_this_scope(&stream, hir()->top_scope());700}701702void Compilation::compile_only_this_scope(outputStream* st, IRScope* scope) {703st->print("CompileOnly=");704scope->method()->holder()->name()->print_symbol_on(st);705st->print(".");706scope->method()->name()->print_symbol_on(st);707st->cr();708}709710void Compilation::exclude_this_method() {711fileStream stream(fopen(".hotspot_compiler", "at"));712stream.print("exclude ");713method()->holder()->name()->print_symbol_on(&stream);714stream.print(" ");715method()->name()->print_symbol_on(&stream);716stream.cr();717stream.cr();718}719720// Called from debugger to get the interval with 'reg_num' during register allocation.721Interval* find_interval(int reg_num) {722return Compilation::current()->allocator()->find_interval_at(reg_num);723}724725#endif // NOT PRODUCT726727728