71#ifdef V8_ENABLE_MAGLEV
81constexpr bool IsOSR(BytecodeOffset osr_offset) {
return !osr_offset.IsNone(); }
83class CompilerTracer :
public AllStatic {
85 static void TraceStartBaselineCompile(
86 Isolate* isolate, DirectHandle<SharedFunctionInfo> shared) {
87 if (!
v8_flags.trace_baseline)
return;
88 CodeTracer::Scope scope(isolate->GetCodeTracer());
89 PrintTracePrefix(scope,
"compiling method", shared, CodeKind::BASELINE);
90 PrintTraceSuffix(scope);
93 static void TraceStartMaglevCompile(Isolate* isolate,
94 DirectHandle<JSFunction> function,
97 CodeTracer::Scope scope(isolate->GetCodeTracer());
98 PrintTracePrefix(scope,
"compiling method", function, CodeKind::MAGLEV);
99 if (osr)
PrintF(scope.file(),
" OSR");
101 PrintTraceSuffix(scope);
104 static void TracePrepareJob(Isolate* isolate, OptimizedCompilationInfo* info,
106 if (!
v8_flags.trace_opt || !info->IsOptimizing())
return;
107 CodeTracer::Scope scope(isolate->GetCodeTracer());
108 PrintTracePrefix(scope,
"compiling method", info);
109 if (info->is_osr())
PrintF(scope.file(),
" OSR");
111 PrintTraceSuffix(scope);
114 static void TraceOptimizeOSRStarted(Isolate* isolate,
115 DirectHandle<JSFunction> function,
116 BytecodeOffset osr_offset,
119 CodeTracer::Scope scope(isolate->GetCodeTracer());
122 "[OSR - compilation started. function: %s, osr offset: %d, mode: %s]\n",
123 function->DebugNameCStr().get(), osr_offset.ToInt(),
ToString(mode));
126 static void TraceOptimizeOSRFinished(Isolate* isolate,
127 DirectHandle<JSFunction> function,
128 BytecodeOffset osr_offset) {
130 CodeTracer::Scope scope(isolate->GetCodeTracer());
132 "[OSR - compilation finished. function: %s, osr offset: %d]\n",
133 function->DebugNameCStr().get(), osr_offset.ToInt());
136 static void TraceOptimizeOSRAvailable(Isolate* isolate,
137 DirectHandle<JSFunction> function,
138 BytecodeOffset osr_offset,
141 CodeTracer::Scope scope(isolate->GetCodeTracer());
143 "[OSR - available (compilation completed or cache hit). function: "
144 "%s, osr offset: %d, mode: %s]\n",
145 function->DebugNameCStr().get(), osr_offset.ToInt(),
ToString(mode));
148 static void TraceOptimizeOSRUnavailable(Isolate* isolate,
149 DirectHandle<JSFunction> function,
150 BytecodeOffset osr_offset,
153 CodeTracer::Scope scope(isolate->GetCodeTracer());
155 "[OSR - unavailable (failed or in progress). function: %s, osr "
156 "offset: %d, mode: %s]\n",
157 function->DebugNameCStr().get(), osr_offset.ToInt(),
ToString(mode));
160 static void TraceFinishTurbofanCompile(Isolate* isolate,
161 OptimizedCompilationInfo* info,
162 double ms_creategraph,
166 DCHECK(info->IsOptimizing());
167 CodeTracer::Scope scope(isolate->GetCodeTracer());
168 PrintTracePrefix(scope,
"completed compiling", info);
169 if (info->is_osr())
PrintF(scope.file(),
" OSR");
170 PrintF(scope.file(),
" - took %0.3f, %0.3f, %0.3f ms", ms_creategraph,
171 ms_optimize, ms_codegen);
172 PrintTraceSuffix(scope);
175 static void TraceFinishBaselineCompile(
176 Isolate* isolate, DirectHandle<SharedFunctionInfo> shared,
177 double ms_timetaken) {
178 if (!
v8_flags.trace_baseline)
return;
179 CodeTracer::Scope scope(isolate->GetCodeTracer());
180 PrintTracePrefix(scope,
"completed compiling", shared, CodeKind::BASELINE);
181 PrintF(scope.file(),
" - took %0.3f ms", ms_timetaken);
182 PrintTraceSuffix(scope);
185 static void TraceFinishMaglevCompile(Isolate* isolate,
186 DirectHandle<JSFunction> function,
187 bool osr,
double ms_prepare,
188 double ms_execute,
double ms_finalize) {
190 CodeTracer::Scope scope(isolate->GetCodeTracer());
191 PrintTracePrefix(scope,
"completed compiling", function, CodeKind::MAGLEV);
192 if (osr)
PrintF(scope.file(),
" OSR");
193 PrintF(scope.file(),
" - took %0.3f, %0.3f, %0.3f ms", ms_prepare,
194 ms_execute, ms_finalize);
195 PrintTraceSuffix(scope);
198 static void TraceAbortedMaglevCompile(Isolate* isolate,
199 DirectHandle<JSFunction> function,
202 CodeTracer::Scope scope(isolate->GetCodeTracer());
203 PrintTracePrefix(scope,
"aborted compiling", function, CodeKind::MAGLEV);
205 PrintTraceSuffix(scope);
208 static void TraceCompletedJob(Isolate* isolate,
209 OptimizedCompilationInfo* info) {
211 CodeTracer::Scope scope(isolate->GetCodeTracer());
212 PrintTracePrefix(scope,
"completed optimizing", info);
213 if (info->is_osr())
PrintF(scope.file(),
" OSR");
214 PrintTraceSuffix(scope);
217 static void TraceAbortedJob(Isolate* isolate, OptimizedCompilationInfo* info,
218 double ms_prepare,
double ms_execute,
219 double ms_finalize) {
221 CodeTracer::Scope scope(isolate->GetCodeTracer());
222 PrintTracePrefix(scope,
"aborted optimizing", info);
223 if (info->is_osr())
PrintF(scope.file(),
" OSR");
224 PrintF(scope.file(),
" because: %s",
226 PrintF(scope.file(),
" - took %0.3f, %0.3f, %0.3f ms", ms_prepare,
227 ms_execute, ms_finalize);
228 PrintTraceSuffix(scope);
231 static void TraceOptimizedCodeCacheHit(Isolate* isolate,
232 DirectHandle<JSFunction> function,
233 BytecodeOffset osr_offset,
236 CodeTracer::Scope scope(isolate->GetCodeTracer());
237 PrintTracePrefix(scope,
"found optimized code for", function, code_kind);
238 if (IsOSR(osr_offset)) {
239 PrintF(scope.file(),
" at OSR bytecode offset %d", osr_offset.ToInt());
241 PrintTraceSuffix(scope);
244 static void TraceOptimizeForAlwaysOpt(Isolate* isolate,
245 DirectHandle<JSFunction> function,
248 CodeTracer::Scope scope(isolate->GetCodeTracer());
249 PrintTracePrefix(scope,
"optimizing", function, code_kind);
250 PrintF(scope.file(),
" because --always-turbofan");
251 PrintTraceSuffix(scope);
254 static void TraceMarkForAlwaysOpt(Isolate* isolate,
255 DirectHandle<JSFunction> function) {
257 CodeTracer::Scope scope(isolate->GetCodeTracer());
258 PrintF(scope.file(),
"[marking ");
261 " for optimized recompilation because --always-turbofan");
262 PrintF(scope.file(),
"]\n");
266 static void PrintTracePrefix(
const CodeTracer::Scope& scope,
268 OptimizedCompilationInfo* info) {
269 PrintTracePrefix(scope, header, info->closure(), info->code_kind());
272 static void PrintTracePrefix(
const CodeTracer::Scope& scope,
274 DirectHandle<JSFunction> function,
276 PrintF(scope.file(),
"[%s ", header);
281 static void PrintTracePrefix(
const CodeTracer::Scope& scope,
283 DirectHandle<SharedFunctionInfo> shared,
285 PrintF(scope.file(),
"[%s ", header);
290 static void PrintTraceSuffix(
const CodeTracer::Scope& scope) {
291 PrintF(scope.file(),
"]\n");
311 if (!isolate->IsLoggingCodeCreation())
return;
315 int line_num = info.line + 1;
316 int column_num = info.column + 1;
323 PROFILE(isolate, CodeCreateEvent(log_tag, abstract_code, shared, script_name,
324 line_num, column_num));
325 if (!vector.is_null()) {
326 LOG(isolate, FeedbackVectorEvent(*vector, *abstract_code));
328 if (!
v8_flags.log_function_events)
return;
332 case CodeKind::INTERPRETED_FUNCTION:
333 name =
"interpreter";
335 case CodeKind::BASELINE:
338 case CodeKind::MAGLEV:
341 case CodeKind::TURBOFAN_JS:
348 case LogEventListener::CodeTag::kEval:
351 case LogEventListener::CodeTag::kScript:
352 case LogEventListener::CodeTag::kFunction:
361 LOG(isolate, FunctionEvent(name.c_str(), script->id(), time_taken_ms,
362 shared->StartPosition(), shared->EndPosition(),
370 bool is_shared_cross_origin =
372 bool is_opaque =
false;
373 if (IsScript(script)) {
374 auto script_origin_options =
Cast<Script>(script)->origin_options();
375 if (script_origin_options.IsSharedCrossOrigin()) {
376 is_shared_cross_origin =
true;
378 if (script_origin_options.IsOpaque()) {
382 return ScriptOriginOptions(is_shared_cross_origin, is_opaque);
402 DisallowJavascriptExecution no_js(isolate);
421void LogUnoptimizedCompilation(
Isolate* isolate,
427 if (shared->HasBytecodeArray()) {
431#if V8_ENABLE_WEBASSEMBLY
432 DCHECK(shared->HasAsmWasmData());
444 isolate, code_type, script, shared, DirectHandle<FeedbackVector>(),
445 abstract_code, CodeKind::INTERPRETED_FUNCTION, time_taken_ms);
455 DisallowJavascriptExecution no_js(isolate);
476 DisallowJavascriptExecution no_js(isolate);
486 DCHECK(code->is_optimized_code());
495 if (code->IsWeakObjectInOptimizedCode(target_object)) {
496 if (IsMap(target_object, cage_base)) {
507 isolate->heap()->AddRetainedMaps(context, std::move(maps));
508 code->set_can_have_weak_objects(
true);
512uint64_t GetNextTraceId() {
518 static std::atomic_uint32_t next_trace_id = 0xfa5701d0;
519 return static_cast<uint64_t
>(next_trace_id++) << 32;
528 compilation_info_(compilation_info),
529 trace_id_(GetNextTraceId() ^ reinterpret_cast<uintptr_t>(this)) {}
556 CompilerTracer::TraceFinishTurbofanCompile(
560 static double compilation_time = 0.0;
561 static int compiled_functions = 0;
562 static int code_size = 0;
564 compilation_time += (ms_creategraph + ms_optimize + ms_codegen);
565 compiled_functions++;
566 code_size += shared->SourceSize();
568 "[turbofan] Compiled: %d functions with %d byte source size in "
570 compiled_functions, code_size, compilation_time);
579 Counters*
const counters = isolate->counters();
580 counters->turbofan_ticks()->AddSample(
static_cast<int>(
584 counters->turbofan_osr_prepare()->AddSample(
586 counters->turbofan_osr_execute()->AddSample(
588 counters->turbofan_osr_finalize()->AddSample(
590 counters->turbofan_osr_total_time()->AddSample(elapsed_microseconds);
595 counters->turbofan_optimize_prepare()->AddSample(
597 counters->turbofan_optimize_execute()->AddSample(
599 counters->turbofan_optimize_finalize()->AddSample(
601 counters->turbofan_optimize_total_time()->AddSample(elapsed_microseconds);
610 counters->turbofan_optimize_concurrent_total_time()->AddSample(
611 elapsed_microseconds);
614 counters->turbofan_optimize_non_concurrent_total_time()->AddSample(
615 elapsed_microseconds);
619 counters->turbofan_optimize_total_background()->AddSample(
621 counters->turbofan_optimize_total_foreground()->AddSample(
624 if (
v8_flags.profile_guided_optimization &&
625 shared->cached_tiering_decision() ==
662#if V8_ENABLE_WEBASSEMBLY
665 if (!
v8_flags.validate_asm)
return false;
669 if (asm_wasm_broken)
return false;
672 if (
v8_flags.stress_validate_asm)
return true;
684 DCHECK(isolate->interpreted_frames_native_stack());
685 if (!IsBytecodeArray(shared_info->GetTrustedData(isolate))) {
686 DCHECK(!shared_info->HasInterpreterData(isolate));
690 shared_info->GetBytecodeArray(isolate), isolate);
696 isolate->factory()->NewInterpreterData(bytecode_array, code);
698 if (shared_info->HasBaselineCode()) {
700 ->set_bytecode_or_interpreter_data(*interpreter_data);
703 shared_info->set_interpreter_data(isolate, *interpreter_data);
710 int line_num = info.line + 1;
711 int column_num = info.column + 1;
716 PROFILE(isolate, CodeCreateEvent(log_tag, abstract_code, shared_info,
717 script_name, line_num, column_num));
722template <
typename IsolateT>
727 DCHECK(!shared_info->HasBytecodeArray());
729 DCHECK(!shared_info->HasFeedbackMetadata());
731#if V8_ENABLE_WEBASSEMBLY
734 if (compilation_info->
literal()->
scope()->IsAsmModule()) {
735 shared_info->set_is_asm_wasm_broken(
true);
741 shared_info->set_feedback_metadata(*feedback_metadata,
kReleaseStore);
743 shared_info->set_age(0);
744 shared_info->set_bytecode_array(*compilation_info->
bytecode_array());
746#if V8_ENABLE_WEBASSEMBLY
749 DCHECK((std::is_same<IsolateT, Isolate>::value));
750 shared_info->set_asm_wasm_data(*compilation_info->
asm_wasm_data());
751 shared_info->set_feedback_metadata(
752 ReadOnlyRoots(isolate).empty_feedback_metadata(),
kReleaseStore);
759template <
typename IsolateT>
760void EnsureInfosArrayOnScript(DirectHandle<Script> script,
761 ParseInfo* parse_info, IsolateT* isolate) {
762 DCHECK(parse_info->flags().is_toplevel());
763 if (script->infos()->length() > 0) {
764 DCHECK_EQ(script->infos()->length(), parse_info->max_info_id() + 1);
767 DirectHandle<WeakFixedArray> infos(isolate->factory()->NewWeakFixedArray(
769 script->set_infos(*infos);
772void UpdateSharedFunctionFlagsAfterCompilation(FunctionLiteral*
literal) {
779 DCHECK_EQ(shared_info->requires_instance_members_initializer(),
781 DCHECK_EQ(shared_info->class_scope_has_private_brand(),
783 DCHECK_EQ(shared_info->has_static_private_methods_or_accessors(),
786 shared_info->set_has_duplicate_parameters(
788 shared_info->UpdateAndFinalizeExpectedNofPropertiesFromEstimate(
literal);
796template <
typename IsolateT>
801 finalize_unoptimized_compilation_data_list) {
802 UnoptimizedCompilationInfo* compilation_info = job->compilation_info();
806 InstallUnoptimizedCode(compilation_info, shared_info, isolate);
808 MaybeHandle<CoverageInfo> coverage_info;
809 if (compilation_info->has_coverage_info()) {
810 MutexGuardIfOffThread<IsolateT> mutex_guard(
811 isolate->shared_function_info_access(), isolate);
812 if (!shared_info->HasCoverageInfo(
813 isolate->GetMainThreadIsolateUnsafe())) {
814 coverage_info = compilation_info->coverage_info();
818 finalize_unoptimized_compilation_data_list->emplace_back(
819 isolate, shared_info, coverage_info, job->time_taken_to_execute(),
820 job->time_taken_to_finalize());
823 (std::is_same<IsolateT, LocalIsolate>::value));
827std::unique_ptr<UnoptimizedCompilationJob>
828ExecuteSingleUnoptimizedCompilationJob(
830 AccountingAllocator* allocator,
831 std::vector<FunctionLiteral*>* eager_inner_literals,
832 LocalIsolate* local_isolate) {
833#if V8_ENABLE_WEBASSEMBLY
834 if (UseAsmWasm(
literal, parse_info->flags().is_asm_wasm_broken())) {
835 std::unique_ptr<UnoptimizedCompilationJob> asm_job(
847 std::unique_ptr<UnoptimizedCompilationJob> job(
849 parse_info,
literal, script, allocator, eager_inner_literals,
854 return std::unique_ptr<UnoptimizedCompilationJob>();
860template <
typename IsolateT>
861bool IterativelyExecuteAndFinalizeUnoptimizedCompilationJobs(
863 AccountingAllocator* allocator, IsCompiledScope* is_compiled_scope,
865 finalize_unoptimized_compilation_data_list,
867 jobs_to_retry_finalization_on_main_thread) {
870 std::vector<FunctionLiteral*> functions_to_compile;
871 functions_to_compile.push_back(parse_info->literal());
873 bool compilation_succeeded =
true;
874 while (!functions_to_compile.empty()) {
875 FunctionLiteral*
literal = functions_to_compile.back();
876 functions_to_compile.pop_back();
881 if (shared_info.is_null())
continue;
882 if (shared_info->is_compiled())
continue;
884 std::unique_ptr<UnoptimizedCompilationJob> job =
885 ExecuteSingleUnoptimizedCompilationJob(parse_info,
literal, script,
886 allocator, &functions_to_compile,
887 isolate->AsLocalIsolate());
893 if (!shared_info->HasUncompiledData()) {
896 compilation_succeeded =
false;
902 UpdateSharedFunctionFlagsAfterCompilation(
literal);
904 auto finalization_status = FinalizeSingleUnoptimizedCompilationJob(
905 job.get(), shared_info, isolate,
906 finalize_unoptimized_compilation_data_list);
908 switch (finalization_status) {
910 if (
literal == parse_info->literal()) {
912 *is_compiled_scope = shared_info->is_compiled_scope(isolate);
913 DCHECK(is_compiled_scope->is_compiled());
918 compilation_succeeded =
false;
925 DCHECK((!std::is_same<IsolateT, Isolate>::value));
930 job->compilation_info()->ClearLiteral();
931 job->ClearParseInfo();
932 jobs_to_retry_finalization_on_main_thread->emplace_back(
933 isolate, shared_info, std::move(job));
939 if (parse_info->pending_error_handler()->has_pending_warnings()) {
940 parse_info->pending_error_handler()->PrepareWarnings(isolate);
943 return compilation_succeeded;
946bool FinalizeDeferredUnoptimizedCompilationJobs(
947 Isolate* isolate, DirectHandle<Script> script,
949 PendingCompilationErrorHandler* pending_error_handler,
951 finalize_unoptimized_compilation_data_list) {
952 DCHECK(AllowCompilation::IsAllowed(isolate));
954 if (deferred_jobs->empty())
return true;
960 for (
auto&& job : *deferred_jobs) {
962 if (FinalizeSingleUnoptimizedCompilationJob(
963 job.job(), shared_info, isolate,
964 finalize_unoptimized_compilation_data_list) !=
971 if (pending_error_handler->has_pending_warnings()) {
972 pending_error_handler->PrepareWarnings(isolate);
979class OptimizedCodeCache :
public AllStatic {
982 Isolate* isolate, DirectHandle<JSFunction> function,
983 BytecodeOffset osr_offset,
CodeKind code_kind) {
986 if (!function->has_feedback_vector())
return {};
990 RCS_SCOPE(isolate, RuntimeCallCounterId::kCompileGetFromOptimizedCodeMap);
994 if (IsOSR(osr_offset)) {
997 interpreter::BytecodeArrayIterator it(bytecode, osr_offset.ToInt());
999 SBXCHECK(it.CurrentBytecodeIsValidOSREntry());
1000 std::optional<Tagged<Code>> maybe_code =
1001 feedback_vector->GetOptimizedOsrCode(isolate, it.GetSlotOperand(2));
1002 if (maybe_code.has_value()) code = maybe_code.value();
1004#ifdef V8_ENABLE_LEAPTIERING
1007 feedback_vector->EvictOptimizedCodeMarkedForDeoptimization(
1008 isolate, shared,
"OptimizedCodeCache::Get");
1009 code = feedback_vector->optimized_code(isolate);
1019 if (code.is_null() || code->kind() < code_kind)
return {};
1021 DCHECK(!code->marked_for_deoptimization());
1022 DCHECK(shared->is_compiled());
1026 CompilerTracer::TraceOptimizedCodeCacheHit(isolate, function, osr_offset,
1028 return handle(code, isolate);
1033 bool is_function_context_specializing) {
1040 if (IsOSR(osr_offset)) {
1042 DCHECK(!is_function_context_specializing);
1046 interpreter::BytecodeArrayIterator it(bytecode, osr_offset.ToInt());
1048 SBXCHECK(it.CurrentBytecodeIsValidOSREntry());
1049 feedback_vector->SetOptimizedOsrCode(isolate, it.GetSlotOperand(2), code);
1053#ifdef V8_ENABLE_LEAPTIERING
1056 DCHECK(!IsOSR(osr_offset));
1058 if (is_function_context_specializing) {
1062 if (feedback_vector->has_optimized_code() &&
1063 feedback_vector->optimized_code(isolate)->kind() == code->kind()) {
1064 feedback_vector->ClearOptimizedCode();
1069 function->shared()->set_function_context_independent_compiled(
true);
1070 feedback_vector->SetOptimizedCode(isolate, code);
1078bool PrepareJobWithHandleScope(OptimizedCompilationJob* job, Isolate* isolate,
1079 OptimizedCompilationInfo* compilation_info,
1081 CompilationHandleScope compilation(isolate, compilation_info);
1082 CompilerTracer::TracePrepareJob(isolate, compilation_info, mode);
1083 compilation_info->ReopenAndCanonicalizeHandlesInNewScope(isolate);
1087bool CompileTurbofan_NotConcurrent(Isolate* isolate,
1088 TurbofanCompilationJob* job) {
1089 OptimizedCompilationInfo*
const compilation_info = job->compilation_info();
1090 DCHECK_EQ(compilation_info->code_kind(), CodeKind::TURBOFAN_JS);
1092 TimerEventScope<TimerEventRecompileSynchronous> timer(isolate);
1093 RCS_SCOPE(isolate, RuntimeCallCounterId::kOptimizeNonConcurrent);
1095 "V8.OptimizeNonConcurrent");
1097 if (!PrepareJobWithHandleScope(job, isolate, compilation_info,
1099 CompilerTracer::TraceAbortedJob(isolate, compilation_info,
1100 job->prepare_in_ms(), job->execute_in_ms(),
1101 job->finalize_in_ms());
1105 if (job->ExecuteJob(isolate->counters()->runtime_call_stats(),
1106 isolate->main_thread_local_isolate())) {
1107 CompilerTracer::TraceAbortedJob(isolate, compilation_info,
1108 job->prepare_in_ms(), job->execute_in_ms(),
1109 job->finalize_in_ms());
1114 CompilerTracer::TraceAbortedJob(isolate, compilation_info,
1115 job->prepare_in_ms(), job->execute_in_ms(),
1116 job->finalize_in_ms());
1122 DCHECK(!isolate->has_exception());
1124 OptimizedCodeCache::Insert(
1125 isolate, *compilation_info->closure(), compilation_info->osr_offset(),
1126 *compilation_info->code(),
1127 compilation_info->function_context_specializing());
1129 job->RecordFunctionCompilation(LogEventListener::CodeTag::kFunction, isolate);
1133bool CompileTurbofan_Concurrent(Isolate* isolate,
1134 std::unique_ptr<TurbofanCompilationJob> job) {
1135 OptimizedCompilationInfo*
const compilation_info = job->compilation_info();
1136 DCHECK_EQ(compilation_info->code_kind(), CodeKind::TURBOFAN_JS);
1137 DirectHandle<JSFunction> function = compilation_info->closure();
1139 if (!isolate->optimizing_compile_dispatcher()->IsQueueAvailable()) {
1140 if (
v8_flags.trace_concurrent_recompilation) {
1141 PrintF(
" ** Compilation queue full, will retry optimizing ");
1148 if (isolate->heap()->HighMemoryPressure()) {
1149 if (
v8_flags.trace_concurrent_recompilation) {
1150 PrintF(
" ** High memory pressure, will retry optimizing ");
1157 TimerEventScope<TimerEventRecompileSynchronous> timer(isolate);
1158 RCS_SCOPE(isolate, RuntimeCallCounterId::kOptimizeConcurrentPrepare);
1160 "V8.OptimizeConcurrentPrepare", job->trace_id(),
1163 if (!PrepareJobWithHandleScope(job.get(), isolate, compilation_info,
1168 if (
V8_LIKELY(!compilation_info->discard_result_for_testing())) {
1169 function->SetTieringInProgress(
true, compilation_info->osr_offset());
1173 if (!isolate->optimizing_compile_dispatcher()->TryQueueForOptimization(job)) {
1174 function->SetTieringInProgress(
false, compilation_info->osr_offset());
1176 if (
v8_flags.trace_concurrent_recompilation) {
1177 PrintF(
" ** Compilation queue full, will retry optimizing ");
1184 if (
v8_flags.trace_concurrent_recompilation) {
1187 PrintF(
" for concurrent optimization.\n");
1190 DCHECK(compilation_info->shared_info()->HasBytecodeArray());
1194enum class CompileResultBehavior {
1201bool ShouldOptimize(
CodeKind code_kind,
1202 DirectHandle<SharedFunctionInfo> shared) {
1204 switch (code_kind) {
1205 case CodeKind::TURBOFAN_JS:
1207 case CodeKind::MAGLEV:
1209 shared->PassesFilter(
v8_flags.maglev_filter);
1216 DirectHandle<SharedFunctionInfo> shared,
1218 BytecodeOffset osr_offset,
1219 CompileResultBehavior result_behavior) {
1220 VMState<COMPILER>
state(isolate);
1221 TimerEventScope<TimerEventOptimizeCode> optimize_code_timer(isolate);
1222 RCS_SCOPE(isolate, RuntimeCallCounterId::kOptimizeCode);
1225 DCHECK(!isolate->has_exception());
1226 PostponeInterruptsScope postpone(isolate);
1233 shared->HasBytecodeArray());
1234 std::unique_ptr<TurbofanCompilationJob> job(
1237 if (result_behavior == CompileResultBehavior::kDiscardForTesting) {
1238 job->compilation_info()->set_discard_result_for_testing();
1241 if (IsOSR(osr_offset)) {
1247 if (CompileTurbofan_Concurrent(isolate, std::move(job)))
return {};
1250 if (CompileTurbofan_NotConcurrent(isolate, job.get())) {
1251 return job->compilation_info()->code();
1255 if (isolate->has_exception()) isolate->clear_exception();
1259#ifdef V8_ENABLE_MAGLEV
1261void RecordMaglevFunctionCompilation(Isolate* isolate,
1262 DirectHandle<JSFunction> function,
1263 DirectHandle<AbstractCode> code) {
1264 PtrComprCageBase cage_base(isolate);
1265 DirectHandle<SharedFunctionInfo>
shared(function->shared(cage_base), isolate);
1267 DirectHandle<FeedbackVector> feedback_vector(
1268 function->feedback_vector(cage_base), isolate);
1271 double time_taken_ms = 0;
1274 isolate, LogEventListener::CodeTag::kFunction, script, shared,
1275 feedback_vector, code, code->kind(cage_base), time_taken_ms);
1281 CompileResultBehavior result_behavior) {
1282#ifdef V8_ENABLE_MAGLEV
1284 CHECK(result_behavior == CompileResultBehavior::kDefault);
1288 DCHECK(!isolate->has_exception());
1289 PostponeInterruptsScope postpone(isolate);
1298 auto job = maglev::MaglevCompilationJob::New(isolate, function, osr_offset);
1301 !isolate->maglev_concurrent_dispatcher()->is_enabled()) {
1308 IsSynchronous(mode) ?
"V8.MaglevPrepare" :
"V8.MaglevConcurrentPrepare",
1310 CompilerTracer::TraceStartMaglevCompile(isolate, function, job->is_osr(),
1318 job->ExecuteJob(isolate->counters()->runtime_call_stats(),
1319 isolate->main_thread_local_isolate());
1333 isolate->maglev_concurrent_dispatcher()->EnqueueJob(std::move(job));
1336 function->SetTieringInProgress(
true, osr_offset);
1346MaybeHandle<Code> GetOrCompileOptimized(
1347 Isolate* isolate, DirectHandle<JSFunction> function,
ConcurrencyMode mode,
1349 CompileResultBehavior result_behavior = CompileResultBehavior::kDefault) {
1350 if (IsOSR(osr_offset)) {
1351 function->TraceOptimizationStatus(
1358 DirectHandle<SharedFunctionInfo>
shared(function->shared(), isolate);
1363 function->feedback_vector()->reset_osr_urgency();
1367 if (!IsOSR(osr_offset)) {
1368 function->ResetTieringRequests();
1370 int invocation_count =
1371 function->feedback_vector()->invocation_count(
kRelaxedLoad);
1376 invocation_count <
v8_flags.minimum_invocations_before_optimization) {
1377 function->feedback_vector()->set_invocation_count(invocation_count + 1,
1384 if (shared->optimization_disabled() &&
1385 shared->disabled_optimization_reason() == BailoutReason::kNeverOptimize) {
1390 if (isolate->debug()->needs_check_on_function_call()) {
1395 if (shared->HasBreakInfo(isolate))
return {};
1399 if (!ShouldOptimize(code_kind, shared))
return {};
1403 if (OptimizedCodeCache::Get(isolate, function, osr_offset, code_kind)
1404 .ToHandle(&cached_code)) {
1405 DCHECK_IMPLIES(!IsOSR(osr_offset), cached_code->kind() <= code_kind);
1409 if (IsOSR(osr_offset)) {
1411 if (function->osr_tiering_in_progress())
return {};
1415 DCHECK(shared->is_compiled());
1417 if (code_kind == CodeKind::TURBOFAN_JS) {
1418 return CompileTurbofan(isolate,
indirect_handle(function, isolate), shared,
1419 mode, osr_offset, result_behavior);
1422 return CompileMaglev(isolate,
indirect_handle(function, isolate), mode,
1423 osr_offset, result_behavior);
1431void SpawnDuplicateConcurrentJobForStressTesting(
1432 Isolate* isolate, DirectHandle<JSFunction> function,
ConcurrencyMode mode,
1435 if (code_kind == CodeKind::MAGLEV)
return;
1437 if (function->ActiveTierIsTurbofan(isolate))
return;
1440 isolate->concurrent_recompilation_enabled() &&
IsSynchronous(mode) &&
1441 isolate->node_observer() ==
nullptr);
1442 CompileResultBehavior result_behavior =
1443 v8_flags.stress_concurrent_inlining_attach_code
1444 ? CompileResultBehavior::kDefault
1445 : CompileResultBehavior::kDiscardForTesting;
1451bool FailAndClearException(Isolate* isolate) {
1452 isolate->clear_internal_exception();
1456template <
typename IsolateT>
1457bool PrepareException(IsolateT* isolate, ParseInfo* parse_info) {
1458 if (parse_info->pending_error_handler()->has_pending_error()) {
1459 parse_info->pending_error_handler()->PrepareErrors(
1460 isolate, parse_info->ast_value_factory());
1465bool FailWithPreparedException(
1467 const PendingCompilationErrorHandler* pending_error_handler,
1470 return FailAndClearException(isolate);
1473 if (!isolate->has_exception()) {
1474 if (pending_error_handler->has_pending_error()) {
1475 pending_error_handler->ReportErrors(isolate, script);
1477 isolate->StackOverflow();
1484 ParseInfo* parse_info,
1486 PrepareException(isolate, parse_info);
1487 return FailWithPreparedException(isolate, script,
1488 parse_info->pending_error_handler(), flag);
1491void FinalizeUnoptimizedCompilation(
1493 const UnoptimizedCompileFlags& flags,
1494 const UnoptimizedCompileState* compile_state,
1496 finalize_unoptimized_compilation_data_list) {
1497 if (compile_state->pending_error_handler()->has_pending_warnings()) {
1498 compile_state->pending_error_handler()->ReportWarnings(isolate, script);
1501 bool need_source_positions =
1502 v8_flags.stress_lazy_source_positions ||
1503 (!flags.collect_source_positions() && isolate->NeedsSourcePositions());
1505 for (
const auto& finalize_data : finalize_unoptimized_compilation_data_list) {
1506 DirectHandle<SharedFunctionInfo> shared_info =
1507 finalize_data.function_handle();
1511 IsCompiledScope is_compiled_scope(*shared_info, isolate);
1512 if (!is_compiled_scope.is_compiled())
continue;
1514 if (need_source_positions) {
1518 if (shared_info->is_toplevel()) {
1519 log_tag = flags.is_eval() ? LogEventListener::CodeTag::kEval
1520 : LogEventListener::CodeTag::kScript;
1522 log_tag = LogEventListener::CodeTag::kFunction;
1525 if (isolate->interpreted_frames_native_stack() &&
1526 isolate->logger()->is_listening_to_code_events()) {
1529 DirectHandle<CoverageInfo> coverage_info;
1530 if (finalize_data.coverage_info().ToHandle(&coverage_info)) {
1531 isolate->debug()->InstallCoverageInfo(shared_info, coverage_info);
1534 LogUnoptimizedCompilation(isolate, shared_info, log_tag,
1535 finalize_data.time_taken_to_execute(),
1536 finalize_data.time_taken_to_finalize());
1540void FinalizeUnoptimizedScriptCompilation(
1542 const UnoptimizedCompileFlags& flags,
1543 const UnoptimizedCompileState* compile_state,
1545 finalize_unoptimized_compilation_data_list) {
1546 FinalizeUnoptimizedCompilation(isolate, script, flags, compile_state,
1547 finalize_unoptimized_compilation_data_list);
1550 DCHECK_IMPLIES(isolate->NeedsSourcePositions(), script->has_line_ends());
1553void CompileAllWithBaseline(Isolate* isolate,
1555 finalize_unoptimized_compilation_data_list) {
1556 for (
const auto& finalize_data : finalize_unoptimized_compilation_data_list) {
1558 IsCompiledScope is_compiled_scope(*shared_info, isolate);
1559 if (!is_compiled_scope.is_compiled())
continue;
1568template <
typename IsolateT>
1570 ParseInfo* parse_info, DirectHandle<Script> script, IsolateT* isolate) {
1571 EnsureInfosArrayOnScript(script, parse_info, isolate);
1573 parse_info->literal()->function_token_position());
1574 return isolate->factory()->NewSharedFunctionInfoForLiteral(
1575 parse_info->literal(), script,
true);
1579 ParseInfo* parse_info, DirectHandle<Script> script, Isolate* isolate,
1580 IsCompiledScope* is_compiled_scope) {
1581 EnsureInfosArrayOnScript(script, parse_info, isolate);
1582 MaybeHandle<SharedFunctionInfo> maybe_shared =
1585 DCHECK_EQ(shared->function_literal_id(),
1586 parse_info->literal()->function_literal_id());
1587 *is_compiled_scope = shared->is_compiled_scope(isolate);
1590 return CreateTopLevelSharedFunctionInfo(parse_info, script, isolate);
1593MaybeHandle<SharedFunctionInfo> CompileToplevel(
1595 MaybeDirectHandle<ScopeInfo> maybe_outer_scope_info, Isolate* isolate,
1596 IsCompiledScope* is_compiled_scope) {
1597 TimerEventScope<TimerEventCompileCode> top_level_timer(isolate);
1601 PostponeInterruptsScope postpone(isolate);
1602 DCHECK(!isolate->native_context().is_null());
1603 RCS_SCOPE(isolate, parse_info->flags().is_eval()
1604 ? RuntimeCallCounterId::kCompileEval
1605 : RuntimeCallCounterId::kCompileScript);
1606 VMState<BYTECODE_COMPILER>
state(isolate);
1607 if (parse_info->literal() ==
nullptr &&
1610 FailWithException(isolate, script, parse_info,
1612 return MaybeHandle<SharedFunctionInfo>();
1617 NestedTimedHistogram* rate = parse_info->flags().is_eval()
1618 ? isolate->counters()->compile_eval()
1619 : isolate->counters()->compile();
1620 NestedTimedHistogramScope timer(rate);
1622 parse_info->flags().is_eval() ?
"V8.CompileEval" :
"V8.Compile");
1626 GetOrCreateTopLevelSharedFunctionInfo(parse_info, script, isolate,
1630 finalize_unoptimized_compilation_data_list;
1633 if (!IterativelyExecuteAndFinalizeUnoptimizedCompilationJobs(
1634 isolate, script, parse_info, isolate->allocator(), is_compiled_scope,
1635 &finalize_unoptimized_compilation_data_list,
nullptr)) {
1636 FailWithException(isolate, script, parse_info,
1638 return MaybeHandle<SharedFunctionInfo>();
1642 parse_info->ResetCharacterStream();
1644 FinalizeUnoptimizedScriptCompilation(
1645 isolate, script, parse_info->flags(), parse_info->state(),
1646 finalize_unoptimized_compilation_data_list);
1649 CompileAllWithBaseline(isolate, finalize_unoptimized_compilation_data_list);
1655#ifdef V8_RUNTIME_CALL_STATS
1656RuntimeCallCounterId RuntimeCallCounterIdForCompile(ParseInfo* parse_info) {
1657 if (parse_info->flags().is_toplevel()) {
1658 if (parse_info->flags().is_eval()) {
1659 return RuntimeCallCounterId::kCompileEval;
1661 return RuntimeCallCounterId::kCompileScript;
1663 return RuntimeCallCounterId::kCompileFunction;
1678 : time_taken_to_execute_(time_taken_to_execute),
1679 time_taken_to_finalize_(time_taken_to_finalize),
1680 function_handle_(isolate->
heap()->NewPersistentHandle(function_handle)),
1681 coverage_info_(isolate->
heap()->NewPersistentMaybeHandle(coverage_info)) {
1686 std::unique_ptr<UnoptimizedCompilationJob> job)
1687 : function_handle_(isolate->
heap()->NewPersistentHandle(function_handle)),
1688 job_(
std::move(job)) {}
1695 : isolate_for_local_isolate_(isolate),
1699 (options &
ScriptCompiler::CompileOptions::kEagerCompile) == 0 &&
1701 character_stream_(
ScannerStream::For(streamed_data->source_stream.get(),
1702 streamed_data->encoding)),
1704 worker_thread_runtime_call_stats_(
1705 isolate->counters()->worker_thread_runtime_call_stats()),
1706 timer_(isolate->counters()->compile_script_on_background()),
1707 compilation_details_(compilation_details),
1711 compile_hint_callback_(compile_hint_callback),
1712 compile_hint_callback_data_(compile_hint_callback_data) {
1714 flags_.set_produce_compile_hints(
true);
1724 flags_.set_compile_hints_magic_enabled(
1727 flags_.set_compile_hints_per_function_magic_enabled(
1729 kFollowCompileHintsPerFunctionMagicComment);
1734 std::unique_ptr<Utf16CharacterStream> character_stream,
1737 : isolate_for_local_isolate_(isolate),
1742 character_stream_(
std::move(character_stream)),
1743 stack_size_(max_stack_size),
1744 worker_thread_runtime_call_stats_(worker_thread_runtime_stats),
1746 compilation_details_(nullptr),
1747 start_position_(shared_info->StartPosition()),
1748 end_position_(shared_info->EndPosition()),
1749 function_literal_id_(shared_info->function_literal_id()) {
1750 DCHECK(!shared_info->is_toplevel());
1767 if (script_details.
name_obj.ToHandle(&script_name)) {
1768 script->set_name(*script_name);
1769 script->set_line_offset(script_details.
line_offset);
1777 IsString(*source_map_url) &&
1779 script->set_source_mapping_url(*source_map_url);
1784 if (IsFixedArray(*host_defined_options)) {
1792#ifdef ENABLE_SLOW_DCHECKS
1799class MergeAssumptionChecker final :
public ObjectVisitor {
1801 explicit MergeAssumptionChecker(LocalIsolate* isolate)
1802 :
isolate_(isolate), cage_base_(isolate->cage_base()) {}
1804 void IterateObjects(Tagged<HeapObject>
start) {
1805 QueueVisit(
start, kNormalObject);
1806 while (to_visit_.size() > 0) {
1807 std::pair<Tagged<HeapObject>, ObjectKind> pair = to_visit_.top();
1809 Tagged<HeapObject> current = pair.first;
1815 if (IsScript(current)) {
1816 Tagged<Script> script = Cast<Script>(current);
1817 Tagged<HeapObject> infos = script->infos();
1818 QueueVisit(infos, kScriptInfosList);
1821 Tagged<HeapObject> eval_from_shared_or_wrapped_arguments;
1822 if (script->eval_from_shared_or_wrapped_arguments()
1823 .GetHeapObjectIfStrong(
1824 &eval_from_shared_or_wrapped_arguments)) {
1825 visited_.insert(eval_from_shared_or_wrapped_arguments);
1827 }
else if (IsBytecodeArray(current)) {
1828 Tagged<HeapObject> constants =
1829 Cast<BytecodeArray>(current)->constant_pool();
1830 QueueVisit(constants, kConstantPool);
1832 current_object_kind_ = pair.second;
1834 QueueVisit(current->map(), kNormalObject);
1839 void VisitPointers(Tagged<HeapObject> host, ObjectSlot
start,
1840 ObjectSlot
end)
override {
1843 VisitPointers(host, maybe_start, maybe_end);
1845 void VisitPointers(Tagged<HeapObject> host, MaybeObjectSlot
start,
1846 MaybeObjectSlot
end)
override {
1848 Tagged<MaybeObject> maybe_obj = current.load(cage_base_);
1849 Tagged<HeapObject> obj;
1850 bool is_weak = maybe_obj.IsWeak();
1851 if (maybe_obj.GetHeapObject(&obj)) {
1852 if (IsSharedFunctionInfo(obj)) {
1853 CHECK((current_object_kind_ == kConstantPool && !is_weak) ||
1854 (current_object_kind_ == kScriptInfosList && is_weak) ||
1856 current.address() ==
1858 Script::kEvalFromSharedOrWrappedArgumentsOffset));
1859 }
else if (IsScopeInfo(obj)) {
1860 CHECK((current_object_kind_ == kConstantPool && !is_weak) ||
1861 (current_object_kind_ == kNormalObject && !is_weak) ||
1862 (current_object_kind_ == kScriptInfosList && is_weak));
1863 }
else if (IsScript(obj)) {
1864 CHECK(IsSharedFunctionInfo(host) &&
1866 SharedFunctionInfo::kScriptOffset));
1867 }
else if (IsFixedArray(obj) && current_object_kind_ == kConstantPool) {
1870 QueueVisit(obj, kConstantPool);
1873 QueueVisit(obj, kNormalObject);
1881 void VisitInstructionStreamPointer(Tagged<Code> host,
1882 InstructionStreamSlot slot)
override {
1885 void VisitCodeTarget(Tagged<InstructionStream> host,
1886 RelocInfo* rinfo)
override {
1889 void VisitEmbeddedPointer(Tagged<InstructionStream> host,
1890 RelocInfo* rinfo)
override {
1903 void QueueVisit(Tagged<HeapObject> obj, ObjectKind
kind) {
1905 to_visit_.push(std::make_pair(obj,
kind));
1912 PtrComprCageBase cage_base_;
1913 std::stack<std::pair<Tagged<HeapObject>, ObjectKind>> to_visit_;
1918 std::unordered_set<Tagged<HeapObject>, Object::Hasher>
visited_;
1920 ObjectKind current_object_kind_ = kNormalObject;
1939 Run(&isolate, &reusable_state);
1945 Run(isolate->main_thread_local_isolate(), &reusable_state);
1957 "BackgroundCompileTask::Run");
1958 RCS_SCOPE(isolate, RuntimeCallCounterId::kCompileCompileTask,
1959 RuntimeCallStats::CounterMode::kThreadSpecific);
1961 bool toplevel_script_compilation =
flags_.is_toplevel();
1970 if (toplevel_script_compilation) {
1979 script_ = isolate->heap()->NewPersistentHandle(script);
1985 script_ = isolate->heap()->NewPersistentHandle(
1987 info.CheckFlagsForFunctionFromScript(*
script_);
1991 info.set_function_name(info.ast_value_factory()->GetString(
1992 shared_info->Name(), access_guard));
1996 if (shared_info->HasUncompiledDataWithPreparseData()) {
1999 handle(shared_info->uncompiled_data_with_preparse_data(isolate)
2000 ->preparse_data(isolate),
2006 info.character_stream()->set_runtime_call_stats(info.runtime_call_stats());
2008 Parser parser(isolate, &info);
2009 if (
flags().is_toplevel()) {
2018 if (shared_info->HasOuterScopeInfo()) {
2019 maybe_outer_scope_info =
2023 isolate, &info, maybe_outer_scope_info,
2032 "V8.CompileCodeBackground");
2033 RCS_SCOPE(isolate, RuntimeCallCounterIdForCompile(&info),
2034 RuntimeCallStats::CounterMode::kThreadSpecific);
2037 if (info.literal() !=
nullptr) {
2038 if (toplevel_script_compilation) {
2039 CreateTopLevelSharedFunctionInfo(&info,
script_, isolate);
2042 info.literal()->set_shared_function_info(
2043 isolate->factory()->CloneSharedFunctionInfo(
2047 if (IterativelyExecuteAndFinalizeUnoptimizedCompilationJobs(
2051 maybe_result = info.literal()->shared_function_info();
2056 PrepareException(isolate, &info);
2057 }
else if (
v8_flags.enable_slow_asserts) {
2058#ifdef ENABLE_SLOW_DCHECKS
2059 MergeAssumptionChecker checker(isolate);
2065 DCHECK(isolate->heap()->ContainsPersistentHandle(
script_.location()));
2081 CHECK(IsBytecodeArray(bytecode_array));
2092 if (!
v8_flags.reuse_scope_infos)
return;
2097 if (!old_sfi->scope_info()->IsEmpty() &&
2098 old_sfi->scope_info()->HasContext()) {
2099 scope_info = old_sfi->scope_info();
2100 }
else if (old_sfi->HasOuterScopeInfo()) {
2101 scope_info = old_sfi->GetOuterScopeInfo();
2116 (*it->second)->
Print();
2117 scope_info->Print();
2124 if (!scope_info->HasOuterScopeInfo())
break;
2125 scope_info = scope_info->OuterScopeInfo();
2155 if (!
v8_flags.reuse_scope_infos)
return false;
2158 sfi->SetScopeInfo(*it->second);
2168 if (!
v8_flags.reuse_scope_infos)
return;
2170 if (!sfi->HasOuterScopeInfo())
return;
2178 if (!outer_info->HasOuterScopeInfo())
return;
2179 parent = outer_info;
2180 outer_info = outer_info->OuterScopeInfo();
2183 if (outer_info == *it->second)
return;
2188 sfi->set_raw_outer_scope_info_or_feedback_metadata(*it->second);
2190 parent->set_outer_scope_info(*it->second);
2197 CHECK_EQ(replacement->EndPosition(), scope_info->EndPosition());
2198 CHECK_EQ(replacement->scope_type(), scope_info->scope_type());
2199 CHECK_EQ(replacement->ContextLength(), scope_info->ContextLength());
2201 template <
typename TArray>
2204 if (
IsSmi(obj))
return;
2212 IsSharedFunctionInfo(heap_obj,
cage_base_)) {
2221 template <
typename TArray>
2225 old_script_->infos()->get(sfi->function_literal_id());
2226 if (maybe_old_sfi.
IsWeak()) {
2232 template <
typename TArray>
2238 if (scope_info != *it->second) {
2242 }
else if (scope_info->HasOuterScopeInfo()) {
2251 scope_info->set_outer_scope_info(*it->second);
2263 for (
int i = 0, length = nested_array->length();
i < length; ++
i) {
2287 isolate->compilation_cache()->LookupScript(source_text, script_details,
2290 if (!lookup_result.
script().ToHandle(&script)) {
2311 if (!
v8_flags.reuse_scope_infos)
return;
2319 std::unordered_map<int, Tagged<ScopeInfo>> scope_infos;
2320 for (
int info_idx = 0; info_idx < script->infos()->
length(); info_idx++) {
2322 if (!script->infos()->get(info_idx).IsWeak())
continue;
2329 if (sfi->HasBytecodeArray()) {
2332 for (
int constant_idx = 0; constant_idx <
constant_pool->length();
2338 int id = inner_sfi->function_literal_id();
2340 CHECK_EQ(inner_sfi->script(), *script);
2345 if (!sfi->scope_info()->IsEmpty()) {
2346 scope_info = sfi->scope_info();
2347 }
else if (sfi->HasOuterScopeInfo()) {
2348 scope_info = sfi->GetOuterScopeInfo();
2356 auto it = scope_infos.find(scope_info->UniqueIdInScript());
2357 if (it != scope_infos.end()) {
2358 if (*it->second != scope_info) {
2359 isolate->PushParamsAndDie(
reinterpret_cast<void*
>(it->second->ptr()),
2360 reinterpret_cast<void*
>(scope_info.
ptr()));
2365 scope_infos[scope_info->UniqueIdInScript()] = scope_info;
2366 if (!scope_info->HasOuterScopeInfo())
break;
2367 scope_info = scope_info->OuterScopeInfo();
2377 VerifyCodeMerge(isolate, cached_script);
2380 VerifyCodeMerge(isolate, cached_script);
2409 if (maybe_old_toplevel_sfi.
IsWeak()) {
2419 CHECK_EQ(old_script->infos()->length(), new_script->infos()->length());
2420 for (
int i = 0;
i < old_script->infos()->
length(); ++
i) {
2426 if (maybe_new_sfi.
IsWeak() &&
2430 if (maybe_old_info.
IsWeak()) {
2442 if (old_sfi->HasBytecodeArray()) {
2447 old_sfi->set_age(0);
2448 }
else if (new_sfi->HasBytecodeArray()) {
2453 if (!info->IsEmpty()) {
2454 new_sfi->SetScopeInfo(info);
2455 }
else if (old_sfi->HasOuterScopeInfo()) {
2456 new_sfi->scope_info()->set_outer_scope_info(
2457 old_sfi->GetOuterScopeInfo());
2466 if (new_sfi->HasBytecodeArray()) {
2472 if (maybe_old_info.
IsWeak()) {
2477 new_script->infos()->set(
i, maybe_old_info);
2487 DCHECK(isolate->is_main_thread());
2518 isolate, isolate->main_thread_local_heap(), old_script);
2522 if (!sfi->is_compiled() && new_compiled_data.new_sfi->is_compiled()) {
2525 DCHECK(!new_compiled_data.cached_sfi->HasDebugInfo(isolate));
2530 new_compiled_data.new_sfi->set_script(sfi->script(
kAcquireLoad),
2532 sfi->CopyFrom(*new_compiled_data.new_sfi, isolate);
2536 for (
int i = 0;
i < old_script->infos()->
length(); ++
i) {
2539 if (maybe_new_info == maybe_old_info)
continue;
2541 if (maybe_old_info.
IsWeak()) {
2552 old_script->infos()->set(
i, maybe_new_info);
2562 if (new_sfi->HasBytecodeArray(isolate)) {
2572 if (new_compiled_data.cached_sfi->HasBytecodeArray(isolate)) {
2574 new_compiled_data.cached_sfi->GetBytecodeArray(isolate));
2589 if (isolate->NeedsSourcePositions()) {
2595 VerifyCodeMerge(isolate, old_script);
2598 VerifyCodeMerge(isolate, old_script);
2619 if (FinalizeDeferredUnoptimizedCompilationJobs(
2627 maybe_cached_script.
ToHandle(&cached_script) && !maybe_result.
is_null()) {
2638 DCHECK(isolate->factory()->script_list()->Contains(
MakeWeak(*script)));
2641 script->set_origin_options(origin_options);
2647 isolate->heap()->SetRootScriptList(*scripts);
2662 FailWithPreparedException(isolate, script,
2685 input_shared_info->ClearUncompiledDataJobPointer(isolate);
2689 if (FinalizeDeferredUnoptimizedCompilationJobs(
2700 FailWithPreparedException(isolate,
script_,
2709 input_shared_info->CopyFrom(*
result, isolate);
2726 isolate->CountUsage(feature);
2731 Isolate* isolate, std::unique_ptr<ScriptCompiler::CachedData> cached_data)
2732 : isolate_for_local_isolate_(isolate),
2734 timer_(isolate->counters()->deserialize_script_on_background()) {
2739 cached_data->buffer_policy = ScriptCompiler::CachedData::BufferNotOwned;
2740 cached_data_.AcquireDataOwnership();
2754#ifdef ENABLE_SLOW_DCHECKS
2755 MergeAssumptionChecker checker(&isolate);
2771 DCHECK(
v8_flags.merge_background_deserialized_script_with_compilation_cache);
2801 DCHECK(shared_info->is_compiled());
2802 DCHECK(shared_info->HasBytecodeArray());
2803 DCHECK(!shared_info->GetBytecodeArray(isolate)->HasSourcePositionTable());
2810 DCHECK(AllowHeapAllocation::IsAllowed());
2813 handle(shared_info->GetBytecodeArray(isolate), isolate);
2821 bytecode->SetSourcePositionsFailedToCollect();
2827 if (
Cast<Script>(shared_info->script())->IsMaybeUnfinalized(isolate)) {
2828 bytecode->SetSourcePositionsFailedToCollect();
2832 DCHECK(AllowCompilation::IsAllowed(isolate));
2835 DCHECK(!isolate->has_exception());
2838 RCS_SCOPE(isolate, RuntimeCallCounterId::kCompileCollectSourcePositions);
2840 "V8.CollectSourcePositions");
2842 isolate->counters()->collect_source_positions());
2847 flags.set_collect_source_positions(
true);
2848 flags.set_is_reparse(
true);
2850 flags.set_post_parallel_compile_tasks_for_eager_toplevel(
false);
2851 flags.set_post_parallel_compile_tasks_for_lazy(
false);
2855 ParseInfo parse_info(isolate, flags, &compile_state, &reusable_state);
2862 bytecode->SetSourcePositionsFailedToCollect();
2863 return FailAndClearException(isolate);
2872 std::unique_ptr<UnoptimizedCompilationJob> job;
2875 &parse_info, parse_info.
literal(), bytecode, isolate->allocator(),
2876 isolate->main_thread_local_isolate());
2881 bytecode->SetSourcePositionsFailedToCollect();
2882 return FailAndClearException(isolate);
2886 DCHECK(job->compilation_info()->flags().collect_source_positions());
2891 shared_info->TryGetDebugInfo(isolate)) {
2892 if (debug_info.value()->HasInstrumentedBytecodeArray()) {
2894 job->compilation_info()->bytecode_array()->SourcePositionTable();
2895 shared_info->GetActiveBytecodeArray(isolate)->set_source_position_table(
2900 DCHECK(!isolate->has_exception());
2901 DCHECK(shared_info->is_compiled_scope(isolate).is_compiled());
2911 DCHECK(!shared_info->is_compiled());
2913 DCHECK(AllowCompilation::IsAllowed(isolate));
2915 DCHECK(!isolate->has_exception());
2916 DCHECK(!shared_info->HasBytecodeArray());
2921 RCS_SCOPE(isolate, RuntimeCallCounterId::kCompileFunction);
2931 flags.set_collect_source_positions(
true);
2936 ParseInfo parse_info(isolate, flags, &compile_state, &reusable_state);
2940 if (dispatcher && dispatcher->IsEnqueued(shared_info)) {
2941 if (!dispatcher->FinishNow(shared_info)) {
2942 return FailWithException(isolate, script, &parse_info, flag);
2944 *is_compiled_scope = shared_info->is_compiled_scope(isolate);
2949 if (shared_info->HasUncompiledDataWithPreparseData()) {
2951 isolate,
handle(shared_info->uncompiled_data_with_preparse_data(isolate)
2959 return FailWithException(isolate, script, &parse_info, flag);
2965 finalize_unoptimized_compilation_data_list;
2967 if (!IterativelyExecuteAndFinalizeUnoptimizedCompilationJobs(
2968 isolate, script, &parse_info, isolate->
allocator(), is_compiled_scope,
2969 &finalize_unoptimized_compilation_data_list,
nullptr)) {
2970 return FailWithException(isolate, script, &parse_info, flag);
2973 FinalizeUnoptimizedCompilation(isolate, script, flags, &compile_state,
2974 finalize_unoptimized_compilation_data_list);
2977 CompileAllWithBaseline(isolate, finalize_unoptimized_compilation_data_list);
2980 if (script->produce_compile_hints()) {
2983 if (IsUndefined(script->compiled_lazy_function_positions())) {
2984 constexpr int kInitialLazyFunctionPositionListSize = 100;
2985 list =
ArrayList::New(isolate, kInitialLazyFunctionPositionListSize);
2988 Cast<ArrayList>(script->compiled_lazy_function_positions()), isolate);
2992 script->set_compiled_lazy_function_positions(*list);
2995 DCHECK(!isolate->has_exception());
3006 DCHECK(!function->is_compiled(isolate));
3008 function->IsTieringRequestedOrInProgress(),
3009 function->shared()->is_compiled());
3011 function->shared()->is_compiled());
3015 function->ResetIfCodeFlushed(isolate);
3020 *is_compiled_scope = shared_info->is_compiled_scope(isolate);
3022 !
Compile(isolate, shared_info, flag, is_compiled_scope)) {
3036 function->ResetTieringRequests();
3038 function->UpdateCode(*code);
3041#if V8_ENABLE_WEBASSEMBLY
3042 if (
v8_flags.always_turbofan && !function->shared()->HasAsmWasmData()) {
3046 DCHECK(!function->tiering_in_progress());
3047 CompilerTracer::TraceOptimizeForAlwaysOpt(isolate, function,
3053 if (
v8_flags.stress_concurrent_inlining &&
3054 isolate->concurrent_recompilation_enabled() &&
3055 isolate->node_observer() ==
nullptr) {
3056 SpawnDuplicateConcurrentJobForStressTesting(isolate, function,
3057 concurrency_mode, code_kind);
3061 if (GetOrCompileOptimized(isolate, function, concurrency_mode, code_kind)
3062 .ToHandle(&maybe_code)) {
3064 function->UpdateOptimizedCode(isolate, *code);
3069 if (code->kind() == CodeKind::BASELINE) {
3074 DCHECK(!isolate->has_exception());
3075 DCHECK(function->shared()->is_compiled());
3076 DCHECK(function->is_compiled(isolate));
3089 if (shared->HasBaselineCode())
return true;
3097 isolate->StackOverflow();
3102 CompilerTracer::TraceStartBaselineCompile(isolate, shared);
3119 CompilerTracer::TraceFinishBaselineCompile(isolate, shared, time_taken_ms);
3121 if (IsScript(shared->script())) {
3123 isolate, LogEventListener::CodeTag::kFunction,
3126 CodeKind::BASELINE, time_taken_ms);
3145 DCHECK_EQ(baseline_code->kind(), CodeKind::BASELINE);
3146 function->UpdateCodeKeepTieringRequests(baseline_code);
3155 isolate, is_compiled_scope);
3163 "V8.FinalizeBackgroundCompileTask");
3165 RuntimeCallCounterId::kCompileFinalizeBackgroundCompileTask);
3171 DCHECK(!isolate->has_exception());
3181 DCHECK(AllowCompilation::IsAllowed(isolate));
3183 if (
v8_flags.stress_concurrent_inlining &&
3184 isolate->concurrent_recompilation_enabled() &&
IsSynchronous(mode) &&
3185 isolate->node_observer() ==
nullptr) {
3186 SpawnDuplicateConcurrentJobForStressTesting(isolate, function, mode,
3193 !function->ActiveTierIsMaglev(isolate));
3195 !function->ActiveTierIsTurbofan(isolate));
3197 bool tiering_was_in_progress = function->tiering_in_progress();
3202 if (GetOrCompileOptimized(isolate, function, mode, code_kind)
3204 function->UpdateOptimizedCode(isolate, *code);
3206 function->IsLoggingRequested(isolate));
3208#ifdef V8_ENABLE_LEAPTIERING
3213 if (!function->is_compiled(isolate)) {
3214 function->UpdateCodeKeepTieringRequests(
3215 function->shared()->GetCode(isolate));
3221 DCHECK(!isolate->has_exception());
3222 DCHECK(function->is_compiled(isolate));
3223 DCHECK(function->shared()->HasBytecodeArray());
3226 !function->IsLoggingRequested(isolate),
3227 function->tiering_in_progress());
3232 DCHECK_IMPLIES(!tiering_was_in_progress && function->tiering_in_progress(),
3233 function->ChecksTieringState(isolate));
3235 DCHECK_IMPLIES(!tiering_was_in_progress && function->tiering_in_progress(),
3245 return v8::internal::CompileToplevel(parse_info, script, outer_scope_info,
3246 isolate, &is_compiled_scope);
3255 Isolate* isolate = context->GetIsolate();
3266 int eval_cache_position = eval_position;
3271 eval_cache_position = -parameters_end_pos;
3275 source, outer_info, context, language_mode, eval_cache_position);
3284 bool allow_eval_cache;
3289 is_compiled_scope = shared_info->is_compiled_scope(isolate);
3290 allow_eval_cache =
true;
3295 flags.set_is_eval(
true);
3296 flags.set_parsing_while_debugging(parsing_while_debugging);
3297 DCHECK(!flags.is_module());
3298 flags.set_parse_restriction(restriction);
3302 ParseInfo parse_info(isolate, flags, &compile_state, &reusable_state);
3306 if (!IsNativeContext(*context)) {
3307 maybe_outer_scope_info =
direct_handle(context->scope_info(), isolate);
3311 OriginOptionsForEval(outer_info->script(), parsing_while_debugging));
3312 script->set_eval_from_shared(*outer_info);
3318 if (!it.done() && it.is_javascript()) {
3320 script->set_eval_from_shared(
3321 summary.AsJavaScript().function()->shared());
3322 script->set_origin_options(
3323 OriginOptionsForEval(*summary.
script(), parsing_while_debugging));
3329 script->set_eval_from_position(eval_position);
3331 if (!v8::internal::CompileToplevel(&parse_info, script,
3332 maybe_outer_scope_info, isolate,
3334 .ToHandle(&shared_info)) {
3357 if (allow_eval_cache) {
3360 result->raw_feedback_cell(), isolate);
3361 compilation_cache->
PutEval(source, outer_info, context, shared_info,
3362 new_feedback_cell, eval_cache_position);
3372 if (allow_eval_cache) {
3377 compilation_cache->
PutEval(source, outer_info, context, shared_info,
3378 new_feedback_cell, eval_cache_position);
3391 bool is_code_like) {
3392 DCHECK(isolate->modify_code_gen_callback());
3398 RCS_SCOPE(isolate, RuntimeCallCounterId::kCodeGenerationFromStringsCallbacks);
3400 isolate->modify_code_gen_callback()(v8::Utils::ToLocal(context),
3401 v8::Utils::ToLocal(*source),
3403 if (
result.codegen_allowed && !
result.modified_source.IsEmpty()) {
3426std::pair<MaybeDirectHandle<String>,
bool>
3430 bool is_code_like) {
3435 if (!IsFalse(context->allow_code_gen_from_strings(), isolate) &&
3436 IsString(*original_source)) {
3443 if (isolate->modify_code_gen_callback()) {
3449 if (!IsString(*modified_source)) {
3455 if (!IsFalse(context->allow_code_gen_from_strings(), isolate) &&
3461 return {stringified_source, stringified_source.
is_null()};
3473 int parameters_end_pos) {
3477 if (source.is_null()) {
3480 THROW_NEW_ERROR(isolate, NewEvalError(MessageTemplate::kCodeGenFromStrings,
3496 int parameters_end_pos,
bool is_code_like) {
3497 Isolate*
const isolate = context->GetIsolate();
3503 parameters_end_pos);
3508struct ScriptCompileTimerScope {
3513 enum class CacheBehaviour {
3515 kHitIsolateCacheWhenNoCache,
3517 kConsumeCodeCacheFailed,
3518 kNoCacheBecauseInlineScript,
3519 kNoCacheBecauseScriptTooSmall,
3520 kNoCacheBecauseCacheTooCold,
3522 kNoCacheBecauseNoResource,
3523 kNoCacheBecauseInspector,
3524 kNoCacheBecauseCachingDisabled,
3525 kNoCacheBecauseModule,
3526 kNoCacheBecauseStreamingSource,
3527 kNoCacheBecauseV8Extension,
3528 kHitIsolateCacheWhenProduceCodeCache,
3529 kHitIsolateCacheWhenConsumeCodeCache,
3530 kNoCacheBecauseExtensionModule,
3531 kNoCacheBecausePacScript,
3532 kNoCacheBecauseInDocumentWrite,
3533 kNoCacheBecauseResourceWithNoCacheHandler,
3534 kHitIsolateCacheWhenStreamingSource,
3535 kNoCacheBecauseStaticCodeCache,
3539 ScriptCompileTimerScope(
3550 ~ScriptCompileTimerScope() {
3551 CacheBehaviour cache_behaviour = GetCacheBehaviour();
3553 Histogram* cache_behaviour_histogram =
3554 isolate_->counters()->compile_script_cache_behaviour();
3556 DCHECK_EQ(0, cache_behaviour_histogram->min());
3557 DCHECK_EQ(
static_cast<int>(CacheBehaviour::kCount),
3558 cache_behaviour_histogram->max() + 1);
3559 DCHECK_EQ(
static_cast<int>(CacheBehaviour::kCount),
3560 cache_behaviour_histogram->num_buckets());
3561 cache_behaviour_histogram->AddSample(
static_cast<int>(cache_behaviour));
3564 GetCacheBehaviourTimedHistogram(cache_behaviour));
3571 void set_consuming_code_cache_failed() {
3586 CacheBehaviour GetCacheBehaviour() {
3589 return CacheBehaviour::kHitIsolateCacheWhenConsumeCodeCache;
3591 return CacheBehaviour::kConsumeCodeCacheFailed;
3593 return CacheBehaviour::kConsumeCodeCache;
3602 ScriptCompiler::kNoCacheBecauseDeferredProduceCodeCache) {
3603 return CacheBehaviour::kHitIsolateCacheWhenProduceCodeCache;
3605 ScriptCompiler::kNoCacheBecauseStreamingSource) {
3606 return CacheBehaviour::kHitIsolateCacheWhenStreamingSource;
3608 return CacheBehaviour::kHitIsolateCacheWhenNoCache;
3612 case ScriptCompiler::kNoCacheBecauseInlineScript:
3613 return CacheBehaviour::kNoCacheBecauseInlineScript;
3614 case ScriptCompiler::kNoCacheBecauseScriptTooSmall:
3615 return CacheBehaviour::kNoCacheBecauseScriptTooSmall;
3616 case ScriptCompiler::kNoCacheBecauseCacheTooCold:
3617 return CacheBehaviour::kNoCacheBecauseCacheTooCold;
3618 case ScriptCompiler::kNoCacheNoReason:
3619 return CacheBehaviour::kNoCacheNoReason;
3620 case ScriptCompiler::kNoCacheBecauseNoResource:
3621 return CacheBehaviour::kNoCacheBecauseNoResource;
3622 case ScriptCompiler::kNoCacheBecauseInspector:
3623 return CacheBehaviour::kNoCacheBecauseInspector;
3624 case ScriptCompiler::kNoCacheBecauseCachingDisabled:
3625 return CacheBehaviour::kNoCacheBecauseCachingDisabled;
3626 case ScriptCompiler::kNoCacheBecauseModule:
3627 return CacheBehaviour::kNoCacheBecauseModule;
3628 case ScriptCompiler::kNoCacheBecauseStreamingSource:
3629 return CacheBehaviour::kNoCacheBecauseStreamingSource;
3630 case ScriptCompiler::kNoCacheBecauseV8Extension:
3631 return CacheBehaviour::kNoCacheBecauseV8Extension;
3632 case ScriptCompiler::kNoCacheBecauseExtensionModule:
3633 return CacheBehaviour::kNoCacheBecauseExtensionModule;
3634 case ScriptCompiler::kNoCacheBecausePacScript:
3635 return CacheBehaviour::kNoCacheBecausePacScript;
3636 case ScriptCompiler::kNoCacheBecauseInDocumentWrite:
3637 return CacheBehaviour::kNoCacheBecauseInDocumentWrite;
3638 case ScriptCompiler::kNoCacheBecauseResourceWithNoCacheHandler:
3639 return CacheBehaviour::kNoCacheBecauseResourceWithNoCacheHandler;
3640 case ScriptCompiler::kNoCacheBecauseDeferredProduceCodeCache:
3641 return CacheBehaviour::kProduceCodeCache;
3642 case ScriptCompiler::kNoCacheBecauseStaticCodeCache:
3643 return CacheBehaviour::kNoCacheBecauseStaticCodeCache;
3648 TimedHistogram* GetCacheBehaviourTimedHistogram(
3649 CacheBehaviour cache_behaviour) {
3650 switch (cache_behaviour) {
3651 case CacheBehaviour::kProduceCodeCache:
3654 case CacheBehaviour::kHitIsolateCacheWhenProduceCodeCache:
3655 return isolate_->counters()->compile_script_with_produce_cache();
3656 case CacheBehaviour::kHitIsolateCacheWhenNoCache:
3657 case CacheBehaviour::kHitIsolateCacheWhenConsumeCodeCache:
3658 case CacheBehaviour::kHitIsolateCacheWhenStreamingSource:
3659 return isolate_->counters()->compile_script_with_isolate_cache_hit();
3660 case CacheBehaviour::kConsumeCodeCacheFailed:
3661 return isolate_->counters()->compile_script_consume_failed();
3662 case CacheBehaviour::kConsumeCodeCache:
3663 return isolate_->counters()->compile_script_with_consume_cache();
3668 case CacheBehaviour::kNoCacheBecauseStreamingSource:
3669 return isolate_->counters()->compile_script_streaming_finalization();
3671 case CacheBehaviour::kNoCacheBecauseInlineScript:
3673 ->compile_script_no_cache_because_inline_script();
3674 case CacheBehaviour::kNoCacheBecauseScriptTooSmall:
3676 ->compile_script_no_cache_because_script_too_small();
3677 case CacheBehaviour::kNoCacheBecauseCacheTooCold:
3679 ->compile_script_no_cache_because_cache_too_cold();
3683 case CacheBehaviour::kNoCacheNoReason:
3684 case CacheBehaviour::kNoCacheBecauseNoResource:
3685 case CacheBehaviour::kNoCacheBecauseInspector:
3686 case CacheBehaviour::kNoCacheBecauseCachingDisabled:
3689 case CacheBehaviour::kNoCacheBecauseModule:
3690 case CacheBehaviour::kNoCacheBecauseV8Extension:
3691 case CacheBehaviour::kNoCacheBecauseExtensionModule:
3692 case CacheBehaviour::kNoCacheBecausePacScript:
3693 case CacheBehaviour::kNoCacheBecauseInDocumentWrite:
3694 case CacheBehaviour::kNoCacheBecauseResourceWithNoCacheHandler:
3695 case CacheBehaviour::kNoCacheBecauseStaticCodeCache:
3696 return isolate_->counters()->compile_script_no_cache_other();
3698 case CacheBehaviour::kCount:
3706 DirectHandle<String> source,
3707 ScriptDetails script_details,
NativesFlag natives) {
3710 isolate, source, script_details.wrapped_arguments,
3711 script_details.origin_options, natives);
3714 LOG(isolate, ScriptDetails(*script));
3718MaybeDirectHandle<SharedFunctionInfo> CompileScriptOnMainThread(
3719 const UnoptimizedCompileFlags flags, DirectHandle<String> source,
3720 const ScriptDetails& script_details,
NativesFlag natives,
3722 MaybeHandle<Script> maybe_script, IsCompiledScope* is_compiled_scope,
3724 void* compile_hint_callback_data =
nullptr) {
3725 UnoptimizedCompileState compile_state;
3726 ReusableUnoptimizedCompileState reusable_state(isolate);
3727 ParseInfo parse_info(isolate, flags, &compile_state, &reusable_state);
3729 parse_info.SetCompileHintCallbackAndData(compile_hint_callback,
3730 compile_hint_callback_data);
3733 if (!maybe_script.ToHandle(&script)) {
3734 script = NewScript(isolate, &parse_info, source, script_details, natives);
3736 DCHECK_EQ(parse_info.flags().is_repl_mode(), script->is_repl_mode());
3742class StressBackgroundCompileThread :
public ParkingThread {
3744 StressBackgroundCompileThread(Isolate* isolate, Handle<String> source,
3745 const ScriptDetails& script_details)
3747 base::Thread::Options(
"StressBackgroundCompileThread", 2 *
i::MB)),
3750 v8::ScriptCompiler::StreamedSource::TWO_BYTE) {
3751 ScriptType type = script_details.origin_options.IsModule()
3752 ? ScriptType::kModule
3753 : ScriptType::kClassic;
3754 data()->task = std::make_unique<i::BackgroundCompileTask>(
3755 data(), isolate, type,
3756 ScriptCompiler::CompileOptions::kNoCompileOptions,
3760 void Run()
override {
data()->task->Run(); }
3769 SourceStream(DirectHandle<String> source, Isolate* isolate) :
done_(false) {
3775 size_t GetMoreData(
const uint8_t** src)
override {
3795bool CanBackgroundCompile(
const ScriptDetails& script_details,
3801 return !script_details.origin_options.IsModule() && !
extension &&
3807bool CompilationExceptionIsRangeError(Isolate* isolate,
3808 DirectHandle<Object> obj) {
3809 if (!IsJSError(*obj, isolate))
return false;
3811 DirectHandle<JSReceiver> constructor;
3815 return *constructor == *isolate->range_error_function();
3818MaybeDirectHandle<SharedFunctionInfo>
3819CompileScriptOnBothBackgroundAndMainThread(Handle<String> source,
3820 const ScriptDetails& script_details,
3822 IsCompiledScope* is_compiled_scope) {
3824 StressBackgroundCompileThread background_compile_thread(isolate, source,
3827 UnoptimizedCompileFlags flags_copy =
3828 background_compile_thread.data()->task->flags();
3830 CHECK(background_compile_thread.Start());
3831 MaybeDirectHandle<SharedFunctionInfo> main_thread_maybe_result;
3832 bool main_thread_had_stack_overflow =
false;
3835 IsCompiledScope inner_is_compiled_scope;
3840 TryCatch ignore_try_catch(
reinterpret_cast<v8::Isolate*
>(isolate));
3842 main_thread_maybe_result = CompileScriptOnMainThread(
3844 MaybeHandle<Script>(), &inner_is_compiled_scope);
3845 if (main_thread_maybe_result.is_null()) {
3847 main_thread_had_stack_overflow = CompilationExceptionIsRangeError(
3849 isolate->clear_exception();
3854 background_compile_thread.ParkedJoin(isolate->main_thread_local_isolate());
3856 ScriptCompiler::CompilationDetails compilation_details;
3857 MaybeDirectHandle<SharedFunctionInfo> maybe_result =
3859 isolate, source, script_details, background_compile_thread.data(),
3860 &compilation_details);
3866 if (main_thread_had_stack_overflow) {
3867 CHECK(main_thread_maybe_result.is_null());
3869 CHECK_EQ(maybe_result.is_null(), main_thread_maybe_result.is_null());
3872 DirectHandle<SharedFunctionInfo>
result;
3873 if (maybe_result.ToHandle(&
result)) {
3877 *is_compiled_scope =
result->is_compiled_scope(isolate);
3880 return maybe_result;
3886 return !lookup_result.toplevel_sfi().is_null()
3888 : !lookup_result.script().is_null()
3894MaybeDirectHandle<SharedFunctionInfo> GetSharedFunctionInfoForScriptImpl(
3895 Isolate* isolate, Handle<String> source,
3897 AlignedCachedData* cached_data, BackgroundDeserializeTask* deserialize_task,
3899 void* compile_hint_callback_data,
3902 ScriptCompiler::CompilationDetails* compilation_details) {
3903 ScriptCompileTimerScope compile_timer(isolate, no_cache_reason,
3904 compilation_details);
3908 DCHECK(cached_data || deserialize_task);
3909 DCHECK(!(cached_data && deserialize_task));
3924 compilation_details->background_time_in_microseconds =
3925 deserialize_task ? deserialize_task->background_time_in_microseconds()
3929 CompilationCache* compilation_cache = isolate->compilation_cache();
3933 const bool use_compilation_cache =
3935 MaybeDirectHandle<SharedFunctionInfo> maybe_result;
3936 MaybeHandle<Script> maybe_script;
3937 IsCompiledScope is_compiled_scope;
3938 if (use_compilation_cache) {
3939 bool can_consume_code_cache =
3941 if (can_consume_code_cache) {
3942 compile_timer.set_consuming_code_cache();
3947 compilation_cache->LookupScript(source, script_details, language_mode);
3948 compilation_details->in_memory_cache_result =
3949 CategorizeLookupResult(lookup_result);
3950 maybe_script = lookup_result.script();
3951 maybe_result = lookup_result.toplevel_sfi();
3952 is_compiled_scope = lookup_result.is_compiled_scope();
3953 if (!maybe_result.is_null()) {
3954 compile_timer.set_hit_isolate_cache();
3955 }
else if (can_consume_code_cache) {
3956 compile_timer.set_consuming_code_cache();
3958 NestedTimedHistogramScope timer(
3959 isolate->counters()->compile_deserialize());
3960 RCS_SCOPE(isolate, RuntimeCallCounterId::kCompileDeserialize);
3962 "V8.CompileDeserialize");
3963 if (deserialize_task) {
3966 deserialize_task->Finish(isolate, source, script_details);
3987 isolate, cached_data, source, script_details, maybe_script);
3990 bool consuming_code_cache_succeeded =
false;
3991 DirectHandle<SharedFunctionInfo>
result;
3992 if (maybe_result.ToHandle(&
result)) {
3993 is_compiled_scope =
result->is_compiled_scope(isolate);
3994 if (is_compiled_scope.is_compiled()) {
3995 consuming_code_cache_succeeded =
true;
3997 compilation_cache->PutScript(source, language_mode,
result);
4000 if (!consuming_code_cache_succeeded) {
4002 compile_timer.set_consuming_code_cache_failed();
4007 if (maybe_result.is_null()) {
4009 if (
v8_flags.stress_background_compile &&
4010 CanBackgroundCompile(script_details,
extension, compile_options,
4014 maybe_result = CompileScriptOnBothBackgroundAndMainThread(
4015 source, script_details, isolate, &is_compiled_scope);
4017 UnoptimizedCompileFlags flags =
4020 script_details.repl_mode,
4026 flags.set_compile_hints_magic_enabled(
4028 flags.set_compile_hints_per_function_magic_enabled(
4032 if (DirectHandle<Script> script; maybe_script.ToHandle(&script)) {
4033 flags.set_script_id(script->id());
4036 maybe_result = CompileScriptOnMainThread(
4037 flags, source, script_details, natives,
extension, isolate,
4038 maybe_script, &is_compiled_scope, compile_hint_callback,
4039 compile_hint_callback_data);
4043 DirectHandle<SharedFunctionInfo>
result;
4044 if (use_compilation_cache && maybe_result.ToHandle(&
result)) {
4045 DCHECK(is_compiled_scope.is_compiled());
4046 compilation_cache->PutScript(source, language_mode,
result);
4047 }
else if (maybe_result.is_null() && natives !=
EXTENSION_CODE) {
4048 isolate->ReportPendingMessages();
4051 DirectHandle<SharedFunctionInfo>
result;
4053 maybe_result.ToHandle(&
result)) {
4057 return maybe_result;
4068 return GetSharedFunctionInfoForScriptImpl(
4069 isolate, source, script_details,
nullptr,
nullptr,
nullptr,
nullptr,
4070 nullptr, compile_options, no_cache_reason, natives, compilation_details);
4079 return GetSharedFunctionInfoForScriptImpl(
4080 isolate, source, script_details,
extension,
nullptr,
nullptr,
nullptr,
4082 natives, compilation_details);
4092 return GetSharedFunctionInfoForScriptImpl(
4093 isolate, source, script_details,
nullptr, cached_data,
nullptr,
nullptr,
4094 nullptr, compile_options, no_cache_reason, natives, compilation_details);
4105 return GetSharedFunctionInfoForScriptImpl(
4106 isolate, source, script_details,
nullptr,
nullptr, deserialize_task,
4107 nullptr,
nullptr, compile_options, no_cache_reason, natives,
4108 compilation_details);
4116 void* compile_hint_callback_data,
4120 return GetSharedFunctionInfoForScriptImpl(
4121 isolate, source, script_details,
nullptr,
nullptr,
nullptr,
4122 compile_hint_callback, compile_hint_callback_data, compile_options,
4123 no_cache_reason, natives, compilation_details);
4132 Isolate* isolate = context->GetIsolate();
4134 ScriptCompileTimerScope compile_timer(isolate, no_cache_reason,
4135 &compilation_details);
4150 bool can_consume_code_cache =
4155 compilation_cache->
LookupScript(source, script_details, language_mode);
4158 is_compiled_scope =
result->is_compiled_scope(isolate);
4159 compile_timer.set_hit_isolate_cache();
4160 }
else if (can_consume_code_cache) {
4161 compile_timer.set_consuming_code_cache();
4164 RCS_SCOPE(isolate, RuntimeCallCounterId::kCompileDeserialize);
4166 "V8.CompileDeserialize");
4169 bool consuming_code_cache_succeeded =
false;
4171 is_compiled_scope =
result->is_compiled_scope(isolate);
4173 consuming_code_cache_succeeded =
true;
4178 if (!consuming_code_cache_succeeded) {
4180 compile_timer.set_consuming_code_cache_failed();
4186 isolate,
true, language_mode, script_details.
repl_mode,
4188 flags.set_is_eval(
true);
4193 flags.set_collect_source_positions(
true);
4198 ParseInfo parse_info(isolate, flags, &compile_state, &reusable_state);
4201 if (!IsNativeContext(*context)) {
4202 maybe_outer_scope_info =
direct_handle(context->scope_info(), isolate);
4204 script = NewScript(isolate, &parse_info, source, script_details,
4208 maybe_result = v8::internal::CompileToplevel(&parse_info, script,
4209 maybe_outer_scope_info,
4210 isolate, &is_compiled_scope);
4211 if (maybe_result.
is_null()) isolate->ReportPendingMessages();
4216 info = infos.
Next()) {
4217 if (info->is_wrapped()) {
4224 is_compiled_scope =
result->is_compiled_scope(isolate);
4227 if (maybe_outer_scope_info.
is_null()) {
4247 ScriptCompileTimerScope compile_timer(
4249 compilation_details);
4261 "V8.StreamingFinalization.CheckCache");
4263 compilation_cache->
LookupScript(source, script_details,
4264 task->
flags().outer_language_mode());
4266 CategorizeLookupResult(lookup_result);
4272 if (!maybe_result.
is_null()) {
4273 compile_timer.set_hit_isolate_cache();
4275 maybe_cached_script = lookup_result.
script();
4283 RuntimeCallCounterId::kCompilePublishBackgroundFinalization);
4285 "V8.OffThreadFinalization.Publish");
4287 maybe_result = task->
FinalizeScript(isolate, source, script_details,
4288 maybe_cached_script);
4292 if (task->
flags().produce_compile_hints()) {
4298 "V8.StreamingFinalization.AddToCache");
4299 compilation_cache->
PutScript(source, task->
flags().outer_language_mode(),
4305 "V8.StreamingFinalization.Release");
4307 return maybe_result;
4311template <
typename IsolateT>
4316 if (!
literal->shared_function_info().is_null()) {
4317 return literal->shared_function_info();
4327 if (maybe_existing.
ToHandle(&existing)) {
4331 if (
literal->produced_preparse_data() !=
nullptr &&
4332 existing->HasUncompiledDataWithoutPreparseData()) {
4334 existing->uncompiled_data(isolate), isolate);
4336 existing_uncompiled_data->start_position());
4338 existing_uncompiled_data->end_position());
4342 handle(existing_uncompiled_data->inferred_name(), isolate);
4344 literal->produced_preparse_data()->Serialize(isolate);
4346 isolate->factory()->NewUncompiledDataWithPreparseData(
4347 inferred_name, existing_uncompiled_data->start_position(),
4348 existing_uncompiled_data->end_position(), preparse_data);
4349 existing->set_uncompiled_data(*new_uncompiled_data);
4356 isolate->factory()->NewSharedFunctionInfoForLiteral(
literal, script,
4371 DCHECK(IsOSR(osr_offset));
4373 if (
V8_UNLIKELY(isolate->serializer_enabled()))
return {};
4374 if (
V8_UNLIKELY(function->shared()->optimization_disabled()))
return {};
4381 if (
V8_UNLIKELY(!function->has_feedback_vector()))
return {};
4383 CompilerTracer::TraceOptimizeOSRStarted(isolate, function, osr_offset, mode);
4385 GetOrCompileOptimized(isolate, function, mode, code_kind, osr_offset);
4388 CompilerTracer::TraceOptimizeOSRUnavailable(isolate, function, osr_offset,
4392 CompilerTracer::TraceOptimizeOSRAvailable(isolate, function, osr_offset,
4403 "V8.OptimizeConcurrentDispose", job->
trace_id(),
4416 RCS_SCOPE(isolate, RuntimeCallCounterId::kOptimizeConcurrentFinalize);
4418 "V8.OptimizeConcurrentFinalize", job->
trace_id(),
4424 const bool use_result = !compilation_info->discard_result_for_testing();
4427 DCHECK(!shared->HasBreakInfo(isolate));
4435 if (shared->optimization_disabled()) {
4442 function->SetTieringInProgress(
false,
4445 OptimizedCodeCache::Insert(
4446 isolate, *compilation_info->
closure(),
4448 compilation_info->function_context_specializing());
4450 CompilerTracer::TraceCompletedJob(isolate, compilation_info);
4451 if (IsOSR(osr_offset)) {
4452 CompilerTracer::TraceOptimizeOSRFinished(isolate, function,
4455 function->UpdateOptimizedCode(isolate, *compilation_info->
code());
4463 CompilerTracer::TraceAbortedJob(isolate, compilation_info,
4467 function->SetTieringInProgress(
false,
4469 if (!IsOSR(osr_offset)) {
4470 function->UpdateCode(shared->GetCode(isolate));
4478#ifdef V8_ENABLE_MAGLEV
4480 function->SetTieringInProgress(
false, job->osr_offset());
4487#ifdef V8_ENABLE_MAGLEV
4493 if (function->ActiveTierIsTurbofan(isolate) && !job->is_osr()) {
4494 function->SetTieringInProgress(
false, osr_offset);
4495 CompilerTracer::TraceAbortedMaglevCompile(
4496 isolate, function, BailoutReason::kHigherTierAvailable);
4500 if (function->native_context()->global_object()->IsDetached()) {
4501 CompilerTracer::TraceAbortedMaglevCompile(
4502 isolate, function, BailoutReason::kDetachedNativeContext);
4514 DCHECK(!shared->HasBreakInfo(isolate));
4520 if (!job->is_osr()) {
4521 job->function()->UpdateOptimizedCode(isolate, *code);
4524 DCHECK(code->is_maglevved());
4526 OptimizedCodeCache::Insert(isolate, *function, osr_offset, *code,
4527 job->specialize_to_function_context());
4530 RecordMaglevFunctionCompilation(isolate, function,
4532 job->RecordCompilationStats(isolate);
4533 if (
v8_flags.profile_guided_optimization &&
4534 shared->cached_tiering_decision() <=
4538 CompilerTracer::TraceFinishMaglevCompile(
4539 isolate, function, job->is_osr(), job->prepare_in_ms(),
4540 job->execute_in_ms(), job->finalize_in_ms());
4542 CompilerTracer::TraceAbortedMaglevCompile(isolate, function,
4543 job->bailout_reason_);
4545 function->SetTieringInProgress(
false, osr_offset);
4557 if (is_compiled_scope->
is_compiled() && shared->HasBytecodeArray()) {
4562#ifndef V8_ENABLE_LEAPTIERING
4563 if (function->has_feedback_vector()) {
4568 function->feedback_vector()->EvictOptimizedCodeMarkedForDeoptimization(
4569 isolate, *shared,
"new function from shared function info");
4570 Tagged<Code> code = function->feedback_vector()->optimized_code(isolate);
4571 if (!code.is_null()) {
4573 DCHECK(!code->marked_for_deoptimization());
4574 DCHECK(function->shared()->is_compiled());
4575 function->UpdateOptimizedCode(isolate, code);
4580 if (
v8_flags.always_turbofan && shared->allows_lazy_compilation() &&
4581 !shared->optimization_disabled() &&
4582 !function->HasAvailableOptimizedCode(isolate)) {
4583 CompilerTracer::TraceMarkForAlwaysOpt(isolate, function);
4585 function->RequestOptimization(isolate, CodeKind::TURBOFAN_JS,
4590 if (shared->is_toplevel() || shared->is_wrapped()) {
4593 isolate->debug()->OnAfterCompile(script);
4594 bool source_rundown_enabled;
4597 &source_rundown_enabled);
4598 if (source_rundown_enabled) {
4599 script->TraceScriptRundown();
4601 bool source_rundown_sources_enabled;
4604 &source_rundown_sources_enabled);
4605 if (source_rundown_sources_enabled) {
4606 script->TraceScriptRundownSources();
4615 std::unique_ptr<ScriptCompiler::ExternalSourceStream> source_stream,
4617 : source_stream(
std::move(source_stream)), encoding(encoding) {}
interpreter::Bytecode bytecode
union v8::internal::@341::BuiltinMetadata::KindSpecificData data
#define BUILTIN_CODE(isolate, name)
#define SBXCHECK(condition)
@ kTurboFanOsrCompileStarted
internal::ScriptStreamingData * impl() const
CompilationDetails & compilation_details()
@ kNoCacheBecauseV8Extension
@ kNoCacheBecauseStreamingSource
@ kFollowCompileHintsMagicComment
@ kFollowCompileHintsPerFunctionMagicComment
static v8::internal::Handle< To > OpenHandle(v8::Local< From > handle)
double InMillisecondsF() const
int64_t InMicroseconds() const
static bool IsHighResolution()
bool HasDataOwnership() const
static V8_EXPORT_PRIVATE DirectHandle< ArrayList > Add(Isolate *isolate, DirectHandle< ArrayList > array, Tagged< Smi > obj, AllocationType allocation=AllocationType::kYoung)
static DirectHandle< ArrayList > New(IsolateT *isolate, int capacity, AllocationType allocation=AllocationType::kYoung)
static std::unique_ptr< UnoptimizedCompilationJob > NewCompilationJob(ParseInfo *parse_info, FunctionLiteral *literal, AccountingAllocator *allocator)
BackgroundCompileTask(ScriptStreamingData *data, Isolate *isolate, v8::ScriptType type, ScriptCompiler::CompileOptions options, ScriptCompiler::CompilationDetails *compilation_details, CompileHintCallback compile_hint_callback=nullptr, void *compile_hint_callback_data=nullptr)
int total_preparse_skipped_
void ReportStatistics(Isolate *isolate)
IsCompiledScope is_compiled_scope_
std::unique_ptr< Utf16CharacterStream > character_stream_
MaybeIndirectHandle< SharedFunctionInfo > outer_function_sfi_
ScriptCompiler::CompilationDetails * compilation_details_
UnoptimizedCompileFlags flags_
bool FinalizeFunction(Isolate *isolate, Compiler::ClearExceptionFlag flag)
Isolate * isolate_for_local_isolate_
DeferredFinalizationJobDataList jobs_to_retry_finalization_on_main_thread_
MaybeHandle< SharedFunctionInfo > FinalizeScript(Isolate *isolate, DirectHandle< String > source, const ScriptDetails &script_details, MaybeDirectHandle< Script > maybe_cached_script)
UnoptimizedCompileState compile_state_
bool is_streaming_compilation() const
FinalizeUnoptimizedCompilationDataList finalize_unoptimized_compilation_data_
CompileHintCallback compile_hint_callback_
UnoptimizedCompileFlags flags() const
void RunOnMainThread(Isolate *isolate)
void * compile_hint_callback_data_
std::unique_ptr< PersistentHandles > persistent_handles_
IndirectHandle< Script > script_
base::SmallVector< v8::Isolate::UseCounterFeature, 8 > use_counts_
MaybeIndirectHandle< SharedFunctionInfo > input_shared_info_
CodeSerializer::OffThreadDeserializeData off_thread_data_
MaybeDirectHandle< SharedFunctionInfo > Finish(Isolate *isolate, DirectHandle< String > source, const ScriptDetails &script_details)
bool ShouldMergeWithExistingScript() const
BackgroundMergeTask background_merge_task_
BackgroundDeserializeTask(Isolate *isolate, std::unique_ptr< ScriptCompiler::CachedData > data)
AlignedCachedData cached_data_
void MergeWithExistingScript()
void SourceTextAvailable(Isolate *isolate, Handle< String > source_text, const ScriptDetails &script_details)
Isolate * isolate_for_local_isolate_
int64_t background_time_in_microseconds_
static void ForceGCDuringNextMergeForTesting()
std::vector< NewCompiledDataForCachedSfi > new_compiled_data_for_cached_sfis_
bool HasPendingBackgroundWork() const
void SetUpOnMainThread(Isolate *isolate, Handle< String > source_text, const ScriptDetails &script_details, LanguageMode language_mode)
MaybeHandle< Script > cached_script_
std::unique_ptr< PersistentHandles > persistent_handles_
bool HasPendingForegroundWork() const
void BeginMergeInBackground(LocalIsolate *isolate, DirectHandle< Script > new_script)
Handle< SharedFunctionInfo > CompleteMergeInForeground(Isolate *isolate, DirectHandle< Script > new_script)
std::vector< Handle< SharedFunctionInfo > > used_new_sfis_
MaybeHandle< SharedFunctionInfo > toplevel_sfi_from_cached_script_
static DirectHandle< Code > CreateInterpreterEntryTrampolineForProfiling(Isolate *isolate)
static constexpr BytecodeOffset None()
static V8_WARN_UNUSED_RESULT MaybeDirectHandle< SharedFunctionInfo > FinishOffThreadDeserialize(Isolate *isolate, OffThreadDeserializeData &&data, AlignedCachedData *cached_data, DirectHandle< String > source, const ScriptDetails &script_details, BackgroundMergeTask *background_merge_task=nullptr)
static V8_WARN_UNUSED_RESULT OffThreadDeserializeData StartDeserializeOffThread(LocalIsolate *isolate, AlignedCachedData *cached_data)
static V8_WARN_UNUSED_RESULT MaybeDirectHandle< SharedFunctionInfo > Deserialize(Isolate *isolate, AlignedCachedData *cached_data, DirectHandle< String > source, const ScriptDetails &script_details, MaybeDirectHandle< Script > maybe_cached_script={})
IsCompiledScope is_compiled_scope() const
MaybeHandle< SharedFunctionInfo > toplevel_sfi() const
MaybeHandle< Script > script() const
CompilationCacheScriptLookupResult LookupResult
CompilationCacheScript::LookupResult LookupScript(Handle< String > source, const ScriptDetails &script_details, LanguageMode language_mode)
void PutScript(Handle< String > source, LanguageMode language_mode, DirectHandle< SharedFunctionInfo > function_info)
InfoCellPair LookupEval(DirectHandle< String > source, DirectHandle< SharedFunctionInfo > outer_info, DirectHandle< Context > context, LanguageMode language_mode, int position)
void PutEval(DirectHandle< String > source, DirectHandle< SharedFunctionInfo > outer_info, DirectHandle< Context > context, DirectHandle< SharedFunctionInfo > function_info, DirectHandle< FeedbackCell > feedback_cell, int position)
V8_EXPORT_PRIVATE ~CompilationHandleScope()
PersistentHandlesScope persistent_
OptimizedCompilationInfo * info_
V8_WARN_UNUSED_RESULT Status UpdateState(Status status, State next_state)
static V8_WARN_UNUSED_RESULT MaybeDirectHandle< JSFunction > GetFunctionFromValidatedString(DirectHandle< NativeContext > context, MaybeDirectHandle< String > source, ParseRestriction restriction, int parameters_end_pos)
static V8_WARN_UNUSED_RESULT MaybeDirectHandle< JSFunction > GetFunctionFromEval(DirectHandle< String > source, DirectHandle< SharedFunctionInfo > outer_info, DirectHandle< Context > context, LanguageMode language_mode, ParseRestriction restriction, int parameters_end_pos, int eval_position, ParsingWhileDebugging parsing_while_debugging=ParsingWhileDebugging::kNo)
static bool CompileSharedWithBaseline(Isolate *isolate, Handle< SharedFunctionInfo > shared, ClearExceptionFlag flag, IsCompiledScope *is_compiled_scope)
static bool CompileBaseline(Isolate *isolate, DirectHandle< JSFunction > function, ClearExceptionFlag flag, IsCompiledScope *is_compiled_scope)
static void CompileOptimized(Isolate *isolate, DirectHandle< JSFunction > function, ConcurrencyMode mode, CodeKind code_kind)
static MaybeDirectHandle< SharedFunctionInfo > GetSharedFunctionInfoForScriptWithCompileHints(Isolate *isolate, Handle< String > source, const ScriptDetails &script_details, v8::CompileHintCallback compile_hint_callback, void *compile_hint_callback_data, ScriptCompiler::CompileOptions compile_options, ScriptCompiler::NoCacheReason no_cache_reason, NativesFlag is_natives_code, ScriptCompiler::CompilationDetails *compilation_details)
static V8_WARN_UNUSED_RESULT std::pair< MaybeDirectHandle< String >, bool > ValidateDynamicCompilationSource(Isolate *isolate, DirectHandle< NativeContext > context, Handle< i::Object > source_object, bool is_code_like=false)
static bool Compile(Isolate *isolate, Handle< SharedFunctionInfo > shared, ClearExceptionFlag flag, IsCompiledScope *is_compiled_scope, CreateSourcePositions create_source_positions_flag=CreateSourcePositions::kNo)
static V8_WARN_UNUSED_RESULT MaybeDirectHandle< JSFunction > GetFunctionFromString(DirectHandle< NativeContext > context, Handle< i::Object > source, int parameters_end_pos, bool is_code_like)
static MaybeDirectHandle< SharedFunctionInfo > GetSharedFunctionInfoForScriptWithExtension(Isolate *isolate, Handle< String > source, const ScriptDetails &script_details, v8::Extension *extension, ScriptCompiler::CompileOptions compile_options, NativesFlag is_natives_code, ScriptCompiler::CompilationDetails *compilation_details)
static V8_WARN_UNUSED_RESULT MaybeDirectHandle< SharedFunctionInfo > CompileForLiveEdit(ParseInfo *parse_info, Handle< Script > script, MaybeDirectHandle< ScopeInfo > outer_scope_info, Isolate *isolate)
static bool CollectSourcePositions(Isolate *isolate, DirectHandle< SharedFunctionInfo > shared)
static void FinalizeTurbofanCompilationJob(TurbofanCompilationJob *job, Isolate *isolate)
static void InstallInterpreterTrampolineCopy(Isolate *isolate, DirectHandle< SharedFunctionInfo > shared_info, LogEventListener::CodeTag log_tag)
static DirectHandle< SharedFunctionInfo > GetSharedFunctionInfo(FunctionLiteral *node, DirectHandle< Script > script, IsolateT *isolate)
static MaybeDirectHandle< SharedFunctionInfo > GetSharedFunctionInfoForScriptWithDeserializeTask(Isolate *isolate, Handle< String > source, const ScriptDetails &script_details, BackgroundDeserializeTask *deserialize_task, ScriptCompiler::CompileOptions compile_options, ScriptCompiler::NoCacheReason no_cache_reason, NativesFlag is_natives_code, ScriptCompiler::CompilationDetails *compilation_details)
static void DisposeTurbofanCompilationJob(Isolate *isolate, TurbofanCompilationJob *job)
static MaybeDirectHandle< SharedFunctionInfo > GetSharedFunctionInfoForStreamedScript(Isolate *isolate, Handle< String > source, const ScriptDetails &script_details, ScriptStreamingData *streaming_data, ScriptCompiler::CompilationDetails *compilation_details)
static void FinalizeMaglevCompilationJob(maglev::MaglevCompilationJob *job, Isolate *isolate)
static bool FinalizeBackgroundCompileTask(BackgroundCompileTask *task, Isolate *isolate, ClearExceptionFlag flag)
static V8_WARN_UNUSED_RESULT MaybeDirectHandle< JSFunction > GetWrappedFunction(Handle< String > source, DirectHandle< Context > context, const ScriptDetails &script_details, AlignedCachedData *cached_data, v8::ScriptCompiler::CompileOptions compile_options, v8::ScriptCompiler::NoCacheReason no_cache_reason)
static MaybeDirectHandle< SharedFunctionInfo > GetSharedFunctionInfoForScript(Isolate *isolate, Handle< String > source, const ScriptDetails &script_details, ScriptCompiler::CompileOptions compile_options, ScriptCompiler::NoCacheReason no_cache_reason, NativesFlag is_natives_code, ScriptCompiler::CompilationDetails *compilation_details)
static V8_WARN_UNUSED_RESULT MaybeHandle< Code > CompileOptimizedOSR(Isolate *isolate, DirectHandle< JSFunction > function, BytecodeOffset osr_offset, ConcurrencyMode mode, CodeKind code_kind)
static void PostInstantiation(Isolate *isolate, DirectHandle< JSFunction > function, IsCompiledScope *is_compiled_scope)
static MaybeHandle< SharedFunctionInfo > CompileToplevel(ParseInfo *parse_info, Handle< Script > script, Isolate *isolate, IsCompiledScope *is_compiled_scope)
static void LogFunctionCompilation(Isolate *isolate, LogEventListener::CodeTag code_type, DirectHandle< Script > script, DirectHandle< SharedFunctionInfo > shared, DirectHandle< FeedbackVector > vector, DirectHandle< AbstractCode > abstract_code, CodeKind kind, double time_taken_ms)
static void DisposeMaglevCompilationJob(maglev::MaglevCompilationJob *job, Isolate *isolate)
static MaybeDirectHandle< SharedFunctionInfo > GetSharedFunctionInfoForScriptWithCachedData(Isolate *isolate, Handle< String > source, const ScriptDetails &script_details, AlignedCachedData *cached_data, ScriptCompiler::CompileOptions compile_options, ScriptCompiler::NoCacheReason no_cache_reason, NativesFlag is_natives_code, ScriptCompiler::CompilationDetails *compilation_details)
std::unordered_map< int, IndirectHandle< ScopeInfo > > scope_infos_to_update_
void VisitSharedFunctionInfo(Tagged< TArray > constant_pool, int i, Tagged< SharedFunctionInfo > sfi)
void VisitScopeInfo(Tagged< TArray > constant_pool, int i, Tagged< ScopeInfo > scope_info)
void VerifyScopeInfo(Tagged< ScopeInfo > scope_info, Tagged< ScopeInfo > replacement)
void set_has_shared_function_info_to_forward()
PtrComprCageBase cage_base_
void RecordScopeInfos(Tagged< HeapObject > info)
bool HasAnythingToForward() const
bool InstallOwnScopeInfo(Tagged< SharedFunctionInfo > sfi)
void IterateConstantPoolEntry(Tagged< TArray > constant_pool, int i)
void UpdateScopeInfo(Tagged< SharedFunctionInfo > sfi)
bool has_shared_function_info_to_forward_
void RecordScopeInfos(Tagged< MaybeObject > maybe_old_info)
DirectHandle< Script > old_script_
void IterateAndForwardPointers()
ConstantPoolPointerForwarder(PtrComprCageBase cage_base, LocalHeap *local_heap, DirectHandle< Script > old_script)
void AddBytecodeArray(Tagged< BytecodeArray > bytecode_array)
void IterateConstantPool(Tagged< TrustedFixedArray > constant_pool)
void IterateConstantPoolNestedArray(Tagged< FixedArray > nested_array)
std::vector< IndirectHandle< BytecodeArray > > bytecode_arrays_to_update_
static V8_EXPORT_PRIVATE std::unique_ptr< ConsumedPreparseData > For(Isolate *isolate, Handle< PreparseData > data)
static V8_EXPORT_PRIVATE void AllocateScopeInfos(ParseInfo *info, DirectHandle< Script > script, IsolateT *isolate)
DeferredFinalizationJobData(Isolate *isolate, DirectHandle< SharedFunctionInfo > function_handle, std::unique_ptr< UnoptimizedCompilationJob > job)
JSFunctionBuilder & set_feedback_cell(DirectHandle< FeedbackCell > v)
JSFunctionBuilder & set_allocation_type(AllocationType v)
V8_WARN_UNUSED_RESULT Handle< JSFunction > Build()
FinalizeUnoptimizedCompilationData(Isolate *isolate, Handle< SharedFunctionInfo > function_handle, MaybeHandle< CoverageInfo > coverage_info, base::TimeDelta time_taken_to_execute, base::TimeDelta time_taken_to_finalize)
Handle< Object > script() const
bool has_duplicate_parameters() const
Handle< SharedFunctionInfo > shared_function_info() const
V8_EXPORT_PRIVATE LanguageMode language_mode() const
bool has_static_private_methods_or_accessors() const
bool class_scope_has_private_brand() const
bool requires_instance_members_initializer() const
DeclarationScope * scope() const
void set_shared_function_info(Handle< SharedFunctionInfo > shared_function_info)
HandleType< T > CloseAndEscape(HandleType< T > handle_value)
V8_EXPORT_PRIVATE void CollectAllAvailableGarbage(GarbageCollectionReason gc_reason)
bool has_feedback_cell() const
Tagged< FeedbackCell > feedback_cell() const
Tagged< SharedFunctionInfo > shared() const
ThreadId thread_id() const
static V8_EXPORT_PRIVATE void EnsureFeedbackVector(Isolate *isolate, DirectHandle< JSFunction > function, IsCompiledScope *compiled_scope)
FeedbackVector eventually. Generally this shouldn't be used to get the.
static void InitializeFeedbackCell(DirectHandle< JSFunction > function, IsCompiledScope *compiled_scope, bool reset_budget_for_feedback_allocation)
static MaybeDirectHandle< JSFunction > GetConstructor(Isolate *isolate, DirectHandle< JSReceiver > receiver)
std::unique_ptr< PersistentHandles > DetachPersistentHandles()
IndirectHandle< T > NewPersistentHandle(Tagged< T > object)
void AttachPersistentHandles(std::unique_ptr< PersistentHandles > persistent_handles)
bool is_main_thread() const
static bool IsMarkedForManualOptimization(Isolate *isolate, Tagged< JSFunction > function)
V8_WARN_UNUSED_RESULT V8_INLINE bool ToHandle(DirectHandle< S > *out) const
V8_INLINE bool is_null() const
V8_INLINE Handle< T > ToHandleChecked() const
static MaybeObjectDirectHandle Weak(Tagged< Object > object, Isolate *isolate)
static V8_WARN_UNUSED_RESULT HandleType< String >::MaybeType ToString(Isolate *isolate, HandleType< T > input)
static V8_EXPORT_PRIVATE bool StrictEquals(Tagged< Object > obj, Tagged< Object > that)
static bool IsCodeLike(Tagged< Object > obj, Isolate *isolate)
bool IsOptimizing() const
BytecodeOffset osr_offset() const
IndirectHandle< Code > code() const
void AbortOptimization(BailoutReason reason)
IndirectHandle< SharedFunctionInfo > shared_info() const
void set_persistent_handles(std::unique_ptr< PersistentHandles > persistent_handles)
IndirectHandle< JSFunction > closure() const
void RetryOptimization(BailoutReason reason)
double prepare_in_ms() const
void RegisterWeakObjectsInOptimizedCode(Isolate *isolate, DirectHandle< NativeContext > context, DirectHandle< Code > code, GlobalHandleVector< Map > maps)
V8_WARN_UNUSED_RESULT base::TimeDelta ElapsedTime() const
base::TimeDelta time_taken_to_prepare_
GlobalHandleVector< Map > CollectRetainedMaps(Isolate *isolate, DirectHandle< Code > code)
V8_EXPORT_PRIVATE V8_WARN_UNUSED_RESULT Status FinalizeJob(Isolate *isolate)
double execute_in_ms() const
virtual Status PrepareJobImpl(Isolate *isolate)=0
virtual Status FinalizeJobImpl(Isolate *isolate)=0
double finalize_in_ms() const
virtual Status ExecuteJobImpl(RuntimeCallStats *stats, LocalIsolate *local_heap)=0
V8_EXPORT_PRIVATE V8_WARN_UNUSED_RESULT Status PrepareJob(Isolate *isolate)
base::TimeDelta time_taken_to_execute_
V8_EXPORT_PRIVATE V8_WARN_UNUSED_RESULT Status ExecuteJob(RuntimeCallStats *stats, LocalIsolate *local_isolate=nullptr)
base::TimeDelta time_taken_to_finalize_
AccountingAllocator * allocator() const
void ResetCharacterStream()
bool allow_eval_cache() const
FunctionLiteral * literal() const
void set_consumed_preparse_data(std::unique_ptr< ConsumedPreparseData > data)
Handle< Script > CreateScript(IsolateT *isolate, DirectHandle< String > source, MaybeDirectHandle< FixedArray > maybe_wrapped_arguments, ScriptOriginOptions origin_options, NativesFlag natives=NOT_NATIVES_CODE)
void set_parameters_end_pos(int parameters_end_pos)
void UpdateStatistics(Isolate *isolate, DirectHandle< Script > script)
void DeserializeScopeChain(IsolateT *isolate, ParseInfo *info, MaybeDirectHandle< ScopeInfo > maybe_outer_scope_info, Scope::DeserializationMode mode=Scope::DeserializationMode::kScopesOnly)
void InitializeEmptyScopeChain(ParseInfo *info)
void ParseOnBackground(LocalIsolate *isolate, ParseInfo *info, DirectHandle< Script > script, int start_position, int end_position, int function_literal_id)
V8_EXPORT_PRIVATE std::unique_ptr< PersistentHandles > Detach()
static constexpr bool IsEmbeddedObjectMode(Mode mode)
static int EmbeddedObjectModeMask()
AccountingAllocator * allocator() const
Handle< ScopeInfo > scope_info() const
static void InitLineEnds(Isolate *isolate, DirectHandle< Script > script)
static constexpr int kTemporaryScriptId
static MaybeHandle< SharedFunctionInfo > FindSharedFunctionInfo(DirectHandle< Script > script, IsolateT *isolate, FunctionLiteral *function_literal)
static void SetSource(Isolate *isolate, DirectHandle< Script > script, DirectHandle< String > source)
static bool GetPositionInfo(DirectHandle< Script > script, int position, PositionInfo *info, OffsetFlag offset_flag=OffsetFlag::kWithOffset)
V8_EXPORT_PRIVATE Tagged< SharedFunctionInfo > Next()
static void EnsureSourcePositionsAvailable(Isolate *isolate, DirectHandle< SharedFunctionInfo > shared_info)
static void CreateAndSetUncompiledData(IsolateT *isolate, FunctionLiteral *lit)
static Handle< String > DebugName(Isolate *isolate, DirectHandle< SharedFunctionInfo > shared)
static constexpr Tagged< Smi > FromInt(int value)
V8_INLINE constexpr StorageType ptr() const
constexpr bool IsWeak() const
Tagged< HeapObject > GetHeapObjectAssumeWeak() const
V8_INLINE constexpr bool is_null() const
static ThreadId Current()
OptimizedCompilationInfo *const compilation_info_
uint64_t trace_id() const
Status RetryOptimization(BailoutReason reason)
Status AbortOptimization(BailoutReason reason)
V8_EXPORT_PRIVATE TurbofanCompilationJob(Isolate *isolate, OptimizedCompilationInfo *compilation_info, State initial_state)
void RecordFunctionCompilation(LogEventListener::CodeTag code_type, Isolate *isolate) const
OptimizedCompilationInfo * compilation_info() const
void RecordCompilationStats(ConcurrencyMode mode, Isolate *isolate) const
bool has_asm_wasm_data() const
bool has_bytecode_array() const
FunctionLiteral * literal() const
DirectHandle< AsmWasmData > asm_wasm_data() const
FeedbackVectorSpec * feedback_vector_spec()
Handle< BytecodeArray > bytecode_array() const
virtual Status ExecuteJobImpl()=0
base::TimeDelta time_taken_to_execute_
V8_WARN_UNUSED_RESULT Status FinalizeJob(DirectHandle< SharedFunctionInfo > shared_info, Isolate *isolate)
base::TimeDelta time_taken_to_finalize_
V8_WARN_UNUSED_RESULT Status ExecuteJob()
virtual Status FinalizeJobImpl(DirectHandle< SharedFunctionInfo > shared_info, Isolate *isolate)=0
static UnoptimizedCompileFlags ForToplevelCompile(Isolate *isolate, bool is_user_javascript, LanguageMode language_mode, REPLMode repl_mode, ScriptType type, bool lazy)
static UnoptimizedCompileFlags ForFunctionCompile(Isolate *isolate, Tagged< SharedFunctionInfo > shared)
const PendingCompilationErrorHandler * pending_error_handler() const
static V8_INLINE CodeTag ToNativeByScript(CodeTag tag, Tagged< Script > script)
static V8_WARN_UNUSED_RESULT DirectHandle< WeakArrayList > Append(Isolate *isolate, DirectHandle< WeakArrayList > array, MaybeObjectDirectHandle value, AllocationType allocation=AllocationType::kYoung)
static std::unique_ptr< UnoptimizedCompilationJob > NewSourcePositionCollectionJob(ParseInfo *parse_info, FunctionLiteral *literal, Handle< BytecodeArray > existing_bytecode, AccountingAllocator *allocator, LocalIsolate *local_isolate)
static std::unique_ptr< UnoptimizedCompilationJob > NewCompilationJob(ParseInfo *parse_info, FunctionLiteral *literal, Handle< Script > script, AccountingAllocator *allocator, std::vector< FunctionLiteral * > *eager_inner_literals, LocalIsolate *local_isolate)
#define PROFILE(the_isolate, Call)
AlignedCachedData * cached_data_
#define V8_ENABLE_LEAPTIERING_BOOL
LazyTimedHistogramScope histogram_scope_
v8::ScriptCompiler::StreamedSource streamed_source_
std::unique_ptr< uint16_t[]> source_buffer_
bool consuming_code_cache_failed_
NestedTimedHistogramScope all_scripts_histogram_scope_
bool consuming_code_cache_
ScriptCompiler::NoCacheReason no_cache_reason_
Handle< SharedFunctionInfo > info
#define ASSIGN_RETURN_ON_EXCEPTION(isolate, dst, call)
#define THROW_NEW_ERROR(isolate, call)
DisallowGarbageCollection no_gc_
SharedFunctionInfoRef shared
ZoneVector< RpoNumber > & result
LiftoffAssembler::CacheState state
FunctionLiteral * literal
#define LOG(isolate, Call)
base::ElapsedTimer timer_
V8_INLINE const Operation & Get(const Graph &graph, OpIndex index)
std::unique_ptr< TurbofanCompilationJob > NewCompilationJob(Isolate *isolate, Handle< JSFunction > function, IsScriptAvailable has_script, BytecodeOffset osr_offset)
static bool IsMaglevEnabled()
bool ParseAny(ParseInfo *info, DirectHandle< SharedFunctionInfo > shared_info, Isolate *isolate, ReportStatisticsMode mode)
bool ParseProgram(ParseInfo *info, DirectHandle< Script > script, MaybeDirectHandle< ScopeInfo > maybe_outer_scope_info, Isolate *isolate, ReportStatisticsMode mode)
V8_INLINE IndirectHandle< T > handle(Tagged< T > object, Isolate *isolate)
static bool force_gc_during_next_merge_for_testing_
constexpr bool CodeKindCanOSR(CodeKind kind)
constexpr const char * ToString(DeoptimizeKind kind)
constexpr NullMaybeHandleType kNullMaybeHandle
constexpr bool CodeKindIsOptimizedJSFunction(CodeKind kind)
PerThreadAssertScopeDebugOnly< false, SAFEPOINTS_ASSERT, HEAP_ALLOCATION_ASSERT > DisallowGarbageCollection
void VisitObjectBody(Isolate *isolate, Tagged< HeapObject > object, ObjectVisitor *visitor)
bool is_sloppy(LanguageMode language_mode)
constexpr int kNoSourcePosition
bool Is(IndirectHandle< U > value)
void PrintF(const char *format,...)
const char * CodeKindToString(CodeKind kind)
Tagged(T object) -> Tagged< T >
constexpr bool CodeKindIsStoredInOptimizedCodeCache(CodeKind kind)
constexpr bool IsSynchronous(ConcurrencyMode mode)
V8_INLINE constexpr bool IsSmi(TaggedImpl< kRefType, StorageType > obj)
V8_INLINE IndirectHandle< T > indirect_handle(DirectHandle< T > handle)
MaybeDirectHandle< Code > GenerateBaselineCode(Isolate *isolate, Handle< SharedFunctionInfo > shared)
bool ModifyCodeGenerationFromStrings(Isolate *isolate, DirectHandle< NativeContext > context, Handle< i::Object > *source, bool is_code_like)
V8_INLINE DirectHandle< T > direct_handle(Tagged< T > object, Isolate *isolate)
too high values may cause the compiler to set high thresholds for inlining to as much as possible avoid inlined allocation of objects that cannot escape trace load stores from virtual maglev objects use TurboFan fast string builder analyze liveness of environment slots and zap dead values trace TurboFan load elimination emit data about basic block usage in builtins to this enable builtin reordering when run mksnapshot flag for emit warnings when applying builtin profile data verify register allocation in TurboFan randomly schedule instructions to stress dependency tracking enable store store elimination in TurboFan rewrite far to near simulate GC compiler thread race related to allow float parameters to be passed in simulator mode JS Wasm Run additional turbo_optimize_inlined_js_wasm_wrappers enable experimental feedback collection in generic lowering enable Turboshaft s WasmLoadElimination enable Turboshaft s low level load elimination for JS enable Turboshaft s escape analysis for string concatenation use enable Turbolev features that we want to ship in the not too far future trace individual Turboshaft reduction steps trace intermediate Turboshaft reduction steps invocation count threshold for early optimization Enables optimizations which favor memory size over execution speed Enables sampling allocation profiler with X as a sample interval min size of a semi the new space consists of two semi spaces max size of the Collect garbage after Collect garbage after keeps maps alive for< n > old space garbage collections print one detailed trace line in name
void Print(Tagged< Object > obj)
void SetScriptFieldsFromDetails(Isolate *isolate, Tagged< Script > script, const ScriptDetails &script_details, DisallowGarbageCollection *no_gc)
CodeKind CodeKindForTopTier()
@ ONLY_SINGLE_FUNCTION_LITERAL
uintptr_t GetCurrentStackPosition()
void ShortPrint(Tagged< Object > obj, FILE *out)
const char * GetBailoutReason(BailoutReason reason)
std::vector< DeferredFinalizationJobData > DeferredFinalizationJobDataList
Tagged< MaybeWeak< T > > MakeWeak(Tagged< T > value)
constexpr int kFunctionLiteralIdTopLevel
bool is_strict(LanguageMode language_mode)
V8_EXPORT_PRIVATE FlagValues v8_flags
std::vector< FinalizeUnoptimizedCompilationData > FinalizeUnoptimizedCompilationDataList
LanguageMode construct_language_mode(bool strict_bit)
constexpr int kStackSpaceRequiredForCompilation
SlotTraits::TMaybeObjectSlot MaybeObjectSlot
constexpr bool IsConcurrent(ConcurrencyMode mode)
bool CanCompileWithBaseline(Isolate *isolate, Tagged< SharedFunctionInfo > shared)
kInterpreterTrampolineOffset script
!IsContextMap !IsContextMap native_context
Tagged< To > Cast(Tagged< From > value, const v8::SourceLocation &loc=INIT_SOURCE_LOCATION_IN_DEBUG)
static constexpr ReleaseStoreTag kReleaseStore
static constexpr RelaxedLoadTag kRelaxedLoad
static constexpr RelaxedStoreTag kRelaxedStore
static constexpr AcquireLoadTag kAcquireLoad
bool(*)(int, void *) CompileHintCallback
#define DCHECK_NOT_NULL(val)
#define DCHECK_IMPLIES(v1, v2)
#define DCHECK_NE(v1, v2)
#define DCHECK_GE(v1, v2)
#define CHECK_EQ(lhs, rhs)
#define DCHECK(condition)
#define DCHECK_EQ(v1, v2)
int64_t background_time_in_microseconds
InMemoryCacheResult in_memory_cache_result
DirectHandle< Script > GetOnlyScript(LocalHeap *heap)
MaybeHandle< Object > name_obj
MaybeHandle< Object > source_map_url
const ScriptOriginOptions origin_options
MaybeHandle< Object > host_defined_options
MaybeHandle< FixedArray > wrapped_arguments
std::unique_ptr< BackgroundCompileTask > task
ScriptStreamingData(std::unique_ptr< ScriptCompiler::ExternalSourceStream > source_stream, ScriptCompiler::StreamedSource::Encoding encoding)
#define TRACE_EVENT0(category_group, name)
#define TRACE_DISABLED_BY_DEFAULT(name)
#define TRACE_EVENT_WITH_FLOW0(category_group, name, bind_id, flow_flags)
#define TRACE_EVENT_CATEGORY_GROUP_ENABLED(category_group, ret)
#define TRACE_EVENT_FLAG_FLOW_OUT
#define TRACE_EVENT_FLAG_FLOW_IN
#define V8_LIKELY(condition)
#define V8_WARN_UNUSED_RESULT
#define V8_UNLIKELY(condition)