1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "src/compiler.h"
9 #include "src/ast-numbering.h"
10 #include "src/bootstrapper.h"
11 #include "src/codegen.h"
12 #include "src/compilation-cache.h"
13 #include "src/compiler/pipeline.h"
14 #include "src/cpu-profiler.h"
15 #include "src/debug.h"
16 #include "src/deoptimizer.h"
17 #include "src/full-codegen.h"
18 #include "src/gdb-jit.h"
19 #include "src/hydrogen.h"
20 #include "src/isolate-inl.h"
21 #include "src/lithium.h"
22 #include "src/liveedit.h"
23 #include "src/messages.h"
24 #include "src/parser.h"
25 #include "src/prettyprinter.h"
26 #include "src/rewriter.h"
27 #include "src/runtime-profiler.h"
28 #include "src/scanner-character-streams.h"
29 #include "src/scopeinfo.h"
30 #include "src/scopes.h"
31 #include "src/snapshot/serialize.h"
32 #include "src/typing.h"
33 #include "src/vm-state-inl.h"
38 std::ostream& operator<<(std::ostream& os, const SourcePosition& p) {
41 } else if (FLAG_hydrogen_track_positions) {
42 return os << "<" << p.inlining_id() << ":" << p.position() << ">";
44 return os << "<0:" << p.raw() << ">";
49 #define PARSE_INFO_GETTER(type, name) \
50 type CompilationInfo::name() const { \
51 CHECK(parse_info()); \
52 return parse_info()->name(); \
56 #define PARSE_INFO_GETTER_WITH_DEFAULT(type, name, def) \
57 type CompilationInfo::name() const { \
58 return parse_info() ? parse_info()->name() : def; \
62 PARSE_INFO_GETTER(Handle<Script>, script)
63 PARSE_INFO_GETTER(bool, is_eval)
64 PARSE_INFO_GETTER(bool, is_native)
65 PARSE_INFO_GETTER(bool, is_module)
66 PARSE_INFO_GETTER(LanguageMode, language_mode)
67 PARSE_INFO_GETTER_WITH_DEFAULT(Handle<JSFunction>, closure,
68 Handle<JSFunction>::null())
69 PARSE_INFO_GETTER(FunctionLiteral*, function)
70 PARSE_INFO_GETTER_WITH_DEFAULT(Scope*, scope, nullptr)
71 PARSE_INFO_GETTER(Handle<Context>, context)
72 PARSE_INFO_GETTER(Handle<SharedFunctionInfo>, shared_info)
74 #undef PARSE_INFO_GETTER
75 #undef PARSE_INFO_GETTER_WITH_DEFAULT
78 // Exactly like a CompilationInfo, except being allocated via {new} and it also
79 // creates and enters a Zone on construction and deallocates it on destruction.
80 class CompilationInfoWithZone : public CompilationInfo {
82 explicit CompilationInfoWithZone(Handle<JSFunction> function)
83 : CompilationInfo(new ParseInfo(&zone_, function)) {}
85 // Virtual destructor because a CompilationInfoWithZone has to exit the
86 // zone scope and get rid of dependent maps even when the destructor is
87 // called when cast as a CompilationInfo.
88 virtual ~CompilationInfoWithZone() {
89 DisableFutureOptimization();
90 RollbackDependencies();
92 parse_info_ = nullptr;
100 bool CompilationInfo::has_shared_info() const {
101 return parse_info_ && !parse_info_->shared_info().is_null();
105 CompilationInfo::CompilationInfo(ParseInfo* parse_info)
106 : CompilationInfo(parse_info, nullptr, BASE, parse_info->isolate(),
107 parse_info->zone()) {
108 // Compiling for the snapshot typically results in different code than
109 // compiling later on. This means that code recompiled with deoptimization
110 // support won't be "equivalent" (as defined by SharedFunctionInfo::
111 // EnableDeoptimizationSupport), so it will replace the old code and all
112 // its type feedback. To avoid this, always compile functions in the snapshot
113 // with deoptimization support.
114 if (isolate_->serializer_enabled()) EnableDeoptimizationSupport();
116 if (isolate_->debug()->is_active()) MarkAsDebug();
117 if (FLAG_context_specialization) MarkAsContextSpecializing();
118 if (FLAG_turbo_builtin_inlining) MarkAsBuiltinInliningEnabled();
119 if (FLAG_turbo_inlining) MarkAsInliningEnabled();
120 if (FLAG_turbo_splitting) MarkAsSplittingEnabled();
121 if (FLAG_turbo_types) MarkAsTypingEnabled();
123 if (has_shared_info() && shared_info()->is_compiled()) {
124 // We should initialize the CompilationInfo feedback vector from the
125 // passed in shared info, rather than creating a new one.
126 feedback_vector_ = Handle<TypeFeedbackVector>(
127 shared_info()->feedback_vector(), parse_info->isolate());
132 CompilationInfo::CompilationInfo(CodeStub* stub, Isolate* isolate, Zone* zone)
133 : CompilationInfo(nullptr, stub, STUB, isolate, zone) {}
136 CompilationInfo::CompilationInfo(ParseInfo* parse_info, CodeStub* code_stub,
137 Mode mode, Isolate* isolate, Zone* zone)
138 : parse_info_(parse_info),
141 code_stub_(code_stub),
143 osr_ast_id_(BailoutId::None()),
145 deferred_handles_(nullptr),
146 bailout_reason_(kNoReason),
147 prologue_offset_(Code::kPrologueOffsetNotSet),
148 no_frame_ranges_(isolate->cpu_profiler()->is_profiling()
149 ? new List<OffsetRange>(2)
151 track_positions_(FLAG_hydrogen_track_positions ||
152 isolate->cpu_profiler()->is_profiling()),
153 opt_count_(has_shared_info() ? shared_info()->opt_count() : 0),
155 optimization_id_(-1),
156 aborted_due_to_dependency_change_(false),
157 osr_expr_stack_height_(0) {
158 std::fill_n(dependencies_, DependentCode::kGroupCount, nullptr);
162 CompilationInfo::~CompilationInfo() {
163 DisableFutureOptimization();
164 delete deferred_handles_;
165 delete no_frame_ranges_;
167 // Check that no dependent maps have been added or added dependent maps have
168 // been rolled back or committed.
169 for (int i = 0; i < DependentCode::kGroupCount; i++) {
170 DCHECK(!dependencies_[i]);
176 void CompilationInfo::CommitDependencies(Handle<Code> code) {
177 bool has_dependencies = false;
178 for (int i = 0; i < DependentCode::kGroupCount; i++) {
180 dependencies_[i] != NULL && dependencies_[i]->length() > 0;
182 // Avoid creating a weak cell for code with no dependencies.
183 if (!has_dependencies) return;
185 AllowDeferredHandleDereference get_object_wrapper;
186 WeakCell* cell = *Code::WeakCellFor(code);
187 for (int i = 0; i < DependentCode::kGroupCount; i++) {
188 ZoneList<Handle<HeapObject> >* group_objects = dependencies_[i];
189 if (group_objects == NULL) continue;
190 DCHECK(!object_wrapper_.is_null());
191 for (int j = 0; j < group_objects->length(); j++) {
192 DependentCode::DependencyGroup group =
193 static_cast<DependentCode::DependencyGroup>(i);
194 Foreign* info = *object_wrapper();
195 DependentCode* dependent_code =
196 DependentCode::ForObject(group_objects->at(j), group);
197 dependent_code->UpdateToFinishedCode(group, info, cell);
199 dependencies_[i] = NULL; // Zone-allocated, no need to delete.
204 void CompilationInfo::RollbackDependencies() {
205 AllowDeferredHandleDereference get_object_wrapper;
206 // Unregister from all dependent maps if not yet committed.
207 for (int i = 0; i < DependentCode::kGroupCount; i++) {
208 ZoneList<Handle<HeapObject> >* group_objects = dependencies_[i];
209 if (group_objects == NULL) continue;
210 for (int j = 0; j < group_objects->length(); j++) {
211 DependentCode::DependencyGroup group =
212 static_cast<DependentCode::DependencyGroup>(i);
213 Foreign* info = *object_wrapper();
214 DependentCode* dependent_code =
215 DependentCode::ForObject(group_objects->at(j), group);
216 dependent_code->RemoveCompilationInfo(group, info);
218 dependencies_[i] = NULL; // Zone-allocated, no need to delete.
223 int CompilationInfo::num_parameters() const {
224 return has_scope() ? scope()->num_parameters() : parameter_count_;
228 int CompilationInfo::num_heap_slots() const {
229 return has_scope() ? scope()->num_heap_slots() : 0;
233 Code::Flags CompilationInfo::flags() const {
234 return code_stub() != nullptr
235 ? Code::ComputeFlags(
236 code_stub()->GetCodeKind(), code_stub()->GetICState(),
237 code_stub()->GetExtraICState(), code_stub()->GetStubType())
238 : Code::ComputeFlags(Code::OPTIMIZED_FUNCTION);
242 // Primitive functions are unlikely to be picked up by the stack-walking
243 // profiler, so they trigger their own optimization when they're called
244 // for the SharedFunctionInfo::kCallsUntilPrimitiveOptimization-th time.
245 bool CompilationInfo::ShouldSelfOptimize() {
246 return FLAG_crankshaft && !function()->flags()->Contains(kDontSelfOptimize) &&
247 !function()->dont_optimize() &&
248 function()->scope()->AllowsLazyCompilation() &&
249 (!has_shared_info() || !shared_info()->optimization_disabled());
253 void CompilationInfo::EnsureFeedbackVector() {
254 if (feedback_vector_.is_null()) {
255 feedback_vector_ = isolate()->factory()->NewTypeFeedbackVector(
256 function()->feedback_vector_spec());
261 bool CompilationInfo::is_simple_parameter_list() {
262 return scope()->is_simple_parameter_list();
266 int CompilationInfo::TraceInlinedFunction(Handle<SharedFunctionInfo> shared,
267 SourcePosition position,
269 DCHECK(track_positions_);
271 int inline_id = static_cast<int>(inlined_function_infos_.size());
272 InlinedFunctionInfo info(parent_id, position, UnboundScript::kNoScriptId,
273 shared->start_position());
274 if (!shared->script()->IsUndefined()) {
275 Handle<Script> script(Script::cast(shared->script()));
276 info.script_id = script->id()->value();
278 if (FLAG_hydrogen_track_positions && !script->source()->IsUndefined()) {
279 CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer());
280 OFStream os(tracing_scope.file());
281 os << "--- FUNCTION SOURCE (" << shared->DebugName()->ToCString().get()
282 << ") id{" << optimization_id() << "," << inline_id << "} ---\n";
284 DisallowHeapAllocation no_allocation;
285 int start = shared->start_position();
286 int len = shared->end_position() - start;
287 String::SubStringRange source(String::cast(script->source()), start,
289 for (const auto& c : source) {
290 os << AsReversiblyEscapedUC16(c);
294 os << "\n--- END ---\n";
298 inlined_function_infos_.push_back(info);
300 if (FLAG_hydrogen_track_positions && inline_id != 0) {
301 CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer());
302 OFStream os(tracing_scope.file());
303 os << "INLINE (" << shared->DebugName()->ToCString().get() << ") id{"
304 << optimization_id() << "," << inline_id << "} AS " << inline_id
305 << " AT " << position << std::endl;
312 void CompilationInfo::LogDeoptCallPosition(int pc_offset, int inlining_id) {
313 if (!track_positions_ || IsStub()) return;
314 DCHECK_LT(static_cast<size_t>(inlining_id), inlined_function_infos_.size());
315 inlined_function_infos_.at(inlining_id).deopt_pc_offsets.push_back(pc_offset);
319 class HOptimizedGraphBuilderWithPositions: public HOptimizedGraphBuilder {
321 explicit HOptimizedGraphBuilderWithPositions(CompilationInfo* info)
322 : HOptimizedGraphBuilder(info) {
325 #define DEF_VISIT(type) \
326 void Visit##type(type* node) OVERRIDE { \
327 SourcePosition old_position = SourcePosition::Unknown(); \
328 if (node->position() != RelocInfo::kNoPosition) { \
329 old_position = source_position(); \
330 SetSourcePosition(node->position()); \
332 HOptimizedGraphBuilder::Visit##type(node); \
333 if (!old_position.IsUnknown()) { \
334 set_source_position(old_position); \
337 EXPRESSION_NODE_LIST(DEF_VISIT)
340 #define DEF_VISIT(type) \
341 void Visit##type(type* node) OVERRIDE { \
342 SourcePosition old_position = SourcePosition::Unknown(); \
343 if (node->position() != RelocInfo::kNoPosition) { \
344 old_position = source_position(); \
345 SetSourcePosition(node->position()); \
347 HOptimizedGraphBuilder::Visit##type(node); \
348 if (!old_position.IsUnknown()) { \
349 set_source_position(old_position); \
352 STATEMENT_NODE_LIST(DEF_VISIT)
355 #define DEF_VISIT(type) \
356 void Visit##type(type* node) OVERRIDE { \
357 HOptimizedGraphBuilder::Visit##type(node); \
359 MODULE_NODE_LIST(DEF_VISIT)
360 DECLARATION_NODE_LIST(DEF_VISIT)
365 OptimizedCompileJob::Status OptimizedCompileJob::CreateGraph() {
366 DCHECK(info()->IsOptimizing());
367 DCHECK(!info()->IsCompilingForDebugging());
369 // Do not use Crankshaft/TurboFan if we need to be able to set break points.
370 if (isolate()->debug()->has_break_points()) {
371 return RetryOptimization(kDebuggerHasBreakPoints);
374 // Limit the number of times we re-compile a functions with
375 // the optimizing compiler.
376 const int kMaxOptCount =
377 FLAG_deopt_every_n_times == 0 ? FLAG_max_opt_count : 1000;
378 if (info()->opt_count() > kMaxOptCount) {
379 return AbortOptimization(kOptimizedTooManyTimes);
382 // Due to an encoding limit on LUnallocated operands in the Lithium
383 // language, we cannot optimize functions with too many formal parameters
384 // or perform on-stack replacement for function with too many
385 // stack-allocated local variables.
387 // The encoding is as a signed value, with parameters and receiver using
388 // the negative indices and locals the non-negative ones.
389 const int parameter_limit = -LUnallocated::kMinFixedSlotIndex;
390 Scope* scope = info()->scope();
391 if ((scope->num_parameters() + 1) > parameter_limit) {
392 return AbortOptimization(kTooManyParameters);
395 const int locals_limit = LUnallocated::kMaxFixedSlotIndex;
396 if (info()->is_osr() &&
397 scope->num_parameters() + 1 + scope->num_stack_slots() > locals_limit) {
398 return AbortOptimization(kTooManyParametersLocals);
401 if (scope->HasIllegalRedeclaration()) {
402 return AbortOptimization(kFunctionWithIllegalRedeclaration);
405 // Check the whitelist for Crankshaft.
406 if (!info()->closure()->PassesFilter(FLAG_hydrogen_filter)) {
407 return AbortOptimization(kHydrogenFilter);
410 // Crankshaft requires a version of fullcode with deoptimization support.
411 // Recompile the unoptimized version of the code if the current version
412 // doesn't have deoptimization support already.
413 // Otherwise, if we are gathering compilation time and space statistics
414 // for hydrogen, gather baseline statistics for a fullcode compilation.
415 bool should_recompile = !info()->shared_info()->has_deoptimization_support();
416 if (should_recompile || FLAG_hydrogen_stats) {
417 base::ElapsedTimer timer;
418 if (FLAG_hydrogen_stats) {
421 if (!Compiler::EnsureDeoptimizationSupport(info())) {
422 return SetLastStatus(FAILED);
424 if (FLAG_hydrogen_stats) {
425 isolate()->GetHStatistics()->IncrementFullCodeGen(timer.Elapsed());
429 DCHECK(info()->shared_info()->has_deoptimization_support());
431 // Check the whitelist for TurboFan.
432 if ((FLAG_turbo_asm && info()->shared_info()->asm_function()) ||
433 info()->closure()->PassesFilter(FLAG_turbo_filter)) {
434 if (FLAG_trace_opt) {
436 os << "[compiling method " << Brief(*info()->closure())
437 << " using TurboFan";
438 if (info()->is_osr()) os << " OSR";
439 os << "]" << std::endl;
442 if (info()->shared_info()->asm_function()) {
443 info()->MarkAsContextSpecializing();
444 } else if (FLAG_turbo_type_feedback) {
445 info()->MarkAsTypeFeedbackEnabled();
448 Timer t(this, &time_taken_to_create_graph_);
449 compiler::Pipeline pipeline(info());
450 pipeline.GenerateCode();
451 if (!info()->code().is_null()) {
452 return SetLastStatus(SUCCEEDED);
456 // Do not use Crankshaft if the code is intended to be serialized.
457 if (!isolate()->use_crankshaft()) return SetLastStatus(FAILED);
459 if (FLAG_trace_opt) {
461 os << "[compiling method " << Brief(*info()->closure())
462 << " using Crankshaft";
463 if (info()->is_osr()) os << " OSR";
464 os << "]" << std::endl;
467 if (FLAG_trace_hydrogen) {
468 isolate()->GetHTracer()->TraceCompilation(info());
471 // Type-check the function.
472 AstTyper::Run(info());
474 // Optimization could have been disabled by the parser. Note that this check
475 // is only needed because the Hydrogen graph builder is missing some bailouts.
476 if (info()->shared_info()->optimization_disabled()) {
477 return AbortOptimization(
478 info()->shared_info()->disable_optimization_reason());
481 graph_builder_ = (info()->is_tracking_positions() || FLAG_trace_ic)
482 ? new (info()->zone())
483 HOptimizedGraphBuilderWithPositions(info())
484 : new (info()->zone()) HOptimizedGraphBuilder(info());
486 Timer t(this, &time_taken_to_create_graph_);
487 graph_ = graph_builder_->CreateGraph();
489 if (isolate()->has_pending_exception()) {
490 return SetLastStatus(FAILED);
493 if (graph_ == NULL) return SetLastStatus(BAILED_OUT);
495 if (info()->HasAbortedDueToDependencyChange()) {
496 // Dependency has changed during graph creation. Let's try again later.
497 return RetryOptimization(kBailedOutDueToDependencyChange);
500 return SetLastStatus(SUCCEEDED);
504 OptimizedCompileJob::Status OptimizedCompileJob::OptimizeGraph() {
505 DisallowHeapAllocation no_allocation;
506 DisallowHandleAllocation no_handles;
507 DisallowHandleDereference no_deref;
508 DisallowCodeDependencyChange no_dependency_change;
510 DCHECK(last_status() == SUCCEEDED);
511 // TODO(turbofan): Currently everything is done in the first phase.
512 if (!info()->code().is_null()) {
513 return last_status();
516 Timer t(this, &time_taken_to_optimize_);
517 DCHECK(graph_ != NULL);
518 BailoutReason bailout_reason = kNoReason;
520 if (graph_->Optimize(&bailout_reason)) {
521 chunk_ = LChunk::NewChunk(graph_);
522 if (chunk_ != NULL) return SetLastStatus(SUCCEEDED);
523 } else if (bailout_reason != kNoReason) {
524 graph_builder_->Bailout(bailout_reason);
527 return SetLastStatus(BAILED_OUT);
531 OptimizedCompileJob::Status OptimizedCompileJob::GenerateCode() {
532 DCHECK(last_status() == SUCCEEDED);
533 // TODO(turbofan): Currently everything is done in the first phase.
534 if (!info()->code().is_null()) {
535 if (FLAG_turbo_deoptimization) {
536 info()->parse_info()->context()->native_context()->AddOptimizedCode(
539 RecordOptimizationStats();
540 return last_status();
543 DCHECK(!info()->HasAbortedDueToDependencyChange());
544 DisallowCodeDependencyChange no_dependency_change;
545 DisallowJavascriptExecution no_js(isolate());
546 { // Scope for timer.
547 Timer timer(this, &time_taken_to_codegen_);
548 DCHECK(chunk_ != NULL);
549 DCHECK(graph_ != NULL);
550 // Deferred handles reference objects that were accessible during
551 // graph creation. To make sure that we don't encounter inconsistencies
552 // between graph creation and code generation, we disallow accessing
553 // objects through deferred handles during the latter, with exceptions.
554 DisallowDeferredHandleDereference no_deferred_handle_deref;
555 Handle<Code> optimized_code = chunk_->Codegen();
556 if (optimized_code.is_null()) {
557 if (info()->bailout_reason() == kNoReason) {
558 return AbortOptimization(kCodeGenerationFailed);
560 return SetLastStatus(BAILED_OUT);
562 info()->SetCode(optimized_code);
564 RecordOptimizationStats();
565 // Add to the weak list of optimized code objects.
566 info()->context()->native_context()->AddOptimizedCode(*info()->code());
567 return SetLastStatus(SUCCEEDED);
571 void OptimizedCompileJob::RecordOptimizationStats() {
572 Handle<JSFunction> function = info()->closure();
573 if (!function->IsOptimized()) {
574 // Concurrent recompilation and OSR may race. Increment only once.
575 int opt_count = function->shared()->opt_count();
576 function->shared()->set_opt_count(opt_count + 1);
578 double ms_creategraph = time_taken_to_create_graph_.InMillisecondsF();
579 double ms_optimize = time_taken_to_optimize_.InMillisecondsF();
580 double ms_codegen = time_taken_to_codegen_.InMillisecondsF();
581 if (FLAG_trace_opt) {
582 PrintF("[optimizing ");
583 function->ShortPrint();
584 PrintF(" - took %0.3f, %0.3f, %0.3f ms]\n", ms_creategraph, ms_optimize,
587 if (FLAG_trace_opt_stats) {
588 static double compilation_time = 0.0;
589 static int compiled_functions = 0;
590 static int code_size = 0;
592 compilation_time += (ms_creategraph + ms_optimize + ms_codegen);
593 compiled_functions++;
594 code_size += function->shared()->SourceSize();
595 PrintF("Compiled: %d functions with %d byte source size in %fms.\n",
600 if (FLAG_hydrogen_stats) {
601 isolate()->GetHStatistics()->IncrementSubtotals(time_taken_to_create_graph_,
602 time_taken_to_optimize_,
603 time_taken_to_codegen_);
608 // Sets the expected number of properties based on estimate from compiler.
609 void SetExpectedNofPropertiesFromEstimate(Handle<SharedFunctionInfo> shared,
611 // If no properties are added in the constructor, they are more likely
612 // to be added later.
613 if (estimate == 0) estimate = 2;
615 // TODO(yangguo): check whether those heuristics are still up-to-date.
616 // We do not shrink objects that go into a snapshot (yet), so we adjust
617 // the estimate conservatively.
618 if (shared->GetIsolate()->serializer_enabled()) {
621 // Inobject slack tracking will reclaim redundant inobject space later,
622 // so we can afford to adjust the estimate generously.
626 shared->set_expected_nof_properties(estimate);
630 static void MaybeDisableOptimization(Handle<SharedFunctionInfo> shared_info,
631 BailoutReason bailout_reason) {
632 if (bailout_reason != kNoReason) {
633 shared_info->DisableOptimization(bailout_reason);
638 static void RecordFunctionCompilation(Logger::LogEventsAndTags tag,
639 CompilationInfo* info,
640 Handle<SharedFunctionInfo> shared) {
641 // SharedFunctionInfo is passed separately, because if CompilationInfo
642 // was created using Script object, it will not have it.
644 // Log the code generation. If source information is available include
645 // script name and line number. Check explicitly whether logging is
646 // enabled as finding the line number is not free.
647 if (info->isolate()->logger()->is_logging_code_events() ||
648 info->isolate()->cpu_profiler()->is_profiling()) {
649 Handle<Script> script = info->parse_info()->script();
650 Handle<Code> code = info->code();
651 if (code.is_identical_to(info->isolate()->builtins()->CompileLazy())) {
654 int line_num = Script::GetLineNumber(script, shared->start_position()) + 1;
656 Script::GetColumnNumber(script, shared->start_position()) + 1;
657 String* script_name = script->name()->IsString()
658 ? String::cast(script->name())
659 : info->isolate()->heap()->empty_string();
660 Logger::LogEventsAndTags log_tag = Logger::ToNativeByScript(tag, *script);
661 PROFILE(info->isolate(),
662 CodeCreateEvent(log_tag, *code, *shared, info, script_name,
663 line_num, column_num));
668 static bool CompileUnoptimizedCode(CompilationInfo* info) {
669 DCHECK(AllowCompilation::IsAllowed(info->isolate()));
670 if (!Compiler::Analyze(info->parse_info()) ||
671 !FullCodeGenerator::MakeCode(info)) {
672 Isolate* isolate = info->isolate();
673 if (!isolate->has_pending_exception()) isolate->StackOverflow();
680 MUST_USE_RESULT static MaybeHandle<Code> GetUnoptimizedCodeCommon(
681 CompilationInfo* info) {
682 VMState<COMPILER> state(info->isolate());
683 PostponeInterruptsScope postpone(info->isolate());
685 // Parse and update CompilationInfo with the results.
686 if (!Parser::ParseStatic(info->parse_info())) return MaybeHandle<Code>();
687 Handle<SharedFunctionInfo> shared = info->shared_info();
688 FunctionLiteral* lit = info->function();
689 shared->set_language_mode(lit->language_mode());
690 SetExpectedNofPropertiesFromEstimate(shared, lit->expected_property_count());
691 MaybeDisableOptimization(shared, lit->dont_optimize_reason());
693 // Compile unoptimized code.
694 if (!CompileUnoptimizedCode(info)) return MaybeHandle<Code>();
696 CHECK_EQ(Code::FUNCTION, info->code()->kind());
697 RecordFunctionCompilation(Logger::LAZY_COMPILE_TAG, info, shared);
699 // Update the shared function info with the scope info. Allocating the
700 // ScopeInfo object may cause a GC.
701 Handle<ScopeInfo> scope_info =
702 ScopeInfo::Create(info->isolate(), info->zone(), info->scope());
703 shared->set_scope_info(*scope_info);
705 // Update the code and feedback vector for the shared function info.
706 shared->ReplaceCode(*info->code());
707 if (shared->optimization_disabled()) info->code()->set_optimizable(false);
708 shared->set_feedback_vector(*info->feedback_vector());
714 MUST_USE_RESULT static MaybeHandle<Code> GetCodeFromOptimizedCodeMap(
715 Handle<JSFunction> function, BailoutId osr_ast_id) {
716 if (FLAG_cache_optimized_code) {
717 Handle<SharedFunctionInfo> shared(function->shared());
718 // Bound functions are not cached.
719 if (shared->bound()) return MaybeHandle<Code>();
720 DisallowHeapAllocation no_gc;
721 int index = shared->SearchOptimizedCodeMap(
722 function->context()->native_context(), osr_ast_id);
724 if (FLAG_trace_opt) {
725 PrintF("[found optimized code for ");
726 function->ShortPrint();
727 if (!osr_ast_id.IsNone()) {
728 PrintF(" at OSR AST id %d", osr_ast_id.ToInt());
732 FixedArray* literals = shared->GetLiteralsFromOptimizedCodeMap(index);
733 if (literals != NULL) function->set_literals(literals);
734 return Handle<Code>(shared->GetCodeFromOptimizedCodeMap(index));
737 return MaybeHandle<Code>();
741 static void InsertCodeIntoOptimizedCodeMap(CompilationInfo* info) {
742 Handle<Code> code = info->code();
743 if (code->kind() != Code::OPTIMIZED_FUNCTION) return; // Nothing to do.
745 // Context specialization folds-in the context, so no sharing can occur.
746 if (code->is_turbofanned() && info->is_context_specializing()) return;
748 // Cache optimized code.
749 if (FLAG_cache_optimized_code) {
750 Handle<JSFunction> function = info->closure();
751 Handle<SharedFunctionInfo> shared(function->shared());
752 // Do not cache bound functions.
753 if (shared->bound()) return;
754 Handle<FixedArray> literals(function->literals());
755 Handle<Context> native_context(function->context()->native_context());
756 SharedFunctionInfo::AddToOptimizedCodeMap(shared, native_context, code,
757 literals, info->osr_ast_id());
762 static bool Renumber(ParseInfo* parse_info) {
763 if (!AstNumbering::Renumber(parse_info->isolate(), parse_info->zone(),
764 parse_info->function())) {
767 Handle<SharedFunctionInfo> shared_info = parse_info->shared_info();
768 if (!shared_info.is_null()) {
769 FunctionLiteral* lit = parse_info->function();
770 shared_info->set_ast_node_count(lit->ast_node_count());
771 MaybeDisableOptimization(shared_info, lit->dont_optimize_reason());
772 shared_info->set_dont_cache(lit->flags()->Contains(kDontCache));
778 bool Compiler::Analyze(ParseInfo* info) {
779 DCHECK(info->function() != NULL);
780 if (!Rewriter::Rewrite(info)) return false;
781 if (!Scope::Analyze(info)) return false;
782 if (!Renumber(info)) return false;
783 DCHECK(info->scope() != NULL);
788 bool Compiler::ParseAndAnalyze(ParseInfo* info) {
789 if (!Parser::ParseStatic(info)) return false;
790 return Compiler::Analyze(info);
794 static bool GetOptimizedCodeNow(CompilationInfo* info) {
795 if (!Compiler::ParseAndAnalyze(info->parse_info())) return false;
797 TimerEventScope<TimerEventRecompileSynchronous> timer(info->isolate());
799 OptimizedCompileJob job(info);
800 if (job.CreateGraph() != OptimizedCompileJob::SUCCEEDED ||
801 job.OptimizeGraph() != OptimizedCompileJob::SUCCEEDED ||
802 job.GenerateCode() != OptimizedCompileJob::SUCCEEDED) {
803 if (FLAG_trace_opt) {
804 PrintF("[aborted optimizing ");
805 info->closure()->ShortPrint();
806 PrintF(" because: %s]\n", GetBailoutReason(info->bailout_reason()));
812 DCHECK(!info->isolate()->has_pending_exception());
813 InsertCodeIntoOptimizedCodeMap(info);
814 RecordFunctionCompilation(Logger::LAZY_COMPILE_TAG, info,
815 info->shared_info());
820 static bool GetOptimizedCodeLater(CompilationInfo* info) {
821 Isolate* isolate = info->isolate();
822 if (!isolate->optimizing_compiler_thread()->IsQueueAvailable()) {
823 if (FLAG_trace_concurrent_recompilation) {
824 PrintF(" ** Compilation queue full, will retry optimizing ");
825 info->closure()->ShortPrint();
831 CompilationHandleScope handle_scope(info);
832 if (!Compiler::ParseAndAnalyze(info->parse_info())) return false;
834 // Reopen handles in the new CompilationHandleScope.
835 info->ReopenHandlesInNewHandleScope();
836 info->parse_info()->ReopenHandlesInNewHandleScope();
838 TimerEventScope<TimerEventRecompileSynchronous> timer(info->isolate());
840 OptimizedCompileJob* job = new (info->zone()) OptimizedCompileJob(info);
841 OptimizedCompileJob::Status status = job->CreateGraph();
842 if (status != OptimizedCompileJob::SUCCEEDED) return false;
843 isolate->optimizing_compiler_thread()->QueueForOptimization(job);
845 if (FLAG_trace_concurrent_recompilation) {
846 PrintF(" ** Queued ");
847 info->closure()->ShortPrint();
848 if (info->is_osr()) {
849 PrintF(" for concurrent OSR at %d.\n", info->osr_ast_id().ToInt());
851 PrintF(" for concurrent optimization.\n");
858 MaybeHandle<Code> Compiler::GetUnoptimizedCode(Handle<JSFunction> function) {
859 DCHECK(!function->GetIsolate()->has_pending_exception());
860 DCHECK(!function->is_compiled());
861 if (function->shared()->is_compiled()) {
862 return Handle<Code>(function->shared()->code());
865 CompilationInfoWithZone info(function);
867 ASSIGN_RETURN_ON_EXCEPTION(info.isolate(), result,
868 GetUnoptimizedCodeCommon(&info),
874 MaybeHandle<Code> Compiler::GetLazyCode(Handle<JSFunction> function) {
875 Isolate* isolate = function->GetIsolate();
876 DCHECK(!isolate->has_pending_exception());
877 DCHECK(!function->is_compiled());
878 AggregatedHistogramTimerScope timer(isolate->counters()->compile_lazy());
879 // If the debugger is active, do not compile with turbofan unless we can
880 // deopt from turbofan code.
881 if (FLAG_turbo_asm && function->shared()->asm_function() &&
882 (FLAG_turbo_deoptimization || !isolate->debug()->is_active()) &&
884 CompilationInfoWithZone info(function);
886 VMState<COMPILER> state(isolate);
887 PostponeInterruptsScope postpone(isolate);
889 info.SetOptimizing(BailoutId::None(), handle(function->shared()->code()));
891 if (GetOptimizedCodeNow(&info)) {
892 DCHECK(function->shared()->is_compiled());
895 // We have failed compilation. If there was an exception clear it so that
896 // we can compile unoptimized code.
897 if (isolate->has_pending_exception()) isolate->clear_pending_exception();
900 if (function->shared()->is_compiled()) {
901 return Handle<Code>(function->shared()->code());
904 CompilationInfoWithZone info(function);
906 ASSIGN_RETURN_ON_EXCEPTION(isolate, result, GetUnoptimizedCodeCommon(&info),
909 if (FLAG_always_opt) {
910 Handle<Code> opt_code;
911 if (Compiler::GetOptimizedCode(
913 Compiler::NOT_CONCURRENT).ToHandle(&opt_code)) {
922 MaybeHandle<Code> Compiler::GetUnoptimizedCode(
923 Handle<SharedFunctionInfo> shared) {
924 DCHECK(!shared->GetIsolate()->has_pending_exception());
925 DCHECK(!shared->is_compiled());
928 ParseInfo parse_info(&zone, shared);
929 CompilationInfo info(&parse_info);
930 return GetUnoptimizedCodeCommon(&info);
934 bool Compiler::EnsureCompiled(Handle<JSFunction> function,
935 ClearExceptionFlag flag) {
936 if (function->is_compiled()) return true;
937 MaybeHandle<Code> maybe_code = Compiler::GetLazyCode(function);
939 if (!maybe_code.ToHandle(&code)) {
940 if (flag == CLEAR_EXCEPTION) {
941 function->GetIsolate()->clear_pending_exception();
945 function->ReplaceCode(*code);
946 DCHECK(function->is_compiled());
951 // TODO(turbofan): In the future, unoptimized code with deopt support could
952 // be generated lazily once deopt is triggered.
953 bool Compiler::EnsureDeoptimizationSupport(CompilationInfo* info) {
954 DCHECK(info->function() != NULL);
955 DCHECK(info->scope() != NULL);
956 Handle<SharedFunctionInfo> shared = info->shared_info();
957 if (!shared->has_deoptimization_support()) {
958 // TODO(titzer): just reuse the ParseInfo for the unoptimized compile.
959 CompilationInfoWithZone unoptimized(info->closure());
960 // Note that we use the same AST that we will use for generating the
962 ParseInfo* parse_info = unoptimized.parse_info();
963 parse_info->set_literal(info->function());
964 parse_info->set_scope(info->scope());
965 parse_info->set_context(info->context());
966 unoptimized.EnableDeoptimizationSupport();
967 // If the current code has reloc info for serialization, also include
968 // reloc info for serialization for the new code, so that deopt support
969 // can be added without losing IC state.
970 if (shared->code()->kind() == Code::FUNCTION &&
971 shared->code()->has_reloc_info_for_serialization()) {
972 unoptimized.PrepareForSerializing();
974 if (!FullCodeGenerator::MakeCode(&unoptimized)) return false;
976 shared->EnableDeoptimizationSupport(*unoptimized.code());
977 shared->set_feedback_vector(*unoptimized.feedback_vector());
979 // The scope info might not have been set if a lazily compiled
980 // function is inlined before being called for the first time.
981 if (shared->scope_info() == ScopeInfo::Empty(info->isolate())) {
982 Handle<ScopeInfo> target_scope_info =
983 ScopeInfo::Create(info->isolate(), info->zone(), info->scope());
984 shared->set_scope_info(*target_scope_info);
987 // The existing unoptimized code was replaced with the new one.
988 RecordFunctionCompilation(Logger::LAZY_COMPILE_TAG, &unoptimized, shared);
994 // Compile full code for debugging. This code will have debug break slots
995 // and deoptimization information. Deoptimization information is required
996 // in case that an optimized version of this function is still activated on
997 // the stack. It will also make sure that the full code is compiled with
998 // the same flags as the previous version, that is flags which can change
999 // the code generated. The current method of mapping from already compiled
1000 // full code without debug break slots to full code with debug break slots
1001 // depends on the generated code is otherwise exactly the same.
1002 // If compilation fails, just keep the existing code.
1003 MaybeHandle<Code> Compiler::GetDebugCode(Handle<JSFunction> function) {
1004 CompilationInfoWithZone info(function);
1005 Isolate* isolate = info.isolate();
1006 VMState<COMPILER> state(isolate);
1010 DCHECK(!isolate->has_pending_exception());
1011 Handle<Code> old_code(function->shared()->code());
1012 DCHECK(old_code->kind() == Code::FUNCTION);
1013 DCHECK(!old_code->has_debug_break_slots());
1015 info.MarkCompilingForDebugging();
1016 if (old_code->is_compiled_optimizable()) {
1017 info.EnableDeoptimizationSupport();
1019 info.MarkNonOptimizable();
1021 MaybeHandle<Code> maybe_new_code = GetUnoptimizedCodeCommon(&info);
1022 Handle<Code> new_code;
1023 if (!maybe_new_code.ToHandle(&new_code)) {
1024 isolate->clear_pending_exception();
1026 DCHECK_EQ(old_code->is_compiled_optimizable(),
1027 new_code->is_compiled_optimizable());
1029 return maybe_new_code;
1033 void Compiler::CompileForLiveEdit(Handle<Script> script) {
1034 // TODO(635): support extensions.
1036 ParseInfo parse_info(&zone, script);
1037 CompilationInfo info(&parse_info);
1038 PostponeInterruptsScope postpone(info.isolate());
1039 VMState<COMPILER> state(info.isolate());
1041 info.parse_info()->set_global();
1042 if (!Parser::ParseStatic(info.parse_info())) return;
1044 LiveEditFunctionTracker tracker(info.isolate(), info.function());
1045 if (!CompileUnoptimizedCode(&info)) return;
1046 if (info.has_shared_info()) {
1047 Handle<ScopeInfo> scope_info =
1048 ScopeInfo::Create(info.isolate(), info.zone(), info.scope());
1049 info.shared_info()->set_scope_info(*scope_info);
1051 tracker.RecordRootFunctionInfo(info.code());
1055 static Handle<SharedFunctionInfo> CompileToplevel(CompilationInfo* info) {
1056 Isolate* isolate = info->isolate();
1057 PostponeInterruptsScope postpone(isolate);
1058 DCHECK(!isolate->native_context().is_null());
1059 ParseInfo* parse_info = info->parse_info();
1060 Handle<Script> script = parse_info->script();
1062 // TODO(svenpanne) Obscure place for this, perhaps move to OnBeforeCompile?
1063 FixedArray* array = isolate->native_context()->embedder_data();
1064 script->set_context_data(array->get(v8::Context::kDebugIdIndex));
1066 isolate->debug()->OnBeforeCompile(script);
1068 DCHECK(parse_info->is_eval() || parse_info->is_global() ||
1069 parse_info->is_module());
1071 parse_info->set_toplevel();
1073 Handle<SharedFunctionInfo> result;
1075 { VMState<COMPILER> state(info->isolate());
1076 if (parse_info->literal() == NULL) {
1077 // Parse the script if needed (if it's already parsed, function() is
1079 ScriptCompiler::CompileOptions options = parse_info->compile_options();
1080 bool parse_allow_lazy = (options == ScriptCompiler::kConsumeParserCache ||
1081 String::cast(script->source())->length() >
1082 FLAG_min_preparse_length) &&
1083 !Compiler::DebuggerWantsEagerCompilation(isolate);
1085 parse_info->set_allow_lazy_parsing(parse_allow_lazy);
1086 if (!parse_allow_lazy &&
1087 (options == ScriptCompiler::kProduceParserCache ||
1088 options == ScriptCompiler::kConsumeParserCache)) {
1089 // We are going to parse eagerly, but we either 1) have cached data
1090 // produced by lazy parsing or 2) are asked to generate cached data.
1091 // Eager parsing cannot benefit from cached data, and producing cached
1092 // data while parsing eagerly is not implemented.
1093 parse_info->set_cached_data(nullptr);
1094 parse_info->set_compile_options(ScriptCompiler::kNoCompileOptions);
1096 if (!Parser::ParseStatic(parse_info)) {
1097 return Handle<SharedFunctionInfo>::null();
1101 FunctionLiteral* lit = info->function();
1102 LiveEditFunctionTracker live_edit_tracker(isolate, lit);
1104 // Measure how long it takes to do the compilation; only take the
1105 // rest of the function into account to avoid overlap with the
1106 // parsing statistics.
1107 HistogramTimer* rate = info->is_eval()
1108 ? info->isolate()->counters()->compile_eval()
1109 : info->isolate()->counters()->compile();
1110 HistogramTimerScope timer(rate);
1112 // Compile the code.
1113 if (!CompileUnoptimizedCode(info)) {
1114 return Handle<SharedFunctionInfo>::null();
1117 // Allocate function.
1118 DCHECK(!info->code().is_null());
1119 result = isolate->factory()->NewSharedFunctionInfo(
1120 lit->name(), lit->materialized_literal_count(), lit->kind(),
1122 ScopeInfo::Create(info->isolate(), info->zone(), info->scope()),
1123 info->feedback_vector());
1125 DCHECK_EQ(RelocInfo::kNoPosition, lit->function_token_position());
1126 SharedFunctionInfo::InitFromFunctionLiteral(result, lit);
1127 result->set_script(*script);
1128 result->set_is_toplevel(true);
1130 Handle<String> script_name = script->name()->IsString()
1131 ? Handle<String>(String::cast(script->name()))
1132 : isolate->factory()->empty_string();
1133 Logger::LogEventsAndTags log_tag = info->is_eval()
1135 : Logger::ToNativeByScript(Logger::SCRIPT_TAG, *script);
1137 PROFILE(isolate, CodeCreateEvent(
1138 log_tag, *info->code(), *result, info, *script_name));
1140 // Hint to the runtime system used when allocating space for initial
1141 // property space by setting the expected number of properties for
1142 // the instances of the function.
1143 SetExpectedNofPropertiesFromEstimate(result,
1144 lit->expected_property_count());
1146 if (!script.is_null())
1147 script->set_compilation_state(Script::COMPILATION_STATE_COMPILED);
1149 live_edit_tracker.RecordFunctionInfo(result, lit, info->zone());
1152 isolate->debug()->OnAfterCompile(script);
1158 MaybeHandle<JSFunction> Compiler::GetFunctionFromEval(
1159 Handle<String> source, Handle<SharedFunctionInfo> outer_info,
1160 Handle<Context> context, LanguageMode language_mode,
1161 ParseRestriction restriction, int scope_position) {
1162 Isolate* isolate = source->GetIsolate();
1163 int source_length = source->length();
1164 isolate->counters()->total_eval_size()->Increment(source_length);
1165 isolate->counters()->total_compile_size()->Increment(source_length);
1167 CompilationCache* compilation_cache = isolate->compilation_cache();
1168 MaybeHandle<SharedFunctionInfo> maybe_shared_info =
1169 compilation_cache->LookupEval(source, outer_info, context, language_mode,
1171 Handle<SharedFunctionInfo> shared_info;
1173 if (!maybe_shared_info.ToHandle(&shared_info)) {
1174 Handle<Script> script = isolate->factory()->NewScript(source);
1176 ParseInfo parse_info(&zone, script);
1177 CompilationInfo info(&parse_info);
1178 parse_info.set_eval();
1179 if (context->IsNativeContext()) parse_info.set_global();
1180 parse_info.set_language_mode(language_mode);
1181 parse_info.set_parse_restriction(restriction);
1182 parse_info.set_context(context);
1184 Debug::RecordEvalCaller(script);
1186 shared_info = CompileToplevel(&info);
1188 if (shared_info.is_null()) {
1189 return MaybeHandle<JSFunction>();
1191 // Explicitly disable optimization for eval code. We're not yet prepared
1192 // to handle eval-code in the optimizing compiler.
1193 if (restriction != ONLY_SINGLE_FUNCTION_LITERAL) {
1194 shared_info->DisableOptimization(kEval);
1197 // If caller is strict mode, the result must be in strict mode as well.
1198 DCHECK(is_sloppy(language_mode) ||
1199 is_strict(shared_info->language_mode()));
1200 if (!shared_info->dont_cache()) {
1201 compilation_cache->PutEval(source, outer_info, context, shared_info,
1205 } else if (shared_info->ic_age() != isolate->heap()->global_ic_age()) {
1206 shared_info->ResetForNewContext(isolate->heap()->global_ic_age());
1209 return isolate->factory()->NewFunctionFromSharedFunctionInfo(
1210 shared_info, context, NOT_TENURED);
1214 Handle<SharedFunctionInfo> Compiler::CompileScript(
1215 Handle<String> source, Handle<Object> script_name, int line_offset,
1216 int column_offset, bool is_embedder_debug_script,
1217 bool is_shared_cross_origin, Handle<Object> source_map_url,
1218 Handle<Context> context, v8::Extension* extension, ScriptData** cached_data,
1219 ScriptCompiler::CompileOptions compile_options, NativesFlag natives,
1221 Isolate* isolate = source->GetIsolate();
1222 if (compile_options == ScriptCompiler::kNoCompileOptions) {
1224 } else if (compile_options == ScriptCompiler::kProduceParserCache ||
1225 compile_options == ScriptCompiler::kProduceCodeCache) {
1226 DCHECK(cached_data && !*cached_data);
1227 DCHECK(extension == NULL);
1228 DCHECK(!isolate->debug()->is_loaded());
1230 DCHECK(compile_options == ScriptCompiler::kConsumeParserCache ||
1231 compile_options == ScriptCompiler::kConsumeCodeCache);
1232 DCHECK(cached_data && *cached_data);
1233 DCHECK(extension == NULL);
1235 int source_length = source->length();
1236 isolate->counters()->total_load_size()->Increment(source_length);
1237 isolate->counters()->total_compile_size()->Increment(source_length);
1239 // TODO(rossberg): The natives do not yet obey strong mode rules
1240 // (for example, some macros use '==').
1241 bool use_strong = FLAG_use_strong && !isolate->bootstrapper()->IsActive();
1242 LanguageMode language_mode =
1243 construct_language_mode(FLAG_use_strict, use_strong);
1245 CompilationCache* compilation_cache = isolate->compilation_cache();
1247 // Do a lookup in the compilation cache but not for extensions.
1248 MaybeHandle<SharedFunctionInfo> maybe_result;
1249 Handle<SharedFunctionInfo> result;
1250 if (extension == NULL) {
1251 // First check per-isolate compilation cache.
1252 maybe_result = compilation_cache->LookupScript(
1253 source, script_name, line_offset, column_offset,
1254 is_embedder_debug_script, is_shared_cross_origin, context,
1256 if (maybe_result.is_null() && FLAG_serialize_toplevel &&
1257 compile_options == ScriptCompiler::kConsumeCodeCache &&
1258 !isolate->debug()->is_loaded()) {
1259 // Then check cached code provided by embedder.
1260 HistogramTimerScope timer(isolate->counters()->compile_deserialize());
1261 Handle<SharedFunctionInfo> result;
1262 if (CodeSerializer::Deserialize(isolate, *cached_data, source)
1263 .ToHandle(&result)) {
1264 // Promote to per-isolate compilation cache.
1265 DCHECK(!result->dont_cache());
1266 compilation_cache->PutScript(source, context, language_mode, result);
1269 // Deserializer failed. Fall through to compile.
1273 base::ElapsedTimer timer;
1274 if (FLAG_profile_deserialization && FLAG_serialize_toplevel &&
1275 compile_options == ScriptCompiler::kProduceCodeCache) {
1279 if (!maybe_result.ToHandle(&result)) {
1280 // No cache entry found. Compile the script.
1282 // Create a script object describing the script to be compiled.
1283 Handle<Script> script = isolate->factory()->NewScript(source);
1284 if (natives == NATIVES_CODE) {
1285 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
1287 if (!script_name.is_null()) {
1288 script->set_name(*script_name);
1289 script->set_line_offset(Smi::FromInt(line_offset));
1290 script->set_column_offset(Smi::FromInt(column_offset));
1292 script->set_is_shared_cross_origin(is_shared_cross_origin);
1293 script->set_is_embedder_debug_script(is_embedder_debug_script);
1294 if (!source_map_url.is_null()) {
1295 script->set_source_mapping_url(*source_map_url);
1298 // Compile the function and add it to the cache.
1300 ParseInfo parse_info(&zone, script);
1301 CompilationInfo info(&parse_info);
1302 if (FLAG_harmony_modules && is_module) {
1303 parse_info.set_module();
1305 parse_info.set_global();
1307 if (compile_options != ScriptCompiler::kNoCompileOptions) {
1308 parse_info.set_cached_data(cached_data);
1310 parse_info.set_compile_options(compile_options);
1311 parse_info.set_extension(extension);
1312 parse_info.set_context(context);
1313 if (FLAG_serialize_toplevel &&
1314 compile_options == ScriptCompiler::kProduceCodeCache) {
1315 info.PrepareForSerializing();
1318 parse_info.set_language_mode(
1319 static_cast<LanguageMode>(info.language_mode() | language_mode));
1320 result = CompileToplevel(&info);
1321 if (extension == NULL && !result.is_null() && !result->dont_cache()) {
1322 compilation_cache->PutScript(source, context, language_mode, result);
1323 if (FLAG_serialize_toplevel &&
1324 compile_options == ScriptCompiler::kProduceCodeCache) {
1325 HistogramTimerScope histogram_timer(
1326 isolate->counters()->compile_serialize());
1327 *cached_data = CodeSerializer::Serialize(isolate, result, source);
1328 if (FLAG_profile_deserialization) {
1329 PrintF("[Compiling and serializing took %0.3f ms]\n",
1330 timer.Elapsed().InMillisecondsF());
1335 if (result.is_null()) isolate->ReportPendingMessages();
1336 } else if (result->ic_age() != isolate->heap()->global_ic_age()) {
1337 result->ResetForNewContext(isolate->heap()->global_ic_age());
1343 Handle<SharedFunctionInfo> Compiler::CompileStreamedScript(
1344 Handle<Script> script, ParseInfo* parse_info, int source_length) {
1345 Isolate* isolate = script->GetIsolate();
1346 // TODO(titzer): increment the counters in caller.
1347 isolate->counters()->total_load_size()->Increment(source_length);
1348 isolate->counters()->total_compile_size()->Increment(source_length);
1350 LanguageMode language_mode =
1351 construct_language_mode(FLAG_use_strict, FLAG_use_strong);
1352 parse_info->set_language_mode(
1353 static_cast<LanguageMode>(parse_info->language_mode() | language_mode));
1355 CompilationInfo compile_info(parse_info);
1356 // TODO(marja): FLAG_serialize_toplevel is not honoured and won't be; when the
1357 // real code caching lands, streaming needs to be adapted to use it.
1358 return CompileToplevel(&compile_info);
1362 Handle<SharedFunctionInfo> Compiler::BuildFunctionInfo(
1363 FunctionLiteral* literal, Handle<Script> script,
1364 CompilationInfo* outer_info) {
1365 // Precondition: code has been parsed and scopes have been analyzed.
1367 ParseInfo parse_info(&zone, script);
1368 CompilationInfo info(&parse_info);
1369 parse_info.set_literal(literal);
1370 parse_info.set_scope(literal->scope());
1371 parse_info.set_language_mode(literal->scope()->language_mode());
1372 if (outer_info->will_serialize()) info.PrepareForSerializing();
1374 Isolate* isolate = info.isolate();
1375 Factory* factory = isolate->factory();
1376 LiveEditFunctionTracker live_edit_tracker(isolate, literal);
1377 // Determine if the function can be lazily compiled. This is necessary to
1378 // allow some of our builtin JS files to be lazily compiled. These
1379 // builtins cannot be handled lazily by the parser, since we have to know
1380 // if a function uses the special natives syntax, which is something the
1382 // If the debugger requests compilation for break points, we cannot be
1383 // aggressive about lazy compilation, because it might trigger compilation
1384 // of functions without an outer context when setting a breakpoint through
1385 // Debug::FindSharedFunctionInfoInScript.
1386 bool allow_lazy_without_ctx = literal->AllowsLazyCompilationWithoutContext();
1388 literal->AllowsLazyCompilation() &&
1389 !DebuggerWantsEagerCompilation(isolate, allow_lazy_without_ctx);
1391 if (outer_info->parse_info()->is_toplevel() && outer_info->will_serialize()) {
1392 // Make sure that if the toplevel code (possibly to be serialized),
1393 // the inner function must be allowed to be compiled lazily.
1394 // This is necessary to serialize toplevel code without inner functions.
1399 Handle<ScopeInfo> scope_info;
1400 if (FLAG_lazy && allow_lazy && !literal->is_parenthesized()) {
1401 Handle<Code> code = isolate->builtins()->CompileLazy();
1403 // There's no need in theory for a lazy-compiled function to have a type
1404 // feedback vector, but some parts of the system expect all
1405 // SharedFunctionInfo instances to have one. The size of the vector depends
1406 // on how many feedback-needing nodes are in the tree, and when lazily
1407 // parsing we might not know that, if this function was never parsed before.
1408 // In that case the vector will be replaced the next time MakeCode is
1410 info.EnsureFeedbackVector();
1411 scope_info = Handle<ScopeInfo>(ScopeInfo::Empty(isolate));
1412 } else if (Renumber(info.parse_info()) &&
1413 FullCodeGenerator::MakeCode(&info)) {
1414 // MakeCode will ensure that the feedback vector is present and
1415 // appropriately sized.
1416 DCHECK(!info.code().is_null());
1417 scope_info = ScopeInfo::Create(info.isolate(), info.zone(), info.scope());
1419 return Handle<SharedFunctionInfo>::null();
1422 // Create a shared function info object.
1423 Handle<SharedFunctionInfo> result = factory->NewSharedFunctionInfo(
1424 literal->name(), literal->materialized_literal_count(), literal->kind(),
1425 info.code(), scope_info, info.feedback_vector());
1427 SharedFunctionInfo::InitFromFunctionLiteral(result, literal);
1428 result->set_script(*script);
1429 result->set_is_toplevel(false);
1431 RecordFunctionCompilation(Logger::FUNCTION_TAG, &info, result);
1432 result->set_allows_lazy_compilation(literal->AllowsLazyCompilation());
1433 result->set_allows_lazy_compilation_without_context(allow_lazy_without_ctx);
1435 // Set the expected number of properties for instances and return
1436 // the resulting function.
1437 SetExpectedNofPropertiesFromEstimate(result,
1438 literal->expected_property_count());
1439 live_edit_tracker.RecordFunctionInfo(result, literal, info.zone());
1444 MaybeHandle<Code> Compiler::GetOptimizedCode(Handle<JSFunction> function,
1445 Handle<Code> current_code,
1446 ConcurrencyMode mode,
1447 BailoutId osr_ast_id) {
1448 Handle<Code> cached_code;
1449 if (GetCodeFromOptimizedCodeMap(
1450 function, osr_ast_id).ToHandle(&cached_code)) {
1454 SmartPointer<CompilationInfo> info(new CompilationInfoWithZone(function));
1455 Isolate* isolate = info->isolate();
1456 DCHECK(AllowCompilation::IsAllowed(isolate));
1457 VMState<COMPILER> state(isolate);
1458 DCHECK(!isolate->has_pending_exception());
1459 PostponeInterruptsScope postpone(isolate);
1461 Handle<SharedFunctionInfo> shared = info->shared_info();
1462 if (shared->code()->kind() != Code::FUNCTION ||
1463 ScopeInfo::Empty(isolate) == shared->scope_info()) {
1464 // The function was never compiled. Compile it unoptimized first.
1465 // TODO(titzer): reuse the AST and scope info from this compile.
1466 CompilationInfoWithZone nested(function);
1467 nested.EnableDeoptimizationSupport();
1468 if (!GetUnoptimizedCodeCommon(&nested).ToHandle(¤t_code)) {
1469 return MaybeHandle<Code>();
1471 shared->ReplaceCode(*current_code);
1473 current_code->set_profiler_ticks(0);
1475 info->SetOptimizing(osr_ast_id, current_code);
1477 if (mode == CONCURRENT) {
1478 if (GetOptimizedCodeLater(info.get())) {
1479 info.Detach(); // The background recompile job owns this now.
1480 return isolate->builtins()->InOptimizationQueue();
1483 if (GetOptimizedCodeNow(info.get())) return info->code();
1486 if (isolate->has_pending_exception()) isolate->clear_pending_exception();
1487 return MaybeHandle<Code>();
1491 Handle<Code> Compiler::GetConcurrentlyOptimizedCode(OptimizedCompileJob* job) {
1492 // Take ownership of compilation info. Deleting compilation info
1493 // also tears down the zone and the recompile job.
1494 SmartPointer<CompilationInfo> info(job->info());
1495 Isolate* isolate = info->isolate();
1497 VMState<COMPILER> state(isolate);
1498 TimerEventScope<TimerEventRecompileSynchronous> timer(info->isolate());
1500 Handle<SharedFunctionInfo> shared = info->shared_info();
1501 shared->code()->set_profiler_ticks(0);
1503 // 1) Optimization on the concurrent thread may have failed.
1504 // 2) The function may have already been optimized by OSR. Simply continue.
1505 // Except when OSR already disabled optimization for some reason.
1506 // 3) The code may have already been invalidated due to dependency change.
1507 // 4) Debugger may have been activated.
1508 // 5) Code generation may have failed.
1509 if (job->last_status() == OptimizedCompileJob::SUCCEEDED) {
1510 if (shared->optimization_disabled()) {
1511 job->RetryOptimization(kOptimizationDisabled);
1512 } else if (info->HasAbortedDueToDependencyChange()) {
1513 job->RetryOptimization(kBailedOutDueToDependencyChange);
1514 } else if (isolate->debug()->has_break_points()) {
1515 job->RetryOptimization(kDebuggerHasBreakPoints);
1516 } else if (job->GenerateCode() == OptimizedCompileJob::SUCCEEDED) {
1517 RecordFunctionCompilation(Logger::LAZY_COMPILE_TAG, info.get(), shared);
1518 if (info->shared_info()->SearchOptimizedCodeMap(
1519 info->context()->native_context(), info->osr_ast_id()) == -1) {
1520 InsertCodeIntoOptimizedCodeMap(info.get());
1522 if (FLAG_trace_opt) {
1523 PrintF("[completed optimizing ");
1524 info->closure()->ShortPrint();
1527 return Handle<Code>(*info->code());
1531 DCHECK(job->last_status() != OptimizedCompileJob::SUCCEEDED);
1532 if (FLAG_trace_opt) {
1533 PrintF("[aborted optimizing ");
1534 info->closure()->ShortPrint();
1535 PrintF(" because: %s]\n", GetBailoutReason(info->bailout_reason()));
1537 return Handle<Code>::null();
1541 bool Compiler::DebuggerWantsEagerCompilation(Isolate* isolate,
1542 bool allow_lazy_without_ctx) {
1543 if (LiveEditFunctionTracker::IsActive(isolate)) return true;
1544 Debug* debug = isolate->debug();
1545 bool debugging = debug->is_active() || debug->has_break_points();
1546 return debugging && !allow_lazy_without_ctx;
1550 CompilationPhase::CompilationPhase(const char* name, CompilationInfo* info)
1551 : name_(name), info_(info) {
1552 if (FLAG_hydrogen_stats) {
1553 info_zone_start_allocation_size_ = info->zone()->allocation_size();
1559 CompilationPhase::~CompilationPhase() {
1560 if (FLAG_hydrogen_stats) {
1561 size_t size = zone()->allocation_size();
1562 size += info_->zone()->allocation_size() - info_zone_start_allocation_size_;
1563 isolate()->GetHStatistics()->SaveTiming(name_, timer_.Elapsed(), size);
1568 bool CompilationPhase::ShouldProduceTraceOutput() const {
1569 // Trace if the appropriate trace flag is set and the phase name's first
1570 // character is in the FLAG_trace_phase command line parameter.
1571 AllowHandleDereference allow_deref;
1572 bool tracing_on = info()->IsStub()
1573 ? FLAG_trace_hydrogen_stubs
1574 : (FLAG_trace_hydrogen &&
1575 info()->closure()->PassesFilter(FLAG_trace_hydrogen_filter));
1576 return (tracing_on &&
1577 base::OS::StrChr(const_cast<char*>(FLAG_trace_phase), name_[0]) != NULL);
1582 void CompilationInfo::PrintAstForTesting() {
1583 PrintF("--- Source from AST ---\n%s\n",
1584 PrettyPrinter(isolate(), zone()).PrintProgram(function()));
1587 } } // namespace v8::internal