1 // Copyright 2009 the V8 project authors. 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
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.
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.
30 #include "bootstrapper.h"
32 #include "codegen-inl.h"
33 #include "compilation-cache.h"
36 #include "oprofile-agent.h"
39 #include "usage-analyzer.h"
44 static Handle<Code> MakeCode(FunctionLiteral* literal,
45 Handle<Script> script,
46 Handle<Context> context,
48 ASSERT(literal != NULL);
50 // Rewrite the AST by introducing .result assignments where needed.
51 if (!Rewriter::Process(literal) || !AnalyzeVariableUsage(literal)) {
52 // Signal a stack overflow by returning a null handle. The stack
53 // overflow exception will be thrown by the caller.
54 return Handle<Code>::null();
58 // Compute top scope and allocate variables. For lazy compilation
59 // the top scope only contains the single lazily compiled function,
60 // so this doesn't re-allocate variables repeatedly.
61 HistogramTimerScope timer(&Counters::variable_allocation);
62 Scope* top = literal->scope();
63 while (top->outer_scope() != NULL) top = top->outer_scope();
64 top->AllocateVariables(context);
68 if (Bootstrapper::IsActive() ?
69 FLAG_print_builtin_scopes :
71 literal->scope()->Print();
76 if (!Rewriter::Optimize(literal)) {
77 // Signal a stack overflow by returning a null handle. The stack
78 // overflow exception will be thrown by the caller.
79 return Handle<Code>::null();
83 CfgGlobals scope(literal);
84 Cfg* cfg = Cfg::Build();
86 if (FLAG_print_cfg && cfg != NULL) {
87 SmartPointer<char> name = literal->name()->ToCString();
88 PrintF("Function \"%s\":\n", *name);
94 return cfg->Compile(script);
98 // Generate code and return it.
99 Handle<Code> result = CodeGenerator::MakeCode(literal, script, is_eval);
104 static bool IsValidJSON(FunctionLiteral* lit) {
105 if (lit->body()->length() != 1)
107 Statement* stmt = lit->body()->at(0);
108 if (stmt->AsExpressionStatement() == NULL)
110 Expression* expr = stmt->AsExpressionStatement()->expression();
111 return expr->IsValidJSON();
115 static Handle<JSFunction> MakeFunction(bool is_global,
117 Compiler::ValidationState validate,
118 Handle<Script> script,
119 Handle<Context> context,
120 v8::Extension* extension,
121 ScriptDataImpl* pre_data) {
122 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
124 // Make sure we have an initial stack limit.
126 PostponeInterruptsScope postpone;
128 ASSERT(!i::Top::global_context().is_null());
129 script->set_context_data((*i::Top::global_context())->data());
131 #ifdef ENABLE_DEBUGGER_SUPPORT
132 bool is_json = (validate == Compiler::VALIDATE_JSON);
133 if (is_eval || is_json) {
134 script->set_compilation_type(
135 is_json ? Smi::FromInt(Script::COMPILATION_TYPE_JSON) :
136 Smi::FromInt(Script::COMPILATION_TYPE_EVAL));
137 // For eval scripts add information on the function from which eval was
140 JavaScriptFrameIterator it;
141 script->set_eval_from_function(it.frame()->function());
142 int offset = it.frame()->pc() - it.frame()->code()->instruction_start();
143 script->set_eval_from_instructions_offset(Smi::FromInt(offset));
148 Debugger::OnBeforeCompile(script);
151 // Only allow non-global compiles for eval.
152 ASSERT(is_eval || is_global);
155 FunctionLiteral* lit = MakeAST(is_global, script, extension, pre_data);
157 // Check for parse errors.
159 ASSERT(Top::has_pending_exception());
160 return Handle<JSFunction>::null();
163 // When parsing JSON we do an ordinary parse and then afterwards
164 // check the AST to ensure it was well-formed. If not we give a
166 if (validate == Compiler::VALIDATE_JSON && !IsValidJSON(lit)) {
168 Handle<JSArray> args = Factory::NewJSArray(1);
169 Handle<Object> source(script->source());
170 SetElement(args, 0, source);
171 Handle<Object> result = Factory::NewSyntaxError("invalid_json", args);
172 Top::Throw(*result, NULL);
173 return Handle<JSFunction>::null();
176 // Measure how long it takes to do the compilation; only take the
177 // rest of the function into account to avoid overlap with the
178 // parsing statistics.
179 HistogramTimer* rate = is_eval
180 ? &Counters::compile_eval
181 : &Counters::compile;
182 HistogramTimerScope timer(rate);
185 Handle<Code> code = MakeCode(lit, script, context, is_eval);
187 // Check for stack-overflow exceptions.
188 if (code.is_null()) {
189 Top::StackOverflow();
190 return Handle<JSFunction>::null();
193 #if defined ENABLE_LOGGING_AND_PROFILING || defined ENABLE_OPROFILE_AGENT
194 // Log the code generation for the script. Check explicit whether logging is
195 // to avoid allocating when not required.
196 if (Logger::is_logging() || OProfileAgent::is_enabled()) {
197 if (script->name()->IsString()) {
198 SmartPointer<char> data =
199 String::cast(script->name())->ToCString(DISALLOW_NULLS);
200 LOG(CodeCreateEvent(is_eval ? Logger::EVAL_TAG : Logger::SCRIPT_TAG,
202 OProfileAgent::CreateNativeCodeRegion(*data,
203 code->instruction_start(),
204 code->instruction_size());
206 LOG(CodeCreateEvent(is_eval ? Logger::EVAL_TAG : Logger::SCRIPT_TAG,
208 OProfileAgent::CreateNativeCodeRegion(is_eval ? "Eval" : "Script",
209 code->instruction_start(),
210 code->instruction_size());
215 // Allocate function.
216 Handle<JSFunction> fun =
217 Factory::NewFunctionBoilerplate(lit->name(),
218 lit->materialized_literal_count(),
219 lit->contains_array_literal(),
222 CodeGenerator::SetFunctionInfo(fun, lit->scope()->num_parameters(),
223 RelocInfo::kNoPosition,
224 lit->start_position(), lit->end_position(),
225 lit->is_expression(), true, script,
226 lit->inferred_name());
228 // Hint to the runtime system used when allocating space for initial
229 // property space by setting the expected number of properties for
230 // the instances of the function.
231 SetExpectedNofPropertiesFromEstimate(fun, lit->expected_property_count());
233 #ifdef ENABLE_DEBUGGER_SUPPORT
235 Debugger::OnAfterCompile(script, fun);
242 static StaticResource<SafeStringInputBuffer> safe_string_input_buffer;
245 Handle<JSFunction> Compiler::Compile(Handle<String> source,
246 Handle<Object> script_name,
247 int line_offset, int column_offset,
248 v8::Extension* extension,
249 ScriptDataImpl* input_pre_data) {
250 int source_length = source->length();
251 Counters::total_load_size.Increment(source_length);
252 Counters::total_compile_size.Increment(source_length);
254 // The VM is in the COMPILER state until exiting this function.
255 VMState state(COMPILER);
257 // Do a lookup in the compilation cache but not for extensions.
258 Handle<JSFunction> result;
259 if (extension == NULL) {
260 result = CompilationCache::LookupScript(source,
266 if (result.is_null()) {
267 // No cache entry found. Do pre-parsing and compile the script.
268 ScriptDataImpl* pre_data = input_pre_data;
269 if (pre_data == NULL && source_length >= FLAG_min_preparse_length) {
270 Access<SafeStringInputBuffer> buf(&safe_string_input_buffer);
271 buf->Reset(source.location());
272 pre_data = PreParse(buf.value(), extension);
275 // Create a script object describing the script to be compiled.
276 Handle<Script> script = Factory::NewScript(source);
277 if (!script_name.is_null()) {
278 script->set_name(*script_name);
279 script->set_line_offset(Smi::FromInt(line_offset));
280 script->set_column_offset(Smi::FromInt(column_offset));
283 // Compile the function and add it to the cache.
284 result = MakeFunction(true,
288 Handle<Context>::null(),
291 if (extension == NULL && !result.is_null()) {
292 CompilationCache::PutScript(source, result);
295 // Get rid of the pre-parsing data (if necessary).
296 if (input_pre_data == NULL && pre_data != NULL) {
301 if (result.is_null()) Top::ReportPendingMessages();
306 Handle<JSFunction> Compiler::CompileEval(Handle<String> source,
307 Handle<Context> context,
309 ValidationState validate) {
310 // Note that if validation is required then no path through this
311 // function is allowed to return a value without validating that
312 // the input is legal json.
314 int source_length = source->length();
315 Counters::total_eval_size.Increment(source_length);
316 Counters::total_compile_size.Increment(source_length);
318 // The VM is in the COMPILER state until exiting this function.
319 VMState state(COMPILER);
321 // Do a lookup in the compilation cache; if the entry is not there,
322 // invoke the compiler and add the result to the cache. If we're
323 // evaluating json we bypass the cache since we can't be sure a
324 // potential value in the cache has been validated.
325 Handle<JSFunction> result;
326 if (validate == DONT_VALIDATE_JSON)
327 result = CompilationCache::LookupEval(source, context, is_global);
329 if (result.is_null()) {
330 // Create a script object describing the script to be compiled.
331 Handle<Script> script = Factory::NewScript(source);
332 result = MakeFunction(is_global,
339 if (!result.is_null() && validate != VALIDATE_JSON) {
340 // For json it's unlikely that we'll ever see exactly the same
341 // string again so we don't use the compilation cache.
342 CompilationCache::PutEval(source, context, is_global, result);
350 bool Compiler::CompileLazy(Handle<SharedFunctionInfo> shared,
352 CompilationZoneScope zone_scope(DELETE_ON_EXIT);
354 // The VM is in the COMPILER state until exiting this function.
355 VMState state(COMPILER);
357 // Make sure we have an initial stack limit.
359 PostponeInterruptsScope postpone;
361 // Compute name, source code and script data.
362 Handle<String> name(String::cast(shared->name()));
363 Handle<Script> script(Script::cast(shared->script()));
365 int start_position = shared->start_position();
366 int end_position = shared->end_position();
367 bool is_expression = shared->is_expression();
368 Counters::total_compile_size.Increment(end_position - start_position);
370 // Generate the AST for the lazily compiled function. The AST may be
371 // NULL in case of parser stack overflow.
372 FunctionLiteral* lit = MakeLazyAST(script, name,
377 // Check for parse errors.
379 ASSERT(Top::has_pending_exception());
383 // Update the loop nesting in the function literal.
384 lit->set_loop_nesting(loop_nesting);
386 // Measure how long it takes to do the lazy compilation; only take
387 // the rest of the function into account to avoid overlap with the
388 // lazy parsing statistics.
389 HistogramTimerScope timer(&Counters::compile_lazy);
392 Handle<Code> code = MakeCode(lit, script, Handle<Context>::null(), false);
394 // Check for stack-overflow exception.
395 if (code.is_null()) {
396 Top::StackOverflow();
400 #if defined ENABLE_LOGGING_AND_PROFILING || defined ENABLE_OPROFILE_AGENT
401 // Log the code generation. If source information is available include script
402 // name and line number. Check explicit whether logging is enabled as finding
403 // the line number is not for free.
404 if (Logger::is_logging() || OProfileAgent::is_enabled()) {
405 Handle<String> func_name(name->length() > 0 ?
406 *name : shared->inferred_name());
407 if (script->name()->IsString()) {
408 int line_num = GetScriptLineNumber(script, start_position) + 1;
409 LOG(CodeCreateEvent(Logger::LAZY_COMPILE_TAG, *code, *func_name,
410 String::cast(script->name()), line_num));
411 OProfileAgent::CreateNativeCodeRegion(*func_name,
412 String::cast(script->name()),
414 code->instruction_start(),
415 code->instruction_size());
417 LOG(CodeCreateEvent(Logger::LAZY_COMPILE_TAG, *code, *func_name));
418 OProfileAgent::CreateNativeCodeRegion(*func_name,
419 code->instruction_start(),
420 code->instruction_size());
425 // Update the shared function info with the compiled code.
426 shared->set_code(*code);
428 // Set the expected number of properties for instances.
429 SetExpectedNofPropertiesFromEstimate(shared, lit->expected_property_count());
431 // Check the function has compiled code.
432 ASSERT(shared->is_compiled());
437 } } // namespace v8::internal