// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/pipeline.h" #include // NOLINT(readability/streams) #include #include #include #include "src/base/optional.h" #include "src/base/platform/elapsed-timer.h" #include "src/codegen/assembler-inl.h" #include "src/codegen/compiler.h" #include "src/codegen/optimized-compilation-info.h" #include "src/codegen/register-configuration.h" #include "src/compiler/add-type-assertions-reducer.h" #include "src/compiler/backend/code-generator.h" #include "src/compiler/backend/frame-elider.h" #include "src/compiler/backend/instruction-selector.h" #include "src/compiler/backend/instruction.h" #include "src/compiler/backend/jump-threading.h" #include "src/compiler/backend/live-range-separator.h" #include "src/compiler/backend/move-optimizer.h" #include "src/compiler/backend/register-allocator-verifier.h" #include "src/compiler/backend/register-allocator.h" #include "src/compiler/basic-block-instrumentor.h" #include "src/compiler/branch-elimination.h" #include "src/compiler/bytecode-graph-builder.h" #include "src/compiler/checkpoint-elimination.h" #include "src/compiler/common-operator-reducer.h" #include "src/compiler/compilation-dependencies.h" #include "src/compiler/compiler-source-position-table.h" #include "src/compiler/constant-folding-reducer.h" #include "src/compiler/control-flow-optimizer.h" #include "src/compiler/csa-load-elimination.h" #include "src/compiler/dead-code-elimination.h" #include "src/compiler/decompression-elimination.h" #include "src/compiler/effect-control-linearizer.h" #include "src/compiler/escape-analysis-reducer.h" #include "src/compiler/escape-analysis.h" #include "src/compiler/graph-trimmer.h" #include "src/compiler/graph-visualizer.h" #include "src/compiler/js-call-reducer.h" #include "src/compiler/js-context-specialization.h" #include "src/compiler/js-create-lowering.h" #include "src/compiler/js-generic-lowering.h" #include "src/compiler/js-heap-broker.h" #include "src/compiler/js-heap-copy-reducer.h" #include "src/compiler/js-inlining-heuristic.h" #include "src/compiler/js-intrinsic-lowering.h" #include "src/compiler/js-native-context-specialization.h" #include "src/compiler/js-typed-lowering.h" #include "src/compiler/load-elimination.h" #include "src/compiler/loop-analysis.h" #include "src/compiler/loop-peeling.h" #include "src/compiler/loop-variable-optimizer.h" #include "src/compiler/machine-graph-verifier.h" #include "src/compiler/machine-operator-reducer.h" #include "src/compiler/memory-optimizer.h" #include "src/compiler/node-origin-table.h" #include "src/compiler/osr.h" #include "src/compiler/pipeline-statistics.h" #include "src/compiler/redundancy-elimination.h" #include "src/compiler/schedule.h" #include "src/compiler/scheduler.h" #include "src/compiler/select-lowering.h" #include "src/compiler/serializer-for-background-compilation.h" #include "src/compiler/simplified-lowering.h" #include "src/compiler/simplified-operator-reducer.h" #include "src/compiler/simplified-operator.h" #include "src/compiler/store-store-elimination.h" #include "src/compiler/type-narrowing-reducer.h" #include "src/compiler/typed-optimization.h" #include "src/compiler/typer.h" #include "src/compiler/value-numbering-reducer.h" #include "src/compiler/verifier.h" #include "src/compiler/wasm-compiler.h" #include "src/compiler/zone-stats.h" #include "src/diagnostics/code-tracer.h" #include "src/diagnostics/disassembler.h" #include "src/execution/isolate-inl.h" #include "src/init/bootstrapper.h" #include "src/objects/shared-function-info.h" #include "src/parsing/parse-info.h" #include "src/tracing/trace-event.h" #include "src/tracing/traced-value.h" #include "src/utils/ostreams.h" #include "src/utils/utils.h" #include "src/wasm/function-body-decoder.h" #include "src/wasm/function-compiler.h" #include "src/wasm/wasm-engine.h" namespace v8 { namespace internal { namespace compiler { static constexpr char kCodegenZoneName[] = "codegen-zone"; static constexpr char kGraphZoneName[] = "graph-zone"; static constexpr char kInstructionZoneName[] = "instruction-zone"; static constexpr char kMachineGraphVerifierZoneName[] = "machine-graph-verifier-zone"; static constexpr char kPipelineCompilationJobZoneName[] = "pipeline-compilation-job-zone"; static constexpr char kRegisterAllocationZoneName[] = "register-allocation-zone"; static constexpr char kRegisterAllocatorVerifierZoneName[] = "register-allocator-verifier-zone"; namespace { Maybe GetModuleContext(Handle closure) { Context current = closure->context(); size_t distance = 0; while (!current.IsNativeContext()) { if (current.IsModuleContext()) { return Just( OuterContext(handle(current, current.GetIsolate()), distance)); } current = current.previous(); distance++; } return Nothing(); } } // anonymous namespace class PipelineData { public: // For main entry point. PipelineData(ZoneStats* zone_stats, Isolate* isolate, OptimizedCompilationInfo* info, PipelineStatistics* pipeline_statistics) : isolate_(isolate), allocator_(isolate->allocator()), info_(info), debug_name_(info_->GetDebugName()), may_have_unverifiable_graph_(false), zone_stats_(zone_stats), pipeline_statistics_(pipeline_statistics), roots_relative_addressing_enabled_( !isolate->serializer_enabled() && !isolate->IsGeneratingEmbeddedBuiltins()), graph_zone_scope_(zone_stats_, kGraphZoneName), graph_zone_(graph_zone_scope_.zone()), instruction_zone_scope_(zone_stats_, kInstructionZoneName), instruction_zone_(instruction_zone_scope_.zone()), codegen_zone_scope_(zone_stats_, kCodegenZoneName), codegen_zone_(codegen_zone_scope_.zone()), broker_(new JSHeapBroker(isolate_, info_->zone(), info_->trace_heap_broker_enabled())), register_allocation_zone_scope_(zone_stats_, kRegisterAllocationZoneName), register_allocation_zone_(register_allocation_zone_scope_.zone()), assembler_options_(AssemblerOptions::Default(isolate)) { PhaseScope scope(pipeline_statistics, "V8.TFInitPipelineData"); graph_ = new (graph_zone_) Graph(graph_zone_); source_positions_ = new (graph_zone_) SourcePositionTable(graph_); node_origins_ = info->trace_turbo_json_enabled() ? new (graph_zone_) NodeOriginTable(graph_) : nullptr; simplified_ = new (graph_zone_) SimplifiedOperatorBuilder(graph_zone_); machine_ = new (graph_zone_) MachineOperatorBuilder( graph_zone_, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements()); common_ = new (graph_zone_) CommonOperatorBuilder(graph_zone_); javascript_ = new (graph_zone_) JSOperatorBuilder(graph_zone_); jsgraph_ = new (graph_zone_) JSGraph(isolate_, graph_, common_, javascript_, simplified_, machine_); dependencies_ = new (info_->zone()) CompilationDependencies(broker_, info_->zone()); } // For WebAssembly compile entry point. PipelineData(ZoneStats* zone_stats, wasm::WasmEngine* wasm_engine, OptimizedCompilationInfo* info, MachineGraph* mcgraph, PipelineStatistics* pipeline_statistics, SourcePositionTable* source_positions, NodeOriginTable* node_origins, const AssemblerOptions& assembler_options) : isolate_(nullptr), wasm_engine_(wasm_engine), allocator_(wasm_engine->allocator()), info_(info), debug_name_(info_->GetDebugName()), may_have_unverifiable_graph_(false), zone_stats_(zone_stats), pipeline_statistics_(pipeline_statistics), graph_zone_scope_(zone_stats_, kGraphZoneName), graph_zone_(graph_zone_scope_.zone()), graph_(mcgraph->graph()), source_positions_(source_positions), node_origins_(node_origins), machine_(mcgraph->machine()), common_(mcgraph->common()), mcgraph_(mcgraph), instruction_zone_scope_(zone_stats_, kInstructionZoneName), instruction_zone_(instruction_zone_scope_.zone()), codegen_zone_scope_(zone_stats_, kCodegenZoneName), codegen_zone_(codegen_zone_scope_.zone()), register_allocation_zone_scope_(zone_stats_, kRegisterAllocationZoneName), register_allocation_zone_(register_allocation_zone_scope_.zone()), assembler_options_(assembler_options) {} // For CodeStubAssembler and machine graph testing entry point. PipelineData(ZoneStats* zone_stats, OptimizedCompilationInfo* info, Isolate* isolate, AccountingAllocator* allocator, Graph* graph, Schedule* schedule, SourcePositionTable* source_positions, NodeOriginTable* node_origins, JumpOptimizationInfo* jump_opt, const AssemblerOptions& assembler_options) : isolate_(isolate), allocator_(allocator), info_(info), debug_name_(info_->GetDebugName()), zone_stats_(zone_stats), graph_zone_scope_(zone_stats_, kGraphZoneName), graph_zone_(graph_zone_scope_.zone()), graph_(graph), source_positions_(source_positions), node_origins_(node_origins), schedule_(schedule), instruction_zone_scope_(zone_stats_, kInstructionZoneName), instruction_zone_(instruction_zone_scope_.zone()), codegen_zone_scope_(zone_stats_, kCodegenZoneName), codegen_zone_(codegen_zone_scope_.zone()), register_allocation_zone_scope_(zone_stats_, kRegisterAllocationZoneName), register_allocation_zone_(register_allocation_zone_scope_.zone()), jump_optimization_info_(jump_opt), assembler_options_(assembler_options) { simplified_ = new (graph_zone_) SimplifiedOperatorBuilder(graph_zone_); machine_ = new (graph_zone_) MachineOperatorBuilder( graph_zone_, MachineType::PointerRepresentation(), InstructionSelector::SupportedMachineOperatorFlags(), InstructionSelector::AlignmentRequirements()); common_ = new (graph_zone_) CommonOperatorBuilder(graph_zone_); javascript_ = new (graph_zone_) JSOperatorBuilder(graph_zone_); jsgraph_ = new (graph_zone_) JSGraph(isolate_, graph_, common_, javascript_, simplified_, machine_); } // For register allocation testing entry point. PipelineData(ZoneStats* zone_stats, OptimizedCompilationInfo* info, Isolate* isolate, InstructionSequence* sequence) : isolate_(isolate), allocator_(isolate->allocator()), info_(info), debug_name_(info_->GetDebugName()), zone_stats_(zone_stats), graph_zone_scope_(zone_stats_, kGraphZoneName), instruction_zone_scope_(zone_stats_, kInstructionZoneName), instruction_zone_(sequence->zone()), sequence_(sequence), codegen_zone_scope_(zone_stats_, kCodegenZoneName), codegen_zone_(codegen_zone_scope_.zone()), register_allocation_zone_scope_(zone_stats_, kRegisterAllocationZoneName), register_allocation_zone_(register_allocation_zone_scope_.zone()), assembler_options_(AssemblerOptions::Default(isolate)) {} ~PipelineData() { // Must happen before zones are destroyed. delete code_generator_; code_generator_ = nullptr; DeleteTyper(); DeleteRegisterAllocationZone(); DeleteInstructionZone(); DeleteCodegenZone(); DeleteGraphZone(); } Isolate* isolate() const { return isolate_; } AccountingAllocator* allocator() const { return allocator_; } OptimizedCompilationInfo* info() const { return info_; } ZoneStats* zone_stats() const { return zone_stats_; } CompilationDependencies* dependencies() const { return dependencies_; } PipelineStatistics* pipeline_statistics() { return pipeline_statistics_; } OsrHelper* osr_helper() { return &(*osr_helper_); } bool compilation_failed() const { return compilation_failed_; } void set_compilation_failed() { compilation_failed_ = true; } bool verify_graph() const { return verify_graph_; } void set_verify_graph(bool value) { verify_graph_ = value; } MaybeHandle code() { return code_; } void set_code(MaybeHandle code) { DCHECK(code_.is_null()); code_ = code; } CodeGenerator* code_generator() const { return code_generator_; } // RawMachineAssembler generally produces graphs which cannot be verified. bool MayHaveUnverifiableGraph() const { return may_have_unverifiable_graph_; } Zone* graph_zone() const { return graph_zone_; } Graph* graph() const { return graph_; } SourcePositionTable* source_positions() const { return source_positions_; } NodeOriginTable* node_origins() const { return node_origins_; } MachineOperatorBuilder* machine() const { return machine_; } CommonOperatorBuilder* common() const { return common_; } JSOperatorBuilder* javascript() const { return javascript_; } JSGraph* jsgraph() const { return jsgraph_; } MachineGraph* mcgraph() const { return mcgraph_; } Handle native_context() const { return handle(info()->native_context(), isolate()); } Handle global_object() const { return handle(info()->global_object(), isolate()); } JSHeapBroker* broker() const { return broker_; } std::unique_ptr ReleaseBroker() { std::unique_ptr broker(broker_); broker_ = nullptr; return broker; } Schedule* schedule() const { return schedule_; } void set_schedule(Schedule* schedule) { DCHECK(!schedule_); schedule_ = schedule; } void reset_schedule() { schedule_ = nullptr; } Zone* instruction_zone() const { return instruction_zone_; } Zone* codegen_zone() const { return codegen_zone_; } InstructionSequence* sequence() const { return sequence_; } Frame* frame() const { return frame_; } Zone* register_allocation_zone() const { return register_allocation_zone_; } RegisterAllocationData* register_allocation_data() const { return register_allocation_data_; } BasicBlockProfiler::Data* profiler_data() const { return profiler_data_; } void set_profiler_data(BasicBlockProfiler::Data* profiler_data) { profiler_data_ = profiler_data; } std::string const& source_position_output() const { return source_position_output_; } void set_source_position_output(std::string const& source_position_output) { source_position_output_ = source_position_output; } JumpOptimizationInfo* jump_optimization_info() const { return jump_optimization_info_; } const AssemblerOptions& assembler_options() const { return assembler_options_; } void ChooseSpecializationContext() { if (info()->is_function_context_specializing()) { DCHECK(info()->has_context()); specialization_context_ = Just(OuterContext(handle(info()->context(), isolate()), 0)); } else { specialization_context_ = GetModuleContext(info()->closure()); } } Maybe specialization_context() const { return specialization_context_; } size_t* address_of_max_unoptimized_frame_height() { return &max_unoptimized_frame_height_; } size_t max_unoptimized_frame_height() const { return max_unoptimized_frame_height_; } CodeTracer* GetCodeTracer() const { return wasm_engine_ == nullptr ? isolate_->GetCodeTracer() : wasm_engine_->GetCodeTracer(); } Typer* CreateTyper() { DCHECK_NULL(typer_); typer_ = new Typer(broker(), typer_flags_, graph(), &info()->tick_counter()); return typer_; } void AddTyperFlag(Typer::Flag flag) { DCHECK_NULL(typer_); typer_flags_ |= flag; } void DeleteTyper() { delete typer_; typer_ = nullptr; } void DeleteGraphZone() { if (graph_zone_ == nullptr) return; graph_zone_scope_.Destroy(); graph_zone_ = nullptr; graph_ = nullptr; source_positions_ = nullptr; node_origins_ = nullptr; simplified_ = nullptr; machine_ = nullptr; common_ = nullptr; javascript_ = nullptr; jsgraph_ = nullptr; mcgraph_ = nullptr; schedule_ = nullptr; } void DeleteInstructionZone() { if (instruction_zone_ == nullptr) return; instruction_zone_scope_.Destroy(); instruction_zone_ = nullptr; sequence_ = nullptr; } void DeleteCodegenZone() { if (codegen_zone_ == nullptr) return; codegen_zone_scope_.Destroy(); codegen_zone_ = nullptr; dependencies_ = nullptr; delete broker_; broker_ = nullptr; frame_ = nullptr; } void DeleteRegisterAllocationZone() { if (register_allocation_zone_ == nullptr) return; register_allocation_zone_scope_.Destroy(); register_allocation_zone_ = nullptr; register_allocation_data_ = nullptr; } void InitializeInstructionSequence(const CallDescriptor* call_descriptor) { DCHECK_NULL(sequence_); InstructionBlocks* instruction_blocks = InstructionSequence::InstructionBlocksFor(instruction_zone(), schedule()); sequence_ = new (instruction_zone()) InstructionSequence(isolate(), instruction_zone(), instruction_blocks); if (call_descriptor && call_descriptor->RequiresFrameAsIncoming()) { sequence_->instruction_blocks()[0]->mark_needs_frame(); } else { DCHECK_EQ(0u, call_descriptor->CalleeSavedFPRegisters()); DCHECK_EQ(0u, call_descriptor->CalleeSavedRegisters()); } } void InitializeFrameData(CallDescriptor* call_descriptor) { DCHECK_NULL(frame_); int fixed_frame_size = 0; if (call_descriptor != nullptr) { fixed_frame_size = call_descriptor->CalculateFixedFrameSize(info()->code_kind()); } frame_ = new (codegen_zone()) Frame(fixed_frame_size); } void InitializeRegisterAllocationData(const RegisterConfiguration* config, CallDescriptor* call_descriptor, RegisterAllocationFlags flags) { DCHECK_NULL(register_allocation_data_); register_allocation_data_ = new (register_allocation_zone()) RegisterAllocationData(config, register_allocation_zone(), frame(), sequence(), flags, &info()->tick_counter(), debug_name()); } void InitializeOsrHelper() { DCHECK(!osr_helper_.has_value()); osr_helper_.emplace(info()); } void set_start_source_position(int position) { DCHECK_EQ(start_source_position_, kNoSourcePosition); start_source_position_ = position; } void InitializeCodeGenerator(Linkage* linkage, std::unique_ptr buffer) { DCHECK_NULL(code_generator_); code_generator_ = new CodeGenerator( codegen_zone(), frame(), linkage, sequence(), info(), isolate(), osr_helper_, start_source_position_, jump_optimization_info_, info()->GetPoisoningMitigationLevel(), assembler_options_, info_->builtin_index(), max_unoptimized_frame_height(), std::move(buffer)); } void BeginPhaseKind(const char* phase_kind_name) { if (pipeline_statistics() != nullptr) { pipeline_statistics()->BeginPhaseKind(phase_kind_name); } } void EndPhaseKind() { if (pipeline_statistics() != nullptr) { pipeline_statistics()->EndPhaseKind(); } } const char* debug_name() const { return debug_name_.get(); } bool roots_relative_addressing_enabled() { return roots_relative_addressing_enabled_; } private: Isolate* const isolate_; wasm::WasmEngine* const wasm_engine_ = nullptr; AccountingAllocator* const allocator_; OptimizedCompilationInfo* const info_; std::unique_ptr debug_name_; bool may_have_unverifiable_graph_ = true; ZoneStats* const zone_stats_; PipelineStatistics* pipeline_statistics_ = nullptr; bool compilation_failed_ = false; bool verify_graph_ = false; int start_source_position_ = kNoSourcePosition; base::Optional osr_helper_; MaybeHandle code_; CodeGenerator* code_generator_ = nullptr; Typer* typer_ = nullptr; Typer::Flags typer_flags_ = Typer::kNoFlags; bool roots_relative_addressing_enabled_ = false; // All objects in the following group of fields are allocated in graph_zone_. // They are all set to nullptr when the graph_zone_ is destroyed. ZoneStats::Scope graph_zone_scope_; Zone* graph_zone_ = nullptr; Graph* graph_ = nullptr; SourcePositionTable* source_positions_ = nullptr; NodeOriginTable* node_origins_ = nullptr; SimplifiedOperatorBuilder* simplified_ = nullptr; MachineOperatorBuilder* machine_ = nullptr; CommonOperatorBuilder* common_ = nullptr; JSOperatorBuilder* javascript_ = nullptr; JSGraph* jsgraph_ = nullptr; MachineGraph* mcgraph_ = nullptr; Schedule* schedule_ = nullptr; // All objects in the following group of fields are allocated in // instruction_zone_. They are all set to nullptr when the instruction_zone_ // is destroyed. ZoneStats::Scope instruction_zone_scope_; Zone* instruction_zone_; InstructionSequence* sequence_ = nullptr; // All objects in the following group of fields are allocated in // codegen_zone_. They are all set to nullptr when the codegen_zone_ // is destroyed. ZoneStats::Scope codegen_zone_scope_; Zone* codegen_zone_; CompilationDependencies* dependencies_ = nullptr; JSHeapBroker* broker_ = nullptr; Frame* frame_ = nullptr; // All objects in the following group of fields are allocated in // register_allocation_zone_. They are all set to nullptr when the zone is // destroyed. ZoneStats::Scope register_allocation_zone_scope_; Zone* register_allocation_zone_; RegisterAllocationData* register_allocation_data_ = nullptr; // Basic block profiling support. BasicBlockProfiler::Data* profiler_data_ = nullptr; // Source position output for --trace-turbo. std::string source_position_output_; JumpOptimizationInfo* jump_optimization_info_ = nullptr; AssemblerOptions assembler_options_; Maybe specialization_context_ = Nothing(); // The maximal combined height of all inlined frames in their unoptimized // state. Calculated during instruction selection, applied during code // generation. size_t max_unoptimized_frame_height_ = 0; DISALLOW_COPY_AND_ASSIGN(PipelineData); }; class PipelineImpl final { public: explicit PipelineImpl(PipelineData* data) : data_(data) {} // Helpers for executing pipeline phases. template void Run(Args&&... args); // Step A.1. Serialize the data needed for the compilation front-end. void Serialize(); // Step A.2. Run the graph creation and initial optimization passes. bool CreateGraph(); // Step B. Run the concurrent optimization passes. bool OptimizeGraph(Linkage* linkage); // Alternative step B. Run minimal concurrent optimization passes for // mid-tier. bool OptimizeGraphForMidTier(Linkage* linkage); // Substep B.1. Produce a scheduled graph. void ComputeScheduledGraph(); // Substep B.2. Select instructions from a scheduled graph. bool SelectInstructions(Linkage* linkage); // Step C. Run the code assembly pass. void AssembleCode(Linkage* linkage, std::unique_ptr buffer = {}); // Step D. Run the code finalization pass. MaybeHandle FinalizeCode(bool retire_broker = true); // Step E. Install any code dependencies. bool CommitDependencies(Handle code); void VerifyGeneratedCodeIsIdempotent(); void RunPrintAndVerify(const char* phase, bool untyped = false); bool SelectInstructionsAndAssemble(CallDescriptor* call_descriptor); MaybeHandle GenerateCode(CallDescriptor* call_descriptor); void AllocateRegisters(const RegisterConfiguration* config, CallDescriptor* call_descriptor, bool run_verifier); OptimizedCompilationInfo* info() const; Isolate* isolate() const; CodeGenerator* code_generator() const; private: PipelineData* const data_; }; namespace { void PrintFunctionSource(OptimizedCompilationInfo* info, Isolate* isolate, int source_id, Handle shared) { if (!shared->script().IsUndefined(isolate)) { Handle