blob: 48502cad148184e55ee975d416a998e9de75beb8 [file] [log] [blame]
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001// Copyright 2006-2008 Google Inc. All Rights Reserved.
2// 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
30#include "bootstrapper.h"
31#include "codegen-inl.h"
32#include "compiler.h"
33#include "debug.h"
34#include "scopes.h"
35#include "rewriter.h"
36#include "usage-analyzer.h"
37
38namespace v8 { namespace internal {
39
40DEFINE_bool(strict, false, "strict error checking");
41DEFINE_int(min_preparse_length, 1024,
42 "Minimum length for automatic enable preparsing");
43DECLARE_bool(debug_info);
44
45#ifdef DEBUG
46DEFINE_bool(print_builtin_scopes, false, "print scopes for builtins");
47DEFINE_bool(print_scopes, false, "print scopes");
48#endif
49
50
51// Helper class to keep track of compilation nesting and to do proper
52// cleanups of generated ASTs.
53class CompilationTracker BASE_EMBEDDED {
54 public:
55 CompilationTracker() {
56 ++nesting_;
57 }
58
59 ~CompilationTracker() {
60 // If we're leaving the top-level compilation, we must make sure
61 // to get rid of all generated ASTs.
62 if (--nesting_ == 0) Zone::DeleteAll();
63 }
64
65 private:
66 static int nesting_;
67};
68
69
70int CompilationTracker::nesting_ = 0;
71
72
73static Handle<Code> MakeCode(FunctionLiteral* literal,
74 Handle<Script> script,
75 bool is_eval) {
76 ASSERT(literal != NULL);
77
78 // Rewrite the AST by introducing .result assignments where needed.
79 if (!Rewriter::Process(literal) || !AnalyzeVariableUsage(literal)) {
kasper.lund212ac232008-07-16 07:07:30 +000080 // Signal a stack overflow by returning a null handle. The stack
81 // overflow exception will be thrown by the caller.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000082 return Handle<Code>::null();
83 }
84
85 // Compute top scope and allocate variables. For lazy compilation
86 // the top scope only contains the single lazily compiled function,
87 // so this doesn't re-allocate variables repeatedly.
88 Scope* top = literal->scope();
89 while (top->outer_scope() != NULL) top = top->outer_scope();
90 top->AllocateVariables();
91
92#ifdef DEBUG
93 if (Bootstrapper::IsActive() ?
94 FLAG_print_builtin_scopes :
95 FLAG_print_scopes) {
96 literal->scope()->Print();
97 }
98#endif
99
100 // Generate code and return it.
101 Handle<Code> result = CodeGenerator::MakeCode(literal, script, is_eval);
102 return result;
103}
104
105
106static Handle<JSFunction> MakeFunction(bool is_global,
107 bool is_eval,
108 Handle<Script> script,
109 v8::Extension* extension,
110 ScriptDataImpl* pre_data) {
111 CompilationTracker tracker;
112
113 // Make sure we have an initial stack limit.
114 StackGuard guard;
115 StackGuard::DisableInterrupts();
116
117 // Notify debugger
118 Debugger::OnBeforeCompile(script);
119
120 // Only allow non-global compiles for eval.
121 ASSERT(is_eval || is_global);
122
123 // Build AST.
124 FunctionLiteral* lit = MakeAST(is_global, script, extension, pre_data);
125
kasper.lund212ac232008-07-16 07:07:30 +0000126 // Check for parse errors.
127 if (lit == NULL) {
128 ASSERT(Top::has_pending_exception());
129 StackGuard::EnableInterrupts();
130 return Handle<JSFunction>::null();
131 }
132
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000133 // Measure how long it takes to do the compilation; only take the
134 // rest of the function into account to avoid overlap with the
135 // parsing statistics.
136 StatsRate* rate = is_eval
137 ? &Counters::compile_eval
138 : &Counters::compile;
139 StatsRateScope timer(rate);
140
141 // Compile the code.
kasper.lund212ac232008-07-16 07:07:30 +0000142 Handle<Code> code = MakeCode(lit, script, is_eval);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000143
kasper.lund212ac232008-07-16 07:07:30 +0000144 // Check for stack-overflow exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000145 if (code.is_null()) {
kasper.lund212ac232008-07-16 07:07:30 +0000146 Top::StackOverflow();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000147 StackGuard::EnableInterrupts();
148 return Handle<JSFunction>::null();
149 }
150
151 if (script->name()->IsString()) {
152 SmartPointer<char> data =
153 String::cast(script->name())->ToCString(DISALLOW_NULLS);
154 LOG(CodeCreateEvent(is_eval ? "Eval" : "Script", *code, *data));
155 } else {
156 LOG(CodeCreateEvent(is_eval ? "Eval" : "Script", *code, ""));
157 }
158
159 // Allocate function.
160 Handle<JSFunction> fun =
161 Factory::NewFunctionBoilerplate(lit->name(),
162 lit->materialized_literal_count(),
163 code);
164
165 CodeGenerator::SetFunctionInfo(fun, lit->scope()->num_parameters(),
166 kNoPosition,
167 lit->start_position(), lit->end_position(),
168 lit->is_expression(), true, script);
169
170 // Hint to the runtime system used when allocating space for initial
171 // property space by setting the expected number of properties for
172 // the instances of the function.
173 SetExpectedNofPropertiesFromEstimate(fun, lit->expected_property_count());
174
175 StackGuard::EnableInterrupts();
176
177 // Notify debugger
178 Debugger::OnAfterCompile(script, fun);
179
180 return fun;
181}
182
183
184static StaticResource<SafeStringInputBuffer> safe_string_input_buffer;
185
186
187Handle<JSFunction> Compiler::Compile(Handle<String> source,
188 Handle<String> script_name,
189 int line_offset, int column_offset,
190 v8::Extension* extension,
191 ScriptDataImpl* input_pre_data) {
192 Counters::total_load_size.Increment(source->length());
193 Counters::total_compile_size.Increment(source->length());
194
195 // The VM is in the COMPILER state until exiting this function.
196 VMState state(COMPILER);
197
198 ScriptDataImpl* pre_data = input_pre_data;
199 if (pre_data == NULL && source->length() >= FLAG_min_preparse_length) {
200 Access<SafeStringInputBuffer> buf(&safe_string_input_buffer);
201 buf->Reset(source.location());
202 pre_data = PreParse(buf.value(), extension);
203 }
204
205 // Create a script object describing the script to be compiled.
206 Handle<Script> script = Factory::NewScript(source);
207 if (!script_name.is_null()) {
208 script->set_name(*script_name);
209 script->set_line_offset(Smi::FromInt(line_offset));
210 script->set_column_offset(Smi::FromInt(column_offset));
211 }
212
213 Handle<JSFunction> result =
214 MakeFunction(true, false, script, extension, pre_data);
215
216 if (input_pre_data == NULL && pre_data != NULL)
217 delete pre_data;
218
219 return result;
220}
221
222
223Handle<JSFunction> Compiler::CompileEval(bool is_global,
224 Handle<String> source) {
225 Counters::total_eval_size.Increment(source->length());
226 Counters::total_compile_size.Increment(source->length());
227
228 // The VM is in the COMPILER state until exiting this function.
229 VMState state(COMPILER);
230
231 // Create a script object describing the script to be compiled.
232 Handle<Script> script = Factory::NewScript(source);
233 return MakeFunction(is_global, true, script, NULL, NULL);
234}
235
236
237bool Compiler::CompileLazy(Handle<SharedFunctionInfo> shared) {
238 CompilationTracker tracker;
239
240 // The VM is in the COMPILER state until exiting this function.
241 VMState state(COMPILER);
242
243 // Make sure we have an initial stack limit.
244 StackGuard guard;
245 StackGuard::DisableInterrupts();
246
247 // Compute name, source code and script data.
248 Handle<String> name(String::cast(shared->name()));
249 Handle<Script> script(Script::cast(shared->script()));
250
251 int start_position = shared->start_position();
252 int end_position = shared->end_position();
253 bool is_expression = shared->is_expression();
254 Counters::total_compile_size.Increment(end_position - start_position);
255
256 // Generate the AST for the lazily compiled function. The AST may be
257 // NULL in case of parser stack overflow.
258 FunctionLiteral* lit = MakeLazyAST(script, name,
259 start_position,
260 end_position,
261 is_expression);
262
kasper.lund212ac232008-07-16 07:07:30 +0000263 // Check for parse errors.
264 if (lit == NULL) {
265 ASSERT(Top::has_pending_exception());
266 StackGuard::EnableInterrupts();
267 return false;
268 }
269
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000270 // Measure how long it takes to do the lazy compilation; only take
271 // the rest of the function into account to avoid overlap with the
272 // lazy parsing statistics.
273 StatsRateScope timer(&Counters::compile_lazy);
274
kasper.lund212ac232008-07-16 07:07:30 +0000275 // Compile the code.
276 Handle<Code> code = MakeCode(lit, script, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000277
kasper.lund212ac232008-07-16 07:07:30 +0000278 // Check for stack-overflow exception.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000279 if (code.is_null()) {
kasper.lund212ac232008-07-16 07:07:30 +0000280 Top::StackOverflow();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000281 StackGuard::EnableInterrupts();
282 return false;
283 }
284
285 // Generate the code, update the function info, and return the code.
286 LOG(CodeCreateEvent("LazyCompile", *code, *lit->name()));
287
288 // Update the shared function info with the compiled code.
289 shared->set_code(*code);
290
291 // Set the expected number of properties for instances.
292 SetExpectedNofPropertiesFromEstimate(shared, lit->expected_property_count());
293
294 // Check the function has compiled code.
295 ASSERT(shared->is_compiled());
296 StackGuard::EnableInterrupts();
297 return true;
298}
299
300
301} } // namespace v8::internal