Steve Block | a7e24c1 | 2009-10-30 11:49:00 +0000 | [diff] [blame^] | 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 |
| 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 "compilation-cache.h" |
| 33 | #include "compiler.h" |
| 34 | #include "debug.h" |
| 35 | #include "oprofile-agent.h" |
| 36 | #include "rewriter.h" |
| 37 | #include "scopes.h" |
| 38 | #include "usage-analyzer.h" |
| 39 | |
| 40 | namespace v8 { |
| 41 | namespace internal { |
| 42 | |
| 43 | static Handle<Code> MakeCode(FunctionLiteral* literal, |
| 44 | Handle<Script> script, |
| 45 | Handle<Context> context, |
| 46 | bool is_eval) { |
| 47 | ASSERT(literal != NULL); |
| 48 | |
| 49 | // Rewrite the AST by introducing .result assignments where needed. |
| 50 | if (!Rewriter::Process(literal) || !AnalyzeVariableUsage(literal)) { |
| 51 | // Signal a stack overflow by returning a null handle. The stack |
| 52 | // overflow exception will be thrown by the caller. |
| 53 | return Handle<Code>::null(); |
| 54 | } |
| 55 | |
| 56 | { |
| 57 | // Compute top scope and allocate variables. For lazy compilation |
| 58 | // the top scope only contains the single lazily compiled function, |
| 59 | // so this doesn't re-allocate variables repeatedly. |
| 60 | HistogramTimerScope timer(&Counters::variable_allocation); |
| 61 | Scope* top = literal->scope(); |
| 62 | while (top->outer_scope() != NULL) top = top->outer_scope(); |
| 63 | top->AllocateVariables(context); |
| 64 | } |
| 65 | |
| 66 | #ifdef DEBUG |
| 67 | if (Bootstrapper::IsActive() ? |
| 68 | FLAG_print_builtin_scopes : |
| 69 | FLAG_print_scopes) { |
| 70 | literal->scope()->Print(); |
| 71 | } |
| 72 | #endif |
| 73 | |
| 74 | // Optimize the AST. |
| 75 | if (!Rewriter::Optimize(literal)) { |
| 76 | // Signal a stack overflow by returning a null handle. The stack |
| 77 | // overflow exception will be thrown by the caller. |
| 78 | return Handle<Code>::null(); |
| 79 | } |
| 80 | |
| 81 | // Generate code and return it. |
| 82 | Handle<Code> result = CodeGenerator::MakeCode(literal, script, is_eval); |
| 83 | return result; |
| 84 | } |
| 85 | |
| 86 | |
| 87 | static bool IsValidJSON(FunctionLiteral* lit) { |
| 88 | if (lit->body()->length() != 1) |
| 89 | return false; |
| 90 | Statement* stmt = lit->body()->at(0); |
| 91 | if (stmt->AsExpressionStatement() == NULL) |
| 92 | return false; |
| 93 | Expression* expr = stmt->AsExpressionStatement()->expression(); |
| 94 | return expr->IsValidJSON(); |
| 95 | } |
| 96 | |
| 97 | |
| 98 | static Handle<JSFunction> MakeFunction(bool is_global, |
| 99 | bool is_eval, |
| 100 | Compiler::ValidationState validate, |
| 101 | Handle<Script> script, |
| 102 | Handle<Context> context, |
| 103 | v8::Extension* extension, |
| 104 | ScriptDataImpl* pre_data) { |
| 105 | CompilationZoneScope zone_scope(DELETE_ON_EXIT); |
| 106 | |
| 107 | PostponeInterruptsScope postpone; |
| 108 | |
| 109 | ASSERT(!i::Top::global_context().is_null()); |
| 110 | script->set_context_data((*i::Top::global_context())->data()); |
| 111 | |
| 112 | #ifdef ENABLE_DEBUGGER_SUPPORT |
| 113 | bool is_json = (validate == Compiler::VALIDATE_JSON); |
| 114 | if (is_eval || is_json) { |
| 115 | script->set_compilation_type( |
| 116 | is_json ? Smi::FromInt(Script::COMPILATION_TYPE_JSON) : |
| 117 | Smi::FromInt(Script::COMPILATION_TYPE_EVAL)); |
| 118 | // For eval scripts add information on the function from which eval was |
| 119 | // called. |
| 120 | if (is_eval) { |
| 121 | JavaScriptFrameIterator it; |
| 122 | script->set_eval_from_function(it.frame()->function()); |
| 123 | int offset = it.frame()->pc() - it.frame()->code()->instruction_start(); |
| 124 | script->set_eval_from_instructions_offset(Smi::FromInt(offset)); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | // Notify debugger |
| 129 | Debugger::OnBeforeCompile(script); |
| 130 | #endif |
| 131 | |
| 132 | // Only allow non-global compiles for eval. |
| 133 | ASSERT(is_eval || is_global); |
| 134 | |
| 135 | // Build AST. |
| 136 | FunctionLiteral* lit = MakeAST(is_global, script, extension, pre_data); |
| 137 | |
| 138 | // Check for parse errors. |
| 139 | if (lit == NULL) { |
| 140 | ASSERT(Top::has_pending_exception()); |
| 141 | return Handle<JSFunction>::null(); |
| 142 | } |
| 143 | |
| 144 | // When parsing JSON we do an ordinary parse and then afterwards |
| 145 | // check the AST to ensure it was well-formed. If not we give a |
| 146 | // syntax error. |
| 147 | if (validate == Compiler::VALIDATE_JSON && !IsValidJSON(lit)) { |
| 148 | HandleScope scope; |
| 149 | Handle<JSArray> args = Factory::NewJSArray(1); |
| 150 | Handle<Object> source(script->source()); |
| 151 | SetElement(args, 0, source); |
| 152 | Handle<Object> result = Factory::NewSyntaxError("invalid_json", args); |
| 153 | Top::Throw(*result, NULL); |
| 154 | return Handle<JSFunction>::null(); |
| 155 | } |
| 156 | |
| 157 | // Measure how long it takes to do the compilation; only take the |
| 158 | // rest of the function into account to avoid overlap with the |
| 159 | // parsing statistics. |
| 160 | HistogramTimer* rate = is_eval |
| 161 | ? &Counters::compile_eval |
| 162 | : &Counters::compile; |
| 163 | HistogramTimerScope timer(rate); |
| 164 | |
| 165 | // Compile the code. |
| 166 | Handle<Code> code = MakeCode(lit, script, context, is_eval); |
| 167 | |
| 168 | // Check for stack-overflow exceptions. |
| 169 | if (code.is_null()) { |
| 170 | Top::StackOverflow(); |
| 171 | return Handle<JSFunction>::null(); |
| 172 | } |
| 173 | |
| 174 | #if defined ENABLE_LOGGING_AND_PROFILING || defined ENABLE_OPROFILE_AGENT |
| 175 | // Log the code generation for the script. Check explicit whether logging is |
| 176 | // to avoid allocating when not required. |
| 177 | if (Logger::is_logging() || OProfileAgent::is_enabled()) { |
| 178 | if (script->name()->IsString()) { |
| 179 | SmartPointer<char> data = |
| 180 | String::cast(script->name())->ToCString(DISALLOW_NULLS); |
| 181 | LOG(CodeCreateEvent(is_eval ? Logger::EVAL_TAG : Logger::SCRIPT_TAG, |
| 182 | *code, *data)); |
| 183 | OProfileAgent::CreateNativeCodeRegion(*data, |
| 184 | code->instruction_start(), |
| 185 | code->instruction_size()); |
| 186 | } else { |
| 187 | LOG(CodeCreateEvent(is_eval ? Logger::EVAL_TAG : Logger::SCRIPT_TAG, |
| 188 | *code, "")); |
| 189 | OProfileAgent::CreateNativeCodeRegion(is_eval ? "Eval" : "Script", |
| 190 | code->instruction_start(), |
| 191 | code->instruction_size()); |
| 192 | } |
| 193 | } |
| 194 | #endif |
| 195 | |
| 196 | // Allocate function. |
| 197 | Handle<JSFunction> fun = |
| 198 | Factory::NewFunctionBoilerplate(lit->name(), |
| 199 | lit->materialized_literal_count(), |
| 200 | lit->contains_array_literal(), |
| 201 | code); |
| 202 | |
| 203 | ASSERT_EQ(RelocInfo::kNoPosition, lit->function_token_position()); |
| 204 | CodeGenerator::SetFunctionInfo(fun, lit, true, script); |
| 205 | |
| 206 | // Hint to the runtime system used when allocating space for initial |
| 207 | // property space by setting the expected number of properties for |
| 208 | // the instances of the function. |
| 209 | SetExpectedNofPropertiesFromEstimate(fun, lit->expected_property_count()); |
| 210 | |
| 211 | #ifdef ENABLE_DEBUGGER_SUPPORT |
| 212 | // Notify debugger |
| 213 | Debugger::OnAfterCompile(script, fun); |
| 214 | #endif |
| 215 | |
| 216 | return fun; |
| 217 | } |
| 218 | |
| 219 | |
| 220 | static StaticResource<SafeStringInputBuffer> safe_string_input_buffer; |
| 221 | |
| 222 | |
| 223 | Handle<JSFunction> Compiler::Compile(Handle<String> source, |
| 224 | Handle<Object> script_name, |
| 225 | int line_offset, int column_offset, |
| 226 | v8::Extension* extension, |
| 227 | ScriptDataImpl* input_pre_data) { |
| 228 | int source_length = source->length(); |
| 229 | Counters::total_load_size.Increment(source_length); |
| 230 | Counters::total_compile_size.Increment(source_length); |
| 231 | |
| 232 | // The VM is in the COMPILER state until exiting this function. |
| 233 | VMState state(COMPILER); |
| 234 | |
| 235 | // Do a lookup in the compilation cache but not for extensions. |
| 236 | Handle<JSFunction> result; |
| 237 | if (extension == NULL) { |
| 238 | result = CompilationCache::LookupScript(source, |
| 239 | script_name, |
| 240 | line_offset, |
| 241 | column_offset); |
| 242 | } |
| 243 | |
| 244 | if (result.is_null()) { |
| 245 | // No cache entry found. Do pre-parsing and compile the script. |
| 246 | ScriptDataImpl* pre_data = input_pre_data; |
| 247 | if (pre_data == NULL && source_length >= FLAG_min_preparse_length) { |
| 248 | Access<SafeStringInputBuffer> buf(&safe_string_input_buffer); |
| 249 | buf->Reset(source.location()); |
| 250 | pre_data = PreParse(source, buf.value(), extension); |
| 251 | } |
| 252 | |
| 253 | // Create a script object describing the script to be compiled. |
| 254 | Handle<Script> script = Factory::NewScript(source); |
| 255 | if (!script_name.is_null()) { |
| 256 | script->set_name(*script_name); |
| 257 | script->set_line_offset(Smi::FromInt(line_offset)); |
| 258 | script->set_column_offset(Smi::FromInt(column_offset)); |
| 259 | } |
| 260 | |
| 261 | // Compile the function and add it to the cache. |
| 262 | result = MakeFunction(true, |
| 263 | false, |
| 264 | DONT_VALIDATE_JSON, |
| 265 | script, |
| 266 | Handle<Context>::null(), |
| 267 | extension, |
| 268 | pre_data); |
| 269 | if (extension == NULL && !result.is_null()) { |
| 270 | CompilationCache::PutScript(source, result); |
| 271 | } |
| 272 | |
| 273 | // Get rid of the pre-parsing data (if necessary). |
| 274 | if (input_pre_data == NULL && pre_data != NULL) { |
| 275 | delete pre_data; |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | if (result.is_null()) Top::ReportPendingMessages(); |
| 280 | return result; |
| 281 | } |
| 282 | |
| 283 | |
| 284 | Handle<JSFunction> Compiler::CompileEval(Handle<String> source, |
| 285 | Handle<Context> context, |
| 286 | bool is_global, |
| 287 | ValidationState validate) { |
| 288 | // Note that if validation is required then no path through this |
| 289 | // function is allowed to return a value without validating that |
| 290 | // the input is legal json. |
| 291 | |
| 292 | int source_length = source->length(); |
| 293 | Counters::total_eval_size.Increment(source_length); |
| 294 | Counters::total_compile_size.Increment(source_length); |
| 295 | |
| 296 | // The VM is in the COMPILER state until exiting this function. |
| 297 | VMState state(COMPILER); |
| 298 | |
| 299 | // Do a lookup in the compilation cache; if the entry is not there, |
| 300 | // invoke the compiler and add the result to the cache. If we're |
| 301 | // evaluating json we bypass the cache since we can't be sure a |
| 302 | // potential value in the cache has been validated. |
| 303 | Handle<JSFunction> result; |
| 304 | if (validate == DONT_VALIDATE_JSON) |
| 305 | result = CompilationCache::LookupEval(source, context, is_global); |
| 306 | |
| 307 | if (result.is_null()) { |
| 308 | // Create a script object describing the script to be compiled. |
| 309 | Handle<Script> script = Factory::NewScript(source); |
| 310 | result = MakeFunction(is_global, |
| 311 | true, |
| 312 | validate, |
| 313 | script, |
| 314 | context, |
| 315 | NULL, |
| 316 | NULL); |
| 317 | if (!result.is_null() && validate != VALIDATE_JSON) { |
| 318 | // For json it's unlikely that we'll ever see exactly the same |
| 319 | // string again so we don't use the compilation cache. |
| 320 | CompilationCache::PutEval(source, context, is_global, result); |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | return result; |
| 325 | } |
| 326 | |
| 327 | |
| 328 | bool Compiler::CompileLazy(Handle<SharedFunctionInfo> shared, |
| 329 | int loop_nesting) { |
| 330 | CompilationZoneScope zone_scope(DELETE_ON_EXIT); |
| 331 | |
| 332 | // The VM is in the COMPILER state until exiting this function. |
| 333 | VMState state(COMPILER); |
| 334 | |
| 335 | PostponeInterruptsScope postpone; |
| 336 | |
| 337 | // Compute name, source code and script data. |
| 338 | Handle<String> name(String::cast(shared->name())); |
| 339 | Handle<Script> script(Script::cast(shared->script())); |
| 340 | |
| 341 | int start_position = shared->start_position(); |
| 342 | int end_position = shared->end_position(); |
| 343 | bool is_expression = shared->is_expression(); |
| 344 | Counters::total_compile_size.Increment(end_position - start_position); |
| 345 | |
| 346 | // Generate the AST for the lazily compiled function. The AST may be |
| 347 | // NULL in case of parser stack overflow. |
| 348 | FunctionLiteral* lit = MakeLazyAST(script, name, |
| 349 | start_position, |
| 350 | end_position, |
| 351 | is_expression); |
| 352 | |
| 353 | // Check for parse errors. |
| 354 | if (lit == NULL) { |
| 355 | ASSERT(Top::has_pending_exception()); |
| 356 | return false; |
| 357 | } |
| 358 | |
| 359 | // Update the loop nesting in the function literal. |
| 360 | lit->set_loop_nesting(loop_nesting); |
| 361 | |
| 362 | // Measure how long it takes to do the lazy compilation; only take |
| 363 | // the rest of the function into account to avoid overlap with the |
| 364 | // lazy parsing statistics. |
| 365 | HistogramTimerScope timer(&Counters::compile_lazy); |
| 366 | |
| 367 | // Compile the code. |
| 368 | Handle<Code> code = MakeCode(lit, script, Handle<Context>::null(), false); |
| 369 | |
| 370 | // Check for stack-overflow exception. |
| 371 | if (code.is_null()) { |
| 372 | Top::StackOverflow(); |
| 373 | return false; |
| 374 | } |
| 375 | |
| 376 | #if defined ENABLE_LOGGING_AND_PROFILING || defined ENABLE_OPROFILE_AGENT |
| 377 | // Log the code generation. If source information is available include script |
| 378 | // name and line number. Check explicit whether logging is enabled as finding |
| 379 | // the line number is not for free. |
| 380 | if (Logger::is_logging() || OProfileAgent::is_enabled()) { |
| 381 | Handle<String> func_name(name->length() > 0 ? |
| 382 | *name : shared->inferred_name()); |
| 383 | if (script->name()->IsString()) { |
| 384 | int line_num = GetScriptLineNumber(script, start_position) + 1; |
| 385 | LOG(CodeCreateEvent(Logger::LAZY_COMPILE_TAG, *code, *func_name, |
| 386 | String::cast(script->name()), line_num)); |
| 387 | OProfileAgent::CreateNativeCodeRegion(*func_name, |
| 388 | String::cast(script->name()), |
| 389 | line_num, |
| 390 | code->instruction_start(), |
| 391 | code->instruction_size()); |
| 392 | } else { |
| 393 | LOG(CodeCreateEvent(Logger::LAZY_COMPILE_TAG, *code, *func_name)); |
| 394 | OProfileAgent::CreateNativeCodeRegion(*func_name, |
| 395 | code->instruction_start(), |
| 396 | code->instruction_size()); |
| 397 | } |
| 398 | } |
| 399 | #endif |
| 400 | |
| 401 | // Update the shared function info with the compiled code. |
| 402 | shared->set_code(*code); |
| 403 | |
| 404 | // Set the expected number of properties for instances. |
| 405 | SetExpectedNofPropertiesFromEstimate(shared, lit->expected_property_count()); |
| 406 | |
| 407 | // Set the optimication hints after performing lazy compilation, as these are |
| 408 | // not set when the function is set up as a lazily compiled function. |
| 409 | shared->SetThisPropertyAssignmentsInfo( |
| 410 | lit->has_only_this_property_assignments(), |
| 411 | lit->has_only_simple_this_property_assignments(), |
| 412 | *lit->this_property_assignments()); |
| 413 | |
| 414 | // Check the function has compiled code. |
| 415 | ASSERT(shared->is_compiled()); |
| 416 | return true; |
| 417 | } |
| 418 | |
| 419 | |
| 420 | } } // namespace v8::internal |