1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "src/code-factory.h"
8 #include "src/codegen.h"
9 #include "src/compiler.h"
10 #include "src/debug.h"
11 #include "src/full-codegen.h"
12 #include "src/liveedit.h"
13 #include "src/macro-assembler.h"
14 #include "src/prettyprinter.h"
15 #include "src/scopeinfo.h"
16 #include "src/scopes.h"
17 #include "src/snapshot.h"
22 void BreakableStatementChecker::Check(Statement* stmt) {
27 void BreakableStatementChecker::Check(Expression* expr) {
32 void BreakableStatementChecker::VisitVariableDeclaration(
33 VariableDeclaration* decl) {
37 void BreakableStatementChecker::VisitFunctionDeclaration(
38 FunctionDeclaration* decl) {
42 void BreakableStatementChecker::VisitModuleDeclaration(
43 ModuleDeclaration* decl) {
47 void BreakableStatementChecker::VisitImportDeclaration(
48 ImportDeclaration* decl) {
52 void BreakableStatementChecker::VisitExportDeclaration(
53 ExportDeclaration* decl) {
57 void BreakableStatementChecker::VisitModuleLiteral(ModuleLiteral* module) {
61 void BreakableStatementChecker::VisitModuleVariable(ModuleVariable* module) {
65 void BreakableStatementChecker::VisitModulePath(ModulePath* module) {
69 void BreakableStatementChecker::VisitModuleUrl(ModuleUrl* module) {
73 void BreakableStatementChecker::VisitModuleStatement(ModuleStatement* stmt) {
77 void BreakableStatementChecker::VisitBlock(Block* stmt) {
81 void BreakableStatementChecker::VisitExpressionStatement(
82 ExpressionStatement* stmt) {
83 // Check if expression is breakable.
84 Visit(stmt->expression());
88 void BreakableStatementChecker::VisitEmptyStatement(EmptyStatement* stmt) {
92 void BreakableStatementChecker::VisitIfStatement(IfStatement* stmt) {
93 // If the condition is breakable the if statement is breakable.
94 Visit(stmt->condition());
98 void BreakableStatementChecker::VisitContinueStatement(
99 ContinueStatement* stmt) {
103 void BreakableStatementChecker::VisitBreakStatement(BreakStatement* stmt) {
107 void BreakableStatementChecker::VisitReturnStatement(ReturnStatement* stmt) {
108 // Return is breakable if the expression is.
109 Visit(stmt->expression());
113 void BreakableStatementChecker::VisitWithStatement(WithStatement* stmt) {
114 Visit(stmt->expression());
118 void BreakableStatementChecker::VisitSwitchStatement(SwitchStatement* stmt) {
119 // Switch statements breakable if the tag expression is.
124 void BreakableStatementChecker::VisitDoWhileStatement(DoWhileStatement* stmt) {
125 // Mark do while as breakable to avoid adding a break slot in front of it.
126 is_breakable_ = true;
130 void BreakableStatementChecker::VisitWhileStatement(WhileStatement* stmt) {
131 // Mark while statements breakable if the condition expression is.
136 void BreakableStatementChecker::VisitForStatement(ForStatement* stmt) {
137 // Mark for statements breakable if the condition expression is.
138 if (stmt->cond() != NULL) {
144 void BreakableStatementChecker::VisitForInStatement(ForInStatement* stmt) {
145 // Mark for in statements breakable if the enumerable expression is.
146 Visit(stmt->enumerable());
150 void BreakableStatementChecker::VisitForOfStatement(ForOfStatement* stmt) {
151 // For-of is breakable because of the next() call.
152 is_breakable_ = true;
156 void BreakableStatementChecker::VisitTryCatchStatement(
157 TryCatchStatement* stmt) {
158 // Mark try catch as breakable to avoid adding a break slot in front of it.
159 is_breakable_ = true;
163 void BreakableStatementChecker::VisitTryFinallyStatement(
164 TryFinallyStatement* stmt) {
165 // Mark try finally as breakable to avoid adding a break slot in front of it.
166 is_breakable_ = true;
170 void BreakableStatementChecker::VisitDebuggerStatement(
171 DebuggerStatement* stmt) {
172 // The debugger statement is breakable.
173 is_breakable_ = true;
177 void BreakableStatementChecker::VisitCaseClause(CaseClause* clause) {
181 void BreakableStatementChecker::VisitFunctionLiteral(FunctionLiteral* expr) {
185 void BreakableStatementChecker::VisitClassLiteral(ClassLiteral* expr) {
186 if (expr->extends() != NULL) {
187 Visit(expr->extends());
192 void BreakableStatementChecker::VisitNativeFunctionLiteral(
193 NativeFunctionLiteral* expr) {
197 void BreakableStatementChecker::VisitConditional(Conditional* expr) {
201 void BreakableStatementChecker::VisitVariableProxy(VariableProxy* expr) {
205 void BreakableStatementChecker::VisitLiteral(Literal* expr) {
209 void BreakableStatementChecker::VisitRegExpLiteral(RegExpLiteral* expr) {
213 void BreakableStatementChecker::VisitObjectLiteral(ObjectLiteral* expr) {
217 void BreakableStatementChecker::VisitArrayLiteral(ArrayLiteral* expr) {
221 void BreakableStatementChecker::VisitAssignment(Assignment* expr) {
222 // If assigning to a property (including a global property) the assignment is
224 VariableProxy* proxy = expr->target()->AsVariableProxy();
225 Property* prop = expr->target()->AsProperty();
226 if (prop != NULL || (proxy != NULL && proxy->var()->IsUnallocated())) {
227 is_breakable_ = true;
231 // Otherwise the assignment is breakable if the assigned value is.
232 Visit(expr->value());
236 void BreakableStatementChecker::VisitYield(Yield* expr) {
237 // Yield is breakable if the expression is.
238 Visit(expr->expression());
242 void BreakableStatementChecker::VisitThrow(Throw* expr) {
243 // Throw is breakable if the expression is.
244 Visit(expr->exception());
248 void BreakableStatementChecker::VisitProperty(Property* expr) {
249 // Property load is breakable.
250 is_breakable_ = true;
254 void BreakableStatementChecker::VisitCall(Call* expr) {
255 // Function calls both through IC and call stub are breakable.
256 is_breakable_ = true;
260 void BreakableStatementChecker::VisitCallNew(CallNew* expr) {
261 // Function calls through new are breakable.
262 is_breakable_ = true;
266 void BreakableStatementChecker::VisitCallRuntime(CallRuntime* expr) {
270 void BreakableStatementChecker::VisitUnaryOperation(UnaryOperation* expr) {
271 Visit(expr->expression());
275 void BreakableStatementChecker::VisitCountOperation(CountOperation* expr) {
276 Visit(expr->expression());
280 void BreakableStatementChecker::VisitBinaryOperation(BinaryOperation* expr) {
282 if (expr->op() != Token::AND &&
283 expr->op() != Token::OR) {
284 Visit(expr->right());
289 void BreakableStatementChecker::VisitCompareOperation(CompareOperation* expr) {
291 Visit(expr->right());
295 void BreakableStatementChecker::VisitThisFunction(ThisFunction* expr) {
299 void BreakableStatementChecker::VisitSuperReference(SuperReference* expr) {}
302 #define __ ACCESS_MASM(masm())
304 bool FullCodeGenerator::MakeCode(CompilationInfo* info) {
305 Isolate* isolate = info->isolate();
307 TimerEventScope<TimerEventCompileFullCode> timer(info->isolate());
309 Handle<Script> script = info->script();
310 if (!script->IsUndefined() && !script->source()->IsUndefined()) {
311 int len = String::cast(script->source())->length();
312 isolate->counters()->total_full_codegen_source_size()->Increment(len);
314 CodeGenerator::MakeCodePrologue(info, "full");
315 const int kInitialBufferSize = 4 * KB;
316 MacroAssembler masm(info->isolate(), NULL, kInitialBufferSize);
317 if (info->will_serialize()) masm.enable_serializer();
319 LOG_CODE_EVENT(isolate,
320 CodeStartLinePosInfoRecordEvent(masm.positions_recorder()));
322 FullCodeGenerator cgen(&masm, info);
324 if (cgen.HasStackOverflow()) {
325 DCHECK(!isolate->has_pending_exception());
328 unsigned table_offset = cgen.EmitBackEdgeTable();
330 Code::Flags flags = Code::ComputeFlags(Code::FUNCTION);
331 Handle<Code> code = CodeGenerator::MakeCodeEpilogue(&masm, flags, info);
332 code->set_optimizable(info->IsOptimizable() &&
333 !info->function()->dont_optimize() &&
334 info->function()->scope()->AllowsLazyCompilation());
335 cgen.PopulateDeoptimizationData(code);
336 cgen.PopulateTypeFeedbackInfo(code);
337 code->set_has_deoptimization_support(info->HasDeoptimizationSupport());
338 code->set_handler_table(*cgen.handler_table());
339 code->set_compiled_optimizable(info->IsOptimizable());
340 code->set_allow_osr_at_loop_nesting_level(0);
341 code->set_profiler_ticks(0);
342 code->set_back_edge_table_offset(table_offset);
343 CodeGenerator::PrintCode(code, info);
345 void* line_info = masm.positions_recorder()->DetachJITHandlerData();
346 LOG_CODE_EVENT(isolate, CodeEndLinePosInfoRecordEvent(*code, line_info));
351 unsigned FullCodeGenerator::EmitBackEdgeTable() {
352 // The back edge table consists of a length (in number of entries)
353 // field, and then a sequence of entries. Each entry is a pair of AST id
354 // and code-relative pc offset.
355 masm()->Align(kPointerSize);
356 unsigned offset = masm()->pc_offset();
357 unsigned length = back_edges_.length();
359 for (unsigned i = 0; i < length; ++i) {
360 __ dd(back_edges_[i].id.ToInt());
361 __ dd(back_edges_[i].pc);
362 __ dd(back_edges_[i].loop_depth);
368 void FullCodeGenerator::EnsureSlotContainsAllocationSite(int slot) {
369 Handle<FixedArray> vector = FeedbackVector();
370 if (!vector->get(slot)->IsAllocationSite()) {
371 Handle<AllocationSite> allocation_site =
372 isolate()->factory()->NewAllocationSite();
373 vector->set(slot, *allocation_site);
378 void FullCodeGenerator::PopulateDeoptimizationData(Handle<Code> code) {
379 // Fill in the deoptimization information.
380 DCHECK(info_->HasDeoptimizationSupport() || bailout_entries_.is_empty());
381 if (!info_->HasDeoptimizationSupport()) return;
382 int length = bailout_entries_.length();
383 Handle<DeoptimizationOutputData> data =
384 DeoptimizationOutputData::New(isolate(), length, TENURED);
385 for (int i = 0; i < length; i++) {
386 data->SetAstId(i, bailout_entries_[i].id);
387 data->SetPcAndState(i, Smi::FromInt(bailout_entries_[i].pc_and_state));
389 code->set_deoptimization_data(*data);
393 void FullCodeGenerator::PopulateTypeFeedbackInfo(Handle<Code> code) {
394 Handle<TypeFeedbackInfo> info = isolate()->factory()->NewTypeFeedbackInfo();
395 info->set_ic_total_count(ic_total_count_);
396 DCHECK(!isolate()->heap()->InNewSpace(*info));
397 code->set_type_feedback_info(*info);
401 void FullCodeGenerator::Initialize() {
402 InitializeAstVisitor(info_->zone());
403 // The generation of debug code must match between the snapshot code and the
404 // code that is generated later. This is assumed by the debugger when it is
405 // calculating PC offsets after generating a debug version of code. Therefore
406 // we disable the production of debug code in the full compiler if we are
407 // either generating a snapshot or we booted from a snapshot.
408 generate_debug_code_ = FLAG_debug_code &&
409 !masm_->serializer_enabled() &&
410 !Snapshot::HaveASnapshotToStartFrom();
411 masm_->set_emit_debug_code(generate_debug_code_);
412 masm_->set_predictable_code_size(true);
416 void FullCodeGenerator::PrepareForBailout(Expression* node, State state) {
417 PrepareForBailoutForId(node->id(), state);
421 void FullCodeGenerator::CallLoadIC(ContextualMode contextual_mode,
423 Handle<Code> ic = CodeFactory::LoadIC(isolate(), contextual_mode).code();
428 void FullCodeGenerator::CallStoreIC(TypeFeedbackId id) {
429 Handle<Code> ic = CodeFactory::StoreIC(isolate(), strict_mode()).code();
434 void FullCodeGenerator::RecordJSReturnSite(Call* call) {
435 // We record the offset of the function return so we can rebuild the frame
436 // if the function was inlined, i.e., this is the return address in the
437 // inlined function's frame.
439 // The state is ignored. We defensively set it to TOS_REG, which is the
440 // real state of the unoptimized code at the return site.
441 PrepareForBailoutForId(call->ReturnId(), TOS_REG);
443 // In debug builds, mark the return so we can verify that this function
445 DCHECK(!call->return_is_recorded_);
446 call->return_is_recorded_ = true;
451 void FullCodeGenerator::PrepareForBailoutForId(BailoutId id, State state) {
452 // There's no need to prepare this code for bailouts from already optimized
453 // code or code that can't be optimized.
454 if (!info_->HasDeoptimizationSupport()) return;
455 unsigned pc_and_state =
456 StateField::encode(state) | PcField::encode(masm_->pc_offset());
457 DCHECK(Smi::IsValid(pc_and_state));
459 for (int i = 0; i < bailout_entries_.length(); ++i) {
460 DCHECK(bailout_entries_[i].id != id);
463 BailoutEntry entry = { id, pc_and_state };
464 bailout_entries_.Add(entry, zone());
468 void FullCodeGenerator::RecordBackEdge(BailoutId ast_id) {
469 // The pc offset does not need to be encoded and packed together with a state.
470 DCHECK(masm_->pc_offset() > 0);
471 DCHECK(loop_depth() > 0);
472 uint8_t depth = Min(loop_depth(), Code::kMaxLoopNestingMarker);
473 BackEdgeEntry entry =
474 { ast_id, static_cast<unsigned>(masm_->pc_offset()), depth };
475 back_edges_.Add(entry, zone());
479 bool FullCodeGenerator::ShouldInlineSmiCase(Token::Value op) {
480 // Inline smi case inside loops, but not division and modulo which
481 // are too complicated and take up too much space.
482 if (op == Token::DIV ||op == Token::MOD) return false;
483 if (FLAG_always_inline_smi_code) return true;
484 return loop_depth_ > 0;
488 void FullCodeGenerator::EffectContext::Plug(Register reg) const {
492 void FullCodeGenerator::AccumulatorValueContext::Plug(Register reg) const {
493 __ Move(result_register(), reg);
497 void FullCodeGenerator::StackValueContext::Plug(Register reg) const {
502 void FullCodeGenerator::TestContext::Plug(Register reg) const {
503 // For simplicity we always test the accumulator register.
504 __ Move(result_register(), reg);
505 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
506 codegen()->DoTest(this);
510 void FullCodeGenerator::EffectContext::PlugTOS() const {
515 void FullCodeGenerator::AccumulatorValueContext::PlugTOS() const {
516 __ Pop(result_register());
520 void FullCodeGenerator::StackValueContext::PlugTOS() const {
524 void FullCodeGenerator::TestContext::PlugTOS() const {
525 // For simplicity we always test the accumulator register.
526 __ Pop(result_register());
527 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
528 codegen()->DoTest(this);
532 void FullCodeGenerator::EffectContext::PrepareTest(
533 Label* materialize_true,
534 Label* materialize_false,
537 Label** fall_through) const {
538 // In an effect context, the true and the false case branch to the
540 *if_true = *if_false = *fall_through = materialize_true;
544 void FullCodeGenerator::AccumulatorValueContext::PrepareTest(
545 Label* materialize_true,
546 Label* materialize_false,
549 Label** fall_through) const {
550 *if_true = *fall_through = materialize_true;
551 *if_false = materialize_false;
555 void FullCodeGenerator::StackValueContext::PrepareTest(
556 Label* materialize_true,
557 Label* materialize_false,
560 Label** fall_through) const {
561 *if_true = *fall_through = materialize_true;
562 *if_false = materialize_false;
566 void FullCodeGenerator::TestContext::PrepareTest(
567 Label* materialize_true,
568 Label* materialize_false,
571 Label** fall_through) const {
572 *if_true = true_label_;
573 *if_false = false_label_;
574 *fall_through = fall_through_;
578 void FullCodeGenerator::DoTest(const TestContext* context) {
579 DoTest(context->condition(),
580 context->true_label(),
581 context->false_label(),
582 context->fall_through());
586 void FullCodeGenerator::AllocateModules(ZoneList<Declaration*>* declarations) {
587 DCHECK(scope_->is_global_scope());
589 for (int i = 0; i < declarations->length(); i++) {
590 ModuleDeclaration* declaration = declarations->at(i)->AsModuleDeclaration();
591 if (declaration != NULL) {
592 ModuleLiteral* module = declaration->module()->AsModuleLiteral();
593 if (module != NULL) {
594 Comment cmnt(masm_, "[ Link nested modules");
595 Scope* scope = module->body()->scope();
596 Interface* interface = scope->interface();
597 DCHECK(interface->IsModule() && interface->IsFrozen());
599 interface->Allocate(scope->module_var()->index());
601 // Set up module context.
602 DCHECK(scope->interface()->Index() >= 0);
603 __ Push(Smi::FromInt(scope->interface()->Index()));
604 __ Push(scope->GetScopeInfo());
605 __ CallRuntime(Runtime::kPushModuleContext, 2);
606 StoreToFrameField(StandardFrameConstants::kContextOffset,
609 AllocateModules(scope->declarations());
611 // Pop module context.
612 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
613 // Update local stack frame context field.
614 StoreToFrameField(StandardFrameConstants::kContextOffset,
622 // Modules have their own local scope, represented by their own context.
623 // Module instance objects have an accessor for every export that forwards
624 // access to the respective slot from the module's context. (Exports that are
625 // modules themselves, however, are simple data properties.)
627 // All modules have a _hosting_ scope/context, which (currently) is the
628 // (innermost) enclosing global scope. To deal with recursion, nested modules
629 // are hosted by the same scope as global ones.
631 // For every (global or nested) module literal, the hosting context has an
632 // internal slot that points directly to the respective module context. This
633 // enables quick access to (statically resolved) module members by 2-dimensional
634 // access through the hosting context. For example,
638 // module B { let y; }
640 // module C { let z; }
642 // allocates contexts as follows:
644 // [header| .A | .B | .C | A | C ] (global)
646 // | | +-- [header| z ] (module)
648 // | +------- [header| y ] (module)
650 // +------------ [header| x | B ] (module)
652 // Here, .A, .B, .C are the internal slots pointing to the hosted module
653 // contexts, whereas A, B, C hold the actual instance objects (note that every
654 // module context also points to the respective instance object through its
655 // extension slot in the header).
657 // To deal with arbitrary recursion and aliases between modules,
658 // they are created and initialized in several stages. Each stage applies to
659 // all modules in the hosting global scope, including nested ones.
661 // 1. Allocate: for each module _literal_, allocate the module contexts and
662 // respective instance object and wire them up. This happens in the
663 // PushModuleContext runtime function, as generated by AllocateModules
664 // (invoked by VisitDeclarations in the hosting scope).
666 // 2. Bind: for each module _declaration_ (i.e. literals as well as aliases),
667 // assign the respective instance object to respective local variables. This
668 // happens in VisitModuleDeclaration, and uses the instance objects created
669 // in the previous stage.
670 // For each module _literal_, this phase also constructs a module descriptor
671 // for the next stage. This happens in VisitModuleLiteral.
673 // 3. Populate: invoke the DeclareModules runtime function to populate each
674 // _instance_ object with accessors for it exports. This is generated by
675 // DeclareModules (invoked by VisitDeclarations in the hosting scope again),
676 // and uses the descriptors generated in the previous stage.
678 // 4. Initialize: execute the module bodies (and other code) in sequence. This
679 // happens by the separate statements generated for module bodies. To reenter
680 // the module scopes properly, the parser inserted ModuleStatements.
682 void FullCodeGenerator::VisitDeclarations(
683 ZoneList<Declaration*>* declarations) {
684 Handle<FixedArray> saved_modules = modules_;
685 int saved_module_index = module_index_;
686 ZoneList<Handle<Object> >* saved_globals = globals_;
687 ZoneList<Handle<Object> > inner_globals(10, zone());
688 globals_ = &inner_globals;
690 if (scope_->num_modules() != 0) {
691 // This is a scope hosting modules. Allocate a descriptor array to pass
692 // to the runtime for initialization.
693 Comment cmnt(masm_, "[ Allocate modules");
694 DCHECK(scope_->is_global_scope());
696 isolate()->factory()->NewFixedArray(scope_->num_modules(), TENURED);
699 // Generate code for allocating all modules, including nested ones.
700 // The allocated contexts are stored in internal variables in this scope.
701 AllocateModules(declarations);
704 AstVisitor::VisitDeclarations(declarations);
706 if (scope_->num_modules() != 0) {
707 // Initialize modules from descriptor array.
708 DCHECK(module_index_ == modules_->length());
709 DeclareModules(modules_);
710 modules_ = saved_modules;
711 module_index_ = saved_module_index;
714 if (!globals_->is_empty()) {
715 // Invoke the platform-dependent code generator to do the actual
716 // declaration of the global functions and variables.
717 Handle<FixedArray> array =
718 isolate()->factory()->NewFixedArray(globals_->length(), TENURED);
719 for (int i = 0; i < globals_->length(); ++i)
720 array->set(i, *globals_->at(i));
721 DeclareGlobals(array);
724 globals_ = saved_globals;
728 void FullCodeGenerator::VisitModuleLiteral(ModuleLiteral* module) {
729 Block* block = module->body();
730 Scope* saved_scope = scope();
731 scope_ = block->scope();
732 Interface* interface = scope_->interface();
734 Comment cmnt(masm_, "[ ModuleLiteral");
735 SetStatementPosition(block);
737 DCHECK(!modules_.is_null());
738 DCHECK(module_index_ < modules_->length());
739 int index = module_index_++;
741 // Set up module context.
742 DCHECK(interface->Index() >= 0);
743 __ Push(Smi::FromInt(interface->Index()));
744 __ Push(Smi::FromInt(0));
745 __ CallRuntime(Runtime::kPushModuleContext, 2);
746 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
749 Comment cmnt(masm_, "[ Declarations");
750 VisitDeclarations(scope_->declarations());
753 // Populate the module description.
754 Handle<ModuleInfo> description =
755 ModuleInfo::Create(isolate(), interface, scope_);
756 modules_->set(index, *description);
758 scope_ = saved_scope;
759 // Pop module context.
760 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
761 // Update local stack frame context field.
762 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
766 void FullCodeGenerator::VisitModuleVariable(ModuleVariable* module) {
768 // The instance object is resolved statically through the module's interface.
772 void FullCodeGenerator::VisitModulePath(ModulePath* module) {
774 // The instance object is resolved statically through the module's interface.
778 void FullCodeGenerator::VisitModuleUrl(ModuleUrl* module) {
779 // TODO(rossberg): dummy allocation for now.
780 Scope* scope = module->body()->scope();
781 Interface* interface = scope_->interface();
783 DCHECK(interface->IsModule() && interface->IsFrozen());
784 DCHECK(!modules_.is_null());
785 DCHECK(module_index_ < modules_->length());
786 interface->Allocate(scope->module_var()->index());
787 int index = module_index_++;
789 Handle<ModuleInfo> description =
790 ModuleInfo::Create(isolate(), interface, scope_);
791 modules_->set(index, *description);
795 int FullCodeGenerator::DeclareGlobalsFlags() {
796 DCHECK(DeclareGlobalsStrictMode::is_valid(strict_mode()));
797 return DeclareGlobalsEvalFlag::encode(is_eval()) |
798 DeclareGlobalsNativeFlag::encode(is_native()) |
799 DeclareGlobalsStrictMode::encode(strict_mode());
803 void FullCodeGenerator::SetFunctionPosition(FunctionLiteral* fun) {
804 CodeGenerator::RecordPositions(masm_, fun->start_position());
808 void FullCodeGenerator::SetReturnPosition(FunctionLiteral* fun) {
809 CodeGenerator::RecordPositions(masm_, fun->end_position() - 1);
813 void FullCodeGenerator::SetStatementPosition(Statement* stmt) {
814 if (!info_->is_debug()) {
815 CodeGenerator::RecordPositions(masm_, stmt->position());
817 // Check if the statement will be breakable without adding a debug break
819 BreakableStatementChecker checker(zone());
821 // Record the statement position right here if the statement is not
822 // breakable. For breakable statements the actual recording of the
823 // position will be postponed to the breakable code (typically an IC).
824 bool position_recorded = CodeGenerator::RecordPositions(
825 masm_, stmt->position(), !checker.is_breakable());
826 // If the position recording did record a new position generate a debug
827 // break slot to make the statement breakable.
828 if (position_recorded) {
829 DebugCodegen::GenerateSlot(masm_);
835 void FullCodeGenerator::VisitSuperReference(SuperReference* super) {
836 __ CallRuntime(Runtime::kThrowUnsupportedSuperError, 0);
840 void FullCodeGenerator::SetExpressionPosition(Expression* expr) {
841 if (!info_->is_debug()) {
842 CodeGenerator::RecordPositions(masm_, expr->position());
844 // Check if the expression will be breakable without adding a debug break
846 BreakableStatementChecker checker(zone());
848 // Record a statement position right here if the expression is not
849 // breakable. For breakable expressions the actual recording of the
850 // position will be postponed to the breakable code (typically an IC).
851 // NOTE this will record a statement position for something which might
852 // not be a statement. As stepping in the debugger will only stop at
853 // statement positions this is used for e.g. the condition expression of
855 bool position_recorded = CodeGenerator::RecordPositions(
856 masm_, expr->position(), !checker.is_breakable());
857 // If the position recording did record a new position generate a debug
858 // break slot to make the statement breakable.
859 if (position_recorded) {
860 DebugCodegen::GenerateSlot(masm_);
866 void FullCodeGenerator::SetSourcePosition(int pos) {
867 if (pos != RelocInfo::kNoPosition) {
868 masm_->positions_recorder()->RecordPosition(pos);
869 masm_->positions_recorder()->WriteRecordedPositions();
874 // Lookup table for code generators for special runtime calls which are
876 #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize) \
877 &FullCodeGenerator::Emit##Name,
879 const FullCodeGenerator::InlineFunctionGenerator
880 FullCodeGenerator::kInlineFunctionGenerators[] = {
881 INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
883 #undef INLINE_FUNCTION_GENERATOR_ADDRESS
886 FullCodeGenerator::InlineFunctionGenerator
887 FullCodeGenerator::FindInlineFunctionGenerator(Runtime::FunctionId id) {
889 static_cast<int>(id) - static_cast<int>(Runtime::kFirstInlineFunction);
890 DCHECK(lookup_index >= 0);
891 DCHECK(static_cast<size_t>(lookup_index) <
892 arraysize(kInlineFunctionGenerators));
893 return kInlineFunctionGenerators[lookup_index];
897 void FullCodeGenerator::EmitInlineRuntimeCall(CallRuntime* expr) {
898 const Runtime::Function* function = expr->function();
899 DCHECK(function != NULL);
900 DCHECK(function->intrinsic_type == Runtime::INLINE);
901 InlineFunctionGenerator generator =
902 FindInlineFunctionGenerator(function->function_id);
903 ((*this).*(generator))(expr);
907 void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
908 ZoneList<Expression*>* args = expr->arguments();
909 DCHECK(args->length() == 2);
910 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
914 void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
915 ZoneList<Expression*>* args = expr->arguments();
916 DCHECK(args->length() == 2);
917 EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
921 void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
922 context()->Plug(handle(Smi::FromInt(0), isolate()));
926 void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
927 switch (expr->op()) {
929 return VisitComma(expr);
932 return VisitLogicalExpression(expr);
934 return VisitArithmeticExpression(expr);
939 void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
940 if (context()->IsEffect()) {
941 VisitForEffect(expr);
942 } else if (context()->IsAccumulatorValue()) {
943 VisitForAccumulatorValue(expr);
944 } else if (context()->IsStackValue()) {
945 VisitForStackValue(expr);
946 } else if (context()->IsTest()) {
947 const TestContext* test = TestContext::cast(context());
948 VisitForControl(expr, test->true_label(), test->false_label(),
949 test->fall_through());
954 void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
955 Comment cmnt(masm_, "[ Comma");
956 VisitForEffect(expr->left());
957 VisitInDuplicateContext(expr->right());
961 void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
962 bool is_logical_and = expr->op() == Token::AND;
963 Comment cmnt(masm_, is_logical_and ? "[ Logical AND" : "[ Logical OR");
964 Expression* left = expr->left();
965 Expression* right = expr->right();
966 BailoutId right_id = expr->RightId();
969 if (context()->IsTest()) {
971 const TestContext* test = TestContext::cast(context());
972 if (is_logical_and) {
973 VisitForControl(left, &eval_right, test->false_label(), &eval_right);
975 VisitForControl(left, test->true_label(), &eval_right, &eval_right);
977 PrepareForBailoutForId(right_id, NO_REGISTERS);
978 __ bind(&eval_right);
980 } else if (context()->IsAccumulatorValue()) {
981 VisitForAccumulatorValue(left);
982 // We want the value in the accumulator for the test, and on the stack in
984 __ Push(result_register());
985 Label discard, restore;
986 if (is_logical_and) {
987 DoTest(left, &discard, &restore, &restore);
989 DoTest(left, &restore, &discard, &restore);
992 __ Pop(result_register());
996 PrepareForBailoutForId(right_id, NO_REGISTERS);
998 } else if (context()->IsStackValue()) {
999 VisitForAccumulatorValue(left);
1000 // We want the value in the accumulator for the test, and on the stack in
1002 __ Push(result_register());
1004 if (is_logical_and) {
1005 DoTest(left, &discard, &done, &discard);
1007 DoTest(left, &done, &discard, &discard);
1011 PrepareForBailoutForId(right_id, NO_REGISTERS);
1014 DCHECK(context()->IsEffect());
1016 if (is_logical_and) {
1017 VisitForControl(left, &eval_right, &done, &eval_right);
1019 VisitForControl(left, &done, &eval_right, &eval_right);
1021 PrepareForBailoutForId(right_id, NO_REGISTERS);
1022 __ bind(&eval_right);
1025 VisitInDuplicateContext(right);
1030 void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
1031 Token::Value op = expr->op();
1032 Comment cmnt(masm_, "[ ArithmeticExpression");
1033 Expression* left = expr->left();
1034 Expression* right = expr->right();
1035 OverwriteMode mode =
1036 left->ResultOverwriteAllowed()
1038 : (right->ResultOverwriteAllowed() ? OVERWRITE_RIGHT : NO_OVERWRITE);
1040 VisitForStackValue(left);
1041 VisitForAccumulatorValue(right);
1043 SetSourcePosition(expr->position());
1044 if (ShouldInlineSmiCase(op)) {
1045 EmitInlineSmiBinaryOp(expr, op, mode, left, right);
1047 EmitBinaryOp(expr, op, mode);
1052 void FullCodeGenerator::VisitBlock(Block* stmt) {
1053 Comment cmnt(masm_, "[ Block");
1054 NestedBlock nested_block(this, stmt);
1055 SetStatementPosition(stmt);
1057 Scope* saved_scope = scope();
1058 // Push a block context when entering a block with block scoped variables.
1059 if (stmt->scope() == NULL) {
1060 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1062 scope_ = stmt->scope();
1063 DCHECK(!scope_->is_module_scope());
1064 { Comment cmnt(masm_, "[ Extend block context");
1065 __ Push(scope_->GetScopeInfo());
1066 PushFunctionArgumentForContextAllocation();
1067 __ CallRuntime(Runtime::kPushBlockContext, 2);
1069 // Replace the context stored in the frame.
1070 StoreToFrameField(StandardFrameConstants::kContextOffset,
1071 context_register());
1072 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1074 { Comment cmnt(masm_, "[ Declarations");
1075 VisitDeclarations(scope_->declarations());
1076 PrepareForBailoutForId(stmt->DeclsId(), NO_REGISTERS);
1080 VisitStatements(stmt->statements());
1081 scope_ = saved_scope;
1082 __ bind(nested_block.break_label());
1084 // Pop block context if necessary.
1085 if (stmt->scope() != NULL) {
1086 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1087 // Update local stack frame context field.
1088 StoreToFrameField(StandardFrameConstants::kContextOffset,
1089 context_register());
1091 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1095 void FullCodeGenerator::VisitModuleStatement(ModuleStatement* stmt) {
1096 Comment cmnt(masm_, "[ Module context");
1098 __ Push(Smi::FromInt(stmt->proxy()->interface()->Index()));
1099 __ Push(Smi::FromInt(0));
1100 __ CallRuntime(Runtime::kPushModuleContext, 2);
1102 StandardFrameConstants::kContextOffset, context_register());
1104 Scope* saved_scope = scope_;
1105 scope_ = stmt->body()->scope();
1106 VisitStatements(stmt->body()->statements());
1107 scope_ = saved_scope;
1108 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1109 // Update local stack frame context field.
1110 StoreToFrameField(StandardFrameConstants::kContextOffset,
1111 context_register());
1115 void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
1116 Comment cmnt(masm_, "[ ExpressionStatement");
1117 SetStatementPosition(stmt);
1118 VisitForEffect(stmt->expression());
1122 void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
1123 Comment cmnt(masm_, "[ EmptyStatement");
1124 SetStatementPosition(stmt);
1128 void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
1129 Comment cmnt(masm_, "[ IfStatement");
1130 SetStatementPosition(stmt);
1131 Label then_part, else_part, done;
1133 if (stmt->HasElseStatement()) {
1134 VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
1135 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1136 __ bind(&then_part);
1137 Visit(stmt->then_statement());
1140 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1141 __ bind(&else_part);
1142 Visit(stmt->else_statement());
1144 VisitForControl(stmt->condition(), &then_part, &done, &then_part);
1145 PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1146 __ bind(&then_part);
1147 Visit(stmt->then_statement());
1149 PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1152 PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
1156 void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
1157 Comment cmnt(masm_, "[ ContinueStatement");
1158 SetStatementPosition(stmt);
1159 NestedStatement* current = nesting_stack_;
1160 int stack_depth = 0;
1161 int context_length = 0;
1162 // When continuing, we clobber the unpredictable value in the accumulator
1163 // with one that's safe for GC. If we hit an exit from the try block of
1164 // try...finally on our way out, we will unconditionally preserve the
1165 // accumulator on the stack.
1167 while (!current->IsContinueTarget(stmt->target())) {
1168 current = current->Exit(&stack_depth, &context_length);
1170 __ Drop(stack_depth);
1171 if (context_length > 0) {
1172 while (context_length > 0) {
1173 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1176 StoreToFrameField(StandardFrameConstants::kContextOffset,
1177 context_register());
1180 __ jmp(current->AsIteration()->continue_label());
1184 void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
1185 Comment cmnt(masm_, "[ BreakStatement");
1186 SetStatementPosition(stmt);
1187 NestedStatement* current = nesting_stack_;
1188 int stack_depth = 0;
1189 int context_length = 0;
1190 // When breaking, we clobber the unpredictable value in the accumulator
1191 // with one that's safe for GC. If we hit an exit from the try block of
1192 // try...finally on our way out, we will unconditionally preserve the
1193 // accumulator on the stack.
1195 while (!current->IsBreakTarget(stmt->target())) {
1196 current = current->Exit(&stack_depth, &context_length);
1198 __ Drop(stack_depth);
1199 if (context_length > 0) {
1200 while (context_length > 0) {
1201 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1204 StoreToFrameField(StandardFrameConstants::kContextOffset,
1205 context_register());
1208 __ jmp(current->AsBreakable()->break_label());
1212 void FullCodeGenerator::EmitUnwindBeforeReturn() {
1213 NestedStatement* current = nesting_stack_;
1214 int stack_depth = 0;
1215 int context_length = 0;
1216 while (current != NULL) {
1217 current = current->Exit(&stack_depth, &context_length);
1219 __ Drop(stack_depth);
1223 void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
1224 Comment cmnt(masm_, "[ ReturnStatement");
1225 SetStatementPosition(stmt);
1226 Expression* expr = stmt->expression();
1227 VisitForAccumulatorValue(expr);
1228 EmitUnwindBeforeReturn();
1229 EmitReturnSequence();
1233 void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
1234 Comment cmnt(masm_, "[ WithStatement");
1235 SetStatementPosition(stmt);
1237 VisitForStackValue(stmt->expression());
1238 PushFunctionArgumentForContextAllocation();
1239 __ CallRuntime(Runtime::kPushWithContext, 2);
1240 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1242 Scope* saved_scope = scope();
1243 scope_ = stmt->scope();
1244 { WithOrCatch body(this);
1245 Visit(stmt->statement());
1247 scope_ = saved_scope;
1250 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1251 // Update local stack frame context field.
1252 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1256 void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
1257 Comment cmnt(masm_, "[ DoWhileStatement");
1258 SetStatementPosition(stmt);
1259 Label body, book_keeping;
1261 Iteration loop_statement(this, stmt);
1262 increment_loop_depth();
1265 Visit(stmt->body());
1267 // Record the position of the do while condition and make sure it is
1268 // possible to break on the condition.
1269 __ bind(loop_statement.continue_label());
1270 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1271 SetExpressionPosition(stmt->cond());
1272 VisitForControl(stmt->cond(),
1274 loop_statement.break_label(),
1277 // Check stack before looping.
1278 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1279 __ bind(&book_keeping);
1280 EmitBackEdgeBookkeeping(stmt, &body);
1283 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1284 __ bind(loop_statement.break_label());
1285 decrement_loop_depth();
1289 void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
1290 Comment cmnt(masm_, "[ WhileStatement");
1293 Iteration loop_statement(this, stmt);
1294 increment_loop_depth();
1298 SetExpressionPosition(stmt->cond());
1299 VisitForControl(stmt->cond(),
1301 loop_statement.break_label(),
1304 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1306 Visit(stmt->body());
1308 __ bind(loop_statement.continue_label());
1310 // Check stack before looping.
1311 EmitBackEdgeBookkeeping(stmt, &loop);
1314 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1315 __ bind(loop_statement.break_label());
1316 decrement_loop_depth();
1320 void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1321 Comment cmnt(masm_, "[ ForStatement");
1324 Iteration loop_statement(this, stmt);
1326 // Set statement position for a break slot before entering the for-body.
1327 SetStatementPosition(stmt);
1329 if (stmt->init() != NULL) {
1330 Visit(stmt->init());
1333 increment_loop_depth();
1334 // Emit the test at the bottom of the loop (even if empty).
1337 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1339 Visit(stmt->body());
1341 PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1342 __ bind(loop_statement.continue_label());
1343 if (stmt->next() != NULL) {
1344 Visit(stmt->next());
1347 // Emit the statement position here as this is where the for
1348 // statement code starts.
1349 SetStatementPosition(stmt);
1351 // Check stack before looping.
1352 EmitBackEdgeBookkeeping(stmt, &body);
1355 if (stmt->cond() != NULL) {
1356 VisitForControl(stmt->cond(),
1358 loop_statement.break_label(),
1359 loop_statement.break_label());
1364 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1365 __ bind(loop_statement.break_label());
1366 decrement_loop_depth();
1370 void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1371 Comment cmnt(masm_, "[ TryCatchStatement");
1372 SetStatementPosition(stmt);
1373 // The try block adds a handler to the exception handler chain before
1374 // entering, and removes it again when exiting normally. If an exception
1375 // is thrown during execution of the try block, the handler is consumed
1376 // and control is passed to the catch block with the exception in the
1379 Label try_entry, handler_entry, exit;
1381 __ bind(&handler_entry);
1382 handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1383 // Exception handler code, the exception is in the result register.
1384 // Extend the context before executing the catch block.
1385 { Comment cmnt(masm_, "[ Extend catch context");
1386 __ Push(stmt->variable()->name());
1387 __ Push(result_register());
1388 PushFunctionArgumentForContextAllocation();
1389 __ CallRuntime(Runtime::kPushCatchContext, 3);
1390 StoreToFrameField(StandardFrameConstants::kContextOffset,
1391 context_register());
1394 Scope* saved_scope = scope();
1395 scope_ = stmt->scope();
1396 DCHECK(scope_->declarations()->is_empty());
1397 { WithOrCatch catch_body(this);
1398 Visit(stmt->catch_block());
1400 // Restore the context.
1401 LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1402 StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1403 scope_ = saved_scope;
1406 // Try block code. Sets up the exception handler chain.
1407 __ bind(&try_entry);
1408 __ PushTryHandler(StackHandler::CATCH, stmt->index());
1409 { TryCatch try_body(this);
1410 Visit(stmt->try_block());
1417 void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1418 Comment cmnt(masm_, "[ TryFinallyStatement");
1419 SetStatementPosition(stmt);
1420 // Try finally is compiled by setting up a try-handler on the stack while
1421 // executing the try body, and removing it again afterwards.
1423 // The try-finally construct can enter the finally block in three ways:
1424 // 1. By exiting the try-block normally. This removes the try-handler and
1425 // calls the finally block code before continuing.
1426 // 2. By exiting the try-block with a function-local control flow transfer
1427 // (break/continue/return). The site of the, e.g., break removes the
1428 // try handler and calls the finally block code before continuing
1429 // its outward control transfer.
1430 // 3. By exiting the try-block with a thrown exception.
1431 // This can happen in nested function calls. It traverses the try-handler
1432 // chain and consumes the try-handler entry before jumping to the
1433 // handler code. The handler code then calls the finally-block before
1434 // rethrowing the exception.
1436 // The finally block must assume a return address on top of the stack
1437 // (or in the link register on ARM chips) and a value (return value or
1438 // exception) in the result register (rax/eax/r0), both of which must
1439 // be preserved. The return address isn't GC-safe, so it should be
1440 // cooked before GC.
1441 Label try_entry, handler_entry, finally_entry;
1443 // Jump to try-handler setup and try-block code.
1445 __ bind(&handler_entry);
1446 handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1447 // Exception handler code. This code is only executed when an exception
1448 // is thrown. The exception is in the result register, and must be
1449 // preserved by the finally block. Call the finally block and then
1450 // rethrow the exception if it returns.
1451 __ Call(&finally_entry);
1452 __ Push(result_register());
1453 __ CallRuntime(Runtime::kReThrow, 1);
1455 // Finally block implementation.
1456 __ bind(&finally_entry);
1457 EnterFinallyBlock();
1458 { Finally finally_body(this);
1459 Visit(stmt->finally_block());
1461 ExitFinallyBlock(); // Return to the calling code.
1463 // Set up try handler.
1464 __ bind(&try_entry);
1465 __ PushTryHandler(StackHandler::FINALLY, stmt->index());
1466 { TryFinally try_body(this, &finally_entry);
1467 Visit(stmt->try_block());
1470 // Execute the finally block on the way out. Clobber the unpredictable
1471 // value in the result register with one that's safe for GC because the
1472 // finally block will unconditionally preserve the result register on the
1475 __ Call(&finally_entry);
1479 void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1480 Comment cmnt(masm_, "[ DebuggerStatement");
1481 SetStatementPosition(stmt);
1484 // Ignore the return value.
1486 PrepareForBailoutForId(stmt->DebugBreakId(), NO_REGISTERS);
1490 void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
1495 void FullCodeGenerator::VisitConditional(Conditional* expr) {
1496 Comment cmnt(masm_, "[ Conditional");
1497 Label true_case, false_case, done;
1498 VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1500 PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1501 __ bind(&true_case);
1502 SetExpressionPosition(expr->then_expression());
1503 if (context()->IsTest()) {
1504 const TestContext* for_test = TestContext::cast(context());
1505 VisitForControl(expr->then_expression(),
1506 for_test->true_label(),
1507 for_test->false_label(),
1510 VisitInDuplicateContext(expr->then_expression());
1514 PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1515 __ bind(&false_case);
1516 SetExpressionPosition(expr->else_expression());
1517 VisitInDuplicateContext(expr->else_expression());
1518 // If control flow falls through Visit, merge it with true case here.
1519 if (!context()->IsTest()) {
1525 void FullCodeGenerator::VisitLiteral(Literal* expr) {
1526 Comment cmnt(masm_, "[ Literal");
1527 context()->Plug(expr->value());
1531 void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
1532 Comment cmnt(masm_, "[ FunctionLiteral");
1534 // Build the function boilerplate and instantiate it.
1535 Handle<SharedFunctionInfo> function_info =
1536 Compiler::BuildFunctionInfo(expr, script(), info_);
1537 if (function_info.is_null()) {
1541 EmitNewClosure(function_info, expr->pretenure());
1545 void FullCodeGenerator::VisitClassLiteral(ClassLiteral* expr) {
1546 // TODO(arv): Implement
1547 Comment cmnt(masm_, "[ ClassLiteral");
1548 if (expr->extends() != NULL) {
1549 VisitForEffect(expr->extends());
1551 context()->Plug(isolate()->factory()->undefined_value());
1555 void FullCodeGenerator::VisitNativeFunctionLiteral(
1556 NativeFunctionLiteral* expr) {
1557 Comment cmnt(masm_, "[ NativeFunctionLiteral");
1559 // Compute the function template for the native function.
1560 Handle<String> name = expr->name();
1561 v8::Handle<v8::FunctionTemplate> fun_template =
1562 expr->extension()->GetNativeFunctionTemplate(
1563 reinterpret_cast<v8::Isolate*>(isolate()), v8::Utils::ToLocal(name));
1564 DCHECK(!fun_template.IsEmpty());
1566 // Instantiate the function and create a shared function info from it.
1567 Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
1568 const int literals = fun->NumberOfLiterals();
1569 Handle<Code> code = Handle<Code>(fun->shared()->code());
1570 Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
1571 Handle<SharedFunctionInfo> shared =
1572 isolate()->factory()->NewSharedFunctionInfo(
1573 name, literals, FunctionKind::kNormalFunction, code,
1574 Handle<ScopeInfo>(fun->shared()->scope_info()),
1575 Handle<TypeFeedbackVector>(fun->shared()->feedback_vector()));
1576 shared->set_construct_stub(*construct_stub);
1578 // Copy the function data to the shared function info.
1579 shared->set_function_data(fun->shared()->function_data());
1580 int parameters = fun->shared()->formal_parameter_count();
1581 shared->set_formal_parameter_count(parameters);
1583 EmitNewClosure(shared, false);
1587 void FullCodeGenerator::VisitThrow(Throw* expr) {
1588 Comment cmnt(masm_, "[ Throw");
1589 VisitForStackValue(expr->exception());
1590 __ CallRuntime(Runtime::kThrow, 1);
1591 // Never returns here.
1595 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryCatch::Exit(
1597 int* context_length) {
1598 // The macros used here must preserve the result register.
1599 __ Drop(*stack_depth);
1606 bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1607 Expression* sub_expr;
1608 Handle<String> check;
1609 if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1610 EmitLiteralCompareTypeof(expr, sub_expr, check);
1614 if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
1615 EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1619 if (expr->IsLiteralCompareNull(&sub_expr)) {
1620 EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1628 void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1629 DisallowHeapAllocation no_gc;
1630 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1632 // Increment loop nesting level by one and iterate over the back edge table
1633 // to find the matching loops to patch the interrupt
1634 // call to an unconditional call to the replacement code.
1635 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level() + 1;
1636 if (loop_nesting_level > Code::kMaxLoopNestingMarker) return;
1638 BackEdgeTable back_edges(unoptimized, &no_gc);
1639 for (uint32_t i = 0; i < back_edges.length(); i++) {
1640 if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1641 DCHECK_EQ(INTERRUPT, GetBackEdgeState(isolate,
1644 PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1648 unoptimized->set_allow_osr_at_loop_nesting_level(loop_nesting_level);
1649 DCHECK(Verify(isolate, unoptimized));
1653 void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1654 DisallowHeapAllocation no_gc;
1655 Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1657 // Iterate over the back edge table and revert the patched interrupt calls.
1658 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1660 BackEdgeTable back_edges(unoptimized, &no_gc);
1661 for (uint32_t i = 0; i < back_edges.length(); i++) {
1662 if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1663 DCHECK_NE(INTERRUPT, GetBackEdgeState(isolate,
1666 PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1670 unoptimized->set_allow_osr_at_loop_nesting_level(0);
1671 // Assert that none of the back edges are patched anymore.
1672 DCHECK(Verify(isolate, unoptimized));
1676 void BackEdgeTable::AddStackCheck(Handle<Code> code, uint32_t pc_offset) {
1677 DisallowHeapAllocation no_gc;
1678 Isolate* isolate = code->GetIsolate();
1679 Address pc = code->instruction_start() + pc_offset;
1680 Code* patch = isolate->builtins()->builtin(Builtins::kOsrAfterStackCheck);
1681 PatchAt(*code, pc, OSR_AFTER_STACK_CHECK, patch);
1685 void BackEdgeTable::RemoveStackCheck(Handle<Code> code, uint32_t pc_offset) {
1686 DisallowHeapAllocation no_gc;
1687 Isolate* isolate = code->GetIsolate();
1688 Address pc = code->instruction_start() + pc_offset;
1690 if (OSR_AFTER_STACK_CHECK == GetBackEdgeState(isolate, *code, pc)) {
1691 Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1692 PatchAt(*code, pc, ON_STACK_REPLACEMENT, patch);
1698 bool BackEdgeTable::Verify(Isolate* isolate, Code* unoptimized) {
1699 DisallowHeapAllocation no_gc;
1700 int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1701 BackEdgeTable back_edges(unoptimized, &no_gc);
1702 for (uint32_t i = 0; i < back_edges.length(); i++) {
1703 uint32_t loop_depth = back_edges.loop_depth(i);
1704 CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
1705 // Assert that all back edges for shallower loops (and only those)
1706 // have already been patched.
1707 CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
1708 GetBackEdgeState(isolate,
1710 back_edges.pc(i)) != INTERRUPT);
1720 } } // namespace v8::internal