1 // Copyright 2012 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.
33 #include "full-codegen.h"
35 #include "macro-assembler.h"
36 #include "prettyprinter.h"
38 #include "scopeinfo.h"
40 #include "stub-cache.h"
45 void BreakableStatementChecker::Check(Statement* stmt) {
50 void BreakableStatementChecker::Check(Expression* expr) {
55 void BreakableStatementChecker::VisitVariableDeclaration(
56 VariableDeclaration* decl) {
59 void BreakableStatementChecker::VisitFunctionDeclaration(
60 FunctionDeclaration* decl) {
63 void BreakableStatementChecker::VisitModuleDeclaration(
64 ModuleDeclaration* decl) {
67 void BreakableStatementChecker::VisitImportDeclaration(
68 ImportDeclaration* decl) {
71 void BreakableStatementChecker::VisitExportDeclaration(
72 ExportDeclaration* decl) {
76 void BreakableStatementChecker::VisitModuleLiteral(ModuleLiteral* module) {
80 void BreakableStatementChecker::VisitModuleVariable(ModuleVariable* module) {
84 void BreakableStatementChecker::VisitModulePath(ModulePath* module) {
88 void BreakableStatementChecker::VisitModuleUrl(ModuleUrl* module) {
92 void BreakableStatementChecker::VisitModuleStatement(ModuleStatement* stmt) {
96 void BreakableStatementChecker::VisitBlock(Block* stmt) {
100 void BreakableStatementChecker::VisitExpressionStatement(
101 ExpressionStatement* stmt) {
102 // Check if expression is breakable.
103 Visit(stmt->expression());
107 void BreakableStatementChecker::VisitEmptyStatement(EmptyStatement* stmt) {
111 void BreakableStatementChecker::VisitIfStatement(IfStatement* stmt) {
112 // If the condition is breakable the if statement is breakable.
113 Visit(stmt->condition());
117 void BreakableStatementChecker::VisitContinueStatement(
118 ContinueStatement* stmt) {
122 void BreakableStatementChecker::VisitBreakStatement(BreakStatement* stmt) {
126 void BreakableStatementChecker::VisitReturnStatement(ReturnStatement* stmt) {
127 // Return is breakable if the expression is.
128 Visit(stmt->expression());
132 void BreakableStatementChecker::VisitWithStatement(WithStatement* stmt) {
133 Visit(stmt->expression());
137 void BreakableStatementChecker::VisitSwitchStatement(SwitchStatement* stmt) {
138 // Switch statements breakable if the tag expression is.
143 void BreakableStatementChecker::VisitDoWhileStatement(DoWhileStatement* stmt) {
144 // Mark do while as breakable to avoid adding a break slot in front of it.
145 is_breakable_ = true;
149 void BreakableStatementChecker::VisitWhileStatement(WhileStatement* stmt) {
150 // Mark while statements breakable if the condition expression is.
155 void BreakableStatementChecker::VisitForStatement(ForStatement* stmt) {
156 // Mark for statements breakable if the condition expression is.
157 if (stmt->cond() != NULL) {
163 void BreakableStatementChecker::VisitForInStatement(ForInStatement* stmt) {
164 // Mark for in statements breakable if the enumerable expression is.
165 Visit(stmt->enumerable());
169 void BreakableStatementChecker::VisitForOfStatement(ForOfStatement* stmt) {
170 // For-of is breakable because of the next() call.
171 is_breakable_ = true;
175 void BreakableStatementChecker::VisitTryCatchStatement(
176 TryCatchStatement* stmt) {
177 // Mark try catch as breakable to avoid adding a break slot in front of it.
178 is_breakable_ = true;
182 void BreakableStatementChecker::VisitTryFinallyStatement(
183 TryFinallyStatement* stmt) {
184 // Mark try finally as breakable to avoid adding a break slot in front of it.
185 is_breakable_ = true;
189 void BreakableStatementChecker::VisitDebuggerStatement(
190 DebuggerStatement* stmt) {
191 // The debugger statement is breakable.
192 is_breakable_ = true;
196 void BreakableStatementChecker::VisitCaseClause(CaseClause* clause) {
200 void BreakableStatementChecker::VisitFunctionLiteral(FunctionLiteral* expr) {
204 void BreakableStatementChecker::VisitNativeFunctionLiteral(
205 NativeFunctionLiteral* expr) {
209 void BreakableStatementChecker::VisitConditional(Conditional* expr) {
213 void BreakableStatementChecker::VisitVariableProxy(VariableProxy* expr) {
217 void BreakableStatementChecker::VisitLiteral(Literal* expr) {
221 void BreakableStatementChecker::VisitRegExpLiteral(RegExpLiteral* expr) {
225 void BreakableStatementChecker::VisitObjectLiteral(ObjectLiteral* expr) {
229 void BreakableStatementChecker::VisitArrayLiteral(ArrayLiteral* expr) {
233 void BreakableStatementChecker::VisitAssignment(Assignment* expr) {
234 // If assigning to a property (including a global property) the assignment is
236 VariableProxy* proxy = expr->target()->AsVariableProxy();
237 Property* prop = expr->target()->AsProperty();
238 if (prop != NULL || (proxy != NULL && proxy->var()->IsUnallocated())) {
239 is_breakable_ = true;
243 // Otherwise the assignment is breakable if the assigned value is.
244 Visit(expr->value());
248 void BreakableStatementChecker::VisitYield(Yield* expr) {
249 // Yield is breakable if the expression is.
250 Visit(expr->expression());
254 void BreakableStatementChecker::VisitThrow(Throw* expr) {
255 // Throw is breakable if the expression is.
256 Visit(expr->exception());
260 void BreakableStatementChecker::VisitProperty(Property* expr) {
261 // Property load is breakable.
262 is_breakable_ = true;
266 void BreakableStatementChecker::VisitCall(Call* expr) {
267 // Function calls both through IC and call stub are breakable.
268 is_breakable_ = true;
272 void BreakableStatementChecker::VisitCallNew(CallNew* expr) {
273 // Function calls through new are breakable.
274 is_breakable_ = true;
278 void BreakableStatementChecker::VisitCallRuntime(CallRuntime* expr) {
282 void BreakableStatementChecker::VisitUnaryOperation(UnaryOperation* expr) {
283 Visit(expr->expression());
287 void BreakableStatementChecker::VisitCountOperation(CountOperation* expr) {
288 Visit(expr->expression());
292 void BreakableStatementChecker::VisitBinaryOperation(BinaryOperation* expr) {
294 if (expr->op() != Token::AND &&
295 expr->op() != Token::OR) {
296 Visit(expr->right());
301 void BreakableStatementChecker::VisitCompareOperation(CompareOperation* expr) {
303 Visit(expr->right());
307 void BreakableStatementChecker::VisitThisFunction(ThisFunction* expr) {
311 #define __ ACCESS_MASM(masm())
313 bool FullCodeGenerator::MakeCode(CompilationInfo* info) {
314 Isolate* isolate = info->isolate();
316 Logger::TimerEventScope timer(
317 isolate, Logger::TimerEventScope::v8_compile_full_code);
319 Handle<Script> script = info->script();
320 if (!script->IsUndefined() && !script->source()->IsUndefined()) {
321 int len = String::cast(script->source())->length();
322 isolate->counters()->total_full_codegen_source_size()->Increment(len);
324 CodeGenerator::MakeCodePrologue(info, "full");
325 const int kInitialBufferSize = 4 * KB;
326 MacroAssembler masm(info->isolate(), NULL, kInitialBufferSize);
327 #ifdef ENABLE_GDB_JIT_INTERFACE
328 masm.positions_recorder()->StartGDBJITLineInfoRecording();
330 LOG_CODE_EVENT(isolate,
331 CodeStartLinePosInfoRecordEvent(masm.positions_recorder()));
333 FullCodeGenerator cgen(&masm, info);
335 if (cgen.HasStackOverflow()) {
336 ASSERT(!isolate->has_pending_exception());
339 unsigned table_offset = cgen.EmitBackEdgeTable();
341 Code::Flags flags = Code::ComputeFlags(Code::FUNCTION);
342 Handle<Code> code = CodeGenerator::MakeCodeEpilogue(&masm, flags, info);
343 code->set_optimizable(info->IsOptimizable() &&
344 !info->function()->dont_optimize() &&
345 info->function()->scope()->AllowsLazyCompilation());
346 cgen.PopulateDeoptimizationData(code);
347 cgen.PopulateTypeFeedbackInfo(code);
348 cgen.PopulateTypeFeedbackCells(code);
349 code->set_has_deoptimization_support(info->HasDeoptimizationSupport());
350 code->set_handler_table(*cgen.handler_table());
351 #ifdef ENABLE_DEBUGGER_SUPPORT
352 code->set_compiled_optimizable(info->IsOptimizable());
353 #endif // ENABLE_DEBUGGER_SUPPORT
354 code->set_allow_osr_at_loop_nesting_level(0);
355 code->set_profiler_ticks(0);
356 code->set_back_edge_table_offset(table_offset);
357 code->set_back_edges_patched_for_osr(false);
358 CodeGenerator::PrintCode(code, info);
360 #ifdef ENABLE_GDB_JIT_INTERFACE
362 GDBJITLineInfo* lineinfo =
363 masm.positions_recorder()->DetachGDBJITLineInfo();
364 GDBJIT(RegisterDetailedLineInfo(*code, lineinfo));
367 void* line_info = masm.positions_recorder()->DetachJITHandlerData();
368 LOG_CODE_EVENT(isolate, CodeEndLinePosInfoRecordEvent(*code, line_info));
373 unsigned FullCodeGenerator::EmitBackEdgeTable() {
374 // The back edge table consists of a length (in number of entries)
375 // field, and then a sequence of entries. Each entry is a pair of AST id
376 // and code-relative pc offset.
377 masm()->Align(kIntSize);
378 unsigned offset = masm()->pc_offset();
379 unsigned length = back_edges_.length();
381 for (unsigned i = 0; i < length; ++i) {
382 __ dd(back_edges_[i].id.ToInt());
383 __ dd(back_edges_[i].pc);
384 __ dd(back_edges_[i].loop_depth);
390 void FullCodeGenerator::PopulateDeoptimizationData(Handle<Code> code) {
391 // Fill in the deoptimization information.
392 ASSERT(info_->HasDeoptimizationSupport() || bailout_entries_.is_empty());
393 if (!info_->HasDeoptimizationSupport()) return;
394 int length = bailout_entries_.length();
395 Handle<DeoptimizationOutputData> data = isolate()->factory()->
396 NewDeoptimizationOutputData(length, TENURED);
397 for (int i = 0; i < length; i++) {
398 data->SetAstId(i, bailout_entries_[i].id);
399 data->SetPcAndState(i, Smi::FromInt(bailout_entries_[i].pc_and_state));
401 code->set_deoptimization_data(*data);
405 void FullCodeGenerator::PopulateTypeFeedbackInfo(Handle<Code> code) {
406 Handle<TypeFeedbackInfo> info = isolate()->factory()->NewTypeFeedbackInfo();
407 info->set_ic_total_count(ic_total_count_);
408 ASSERT(!isolate()->heap()->InNewSpace(*info));
409 code->set_type_feedback_info(*info);
413 void FullCodeGenerator::Initialize() {
414 // The generation of debug code must match between the snapshot code and the
415 // code that is generated later. This is assumed by the debugger when it is
416 // calculating PC offsets after generating a debug version of code. Therefore
417 // we disable the production of debug code in the full compiler if we are
418 // either generating a snapshot or we booted from a snapshot.
419 generate_debug_code_ = FLAG_debug_code &&
420 !Serializer::enabled() &&
421 !Snapshot::HaveASnapshotToStartFrom();
422 masm_->set_emit_debug_code(generate_debug_code_);
423 masm_->set_predictable_code_size(true);
424 InitializeAstVisitor(info_->zone());
428 void FullCodeGenerator::PopulateTypeFeedbackCells(Handle<Code> code) {
429 if (type_feedback_cells_.is_empty()) return;
430 int length = type_feedback_cells_.length();
431 int array_size = TypeFeedbackCells::LengthOfFixedArray(length);
432 Handle<TypeFeedbackCells> cache = Handle<TypeFeedbackCells>::cast(
433 isolate()->factory()->NewFixedArray(array_size, TENURED));
434 for (int i = 0; i < length; i++) {
435 cache->SetAstId(i, type_feedback_cells_[i].ast_id);
436 cache->SetCell(i, *type_feedback_cells_[i].cell);
438 TypeFeedbackInfo::cast(code->type_feedback_info())->set_type_feedback_cells(
443 void FullCodeGenerator::PrepareForBailout(Expression* node, State state) {
444 PrepareForBailoutForId(node->id(), state);
448 void FullCodeGenerator::CallLoadIC(ContextualMode contextual_mode,
450 ExtraICState extra_state = LoadIC::ComputeExtraICState(contextual_mode);
451 Handle<Code> ic = LoadIC::initialize_stub(isolate(), extra_state);
452 CallIC(ic, contextual_mode, id);
456 void FullCodeGenerator::CallStoreIC(ContextualMode mode, TypeFeedbackId id) {
457 Handle<Code> ic = StoreIC::initialize_stub(isolate(), strict_mode());
458 CallIC(ic, mode, id);
462 void FullCodeGenerator::RecordJSReturnSite(Call* call) {
463 // We record the offset of the function return so we can rebuild the frame
464 // if the function was inlined, i.e., this is the return address in the
465 // inlined function's frame.
467 // The state is ignored. We defensively set it to TOS_REG, which is the
468 // real state of the unoptimized code at the return site.
469 PrepareForBailoutForId(call->ReturnId(), TOS_REG);
471 // In debug builds, mark the return so we can verify that this function
473 ASSERT(!call->return_is_recorded_);
474 call->return_is_recorded_ = true;
479 void FullCodeGenerator::PrepareForBailoutForId(BailoutId id, State state) {
480 // There's no need to prepare this code for bailouts from already optimized
481 // code or code that can't be optimized.
482 if (!info_->HasDeoptimizationSupport()) return;
483 unsigned pc_and_state =
484 StateField::encode(state) | PcField::encode(masm_->pc_offset());
485 ASSERT(Smi::IsValid(pc_and_state));
486 BailoutEntry entry = { id, pc_and_state };
487 ASSERT(!prepared_bailout_ids_.Contains(id.ToInt()));
488 prepared_bailout_ids_.Add(id.ToInt(), zone());
489 bailout_entries_.Add(entry, zone());
493 void FullCodeGenerator::RecordTypeFeedbackCell(
494 TypeFeedbackId id, Handle<Cell> cell) {
495 TypeFeedbackCellEntry entry = { id, cell };
496 type_feedback_cells_.Add(entry, zone());
500 void FullCodeGenerator::RecordBackEdge(BailoutId ast_id) {
501 // The pc offset does not need to be encoded and packed together with a state.
502 ASSERT(masm_->pc_offset() > 0);
503 ASSERT(loop_depth() > 0);
504 uint8_t depth = Min(loop_depth(), Code::kMaxLoopNestingMarker);
505 BackEdgeEntry entry =
506 { ast_id, static_cast<unsigned>(masm_->pc_offset()), depth };
507 back_edges_.Add(entry, zone());
511 bool FullCodeGenerator::ShouldInlineSmiCase(Token::Value op) {
512 // Inline smi case inside loops, but not division and modulo which
513 // are too complicated and take up too much space.
514 if (op == Token::DIV ||op == Token::MOD) return false;
515 if (FLAG_always_inline_smi_code) return true;
516 return loop_depth_ > 0;
520 void FullCodeGenerator::EffectContext::Plug(Register reg) const {
524 void FullCodeGenerator::AccumulatorValueContext::Plug(Register reg) const {
525 __ Move(result_register(), reg);
529 void FullCodeGenerator::StackValueContext::Plug(Register reg) const {
534 void FullCodeGenerator::TestContext::Plug(Register reg) const {
535 // For simplicity we always test the accumulator register.
536 __ Move(result_register(), reg);
537 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
538 codegen()->DoTest(this);
542 void FullCodeGenerator::EffectContext::PlugTOS() const {
547 void FullCodeGenerator::AccumulatorValueContext::PlugTOS() const {
548 __ Pop(result_register());
552 void FullCodeGenerator::StackValueContext::PlugTOS() const {
556 void FullCodeGenerator::TestContext::PlugTOS() const {
557 // For simplicity we always test the accumulator register.
558 __ Pop(result_register());
559 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
560 codegen()->DoTest(this);
564 void FullCodeGenerator::EffectContext::PrepareTest(
565 Label* materialize_true,
566 Label* materialize_false,
569 Label** fall_through) const {
570 // In an effect context, the true and the false case branch to the
572 *if_true = *if_false = *fall_through = materialize_true;
576 void FullCodeGenerator::AccumulatorValueContext::PrepareTest(
577 Label* materialize_true,
578 Label* materialize_false,
581 Label** fall_through) const {
582 *if_true = *fall_through = materialize_true;
583 *if_false = materialize_false;
587 void FullCodeGenerator::StackValueContext::PrepareTest(
588 Label* materialize_true,
589 Label* materialize_false,
592 Label** fall_through) const {
593 *if_true = *fall_through = materialize_true;
594 *if_false = materialize_false;
598 void FullCodeGenerator::TestContext::PrepareTest(
599 Label* materialize_true,
600 Label* materialize_false,
603 Label** fall_through) const {
604 *if_true = true_label_;
605 *if_false = false_label_;
606 *fall_through = fall_through_;
610 void FullCodeGenerator::DoTest(const TestContext* context) {
611 DoTest(context->condition(),
612 context->true_label(),
613 context->false_label(),
614 context->fall_through());
618 void FullCodeGenerator::AllocateModules(ZoneList<Declaration*>* declarations) {
619 ASSERT(scope_->is_global_scope());
621 for (int i = 0; i < declarations->length(); i++) {
622 ModuleDeclaration* declaration = declarations->at(i)->AsModuleDeclaration();
623 if (declaration != NULL) {
624 ModuleLiteral* module = declaration->module()->AsModuleLiteral();
625 if (module != NULL) {
626 Comment cmnt(masm_, "[ Link nested modules");
627 Scope* scope = module->body()->scope();
628 Interface* interface = scope->interface();
629 ASSERT(interface->IsModule() && interface->IsFrozen());
631 interface->Allocate(scope->module_var()->index());
633 // Set up module context.
634 ASSERT(scope->interface()->Index() >= 0);
635 __ Push(Smi::FromInt(scope->interface()->Index()));
636 __ Push(scope->GetScopeInfo());
637 __ CallRuntime(Runtime::kPushModuleContext, 2);
638 StoreToFrameField(StandardFrameConstants::kContextOffset,
641 AllocateModules(scope->declarations());
643 // Pop module context.
644 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
645 // Update local stack frame context field.
646 StoreToFrameField(StandardFrameConstants::kContextOffset,
654 // Modules have their own local scope, represented by their own context.
655 // Module instance objects have an accessor for every export that forwards
656 // access to the respective slot from the module's context. (Exports that are
657 // modules themselves, however, are simple data properties.)
659 // All modules have a _hosting_ scope/context, which (currently) is the
660 // (innermost) enclosing global scope. To deal with recursion, nested modules
661 // are hosted by the same scope as global ones.
663 // For every (global or nested) module literal, the hosting context has an
664 // internal slot that points directly to the respective module context. This
665 // enables quick access to (statically resolved) module members by 2-dimensional
666 // access through the hosting context. For example,
670 // module B { let y; }
672 // module C { let z; }
674 // allocates contexts as follows:
676 // [header| .A | .B | .C | A | C ] (global)
678 // | | +-- [header| z ] (module)
680 // | +------- [header| y ] (module)
682 // +------------ [header| x | B ] (module)
684 // Here, .A, .B, .C are the internal slots pointing to the hosted module
685 // contexts, whereas A, B, C hold the actual instance objects (note that every
686 // module context also points to the respective instance object through its
687 // extension slot in the header).
689 // To deal with arbitrary recursion and aliases between modules,
690 // they are created and initialized in several stages. Each stage applies to
691 // all modules in the hosting global scope, including nested ones.
693 // 1. Allocate: for each module _literal_, allocate the module contexts and
694 // respective instance object and wire them up. This happens in the
695 // PushModuleContext runtime function, as generated by AllocateModules
696 // (invoked by VisitDeclarations in the hosting scope).
698 // 2. Bind: for each module _declaration_ (i.e. literals as well as aliases),
699 // assign the respective instance object to respective local variables. This
700 // happens in VisitModuleDeclaration, and uses the instance objects created
701 // in the previous stage.
702 // For each module _literal_, this phase also constructs a module descriptor
703 // for the next stage. This happens in VisitModuleLiteral.
705 // 3. Populate: invoke the DeclareModules runtime function to populate each
706 // _instance_ object with accessors for it exports. This is generated by
707 // DeclareModules (invoked by VisitDeclarations in the hosting scope again),
708 // and uses the descriptors generated in the previous stage.
710 // 4. Initialize: execute the module bodies (and other code) in sequence. This
711 // happens by the separate statements generated for module bodies. To reenter
712 // the module scopes properly, the parser inserted ModuleStatements.
714 void FullCodeGenerator::VisitDeclarations(
715 ZoneList<Declaration*>* declarations) {
716 Handle<FixedArray> saved_modules = modules_;
717 int saved_module_index = module_index_;
718 ZoneList<Handle<Object> >* saved_globals = globals_;
719 ZoneList<Handle<Object> > inner_globals(10, zone());
720 globals_ = &inner_globals;
722 if (scope_->num_modules() != 0) {
723 // This is a scope hosting modules. Allocate a descriptor array to pass
724 // to the runtime for initialization.
725 Comment cmnt(masm_, "[ Allocate modules");
726 ASSERT(scope_->is_global_scope());
728 isolate()->factory()->NewFixedArray(scope_->num_modules(), TENURED);
731 // Generate code for allocating all modules, including nested ones.
732 // The allocated contexts are stored in internal variables in this scope.
733 AllocateModules(declarations);
736 AstVisitor::VisitDeclarations(declarations);
738 if (scope_->num_modules() != 0) {
739 // Initialize modules from descriptor array.
740 ASSERT(module_index_ == modules_->length());
741 DeclareModules(modules_);
742 modules_ = saved_modules;
743 module_index_ = saved_module_index;
746 if (!globals_->is_empty()) {
747 // Invoke the platform-dependent code generator to do the actual
748 // declaration of the global functions and variables.
749 Handle<FixedArray> array =
750 isolate()->factory()->NewFixedArray(globals_->length(), TENURED);
751 for (int i = 0; i < globals_->length(); ++i)
752 array->set(i, *globals_->at(i));
753 DeclareGlobals(array);
756 globals_ = saved_globals;
760 void FullCodeGenerator::VisitModuleLiteral(ModuleLiteral* module) {
761 Block* block = module->body();
762 Scope* saved_scope = scope();
763 scope_ = block->scope();
764 Interface* interface = scope_->interface();
766 Comment cmnt(masm_, "[ ModuleLiteral");
767 SetStatementPosition(block);
769 ASSERT(!modules_.is_null());
770 ASSERT(module_index_ < modules_->length());
771 int index = module_index_++;
773 // Set up module context.
774 ASSERT(interface->Index() >= 0);
775 __ Push(Smi::FromInt(interface->Index()));
776 __ Push(Smi::FromInt(0));
777 __ CallRuntime(Runtime::kPushModuleContext, 2);
778 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
781 Comment cmnt(masm_, "[ Declarations");
782 VisitDeclarations(scope_->declarations());
785 // Populate the module description.
786 Handle<ModuleInfo> description =
787 ModuleInfo::Create(isolate(), interface, scope_);
788 modules_->set(index, *description);
790 scope_ = saved_scope;
791 // Pop module context.
792 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
793 // Update local stack frame context field.
794 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
798 void FullCodeGenerator::VisitModuleVariable(ModuleVariable* module) {
800 // The instance object is resolved statically through the module's interface.
804 void FullCodeGenerator::VisitModulePath(ModulePath* module) {
806 // The instance object is resolved statically through the module's interface.
810 void FullCodeGenerator::VisitModuleUrl(ModuleUrl* module) {
811 // TODO(rossberg): dummy allocation for now.
812 Scope* scope = module->body()->scope();
813 Interface* interface = scope_->interface();
815 ASSERT(interface->IsModule() && interface->IsFrozen());
816 ASSERT(!modules_.is_null());
817 ASSERT(module_index_ < modules_->length());
818 interface->Allocate(scope->module_var()->index());
819 int index = module_index_++;
821 Handle<ModuleInfo> description =
822 ModuleInfo::Create(isolate(), interface, scope_);
823 modules_->set(index, *description);
827 int FullCodeGenerator::DeclareGlobalsFlags() {
828 ASSERT(DeclareGlobalsLanguageMode::is_valid(language_mode()));
829 return DeclareGlobalsEvalFlag::encode(is_eval()) |
830 DeclareGlobalsNativeFlag::encode(is_native()) |
831 DeclareGlobalsLanguageMode::encode(language_mode());
835 void FullCodeGenerator::SetFunctionPosition(FunctionLiteral* fun) {
836 CodeGenerator::RecordPositions(masm_, fun->start_position());
840 void FullCodeGenerator::SetReturnPosition(FunctionLiteral* fun) {
841 CodeGenerator::RecordPositions(masm_, fun->end_position() - 1);
845 void FullCodeGenerator::SetStatementPosition(Statement* stmt) {
846 #ifdef ENABLE_DEBUGGER_SUPPORT
847 if (!isolate()->debugger()->IsDebuggerActive()) {
848 CodeGenerator::RecordPositions(masm_, stmt->position());
850 // Check if the statement will be breakable without adding a debug break
852 BreakableStatementChecker checker(zone());
854 // Record the statement position right here if the statement is not
855 // breakable. For breakable statements the actual recording of the
856 // position will be postponed to the breakable code (typically an IC).
857 bool position_recorded = CodeGenerator::RecordPositions(
858 masm_, stmt->position(), !checker.is_breakable());
859 // If the position recording did record a new position generate a debug
860 // break slot to make the statement breakable.
861 if (position_recorded) {
862 Debug::GenerateSlot(masm_);
866 CodeGenerator::RecordPositions(masm_, stmt->position());
871 void FullCodeGenerator::SetExpressionPosition(Expression* expr) {
872 #ifdef ENABLE_DEBUGGER_SUPPORT
873 if (!isolate()->debugger()->IsDebuggerActive()) {
874 CodeGenerator::RecordPositions(masm_, expr->position());
876 // Check if the expression will be breakable without adding a debug break
878 BreakableStatementChecker checker(zone());
880 // Record a statement position right here if the expression is not
881 // breakable. For breakable expressions the actual recording of the
882 // position will be postponed to the breakable code (typically an IC).
883 // NOTE this will record a statement position for something which might
884 // not be a statement. As stepping in the debugger will only stop at
885 // statement positions this is used for e.g. the condition expression of
887 bool position_recorded = CodeGenerator::RecordPositions(
888 masm_, expr->position(), !checker.is_breakable());
889 // If the position recording did record a new position generate a debug
890 // break slot to make the statement breakable.
891 if (position_recorded) {
892 Debug::GenerateSlot(masm_);
896 CodeGenerator::RecordPositions(masm_, pos);
901 void FullCodeGenerator::SetStatementPosition(int pos) {
902 CodeGenerator::RecordPositions(masm_, pos);
906 void FullCodeGenerator::SetSourcePosition(int pos) {
907 if (pos != RelocInfo::kNoPosition) {
908 masm_->positions_recorder()->RecordPosition(pos);
913 // Lookup table for code generators for special runtime calls which are
915 #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize) \
916 &FullCodeGenerator::Emit##Name,
918 const FullCodeGenerator::InlineFunctionGenerator
919 FullCodeGenerator::kInlineFunctionGenerators[] = {
920 INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
921 INLINE_RUNTIME_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
923 #undef INLINE_FUNCTION_GENERATOR_ADDRESS
926 FullCodeGenerator::InlineFunctionGenerator
927 FullCodeGenerator::FindInlineFunctionGenerator(Runtime::FunctionId id) {
929 static_cast<int>(id) - static_cast<int>(Runtime::kFirstInlineFunction);
930 ASSERT(lookup_index >= 0);
931 ASSERT(static_cast<size_t>(lookup_index) <
932 ARRAY_SIZE(kInlineFunctionGenerators));
933 return kInlineFunctionGenerators[lookup_index];
937 void FullCodeGenerator::EmitInlineRuntimeCall(CallRuntime* expr) {
938 const Runtime::Function* function = expr->function();
939 ASSERT(function != NULL);
940 ASSERT(function->intrinsic_type == Runtime::INLINE);
941 InlineFunctionGenerator generator =
942 FindInlineFunctionGenerator(function->function_id);
943 ((*this).*(generator))(expr);
947 void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
948 ZoneList<Expression*>* args = expr->arguments();
949 ASSERT(args->length() == 2);
950 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
954 void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
955 ZoneList<Expression*>* args = expr->arguments();
956 ASSERT(args->length() == 2);
957 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
961 void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
962 context()->Plug(handle(Smi::FromInt(0), isolate()));
966 void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
967 switch (expr->op()) {
969 return VisitComma(expr);
972 return VisitLogicalExpression(expr);
974 return VisitArithmeticExpression(expr);
979 void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
980 if (context()->IsEffect()) {
981 VisitForEffect(expr);
982 } else if (context()->IsAccumulatorValue()) {
983 VisitForAccumulatorValue(expr);
984 } else if (context()->IsStackValue()) {
985 VisitForStackValue(expr);
986 } else if (context()->IsTest()) {
987 const TestContext* test = TestContext::cast(context());
988 VisitForControl(expr, test->true_label(), test->false_label(),
989 test->fall_through());
994 void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
995 Comment cmnt(masm_, "[ Comma");
996 VisitForEffect(expr->left());
997 VisitInDuplicateContext(expr->right());
1001 void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
1002 bool is_logical_and = expr->op() == Token::AND;
1003 Comment cmnt(masm_, is_logical_and ? "[ Logical AND" : "[ Logical OR");
1004 Expression* left = expr->left();
1005 Expression* right = expr->right();
1006 BailoutId right_id = expr->RightId();
1009 if (context()->IsTest()) {
1011 const TestContext* test = TestContext::cast(context());
1012 if (is_logical_and) {
1013 VisitForControl(left, &eval_right, test->false_label(), &eval_right);
1015 VisitForControl(left, test->true_label(), &eval_right, &eval_right);
1017 PrepareForBailoutForId(right_id, NO_REGISTERS);
1018 __ bind(&eval_right);
1020 } else if (context()->IsAccumulatorValue()) {
1021 VisitForAccumulatorValue(left);
1022 // We want the value in the accumulator for the test, and on the stack in
1024 __ Push(result_register());
1025 Label discard, restore;
1026 if (is_logical_and) {
1027 DoTest(left, &discard, &restore, &restore);
1029 DoTest(left, &restore, &discard, &restore);
1032 __ Pop(result_register());
1036 PrepareForBailoutForId(right_id, NO_REGISTERS);
1038 } else if (context()->IsStackValue()) {
1039 VisitForAccumulatorValue(left);
1040 // We want the value in the accumulator for the test, and on the stack in
1042 __ Push(result_register());
1044 if (is_logical_and) {
1045 DoTest(left, &discard, &done, &discard);
1047 DoTest(left, &done, &discard, &discard);
1051 PrepareForBailoutForId(right_id, NO_REGISTERS);
1054 ASSERT(context()->IsEffect());
1056 if (is_logical_and) {
1057 VisitForControl(left, &eval_right, &done, &eval_right);
1059 VisitForControl(left, &done, &eval_right, &eval_right);
1061 PrepareForBailoutForId(right_id, NO_REGISTERS);
1062 __ bind(&eval_right);
1065 VisitInDuplicateContext(right);
1070 void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
1071 Token::Value op = expr->op();
1072 Comment cmnt(masm_, "[ ArithmeticExpression");
1073 Expression* left = expr->left();
1074 Expression* right = expr->right();
1075 OverwriteMode mode =
1076 left->ResultOverwriteAllowed()
1078 : (right->ResultOverwriteAllowed() ? OVERWRITE_RIGHT : NO_OVERWRITE);
1080 VisitForStackValue(left);
1081 VisitForAccumulatorValue(right);
1083 SetSourcePosition(expr->position());
1084 if (ShouldInlineSmiCase(op)) {
1085 EmitInlineSmiBinaryOp(expr, op, mode, left, right);
1087 EmitBinaryOp(expr, op, mode);
1092 void FullCodeGenerator::VisitBlock(Block* stmt) {
1093 Comment cmnt(masm_, "[ Block");
1094 NestedBlock nested_block(this, stmt);
1095 SetStatementPosition(stmt);
1097 Scope* saved_scope = scope();
1098 // Push a block context when entering a block with block scoped variables.
1099 if (stmt->scope() != NULL) {
1100 scope_ = stmt->scope();
1101 ASSERT(!scope_->is_module_scope());
1102 { Comment cmnt(masm_, "[ Extend block context");
1103 __ Push(scope_->GetScopeInfo());
1104 PushFunctionArgumentForContextAllocation();
1105 __ CallRuntime(Runtime::kPushBlockContext, 2);
1107 // Replace the context stored in the frame.
1108 StoreToFrameField(StandardFrameConstants::kContextOffset,
1109 context_register());
1111 { Comment cmnt(masm_, "[ Declarations");
1112 VisitDeclarations(scope_->declarations());
1116 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1117 VisitStatements(stmt->statements());
1118 scope_ = saved_scope;
1119 __ bind(nested_block.break_label());
1120 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1122 // Pop block context if necessary.
1123 if (stmt->scope() != NULL) {
1124 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1125 // Update local stack frame context field.
1126 StoreToFrameField(StandardFrameConstants::kContextOffset,
1127 context_register());
1132 void FullCodeGenerator::VisitModuleStatement(ModuleStatement* stmt) {
1133 Comment cmnt(masm_, "[ Module context");
1135 __ Push(Smi::FromInt(stmt->proxy()->interface()->Index()));
1136 __ Push(Smi::FromInt(0));
1137 __ CallRuntime(Runtime::kPushModuleContext, 2);
1139 StandardFrameConstants::kContextOffset, context_register());
1141 Scope* saved_scope = scope_;
1142 scope_ = stmt->body()->scope();
1143 VisitStatements(stmt->body()->statements());
1144 scope_ = saved_scope;
1145 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1146 // Update local stack frame context field.
1147 StoreToFrameField(StandardFrameConstants::kContextOffset,
1148 context_register());
1152 void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
1153 Comment cmnt(masm_, "[ ExpressionStatement");
1154 SetStatementPosition(stmt);
1155 VisitForEffect(stmt->expression());
1159 void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
1160 Comment cmnt(masm_, "[ EmptyStatement");
1161 SetStatementPosition(stmt);
1165 void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
1166 Comment cmnt(masm_, "[ IfStatement");
1167 SetStatementPosition(stmt);
1168 Label then_part, else_part, done;
1170 if (stmt->HasElseStatement()) {
1171 VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
1172 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1173 __ bind(&then_part);
1174 Visit(stmt->then_statement());
1177 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1178 __ bind(&else_part);
1179 Visit(stmt->else_statement());
1181 VisitForControl(stmt->condition(), &then_part, &done, &then_part);
1182 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1183 __ bind(&then_part);
1184 Visit(stmt->then_statement());
1186 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1189 PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
1193 void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
1194 Comment cmnt(masm_, "[ ContinueStatement");
1195 SetStatementPosition(stmt);
1196 NestedStatement* current = nesting_stack_;
1197 int stack_depth = 0;
1198 int context_length = 0;
1199 // When continuing, we clobber the unpredictable value in the accumulator
1200 // with one that's safe for GC. If we hit an exit from the try block of
1201 // try...finally on our way out, we will unconditionally preserve the
1202 // accumulator on the stack.
1204 while (!current->IsContinueTarget(stmt->target())) {
1205 current = current->Exit(&stack_depth, &context_length);
1207 __ Drop(stack_depth);
1208 if (context_length > 0) {
1209 while (context_length > 0) {
1210 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1213 StoreToFrameField(StandardFrameConstants::kContextOffset,
1214 context_register());
1217 __ jmp(current->AsIteration()->continue_label());
1221 void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
1222 Comment cmnt(masm_, "[ BreakStatement");
1223 SetStatementPosition(stmt);
1224 NestedStatement* current = nesting_stack_;
1225 int stack_depth = 0;
1226 int context_length = 0;
1227 // When breaking, we clobber the unpredictable value in the accumulator
1228 // with one that's safe for GC. If we hit an exit from the try block of
1229 // try...finally on our way out, we will unconditionally preserve the
1230 // accumulator on the stack.
1232 while (!current->IsBreakTarget(stmt->target())) {
1233 current = current->Exit(&stack_depth, &context_length);
1235 __ Drop(stack_depth);
1236 if (context_length > 0) {
1237 while (context_length > 0) {
1238 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1241 StoreToFrameField(StandardFrameConstants::kContextOffset,
1242 context_register());
1245 __ jmp(current->AsBreakable()->break_label());
1249 void FullCodeGenerator::EmitUnwindBeforeReturn() {
1250 NestedStatement* current = nesting_stack_;
1251 int stack_depth = 0;
1252 int context_length = 0;
1253 while (current != NULL) {
1254 current = current->Exit(&stack_depth, &context_length);
1256 __ Drop(stack_depth);
1260 void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
1261 Comment cmnt(masm_, "[ ReturnStatement");
1262 SetStatementPosition(stmt);
1263 Expression* expr = stmt->expression();
1264 VisitForAccumulatorValue(expr);
1265 EmitUnwindBeforeReturn();
1266 EmitReturnSequence();
1270 void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
1271 Comment cmnt(masm_, "[ WithStatement");
1272 SetStatementPosition(stmt);
1274 VisitForStackValue(stmt->expression());
1275 PushFunctionArgumentForContextAllocation();
1276 __ CallRuntime(Runtime::kPushWithContext, 2);
1277 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1279 Scope* saved_scope = scope();
1280 scope_ = stmt->scope();
1281 { WithOrCatch body(this);
1282 Visit(stmt->statement());
1284 scope_ = saved_scope;
1287 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1288 // Update local stack frame context field.
1289 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1293 void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
1294 Comment cmnt(masm_, "[ DoWhileStatement");
1295 SetStatementPosition(stmt);
1296 Label body, book_keeping;
1298 Iteration loop_statement(this, stmt);
1299 increment_loop_depth();
1302 Visit(stmt->body());
1304 // Record the position of the do while condition and make sure it is
1305 // possible to break on the condition.
1306 __ bind(loop_statement.continue_label());
1307 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1308 SetExpressionPosition(stmt->cond());
1309 VisitForControl(stmt->cond(),
1311 loop_statement.break_label(),
1314 // Check stack before looping.
1315 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1316 __ bind(&book_keeping);
1317 EmitBackEdgeBookkeeping(stmt, &body);
1320 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1321 __ bind(loop_statement.break_label());
1322 decrement_loop_depth();
1326 void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
1327 Comment cmnt(masm_, "[ WhileStatement");
1330 Iteration loop_statement(this, stmt);
1331 increment_loop_depth();
1333 // Emit the test at the bottom of the loop.
1336 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1338 Visit(stmt->body());
1340 // Emit the statement position here as this is where the while
1341 // statement code starts.
1342 __ bind(loop_statement.continue_label());
1343 SetStatementPosition(stmt);
1345 // Check stack before looping.
1346 EmitBackEdgeBookkeeping(stmt, &body);
1349 VisitForControl(stmt->cond(),
1351 loop_statement.break_label(),
1352 loop_statement.break_label());
1354 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1355 __ bind(loop_statement.break_label());
1356 decrement_loop_depth();
1360 void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1361 Comment cmnt(masm_, "[ ForStatement");
1364 Iteration loop_statement(this, stmt);
1366 // Set statement position for a break slot before entering the for-body.
1367 SetStatementPosition(stmt);
1369 if (stmt->init() != NULL) {
1370 Visit(stmt->init());
1373 increment_loop_depth();
1374 // Emit the test at the bottom of the loop (even if empty).
1377 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1379 Visit(stmt->body());
1381 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1382 __ bind(loop_statement.continue_label());
1383 if (stmt->next() != NULL) {
1384 Visit(stmt->next());
1387 // Emit the statement position here as this is where the for
1388 // statement code starts.
1389 SetStatementPosition(stmt);
1391 // Check stack before looping.
1392 EmitBackEdgeBookkeeping(stmt, &body);
1395 if (stmt->cond() != NULL) {
1396 VisitForControl(stmt->cond(),
1398 loop_statement.break_label(),
1399 loop_statement.break_label());
1404 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1405 __ bind(loop_statement.break_label());
1406 decrement_loop_depth();
1410 void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1411 Comment cmnt(masm_, "[ TryCatchStatement");
1412 SetStatementPosition(stmt);
1413 // The try block adds a handler to the exception handler chain before
1414 // entering, and removes it again when exiting normally. If an exception
1415 // is thrown during execution of the try block, the handler is consumed
1416 // and control is passed to the catch block with the exception in the
1419 Label try_entry, handler_entry, exit;
1421 __ bind(&handler_entry);
1422 handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1423 // Exception handler code, the exception is in the result register.
1424 // Extend the context before executing the catch block.
1425 { Comment cmnt(masm_, "[ Extend catch context");
1426 __ Push(stmt->variable()->name());
1427 __ Push(result_register());
1428 PushFunctionArgumentForContextAllocation();
1429 __ CallRuntime(Runtime::kPushCatchContext, 3);
1430 StoreToFrameField(StandardFrameConstants::kContextOffset,
1431 context_register());
1434 Scope* saved_scope = scope();
1435 scope_ = stmt->scope();
1436 ASSERT(scope_->declarations()->is_empty());
1437 { WithOrCatch catch_body(this);
1438 Visit(stmt->catch_block());
1440 // Restore the context.
1441 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1442 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1443 scope_ = saved_scope;
1446 // Try block code. Sets up the exception handler chain.
1447 __ bind(&try_entry);
1448 __ PushTryHandler(StackHandler::CATCH, stmt->index());
1449 { TryCatch try_body(this);
1450 Visit(stmt->try_block());
1457 void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1458 Comment cmnt(masm_, "[ TryFinallyStatement");
1459 SetStatementPosition(stmt);
1460 // Try finally is compiled by setting up a try-handler on the stack while
1461 // executing the try body, and removing it again afterwards.
1463 // The try-finally construct can enter the finally block in three ways:
1464 // 1. By exiting the try-block normally. This removes the try-handler and
1465 // calls the finally block code before continuing.
1466 // 2. By exiting the try-block with a function-local control flow transfer
1467 // (break/continue/return). The site of the, e.g., break removes the
1468 // try handler and calls the finally block code before continuing
1469 // its outward control transfer.
1470 // 3. By exiting the try-block with a thrown exception.
1471 // This can happen in nested function calls. It traverses the try-handler
1472 // chain and consumes the try-handler entry before jumping to the
1473 // handler code. The handler code then calls the finally-block before
1474 // rethrowing the exception.
1476 // The finally block must assume a return address on top of the stack
1477 // (or in the link register on ARM chips) and a value (return value or
1478 // exception) in the result register (rax/eax/r0), both of which must
1479 // be preserved. The return address isn't GC-safe, so it should be
1480 // cooked before GC.
1481 Label try_entry, handler_entry, finally_entry;
1483 // Jump to try-handler setup and try-block code.
1485 __ bind(&handler_entry);
1486 handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1487 // Exception handler code. This code is only executed when an exception
1488 // is thrown. The exception is in the result register, and must be
1489 // preserved by the finally block. Call the finally block and then
1490 // rethrow the exception if it returns.
1491 __ Call(&finally_entry);
1492 __ Push(result_register());
1493 __ CallRuntime(Runtime::kReThrow, 1);
1495 // Finally block implementation.
1496 __ bind(&finally_entry);
1497 EnterFinallyBlock();
1498 { Finally finally_body(this);
1499 Visit(stmt->finally_block());
1501 ExitFinallyBlock(); // Return to the calling code.
1503 // Set up try handler.
1504 __ bind(&try_entry);
1505 __ PushTryHandler(StackHandler::FINALLY, stmt->index());
1506 { TryFinally try_body(this, &finally_entry);
1507 Visit(stmt->try_block());
1510 // Execute the finally block on the way out. Clobber the unpredictable
1511 // value in the result register with one that's safe for GC because the
1512 // finally block will unconditionally preserve the result register on the
1515 __ Call(&finally_entry);
1519 void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1520 #ifdef ENABLE_DEBUGGER_SUPPORT
1521 Comment cmnt(masm_, "[ DebuggerStatement");
1522 SetStatementPosition(stmt);
1525 // Ignore the return value.
1530 void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
1535 void FullCodeGenerator::VisitConditional(Conditional* expr) {
1536 Comment cmnt(masm_, "[ Conditional");
1537 Label true_case, false_case, done;
1538 VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1540 PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1541 __ bind(&true_case);
1542 SetExpressionPosition(expr->then_expression());
1543 if (context()->IsTest()) {
1544 const TestContext* for_test = TestContext::cast(context());
1545 VisitForControl(expr->then_expression(),
1546 for_test->true_label(),
1547 for_test->false_label(),
1550 VisitInDuplicateContext(expr->then_expression());
1554 PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1555 __ bind(&false_case);
1556 SetExpressionPosition(expr->else_expression());
1557 VisitInDuplicateContext(expr->else_expression());
1558 // If control flow falls through Visit, merge it with true case here.
1559 if (!context()->IsTest()) {
1565 void FullCodeGenerator::VisitLiteral(Literal* expr) {
1566 Comment cmnt(masm_, "[ Literal");
1567 context()->Plug(expr->value());
1571 void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
1572 Comment cmnt(masm_, "[ FunctionLiteral");
1574 // Build the function boilerplate and instantiate it.
1575 Handle<SharedFunctionInfo> function_info =
1576 Compiler::BuildFunctionInfo(expr, script());
1577 if (function_info.is_null()) {
1581 EmitNewClosure(function_info, expr->pretenure());
1585 void FullCodeGenerator::VisitNativeFunctionLiteral(
1586 NativeFunctionLiteral* expr) {
1587 Comment cmnt(masm_, "[ NativeFunctionLiteral");
1589 // Compute the function template for the native function.
1590 Handle<String> name = expr->name();
1591 v8::Handle<v8::FunctionTemplate> fun_template =
1592 expr->extension()->GetNativeFunctionTemplate(
1593 reinterpret_cast<v8::Isolate*>(isolate()), v8::Utils::ToLocal(name));
1594 ASSERT(!fun_template.IsEmpty());
1596 // Instantiate the function and create a shared function info from it.
1597 Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
1598 const int literals = fun->NumberOfLiterals();
1599 Handle<Code> code = Handle<Code>(fun->shared()->code());
1600 Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
1601 bool is_generator = false;
1602 Handle<SharedFunctionInfo> shared =
1603 isolate()->factory()->NewSharedFunctionInfo(name, literals, is_generator,
1604 code, Handle<ScopeInfo>(fun->shared()->scope_info()));
1605 shared->set_construct_stub(*construct_stub);
1607 // Copy the function data to the shared function info.
1608 shared->set_function_data(fun->shared()->function_data());
1609 int parameters = fun->shared()->formal_parameter_count();
1610 shared->set_formal_parameter_count(parameters);
1612 EmitNewClosure(shared, false);
1616 void FullCodeGenerator::VisitThrow(Throw* expr) {
1617 Comment cmnt(masm_, "[ Throw");
1618 VisitForStackValue(expr->exception());
1619 __ CallRuntime(Runtime::kThrow, 1);
1620 // Never returns here.
1624 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryCatch::Exit(
1626 int* context_length) {
1627 // The macros used here must preserve the result register.
1628 __ Drop(*stack_depth);
1635 bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1636 Expression* sub_expr;
1637 Handle<String> check;
1638 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1639 EmitLiteralCompareTypeof(expr, sub_expr, check);
1643 if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
1644 EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1648 if (expr->IsLiteralCompareNull(&sub_expr)) {
1649 EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1657 void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1658 DisallowHeapAllocation no_gc;
1659 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1661 // Iterate over the back edge table and patch every interrupt
1662 // call to an unconditional call to the replacement code.
1663 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1665 BackEdgeTable back_edges(unoptimized, &no_gc);
1666 for (uint32_t i = 0; i < back_edges.length(); i++) {
1667 if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1668 ASSERT_EQ(INTERRUPT, GetBackEdgeState(isolate,
1671 PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1675 unoptimized->set_back_edges_patched_for_osr(true);
1676 ASSERT(Verify(isolate, unoptimized, loop_nesting_level));
1680 void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1681 DisallowHeapAllocation no_gc;
1682 Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1684 // Iterate over the back edge table and revert the patched interrupt calls.
1685 ASSERT(unoptimized->back_edges_patched_for_osr());
1686 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1688 BackEdgeTable back_edges(unoptimized, &no_gc);
1689 for (uint32_t i = 0; i < back_edges.length(); i++) {
1690 if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1691 ASSERT_NE(INTERRUPT, GetBackEdgeState(isolate,
1694 PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1698 unoptimized->set_back_edges_patched_for_osr(false);
1699 unoptimized->set_allow_osr_at_loop_nesting_level(0);
1700 // Assert that none of the back edges are patched anymore.
1701 ASSERT(Verify(isolate, unoptimized, -1));
1705 void BackEdgeTable::AddStackCheck(Handle<Code> code, uint32_t pc_offset) {
1706 DisallowHeapAllocation no_gc;
1707 Isolate* isolate = code->GetIsolate();
1708 Address pc = code->instruction_start() + pc_offset;
1709 Code* patch = isolate->builtins()->builtin(Builtins::kOsrAfterStackCheck);
1710 PatchAt(*code, pc, OSR_AFTER_STACK_CHECK, patch);
1714 void BackEdgeTable::RemoveStackCheck(Handle<Code> code, uint32_t pc_offset) {
1715 DisallowHeapAllocation no_gc;
1716 Isolate* isolate = code->GetIsolate();
1717 Address pc = code->instruction_start() + pc_offset;
1719 if (OSR_AFTER_STACK_CHECK == GetBackEdgeState(isolate, *code, pc)) {
1720 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1721 PatchAt(*code, pc, ON_STACK_REPLACEMENT, patch);
1727 bool BackEdgeTable::Verify(Isolate* isolate,
1729 int loop_nesting_level) {
1730 DisallowHeapAllocation no_gc;
1731 BackEdgeTable back_edges(unoptimized, &no_gc);
1732 for (uint32_t i = 0; i < back_edges.length(); i++) {
1733 uint32_t loop_depth = back_edges.loop_depth(i);
1734 CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
1735 // Assert that all back edges for shallower loops (and only those)
1736 // have already been patched.
1737 CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
1738 GetBackEdgeState(isolate,
1740 back_edges.pc(i)) != INTERRUPT);
1750 } } // namespace v8::internal