blob: ae7b2b9f98eff8a6a3d1bb40fae2c388f4e8c4a6 [file] [log] [blame]
Steve Block6ded16b2010-05-10 14:33:55 +01001// Copyright 2010 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
Ben Murdochf87a2032010-10-22 12:50:53 +010030#include "compiler.h"
31
Steve Blocka7e24c12009-10-30 11:49:00 +000032#include "bootstrapper.h"
33#include "codegen-inl.h"
34#include "compilation-cache.h"
Steve Block6ded16b2010-05-10 14:33:55 +010035#include "data-flow.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000036#include "debug.h"
Leon Clarked91b9f72010-01-27 17:25:45 +000037#include "full-codegen.h"
Ben Murdochb8e0da22011-05-16 14:20:40 +010038#include "gdb-jit.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010039#include "hydrogen.h"
Steve Block1e0659c2011-05-24 12:43:12 +010040#include "lithium.h"
Steve Block6ded16b2010-05-10 14:33:55 +010041#include "liveedit.h"
Ben Murdochf87a2032010-10-22 12:50:53 +010042#include "parser.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000043#include "rewriter.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010044#include "runtime-profiler.h"
Ben Murdoch3bec4d22010-07-22 14:51:16 +010045#include "scopeinfo.h"
Ben Murdochf87a2032010-10-22 12:50:53 +010046#include "scopes.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010047#include "vm-state-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000048
49namespace v8 {
50namespace internal {
51
Ben Murdochf87a2032010-10-22 12:50:53 +010052
53CompilationInfo::CompilationInfo(Handle<Script> script)
54 : flags_(0),
55 function_(NULL),
56 scope_(NULL),
57 script_(script),
58 extension_(NULL),
Ben Murdochb0fe1622011-05-05 13:52:32 +010059 pre_parse_data_(NULL),
60 supports_deoptimization_(false),
61 osr_ast_id_(AstNode::kNoNumber) {
62 Initialize(NONOPT);
Ben Murdochf87a2032010-10-22 12:50:53 +010063}
64
65
66CompilationInfo::CompilationInfo(Handle<SharedFunctionInfo> shared_info)
67 : flags_(IsLazy::encode(true)),
68 function_(NULL),
69 scope_(NULL),
70 shared_info_(shared_info),
71 script_(Handle<Script>(Script::cast(shared_info->script()))),
72 extension_(NULL),
Ben Murdochb0fe1622011-05-05 13:52:32 +010073 pre_parse_data_(NULL),
74 supports_deoptimization_(false),
75 osr_ast_id_(AstNode::kNoNumber) {
76 Initialize(BASE);
Ben Murdochf87a2032010-10-22 12:50:53 +010077}
78
79
80CompilationInfo::CompilationInfo(Handle<JSFunction> closure)
81 : flags_(IsLazy::encode(true)),
82 function_(NULL),
83 scope_(NULL),
84 closure_(closure),
85 shared_info_(Handle<SharedFunctionInfo>(closure->shared())),
86 script_(Handle<Script>(Script::cast(shared_info_->script()))),
87 extension_(NULL),
Ben Murdochb0fe1622011-05-05 13:52:32 +010088 pre_parse_data_(NULL),
89 supports_deoptimization_(false),
90 osr_ast_id_(AstNode::kNoNumber) {
91 Initialize(BASE);
Ben Murdochf87a2032010-10-22 12:50:53 +010092}
93
94
Ben Murdochb8e0da22011-05-16 14:20:40 +010095void CompilationInfo::DisableOptimization() {
96 if (FLAG_optimize_closures) {
97 // If we allow closures optimizations and it's an optimizable closure
98 // mark it correspondingly.
99 bool is_closure = closure_.is_null() && !scope_->HasTrivialOuterContext();
100 if (is_closure) {
101 bool is_optimizable_closure =
102 !scope_->outer_scope_calls_eval() && !scope_->inside_with();
103 if (is_optimizable_closure) {
104 SetMode(BASE);
105 return;
106 }
107 }
108 }
109
110 SetMode(NONOPT);
111}
112
113
Ben Murdochb0fe1622011-05-05 13:52:32 +0100114// Determine whether to use the full compiler for all code. If the flag
115// --always-full-compiler is specified this is the case. For the virtual frame
116// based compiler the full compiler is also used if a debugger is connected, as
117// the code from the full compiler supports mode precise break points. For the
118// crankshaft adaptive compiler debugging the optimized code is not possible at
119// all. However crankshaft support recompilation of functions, so in this case
120// the full compiler need not be be used if a debugger is attached, but only if
121// break points has actually been set.
Leon Clarkef7060e22010-06-03 12:02:55 +0100122static bool AlwaysFullCompiler() {
123#ifdef ENABLE_DEBUGGER_SUPPORT
Ben Murdochb0fe1622011-05-05 13:52:32 +0100124 if (V8::UseCrankshaft()) {
125 return FLAG_always_full_compiler || Debug::has_break_points();
126 } else {
127 return FLAG_always_full_compiler || Debugger::IsDebuggerActive();
128 }
Leon Clarkef7060e22010-06-03 12:02:55 +0100129#else
130 return FLAG_always_full_compiler;
131#endif
132}
133
Steve Block3ce2e202009-11-05 08:53:23 +0000134
Ben Murdochb0fe1622011-05-05 13:52:32 +0100135static void FinishOptimization(Handle<JSFunction> function, int64_t start) {
136 int opt_count = function->shared()->opt_count();
137 function->shared()->set_opt_count(opt_count + 1);
138 double ms = static_cast<double>(OS::Ticks() - start) / 1000;
139 if (FLAG_trace_opt) {
140 PrintF("[optimizing: ");
141 function->PrintName();
142 PrintF(" / %" V8PRIxPTR, reinterpret_cast<intptr_t>(*function));
143 PrintF(" - took %0.3f ms]\n", ms);
144 }
145 if (FLAG_trace_opt_stats) {
146 static double compilation_time = 0.0;
147 static int compiled_functions = 0;
148 static int code_size = 0;
149
150 compilation_time += ms;
151 compiled_functions++;
152 code_size += function->shared()->SourceSize();
153 PrintF("Compiled: %d functions with %d byte source size in %fms.\n",
154 compiled_functions,
155 code_size,
156 compilation_time);
157 }
158}
159
160
161static void AbortAndDisable(CompilationInfo* info) {
162 // Disable optimization for the shared function info and mark the
163 // code as non-optimizable. The marker on the shared function info
164 // is there because we flush non-optimized code thereby loosing the
165 // non-optimizable information for the code. When the code is
166 // regenerated and set on the shared function info it is marked as
167 // non-optimizable if optimization is disabled for the shared
168 // function info.
169 Handle<SharedFunctionInfo> shared = info->shared_info();
170 shared->set_optimization_disabled(true);
171 Handle<Code> code = Handle<Code>(shared->code());
172 ASSERT(code->kind() == Code::FUNCTION);
173 code->set_optimizable(false);
174 info->SetCode(code);
175 if (FLAG_trace_opt) {
176 PrintF("[disabled optimization for: ");
177 info->closure()->PrintName();
178 PrintF(" / %" V8PRIxPTR "]\n",
179 reinterpret_cast<intptr_t>(*info->closure()));
180 }
181}
182
183
184static bool MakeCrankshaftCode(CompilationInfo* info) {
185 // Test if we can optimize this function when asked to. We can only
186 // do this after the scopes are computed.
187 if (!info->AllowOptimize()) info->DisableOptimization();
188
189 // In case we are not optimizing simply return the code from
190 // the full code generator.
191 if (!info->IsOptimizing()) {
192 return FullCodeGenerator::MakeCode(info);
193 }
194
195 // We should never arrive here if there is not code object on the
196 // shared function object.
197 Handle<Code> code(info->shared_info()->code());
198 ASSERT(code->kind() == Code::FUNCTION);
199
200 // Fall back to using the full code generator if it's not possible
201 // to use the Hydrogen-based optimizing compiler. We already have
202 // generated code for this from the shared function object.
203 if (AlwaysFullCompiler() || !FLAG_use_hydrogen) {
204 info->SetCode(code);
205 return true;
206 }
207
208 // Limit the number of times we re-compile a functions with
209 // the optimizing compiler.
Ben Murdochb8e0da22011-05-16 14:20:40 +0100210 const int kMaxOptCount =
211 FLAG_deopt_every_n_times == 0 ? Compiler::kDefaultMaxOptCount : 1000;
Ben Murdochb0fe1622011-05-05 13:52:32 +0100212 if (info->shared_info()->opt_count() > kMaxOptCount) {
213 AbortAndDisable(info);
214 // True indicates the compilation pipeline is still going, not
215 // necessarily that we optimized the code.
216 return true;
217 }
218
219 // Due to an encoding limit on LUnallocated operands in the Lithium
220 // language, we cannot optimize functions with too many formal parameters
221 // or perform on-stack replacement for function with too many
222 // stack-allocated local variables.
223 //
224 // The encoding is as a signed value, with parameters using the negative
225 // indices and locals the non-negative ones.
226 const int limit = LUnallocated::kMaxFixedIndices / 2;
227 Scope* scope = info->scope();
228 if (scope->num_parameters() > limit || scope->num_stack_slots() > limit) {
229 AbortAndDisable(info);
230 // True indicates the compilation pipeline is still going, not
231 // necessarily that we optimized the code.
232 return true;
233 }
234
235 // Take --hydrogen-filter into account.
236 Vector<const char> filter = CStrVector(FLAG_hydrogen_filter);
237 Handle<String> name = info->function()->debug_name();
238 bool match = filter.is_empty() || name->IsEqualTo(filter);
239 if (!match) {
240 info->SetCode(code);
241 return true;
242 }
243
244 // Recompile the unoptimized version of the code if the current version
245 // doesn't have deoptimization support. Alternatively, we may decide to
246 // run the full code generator to get a baseline for the compile-time
247 // performance of the hydrogen-based compiler.
248 int64_t start = OS::Ticks();
249 bool should_recompile = !info->shared_info()->has_deoptimization_support();
250 if (should_recompile || FLAG_time_hydrogen) {
251 HPhase phase(HPhase::kFullCodeGen);
252 CompilationInfo unoptimized(info->shared_info());
253 // Note that we use the same AST that we will use for generating the
254 // optimized code.
255 unoptimized.SetFunction(info->function());
256 unoptimized.SetScope(info->scope());
257 if (should_recompile) unoptimized.EnableDeoptimizationSupport();
258 bool succeeded = FullCodeGenerator::MakeCode(&unoptimized);
259 if (should_recompile) {
260 if (!succeeded) return false;
261 Handle<SharedFunctionInfo> shared = info->shared_info();
262 shared->EnableDeoptimizationSupport(*unoptimized.code());
263 // The existing unoptimized code was replaced with the new one.
264 Compiler::RecordFunctionCompilation(Logger::LAZY_COMPILE_TAG,
265 Handle<String>(shared->DebugName()),
266 shared->start_position(),
267 &unoptimized);
268 }
269 }
270
271 // Check that the unoptimized, shared code is ready for
272 // optimizations. When using the always_opt flag we disregard the
273 // optimizable marker in the code object and optimize anyway. This
274 // is safe as long as the unoptimized code has deoptimization
275 // support.
276 ASSERT(FLAG_always_opt || info->shared_info()->code()->optimizable());
277 ASSERT(info->shared_info()->has_deoptimization_support());
278
279 if (FLAG_trace_hydrogen) {
280 PrintF("-----------------------------------------------------------\n");
281 PrintF("Compiling method %s using hydrogen\n", *name->ToCString());
282 HTracer::Instance()->TraceCompilation(info->function());
283 }
284
Ben Murdochb8e0da22011-05-16 14:20:40 +0100285 TypeFeedbackOracle oracle(
286 Handle<Code>(info->shared_info()->code()),
287 Handle<Context>(info->closure()->context()->global_context()));
Ben Murdochb0fe1622011-05-05 13:52:32 +0100288 HGraphBuilder builder(&oracle);
289 HPhase phase(HPhase::kTotal);
290 HGraph* graph = builder.CreateGraph(info);
Steve Block1e0659c2011-05-24 12:43:12 +0100291 if (Top::has_pending_exception()) {
292 info->SetCode(Handle<Code>::null());
293 return false;
294 }
295
Ben Murdochb0fe1622011-05-05 13:52:32 +0100296 if (graph != NULL && FLAG_build_lithium) {
297 Handle<Code> code = graph->Compile();
298 if (!code.is_null()) {
299 info->SetCode(code);
300 FinishOptimization(info->closure(), start);
301 return true;
302 }
303 }
304
305 // Compilation with the Hydrogen compiler failed. Keep using the
306 // shared code but mark it as unoptimizable.
307 AbortAndDisable(info);
308 // True indicates the compilation pipeline is still going, not necessarily
309 // that we optimized the code.
310 return true;
311}
312
313
Ben Murdochf87a2032010-10-22 12:50:53 +0100314static bool MakeCode(CompilationInfo* info) {
315 // Precondition: code has been parsed. Postcondition: the code field in
316 // the compilation info is set if compilation succeeded.
317 ASSERT(info->function() != NULL);
318
Ben Murdochb0fe1622011-05-05 13:52:32 +0100319 if (Rewriter::Rewrite(info) && Scope::Analyze(info)) {
320 if (V8::UseCrankshaft()) return MakeCrankshaftCode(info);
321
Ben Murdochf87a2032010-10-22 12:50:53 +0100322 // Generate code and return it. Code generator selection is governed by
323 // which backends are enabled and whether the function is considered
324 // run-once code or not.
325 //
326 // --full-compiler enables the dedicated backend for code we expect to
327 // be run once
328 //
329 // The normal choice of backend can be overridden with the flags
330 // --always-full-compiler.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100331 if (Rewriter::Analyze(info)) {
332 Handle<SharedFunctionInfo> shared = info->shared_info();
333 bool is_run_once = (shared.is_null())
334 ? info->scope()->is_global_scope()
335 : (shared->is_toplevel() || shared->try_full_codegen());
336 bool can_use_full =
337 FLAG_full_compiler && !info->function()->contains_loops();
338 if (AlwaysFullCompiler() || (is_run_once && can_use_full)) {
339 return FullCodeGenerator::MakeCode(info);
340 } else {
341 return AssignedVariablesAnalyzer::Analyze(info) &&
342 CodeGenerator::MakeCode(info);
343 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100344 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000345 }
346
Ben Murdochf87a2032010-10-22 12:50:53 +0100347 return false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000348}
349
350
Steve Block6ded16b2010-05-10 14:33:55 +0100351#ifdef ENABLE_DEBUGGER_SUPPORT
Ben Murdochf87a2032010-10-22 12:50:53 +0100352bool Compiler::MakeCodeForLiveEdit(CompilationInfo* info) {
353 // Precondition: code has been parsed. Postcondition: the code field in
354 // the compilation info is set if compilation succeeded.
355 bool succeeded = MakeCode(info);
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100356 if (!info->shared_info().is_null()) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100357 Handle<SerializedScopeInfo> scope_info =
358 SerializedScopeInfo::Create(info->scope());
359 info->shared_info()->set_scope_info(*scope_info);
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100360 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100361 return succeeded;
Steve Block6ded16b2010-05-10 14:33:55 +0100362}
363#endif
364
365
Ben Murdochf87a2032010-10-22 12:50:53 +0100366static Handle<SharedFunctionInfo> MakeFunctionInfo(CompilationInfo* info) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000367 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
368
369 PostponeInterruptsScope postpone;
370
371 ASSERT(!i::Top::global_context().is_null());
Ben Murdochf87a2032010-10-22 12:50:53 +0100372 Handle<Script> script = info->script();
Steve Blocka7e24c12009-10-30 11:49:00 +0000373 script->set_context_data((*i::Top::global_context())->data());
374
Leon Clarke4515c472010-02-03 11:58:03 +0000375#ifdef ENABLE_DEBUGGER_SUPPORT
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800376 if (info->is_eval()) {
377 Script::CompilationType compilation_type = Script::COMPILATION_TYPE_EVAL;
Ben Murdochf87a2032010-10-22 12:50:53 +0100378 script->set_compilation_type(Smi::FromInt(compilation_type));
Steve Blocka7e24c12009-10-30 11:49:00 +0000379 // For eval scripts add information on the function from which eval was
380 // called.
Ben Murdochf87a2032010-10-22 12:50:53 +0100381 if (info->is_eval()) {
Leon Clarke4515c472010-02-03 11:58:03 +0000382 StackTraceFrameIterator it;
383 if (!it.done()) {
384 script->set_eval_from_shared(
385 JSFunction::cast(it.frame()->function())->shared());
386 int offset = static_cast<int>(
387 it.frame()->pc() - it.frame()->code()->instruction_start());
388 script->set_eval_from_instructions_offset(Smi::FromInt(offset));
389 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000390 }
391 }
392
393 // Notify debugger
394 Debugger::OnBeforeCompile(script);
395#endif
396
397 // Only allow non-global compiles for eval.
Ben Murdochf87a2032010-10-22 12:50:53 +0100398 ASSERT(info->is_eval() || info->is_global());
Steve Blocka7e24c12009-10-30 11:49:00 +0000399
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800400 if (!ParserApi::Parse(info)) return Handle<SharedFunctionInfo>::null();
Steve Blocka7e24c12009-10-30 11:49:00 +0000401
Steve Blocka7e24c12009-10-30 11:49:00 +0000402 // Measure how long it takes to do the compilation; only take the
403 // rest of the function into account to avoid overlap with the
404 // parsing statistics.
Ben Murdochf87a2032010-10-22 12:50:53 +0100405 HistogramTimer* rate = info->is_eval()
Steve Blocka7e24c12009-10-30 11:49:00 +0000406 ? &Counters::compile_eval
407 : &Counters::compile;
408 HistogramTimerScope timer(rate);
409
410 // Compile the code.
Ben Murdochf87a2032010-10-22 12:50:53 +0100411 FunctionLiteral* lit = info->function();
412 LiveEditFunctionTracker live_edit_tracker(lit);
413 if (!MakeCode(info)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000414 Top::StackOverflow();
Steve Block6ded16b2010-05-10 14:33:55 +0100415 return Handle<SharedFunctionInfo>::null();
Steve Blocka7e24c12009-10-30 11:49:00 +0000416 }
417
Ben Murdochf87a2032010-10-22 12:50:53 +0100418 ASSERT(!info->code().is_null());
Steve Block6ded16b2010-05-10 14:33:55 +0100419 if (script->name()->IsString()) {
420 PROFILE(CodeCreateEvent(
Ben Murdochf87a2032010-10-22 12:50:53 +0100421 info->is_eval()
422 ? Logger::EVAL_TAG
423 : Logger::ToNativeByScript(Logger::SCRIPT_TAG, *script),
424 *info->code(),
425 String::cast(script->name())));
Ben Murdochb8e0da22011-05-16 14:20:40 +0100426 GDBJIT(AddCode(Handle<String>(String::cast(script->name())),
427 script,
428 info->code()));
Steve Block6ded16b2010-05-10 14:33:55 +0100429 } else {
430 PROFILE(CodeCreateEvent(
Ben Murdochf87a2032010-10-22 12:50:53 +0100431 info->is_eval()
432 ? Logger::EVAL_TAG
433 : Logger::ToNativeByScript(Logger::SCRIPT_TAG, *script),
434 *info->code(),
435 ""));
Ben Murdochb8e0da22011-05-16 14:20:40 +0100436 GDBJIT(AddCode(Handle<String>(), script, info->code()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000437 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000438
439 // Allocate function.
Steve Block6ded16b2010-05-10 14:33:55 +0100440 Handle<SharedFunctionInfo> result =
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100441 Factory::NewSharedFunctionInfo(
442 lit->name(),
443 lit->materialized_literal_count(),
Ben Murdochf87a2032010-10-22 12:50:53 +0100444 info->code(),
445 SerializedScopeInfo::Create(info->scope()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000446
447 ASSERT_EQ(RelocInfo::kNoPosition, lit->function_token_position());
Steve Block6ded16b2010-05-10 14:33:55 +0100448 Compiler::SetFunctionInfo(result, lit, true, script);
Steve Blocka7e24c12009-10-30 11:49:00 +0000449
450 // Hint to the runtime system used when allocating space for initial
451 // property space by setting the expected number of properties for
452 // the instances of the function.
Steve Block6ded16b2010-05-10 14:33:55 +0100453 SetExpectedNofPropertiesFromEstimate(result, lit->expected_property_count());
Steve Blocka7e24c12009-10-30 11:49:00 +0000454
455#ifdef ENABLE_DEBUGGER_SUPPORT
456 // Notify debugger
Steve Block6ded16b2010-05-10 14:33:55 +0100457 Debugger::OnAfterCompile(script, Debugger::NO_AFTER_COMPILE_FLAGS);
Steve Blocka7e24c12009-10-30 11:49:00 +0000458#endif
459
Steve Block6ded16b2010-05-10 14:33:55 +0100460 live_edit_tracker.RecordFunctionInfo(result, lit);
461
462 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000463}
464
465
Steve Block6ded16b2010-05-10 14:33:55 +0100466Handle<SharedFunctionInfo> Compiler::Compile(Handle<String> source,
467 Handle<Object> script_name,
468 int line_offset,
469 int column_offset,
470 v8::Extension* extension,
471 ScriptDataImpl* input_pre_data,
472 Handle<Object> script_data,
473 NativesFlag natives) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000474 int source_length = source->length();
475 Counters::total_load_size.Increment(source_length);
476 Counters::total_compile_size.Increment(source_length);
477
478 // The VM is in the COMPILER state until exiting this function.
479 VMState state(COMPILER);
480
481 // Do a lookup in the compilation cache but not for extensions.
Steve Block6ded16b2010-05-10 14:33:55 +0100482 Handle<SharedFunctionInfo> result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000483 if (extension == NULL) {
484 result = CompilationCache::LookupScript(source,
485 script_name,
486 line_offset,
487 column_offset);
488 }
489
490 if (result.is_null()) {
Steve Block59151502010-09-22 15:07:15 +0100491 // No cache entry found. Do pre-parsing, if it makes sense, and compile
492 // the script.
493 // Building preparse data that is only used immediately after is only a
494 // saving if we might skip building the AST for lazily compiled functions.
495 // I.e., preparse data isn't relevant when the lazy flag is off, and
496 // for small sources, odds are that there aren't many functions
497 // that would be compiled lazily anyway, so we skip the preparse step
498 // in that case too.
Steve Blocka7e24c12009-10-30 11:49:00 +0000499 ScriptDataImpl* pre_data = input_pre_data;
Steve Block59151502010-09-22 15:07:15 +0100500 if (pre_data == NULL
Steve Block59151502010-09-22 15:07:15 +0100501 && source_length >= FLAG_min_preparse_length) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100502 if (source->IsExternalTwoByteString()) {
503 ExternalTwoByteStringUC16CharacterStream stream(
504 Handle<ExternalTwoByteString>::cast(source), 0, source->length());
505 pre_data = ParserApi::PartialPreParse(&stream, extension);
506 } else {
507 GenericStringUC16CharacterStream stream(source, 0, source->length());
508 pre_data = ParserApi::PartialPreParse(&stream, extension);
509 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000510 }
511
512 // Create a script object describing the script to be compiled.
513 Handle<Script> script = Factory::NewScript(source);
Andrei Popescu31002712010-02-23 13:46:05 +0000514 if (natives == NATIVES_CODE) {
515 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
516 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000517 if (!script_name.is_null()) {
518 script->set_name(*script_name);
519 script->set_line_offset(Smi::FromInt(line_offset));
520 script->set_column_offset(Smi::FromInt(column_offset));
521 }
522
Andrei Popescu402d9372010-02-26 13:31:12 +0000523 script->set_data(script_data.is_null() ? Heap::undefined_value()
524 : *script_data);
525
Steve Blocka7e24c12009-10-30 11:49:00 +0000526 // Compile the function and add it to the cache.
Ben Murdochf87a2032010-10-22 12:50:53 +0100527 CompilationInfo info(script);
528 info.MarkAsGlobal();
529 info.SetExtension(extension);
530 info.SetPreParseData(pre_data);
531 result = MakeFunctionInfo(&info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000532 if (extension == NULL && !result.is_null()) {
533 CompilationCache::PutScript(source, result);
534 }
535
536 // Get rid of the pre-parsing data (if necessary).
537 if (input_pre_data == NULL && pre_data != NULL) {
538 delete pre_data;
539 }
540 }
541
542 if (result.is_null()) Top::ReportPendingMessages();
543 return result;
544}
545
546
Steve Block6ded16b2010-05-10 14:33:55 +0100547Handle<SharedFunctionInfo> Compiler::CompileEval(Handle<String> source,
548 Handle<Context> context,
Steve Block1e0659c2011-05-24 12:43:12 +0100549 bool is_global,
550 StrictModeFlag strict_mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000551 int source_length = source->length();
552 Counters::total_eval_size.Increment(source_length);
553 Counters::total_compile_size.Increment(source_length);
554
555 // The VM is in the COMPILER state until exiting this function.
556 VMState state(COMPILER);
557
Ben Murdochf87a2032010-10-22 12:50:53 +0100558 // Do a lookup in the compilation cache; if the entry is not there, invoke
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800559 // the compiler and add the result to the cache.
Steve Block6ded16b2010-05-10 14:33:55 +0100560 Handle<SharedFunctionInfo> result;
Steve Block1e0659c2011-05-24 12:43:12 +0100561 result = CompilationCache::LookupEval(source,
562 context,
563 is_global,
564 strict_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000565
566 if (result.is_null()) {
567 // Create a script object describing the script to be compiled.
568 Handle<Script> script = Factory::NewScript(source);
Ben Murdochf87a2032010-10-22 12:50:53 +0100569 CompilationInfo info(script);
570 info.MarkAsEval();
571 if (is_global) info.MarkAsGlobal();
Steve Block1e0659c2011-05-24 12:43:12 +0100572 if (strict_mode == kStrictMode) info.MarkAsStrict();
Ben Murdochf87a2032010-10-22 12:50:53 +0100573 info.SetCallingContext(context);
574 result = MakeFunctionInfo(&info);
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800575 if (!result.is_null()) {
Steve Block1e0659c2011-05-24 12:43:12 +0100576 // If caller is strict mode, the result must be strict as well,
577 // but not the other way around. Consider:
578 // eval("'use strict'; ...");
579 ASSERT(strict_mode == kNonStrictMode || result->strict_mode());
Steve Blocka7e24c12009-10-30 11:49:00 +0000580 CompilationCache::PutEval(source, context, is_global, result);
581 }
582 }
583
584 return result;
585}
586
587
Leon Clarke4515c472010-02-03 11:58:03 +0000588bool Compiler::CompileLazy(CompilationInfo* info) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000589 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
590
591 // The VM is in the COMPILER state until exiting this function.
592 VMState state(COMPILER);
593
594 PostponeInterruptsScope postpone;
595
Leon Clarke4515c472010-02-03 11:58:03 +0000596 Handle<SharedFunctionInfo> shared = info->shared_info();
Ben Murdochf87a2032010-10-22 12:50:53 +0100597 int compiled_size = shared->end_position() - shared->start_position();
598 Counters::total_compile_size.Increment(compiled_size);
Steve Blocka7e24c12009-10-30 11:49:00 +0000599
Ben Murdochf87a2032010-10-22 12:50:53 +0100600 // Generate the AST for the lazily compiled function.
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800601 if (ParserApi::Parse(info)) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100602 // Measure how long it takes to do the lazy compilation; only take the
603 // rest of the function into account to avoid overlap with the lazy
604 // parsing statistics.
605 HistogramTimerScope timer(&Counters::compile_lazy);
Steve Blocka7e24c12009-10-30 11:49:00 +0000606
Ben Murdochf87a2032010-10-22 12:50:53 +0100607 // Compile the code.
608 if (!MakeCode(info)) {
Steve Block1e0659c2011-05-24 12:43:12 +0100609 if (!Top::has_pending_exception()) {
610 Top::StackOverflow();
611 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100612 } else {
613 ASSERT(!info->code().is_null());
Ben Murdochb0fe1622011-05-05 13:52:32 +0100614 Handle<Code> code = info->code();
615 Handle<JSFunction> function = info->closure();
Ben Murdochf87a2032010-10-22 12:50:53 +0100616 RecordFunctionCompilation(Logger::LAZY_COMPILE_TAG,
617 Handle<String>(shared->DebugName()),
618 shared->start_position(),
619 info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000620
Ben Murdochb0fe1622011-05-05 13:52:32 +0100621 if (info->IsOptimizing()) {
622 function->ReplaceCode(*code);
623 } else {
624 // Update the shared function info with the compiled code and the
625 // scope info. Please note, that the order of the shared function
626 // info initialization is important since set_scope_info might
627 // trigger a GC, causing the ASSERT below to be invalid if the code
628 // was flushed. By settting the code object last we avoid this.
629 Handle<SerializedScopeInfo> scope_info =
630 SerializedScopeInfo::Create(info->scope());
631 shared->set_scope_info(*scope_info);
632 shared->set_code(*code);
633 if (!function.is_null()) {
634 function->ReplaceCode(*code);
635 ASSERT(!function->IsOptimized());
636 }
637
638 // Set the expected number of properties for instances.
639 FunctionLiteral* lit = info->function();
640 int expected = lit->expected_property_count();
641 SetExpectedNofPropertiesFromEstimate(shared, expected);
642
643 // Set the optimization hints after performing lazy compilation, as
644 // these are not set when the function is set up as a lazily
645 // compiled function.
646 shared->SetThisPropertyAssignmentsInfo(
647 lit->has_only_simple_this_property_assignments(),
648 *lit->this_property_assignments());
649
650 // Check the function has compiled code.
651 ASSERT(shared->is_compiled());
652 shared->set_code_age(0);
653
654 if (V8::UseCrankshaft() && info->AllowOptimize()) {
655 // If we're asked to always optimize, we compile the optimized
656 // version of the function right away - unless the debugger is
657 // active as it makes no sense to compile optimized code then.
658 if (FLAG_always_opt && !Debug::has_break_points()) {
659 CompilationInfo optimized(function);
660 optimized.SetOptimizing(AstNode::kNoNumber);
661 return CompileLazy(&optimized);
662 } else if (CompilationCache::ShouldOptimizeEagerly(function)) {
663 RuntimeProfiler::OptimizeSoon(*function);
664 }
665 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100666 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000667
Ben Murdochf87a2032010-10-22 12:50:53 +0100668 return true;
669 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000670 }
671
Ben Murdochf87a2032010-10-22 12:50:53 +0100672 ASSERT(info->code().is_null());
673 return false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000674}
675
676
Steve Block6ded16b2010-05-10 14:33:55 +0100677Handle<SharedFunctionInfo> Compiler::BuildFunctionInfo(FunctionLiteral* literal,
Ben Murdochf87a2032010-10-22 12:50:53 +0100678 Handle<Script> script) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100679 // Precondition: code has been parsed and scopes have been analyzed.
680 CompilationInfo info(script);
681 info.SetFunction(literal);
682 info.SetScope(literal->scope());
683
684 LiveEditFunctionTracker live_edit_tracker(literal);
685 // Determine if the function can be lazily compiled. This is necessary to
686 // allow some of our builtin JS files to be lazily compiled. These
687 // builtins cannot be handled lazily by the parser, since we have to know
688 // if a function uses the special natives syntax, which is something the
689 // parser records.
Andrei Popescu402d9372010-02-26 13:31:12 +0000690 bool allow_lazy = literal->AllowsLazyCompilation() &&
691 !LiveEditFunctionTracker::IsActive();
Steve Blockd0582a62009-12-15 09:54:21 +0000692
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100693 Handle<SerializedScopeInfo> scope_info(SerializedScopeInfo::Empty());
694
Steve Blockd0582a62009-12-15 09:54:21 +0000695 // Generate code
Steve Blockd0582a62009-12-15 09:54:21 +0000696 if (FLAG_lazy && allow_lazy) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100697 Handle<Code> code(Builtins::builtin(Builtins::LazyCompile));
698 info.SetCode(code);
Steve Blockd0582a62009-12-15 09:54:21 +0000699 } else {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100700 if (V8::UseCrankshaft()) {
701 if (!MakeCrankshaftCode(&info)) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100702 return Handle<SharedFunctionInfo>::null();
703 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100704 } else {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100705 // The bodies of function literals have not yet been visited by the
706 // AST optimizer/analyzer.
707 if (!Rewriter::Analyze(&info)) return Handle<SharedFunctionInfo>::null();
708
709 bool is_run_once = literal->try_full_codegen();
710 bool can_use_full = FLAG_full_compiler && !literal->contains_loops();
711
712 if (AlwaysFullCompiler() || (is_run_once && can_use_full)) {
713 if (!FullCodeGenerator::MakeCode(&info)) {
714 return Handle<SharedFunctionInfo>::null();
715 }
716 } else {
717 // We fall back to the classic V8 code generator.
718 if (!AssignedVariablesAnalyzer::Analyze(&info) ||
719 !CodeGenerator::MakeCode(&info)) {
720 return Handle<SharedFunctionInfo>::null();
721 }
Ben Murdochf87a2032010-10-22 12:50:53 +0100722 }
Steve Blockd0582a62009-12-15 09:54:21 +0000723 }
Ben Murdochb0fe1622011-05-05 13:52:32 +0100724 ASSERT(!info.code().is_null());
Steve Blockd0582a62009-12-15 09:54:21 +0000725
726 // Function compilation complete.
Steve Block6ded16b2010-05-10 14:33:55 +0100727 RecordFunctionCompilation(Logger::FUNCTION_TAG,
Ben Murdochf87a2032010-10-22 12:50:53 +0100728 literal->debug_name(),
Steve Block6ded16b2010-05-10 14:33:55 +0100729 literal->start_position(),
Ben Murdochf87a2032010-10-22 12:50:53 +0100730 &info);
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100731 scope_info = SerializedScopeInfo::Create(info.scope());
Steve Blockd0582a62009-12-15 09:54:21 +0000732 }
733
Steve Block6ded16b2010-05-10 14:33:55 +0100734 // Create a shared function info object.
735 Handle<SharedFunctionInfo> result =
736 Factory::NewSharedFunctionInfo(literal->name(),
737 literal->materialized_literal_count(),
Ben Murdochf87a2032010-10-22 12:50:53 +0100738 info.code(),
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100739 scope_info);
Steve Block6ded16b2010-05-10 14:33:55 +0100740 SetFunctionInfo(result, literal, false, script);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100741 result->set_allows_lazy_compilation(allow_lazy);
Steve Blockd0582a62009-12-15 09:54:21 +0000742
743 // Set the expected number of properties for instances and return
744 // the resulting function.
Steve Block6ded16b2010-05-10 14:33:55 +0100745 SetExpectedNofPropertiesFromEstimate(result,
Steve Blockd0582a62009-12-15 09:54:21 +0000746 literal->expected_property_count());
Steve Block6ded16b2010-05-10 14:33:55 +0100747 live_edit_tracker.RecordFunctionInfo(result, literal);
748 return result;
Steve Blockd0582a62009-12-15 09:54:21 +0000749}
750
751
752// Sets the function info on a function.
753// The start_position points to the first '(' character after the function name
754// in the full script source. When counting characters in the script source the
755// the first character is number 0 (not 1).
Steve Block6ded16b2010-05-10 14:33:55 +0100756void Compiler::SetFunctionInfo(Handle<SharedFunctionInfo> function_info,
Steve Blockd0582a62009-12-15 09:54:21 +0000757 FunctionLiteral* lit,
758 bool is_toplevel,
759 Handle<Script> script) {
Steve Block6ded16b2010-05-10 14:33:55 +0100760 function_info->set_length(lit->num_parameters());
761 function_info->set_formal_parameter_count(lit->num_parameters());
762 function_info->set_script(*script);
763 function_info->set_function_token_position(lit->function_token_position());
764 function_info->set_start_position(lit->start_position());
765 function_info->set_end_position(lit->end_position());
766 function_info->set_is_expression(lit->is_expression());
767 function_info->set_is_toplevel(is_toplevel);
768 function_info->set_inferred_name(*lit->inferred_name());
769 function_info->SetThisPropertyAssignmentsInfo(
Steve Blockd0582a62009-12-15 09:54:21 +0000770 lit->has_only_simple_this_property_assignments(),
771 *lit->this_property_assignments());
Steve Block6ded16b2010-05-10 14:33:55 +0100772 function_info->set_try_full_codegen(lit->try_full_codegen());
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100773 function_info->set_allows_lazy_compilation(lit->AllowsLazyCompilation());
Steve Block1e0659c2011-05-24 12:43:12 +0100774 function_info->set_strict_mode(lit->strict_mode());
Steve Blockd0582a62009-12-15 09:54:21 +0000775}
776
777
Steve Block6ded16b2010-05-10 14:33:55 +0100778void Compiler::RecordFunctionCompilation(Logger::LogEventsAndTags tag,
779 Handle<String> name,
Steve Block6ded16b2010-05-10 14:33:55 +0100780 int start_position,
Ben Murdochf87a2032010-10-22 12:50:53 +0100781 CompilationInfo* info) {
782 // Log the code generation. If source information is available include
783 // script name and line number. Check explicitly whether logging is
784 // enabled as finding the line number is not free.
785 if (Logger::is_logging() ||
Ben Murdochf87a2032010-10-22 12:50:53 +0100786 CpuProfiler::is_profiling()) {
787 Handle<Script> script = info->script();
788 Handle<Code> code = info->code();
Andrei Popescu31002712010-02-23 13:46:05 +0000789 if (script->name()->IsString()) {
790 int line_num = GetScriptLineNumber(script, start_position) + 1;
Steve Block6ded16b2010-05-10 14:33:55 +0100791 USE(line_num);
792 PROFILE(CodeCreateEvent(Logger::ToNativeByScript(tag, *script),
Ben Murdochf87a2032010-10-22 12:50:53 +0100793 *code,
794 *name,
795 String::cast(script->name()),
796 line_num));
Andrei Popescu31002712010-02-23 13:46:05 +0000797 } else {
Steve Block6ded16b2010-05-10 14:33:55 +0100798 PROFILE(CodeCreateEvent(Logger::ToNativeByScript(tag, *script),
Ben Murdochf87a2032010-10-22 12:50:53 +0100799 *code,
800 *name));
Andrei Popescu31002712010-02-23 13:46:05 +0000801 }
802 }
Ben Murdochb8e0da22011-05-16 14:20:40 +0100803
804 GDBJIT(AddCode(name,
805 Handle<Script>(info->script()),
806 Handle<Code>(info->code())));
Andrei Popescu31002712010-02-23 13:46:05 +0000807}
Andrei Popescu31002712010-02-23 13:46:05 +0000808
Steve Blocka7e24c12009-10-30 11:49:00 +0000809} } // namespace v8::internal