deps: update v8 to 4.3.61.21
[platform/upstream/nodejs.git] / deps / v8 / src / full-codegen.cc
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.
4
5 #include "src/v8.h"
6
7 #include "src/ast.h"
8 #include "src/ast-numbering.h"
9 #include "src/code-factory.h"
10 #include "src/codegen.h"
11 #include "src/compiler.h"
12 #include "src/debug.h"
13 #include "src/full-codegen.h"
14 #include "src/liveedit.h"
15 #include "src/macro-assembler.h"
16 #include "src/prettyprinter.h"
17 #include "src/scopeinfo.h"
18 #include "src/scopes.h"
19 #include "src/snapshot/snapshot.h"
20
21 namespace v8 {
22 namespace internal {
23
24 void BreakableStatementChecker::Check(Statement* stmt) {
25   Visit(stmt);
26 }
27
28
29 void BreakableStatementChecker::Check(Expression* expr) {
30   Visit(expr);
31 }
32
33
34 void BreakableStatementChecker::VisitVariableDeclaration(
35     VariableDeclaration* decl) {
36 }
37
38
39 void BreakableStatementChecker::VisitFunctionDeclaration(
40     FunctionDeclaration* decl) {
41 }
42
43
44 void BreakableStatementChecker::VisitModuleDeclaration(
45     ModuleDeclaration* decl) {
46 }
47
48
49 void BreakableStatementChecker::VisitImportDeclaration(
50     ImportDeclaration* decl) {
51 }
52
53
54 void BreakableStatementChecker::VisitExportDeclaration(
55     ExportDeclaration* decl) {
56 }
57
58
59 void BreakableStatementChecker::VisitModuleLiteral(ModuleLiteral* module) {
60 }
61
62
63 void BreakableStatementChecker::VisitModulePath(ModulePath* module) {
64 }
65
66
67 void BreakableStatementChecker::VisitModuleUrl(ModuleUrl* module) {
68 }
69
70
71 void BreakableStatementChecker::VisitModuleStatement(ModuleStatement* stmt) {
72 }
73
74
75 void BreakableStatementChecker::VisitBlock(Block* stmt) {
76 }
77
78
79 void BreakableStatementChecker::VisitExpressionStatement(
80     ExpressionStatement* stmt) {
81   // Check if expression is breakable.
82   Visit(stmt->expression());
83 }
84
85
86 void BreakableStatementChecker::VisitEmptyStatement(EmptyStatement* stmt) {
87 }
88
89
90 void BreakableStatementChecker::VisitIfStatement(IfStatement* stmt) {
91   // If the condition is breakable the if statement is breakable.
92   Visit(stmt->condition());
93 }
94
95
96 void BreakableStatementChecker::VisitContinueStatement(
97     ContinueStatement* stmt) {
98 }
99
100
101 void BreakableStatementChecker::VisitBreakStatement(BreakStatement* stmt) {
102 }
103
104
105 void BreakableStatementChecker::VisitReturnStatement(ReturnStatement* stmt) {
106   // Return is breakable if the expression is.
107   Visit(stmt->expression());
108 }
109
110
111 void BreakableStatementChecker::VisitWithStatement(WithStatement* stmt) {
112   Visit(stmt->expression());
113 }
114
115
116 void BreakableStatementChecker::VisitSwitchStatement(SwitchStatement* stmt) {
117   // Switch statements breakable if the tag expression is.
118   Visit(stmt->tag());
119 }
120
121
122 void BreakableStatementChecker::VisitDoWhileStatement(DoWhileStatement* stmt) {
123   // Mark do while as breakable to avoid adding a break slot in front of it.
124   is_breakable_ = true;
125 }
126
127
128 void BreakableStatementChecker::VisitWhileStatement(WhileStatement* stmt) {
129   // Mark while statements breakable if the condition expression is.
130   Visit(stmt->cond());
131 }
132
133
134 void BreakableStatementChecker::VisitForStatement(ForStatement* stmt) {
135   // We set positions for both init and condition, if they exist.
136   if (stmt->cond() != NULL || stmt->init() != NULL) is_breakable_ = true;
137 }
138
139
140 void BreakableStatementChecker::VisitForInStatement(ForInStatement* stmt) {
141   // For-in is breakable because we set the position for the enumerable.
142   is_breakable_ = true;
143 }
144
145
146 void BreakableStatementChecker::VisitForOfStatement(ForOfStatement* stmt) {
147   // For-of is breakable because we set the position for the next() call.
148   is_breakable_ = true;
149 }
150
151
152 void BreakableStatementChecker::VisitTryCatchStatement(
153     TryCatchStatement* stmt) {
154   // Mark try catch as breakable to avoid adding a break slot in front of it.
155   is_breakable_ = true;
156 }
157
158
159 void BreakableStatementChecker::VisitTryFinallyStatement(
160     TryFinallyStatement* stmt) {
161   // Mark try finally as breakable to avoid adding a break slot in front of it.
162   is_breakable_ = true;
163 }
164
165
166 void BreakableStatementChecker::VisitDebuggerStatement(
167     DebuggerStatement* stmt) {
168   // The debugger statement is breakable.
169   is_breakable_ = true;
170 }
171
172
173 void BreakableStatementChecker::VisitCaseClause(CaseClause* clause) {
174 }
175
176
177 void BreakableStatementChecker::VisitFunctionLiteral(FunctionLiteral* expr) {
178 }
179
180
181 void BreakableStatementChecker::VisitClassLiteral(ClassLiteral* expr) {
182   if (expr->extends() != NULL) {
183     Visit(expr->extends());
184   }
185 }
186
187
188 void BreakableStatementChecker::VisitNativeFunctionLiteral(
189     NativeFunctionLiteral* expr) {
190 }
191
192
193 void BreakableStatementChecker::VisitConditional(Conditional* expr) {
194 }
195
196
197 void BreakableStatementChecker::VisitVariableProxy(VariableProxy* expr) {
198 }
199
200
201 void BreakableStatementChecker::VisitLiteral(Literal* expr) {
202 }
203
204
205 void BreakableStatementChecker::VisitRegExpLiteral(RegExpLiteral* expr) {
206 }
207
208
209 void BreakableStatementChecker::VisitObjectLiteral(ObjectLiteral* expr) {
210 }
211
212
213 void BreakableStatementChecker::VisitArrayLiteral(ArrayLiteral* expr) {
214 }
215
216
217 void BreakableStatementChecker::VisitAssignment(Assignment* expr) {
218   // If assigning to a property (including a global property) the assignment is
219   // breakable.
220   VariableProxy* proxy = expr->target()->AsVariableProxy();
221   Property* prop = expr->target()->AsProperty();
222   if (prop != NULL || (proxy != NULL && proxy->var()->IsUnallocated())) {
223     is_breakable_ = true;
224     return;
225   }
226
227   // Otherwise the assignment is breakable if the assigned value is.
228   Visit(expr->value());
229 }
230
231
232 void BreakableStatementChecker::VisitYield(Yield* expr) {
233   // Yield is breakable if the expression is.
234   Visit(expr->expression());
235 }
236
237
238 void BreakableStatementChecker::VisitThrow(Throw* expr) {
239   // Throw is breakable if the expression is.
240   Visit(expr->exception());
241 }
242
243
244 void BreakableStatementChecker::VisitProperty(Property* expr) {
245   // Property load is breakable.
246   is_breakable_ = true;
247 }
248
249
250 void BreakableStatementChecker::VisitCall(Call* expr) {
251   // Function calls both through IC and call stub are breakable.
252   is_breakable_ = true;
253 }
254
255
256 void BreakableStatementChecker::VisitCallNew(CallNew* expr) {
257   // Function calls through new are breakable.
258   is_breakable_ = true;
259 }
260
261
262 void BreakableStatementChecker::VisitCallRuntime(CallRuntime* expr) {
263 }
264
265
266 void BreakableStatementChecker::VisitUnaryOperation(UnaryOperation* expr) {
267   Visit(expr->expression());
268 }
269
270
271 void BreakableStatementChecker::VisitCountOperation(CountOperation* expr) {
272   Visit(expr->expression());
273 }
274
275
276 void BreakableStatementChecker::VisitBinaryOperation(BinaryOperation* expr) {
277   Visit(expr->left());
278   if (expr->op() != Token::AND &&
279       expr->op() != Token::OR) {
280     Visit(expr->right());
281   }
282 }
283
284
285 void BreakableStatementChecker::VisitCompareOperation(CompareOperation* expr) {
286   Visit(expr->left());
287   Visit(expr->right());
288 }
289
290
291 void BreakableStatementChecker::VisitThisFunction(ThisFunction* expr) {
292 }
293
294
295 void BreakableStatementChecker::VisitSuperReference(SuperReference* expr) {}
296
297
298 #define __ ACCESS_MASM(masm())
299
300 bool FullCodeGenerator::MakeCode(CompilationInfo* info) {
301   Isolate* isolate = info->isolate();
302
303   TimerEventScope<TimerEventCompileFullCode> timer(info->isolate());
304
305   // Ensure that the feedback vector is large enough.
306   info->EnsureFeedbackVector();
307
308   Handle<Script> script = info->script();
309   if (!script->IsUndefined() && !script->source()->IsUndefined()) {
310     int len = String::cast(script->source())->length();
311     isolate->counters()->total_full_codegen_source_size()->Increment(len);
312   }
313   CodeGenerator::MakeCodePrologue(info, "full");
314   const int kInitialBufferSize = 4 * KB;
315   MacroAssembler masm(info->isolate(), NULL, kInitialBufferSize);
316   if (info->will_serialize()) masm.enable_serializer();
317
318   LOG_CODE_EVENT(isolate,
319                  CodeStartLinePosInfoRecordEvent(masm.positions_recorder()));
320
321   FullCodeGenerator cgen(&masm, info);
322   cgen.Generate();
323   if (cgen.HasStackOverflow()) {
324     DCHECK(!isolate->has_pending_exception());
325     return false;
326   }
327   unsigned table_offset = cgen.EmitBackEdgeTable();
328
329   Code::Flags flags = Code::ComputeFlags(Code::FUNCTION);
330   Handle<Code> code = CodeGenerator::MakeCodeEpilogue(&masm, flags, info);
331   code->set_optimizable(info->IsOptimizable() &&
332                         !info->function()->dont_optimize() &&
333                         info->function()->scope()->AllowsLazyCompilation());
334   cgen.PopulateDeoptimizationData(code);
335   cgen.PopulateTypeFeedbackInfo(code);
336   code->set_has_deoptimization_support(info->HasDeoptimizationSupport());
337   code->set_has_reloc_info_for_serialization(info->will_serialize());
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);
344   info->SetCode(code);
345   void* line_info = masm.positions_recorder()->DetachJITHandlerData();
346   LOG_CODE_EVENT(isolate, CodeEndLinePosInfoRecordEvent(*code, line_info));
347
348 #ifdef DEBUG
349   // Check that no context-specific object has been embedded.
350   code->VerifyEmbeddedObjects(Code::kNoContextSpecificPointers);
351 #endif  // DEBUG
352   return true;
353 }
354
355
356 unsigned FullCodeGenerator::EmitBackEdgeTable() {
357   // The back edge table consists of a length (in number of entries)
358   // field, and then a sequence of entries.  Each entry is a pair of AST id
359   // and code-relative pc offset.
360   masm()->Align(kPointerSize);
361   unsigned offset = masm()->pc_offset();
362   unsigned length = back_edges_.length();
363   __ dd(length);
364   for (unsigned i = 0; i < length; ++i) {
365     __ dd(back_edges_[i].id.ToInt());
366     __ dd(back_edges_[i].pc);
367     __ dd(back_edges_[i].loop_depth);
368   }
369   return offset;
370 }
371
372
373 void FullCodeGenerator::EnsureSlotContainsAllocationSite(
374     FeedbackVectorSlot slot) {
375   Handle<TypeFeedbackVector> vector = FeedbackVector();
376   if (!vector->Get(slot)->IsAllocationSite()) {
377     Handle<AllocationSite> allocation_site =
378         isolate()->factory()->NewAllocationSite();
379     vector->Set(slot, *allocation_site);
380   }
381 }
382
383
384 void FullCodeGenerator::EnsureSlotContainsAllocationSite(
385     FeedbackVectorICSlot slot) {
386   Handle<TypeFeedbackVector> vector = FeedbackVector();
387   if (!vector->Get(slot)->IsAllocationSite()) {
388     Handle<AllocationSite> allocation_site =
389         isolate()->factory()->NewAllocationSite();
390     vector->Set(slot, *allocation_site);
391   }
392 }
393
394
395 void FullCodeGenerator::PopulateDeoptimizationData(Handle<Code> code) {
396   // Fill in the deoptimization information.
397   DCHECK(info_->HasDeoptimizationSupport() || bailout_entries_.is_empty());
398   if (!info_->HasDeoptimizationSupport()) return;
399   int length = bailout_entries_.length();
400   Handle<DeoptimizationOutputData> data =
401       DeoptimizationOutputData::New(isolate(), length, TENURED);
402   for (int i = 0; i < length; i++) {
403     data->SetAstId(i, bailout_entries_[i].id);
404     data->SetPcAndState(i, Smi::FromInt(bailout_entries_[i].pc_and_state));
405   }
406   code->set_deoptimization_data(*data);
407 }
408
409
410 void FullCodeGenerator::PopulateTypeFeedbackInfo(Handle<Code> code) {
411   Handle<TypeFeedbackInfo> info = isolate()->factory()->NewTypeFeedbackInfo();
412   info->set_ic_total_count(ic_total_count_);
413   DCHECK(!isolate()->heap()->InNewSpace(*info));
414   code->set_type_feedback_info(*info);
415 }
416
417
418 bool FullCodeGenerator::MustCreateObjectLiteralWithRuntime(
419     ObjectLiteral* expr) const {
420   // FastCloneShallowObjectStub doesn't copy elements, and object literals don't
421   // support copy-on-write (COW) elements for now.
422   // TODO(mvstanton): make object literals support COW elements.
423   return expr->may_store_doubles() || expr->depth() > 1 ||
424          masm()->serializer_enabled() ||
425          expr->ComputeFlags() != ObjectLiteral::kFastElements ||
426          expr->has_elements() ||
427          expr->properties_count() >
428              FastCloneShallowObjectStub::kMaximumClonedProperties;
429 }
430
431
432 bool FullCodeGenerator::MustCreateArrayLiteralWithRuntime(
433     ArrayLiteral* expr) const {
434   return expr->depth() > 1 ||
435          expr->values()->length() > JSObject::kInitialMaxFastElementArray;
436 }
437
438
439 void FullCodeGenerator::Initialize() {
440   InitializeAstVisitor(info_->isolate(), info_->zone());
441   // The generation of debug code must match between the snapshot code and the
442   // code that is generated later.  This is assumed by the debugger when it is
443   // calculating PC offsets after generating a debug version of code.  Therefore
444   // we disable the production of debug code in the full compiler if we are
445   // either generating a snapshot or we booted from a snapshot.
446   generate_debug_code_ = FLAG_debug_code && !masm_->serializer_enabled() &&
447                          !info_->isolate()->snapshot_available();
448   masm_->set_emit_debug_code(generate_debug_code_);
449   masm_->set_predictable_code_size(true);
450 }
451
452
453 void FullCodeGenerator::PrepareForBailout(Expression* node, State state) {
454   PrepareForBailoutForId(node->id(), state);
455 }
456
457
458 void FullCodeGenerator::CallLoadIC(ContextualMode contextual_mode,
459                                    TypeFeedbackId id) {
460   Handle<Code> ic = CodeFactory::LoadIC(isolate(), contextual_mode).code();
461   CallIC(ic, id);
462 }
463
464
465 void FullCodeGenerator::CallGlobalLoadIC(Handle<String> name) {
466   if (masm()->serializer_enabled() || FLAG_vector_ics) {
467     // Vector-ICs don't work with LoadGlobalIC.
468     return CallLoadIC(CONTEXTUAL);
469   }
470   Handle<Code> ic = CodeFactory::LoadGlobalIC(
471                         isolate(), isolate()->global_object(), name).code();
472   CallIC(ic, TypeFeedbackId::None());
473 }
474
475
476 void FullCodeGenerator::CallStoreIC(TypeFeedbackId id) {
477   Handle<Code> ic = CodeFactory::StoreIC(isolate(), language_mode()).code();
478   CallIC(ic, id);
479 }
480
481
482 void FullCodeGenerator::RecordJSReturnSite(Call* call) {
483   // We record the offset of the function return so we can rebuild the frame
484   // if the function was inlined, i.e., this is the return address in the
485   // inlined function's frame.
486   //
487   // The state is ignored.  We defensively set it to TOS_REG, which is the
488   // real state of the unoptimized code at the return site.
489   PrepareForBailoutForId(call->ReturnId(), TOS_REG);
490 #ifdef DEBUG
491   // In debug builds, mark the return so we can verify that this function
492   // was called.
493   DCHECK(!call->return_is_recorded_);
494   call->return_is_recorded_ = true;
495 #endif
496 }
497
498
499 void FullCodeGenerator::PrepareForBailoutForId(BailoutId id, State state) {
500   // There's no need to prepare this code for bailouts from already optimized
501   // code or code that can't be optimized.
502   if (!info_->HasDeoptimizationSupport()) return;
503   unsigned pc_and_state =
504       StateField::encode(state) | PcField::encode(masm_->pc_offset());
505   DCHECK(Smi::IsValid(pc_and_state));
506 #ifdef DEBUG
507   for (int i = 0; i < bailout_entries_.length(); ++i) {
508     DCHECK(bailout_entries_[i].id != id);
509   }
510 #endif
511   BailoutEntry entry = { id, pc_and_state };
512   bailout_entries_.Add(entry, zone());
513 }
514
515
516 void FullCodeGenerator::RecordBackEdge(BailoutId ast_id) {
517   // The pc offset does not need to be encoded and packed together with a state.
518   DCHECK(masm_->pc_offset() > 0);
519   DCHECK(loop_depth() > 0);
520   uint8_t depth = Min(loop_depth(), Code::kMaxLoopNestingMarker);
521   BackEdgeEntry entry =
522       { ast_id, static_cast<unsigned>(masm_->pc_offset()), depth };
523   back_edges_.Add(entry, zone());
524 }
525
526
527 bool FullCodeGenerator::ShouldInlineSmiCase(Token::Value op) {
528   // Inline smi case inside loops, but not division and modulo which
529   // are too complicated and take up too much space.
530   if (op == Token::DIV ||op == Token::MOD) return false;
531   if (FLAG_always_inline_smi_code) return true;
532   return loop_depth_ > 0;
533 }
534
535
536 void FullCodeGenerator::EffectContext::Plug(Register reg) const {
537 }
538
539
540 void FullCodeGenerator::AccumulatorValueContext::Plug(Register reg) const {
541   __ Move(result_register(), reg);
542 }
543
544
545 void FullCodeGenerator::StackValueContext::Plug(Register reg) const {
546   __ Push(reg);
547 }
548
549
550 void FullCodeGenerator::TestContext::Plug(Register reg) const {
551   // For simplicity we always test the accumulator register.
552   __ Move(result_register(), reg);
553   codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
554   codegen()->DoTest(this);
555 }
556
557
558 void FullCodeGenerator::EffectContext::PlugTOS() const {
559   __ Drop(1);
560 }
561
562
563 void FullCodeGenerator::AccumulatorValueContext::PlugTOS() const {
564   __ Pop(result_register());
565 }
566
567
568 void FullCodeGenerator::StackValueContext::PlugTOS() const {
569 }
570
571
572 void FullCodeGenerator::TestContext::PlugTOS() const {
573   // For simplicity we always test the accumulator register.
574   __ Pop(result_register());
575   codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
576   codegen()->DoTest(this);
577 }
578
579
580 void FullCodeGenerator::EffectContext::PrepareTest(
581     Label* materialize_true,
582     Label* materialize_false,
583     Label** if_true,
584     Label** if_false,
585     Label** fall_through) const {
586   // In an effect context, the true and the false case branch to the
587   // same label.
588   *if_true = *if_false = *fall_through = materialize_true;
589 }
590
591
592 void FullCodeGenerator::AccumulatorValueContext::PrepareTest(
593     Label* materialize_true,
594     Label* materialize_false,
595     Label** if_true,
596     Label** if_false,
597     Label** fall_through) const {
598   *if_true = *fall_through = materialize_true;
599   *if_false = materialize_false;
600 }
601
602
603 void FullCodeGenerator::StackValueContext::PrepareTest(
604     Label* materialize_true,
605     Label* materialize_false,
606     Label** if_true,
607     Label** if_false,
608     Label** fall_through) const {
609   *if_true = *fall_through = materialize_true;
610   *if_false = materialize_false;
611 }
612
613
614 void FullCodeGenerator::TestContext::PrepareTest(
615     Label* materialize_true,
616     Label* materialize_false,
617     Label** if_true,
618     Label** if_false,
619     Label** fall_through) const {
620   *if_true = true_label_;
621   *if_false = false_label_;
622   *fall_through = fall_through_;
623 }
624
625
626 void FullCodeGenerator::DoTest(const TestContext* context) {
627   DoTest(context->condition(),
628          context->true_label(),
629          context->false_label(),
630          context->fall_through());
631 }
632
633
634 void FullCodeGenerator::AllocateModules(ZoneList<Declaration*>* declarations) {
635   DCHECK(scope_->is_script_scope());
636
637   for (int i = 0; i < declarations->length(); i++) {
638     ModuleDeclaration* declaration = declarations->at(i)->AsModuleDeclaration();
639     if (declaration != NULL) {
640       ModuleLiteral* module = declaration->module()->AsModuleLiteral();
641       if (module != NULL) {
642         Comment cmnt(masm_, "[ Link nested modules");
643         Scope* scope = module->body()->scope();
644         DCHECK(scope->module()->IsFrozen());
645
646         scope->module()->Allocate(scope->module_var()->index());
647
648         // Set up module context.
649         DCHECK(scope->module()->Index() >= 0);
650         __ Push(Smi::FromInt(scope->module()->Index()));
651         __ Push(scope->GetScopeInfo(isolate()));
652         __ CallRuntime(Runtime::kPushModuleContext, 2);
653         StoreToFrameField(StandardFrameConstants::kContextOffset,
654                           context_register());
655
656         AllocateModules(scope->declarations());
657
658         // Pop module context.
659         LoadContextField(context_register(), Context::PREVIOUS_INDEX);
660         // Update local stack frame context field.
661         StoreToFrameField(StandardFrameConstants::kContextOffset,
662                           context_register());
663       }
664     }
665   }
666 }
667
668
669 // Modules have their own local scope, represented by their own context.
670 // Module instance objects have an accessor for every export that forwards
671 // access to the respective slot from the module's context. (Exports that are
672 // modules themselves, however, are simple data properties.)
673 //
674 // All modules have a _hosting_ scope/context, which (currently) is the
675 // enclosing script scope. To deal with recursion, nested modules are hosted
676 // by the same scope as global ones.
677 //
678 // For every (global or nested) module literal, the hosting context has an
679 // internal slot that points directly to the respective module context. This
680 // enables quick access to (statically resolved) module members by 2-dimensional
681 // access through the hosting context. For example,
682 //
683 //   module A {
684 //     let x;
685 //     module B { let y; }
686 //   }
687 //   module C { let z; }
688 //
689 // allocates contexts as follows:
690 //
691 // [header| .A | .B | .C | A | C ]  (global)
692 //           |    |    |
693 //           |    |    +-- [header| z ]  (module)
694 //           |    |
695 //           |    +------- [header| y ]  (module)
696 //           |
697 //           +------------ [header| x | B ]  (module)
698 //
699 // Here, .A, .B, .C are the internal slots pointing to the hosted module
700 // contexts, whereas A, B, C hold the actual instance objects (note that every
701 // module context also points to the respective instance object through its
702 // extension slot in the header).
703 //
704 // To deal with arbitrary recursion and aliases between modules,
705 // they are created and initialized in several stages. Each stage applies to
706 // all modules in the hosting script scope, including nested ones.
707 //
708 // 1. Allocate: for each module _literal_, allocate the module contexts and
709 //    respective instance object and wire them up. This happens in the
710 //    PushModuleContext runtime function, as generated by AllocateModules
711 //    (invoked by VisitDeclarations in the hosting scope).
712 //
713 // 2. Bind: for each module _declaration_ (i.e. literals as well as aliases),
714 //    assign the respective instance object to respective local variables. This
715 //    happens in VisitModuleDeclaration, and uses the instance objects created
716 //    in the previous stage.
717 //    For each module _literal_, this phase also constructs a module descriptor
718 //    for the next stage. This happens in VisitModuleLiteral.
719 //
720 // 3. Populate: invoke the DeclareModules runtime function to populate each
721 //    _instance_ object with accessors for it exports. This is generated by
722 //    DeclareModules (invoked by VisitDeclarations in the hosting scope again),
723 //    and uses the descriptors generated in the previous stage.
724 //
725 // 4. Initialize: execute the module bodies (and other code) in sequence. This
726 //    happens by the separate statements generated for module bodies. To reenter
727 //    the module scopes properly, the parser inserted ModuleStatements.
728
729 void FullCodeGenerator::VisitDeclarations(
730     ZoneList<Declaration*>* declarations) {
731   Handle<FixedArray> saved_modules = modules_;
732   int saved_module_index = module_index_;
733   ZoneList<Handle<Object> >* saved_globals = globals_;
734   ZoneList<Handle<Object> > inner_globals(10, zone());
735   globals_ = &inner_globals;
736
737   if (scope_->num_modules() != 0) {
738     // This is a scope hosting modules. Allocate a descriptor array to pass
739     // to the runtime for initialization.
740     Comment cmnt(masm_, "[ Allocate modules");
741     DCHECK(scope_->is_script_scope());
742     modules_ =
743         isolate()->factory()->NewFixedArray(scope_->num_modules(), TENURED);
744     module_index_ = 0;
745
746     // Generate code for allocating all modules, including nested ones.
747     // The allocated contexts are stored in internal variables in this scope.
748     AllocateModules(declarations);
749   }
750
751   AstVisitor::VisitDeclarations(declarations);
752
753   if (scope_->num_modules() != 0) {
754     // TODO(ES6): This step, which creates module instance objects,
755     // can probably be delayed until an "import *" declaration
756     // reifies a module instance. Until imports are implemented,
757     // we skip it altogether.
758     //
759     // Initialize modules from descriptor array.
760     //  DCHECK(module_index_ == modules_->length());
761     //  DeclareModules(modules_);
762     modules_ = saved_modules;
763     module_index_ = saved_module_index;
764   }
765
766   if (!globals_->is_empty()) {
767     // Invoke the platform-dependent code generator to do the actual
768     // declaration of the global functions and variables.
769     Handle<FixedArray> array =
770        isolate()->factory()->NewFixedArray(globals_->length(), TENURED);
771     for (int i = 0; i < globals_->length(); ++i)
772       array->set(i, *globals_->at(i));
773     DeclareGlobals(array);
774   }
775
776   globals_ = saved_globals;
777 }
778
779
780 void FullCodeGenerator::VisitModuleLiteral(ModuleLiteral* module) {
781   Block* block = module->body();
782   Scope* saved_scope = scope();
783   scope_ = block->scope();
784   ModuleDescriptor* descriptor = scope_->module();
785
786   Comment cmnt(masm_, "[ ModuleLiteral");
787   SetStatementPosition(block);
788
789   DCHECK(!modules_.is_null());
790   DCHECK(module_index_ < modules_->length());
791   int index = module_index_++;
792
793   // Set up module context.
794   DCHECK(descriptor->Index() >= 0);
795   __ Push(Smi::FromInt(descriptor->Index()));
796   __ Push(Smi::FromInt(0));
797   __ CallRuntime(Runtime::kPushModuleContext, 2);
798   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
799
800   {
801     Comment cmnt(masm_, "[ Declarations");
802     VisitDeclarations(scope_->declarations());
803   }
804
805   // Populate the module description.
806   Handle<ModuleInfo> description =
807       ModuleInfo::Create(isolate(), descriptor, scope_);
808   modules_->set(index, *description);
809
810   scope_ = saved_scope;
811   // Pop module context.
812   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
813   // Update local stack frame context field.
814   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
815 }
816
817
818 // TODO(adamk): Delete ModulePath.
819 void FullCodeGenerator::VisitModulePath(ModulePath* module) {
820 }
821
822
823 // TODO(adamk): Delete ModuleUrl.
824 void FullCodeGenerator::VisitModuleUrl(ModuleUrl* module) {
825 }
826
827
828 int FullCodeGenerator::DeclareGlobalsFlags() {
829   DCHECK(DeclareGlobalsLanguageMode::is_valid(language_mode()));
830   return DeclareGlobalsEvalFlag::encode(is_eval()) |
831          DeclareGlobalsNativeFlag::encode(is_native()) |
832          DeclareGlobalsLanguageMode::encode(language_mode());
833 }
834
835
836 void FullCodeGenerator::SetFunctionPosition(FunctionLiteral* fun) {
837   CodeGenerator::RecordPositions(masm_, fun->start_position());
838 }
839
840
841 void FullCodeGenerator::SetReturnPosition(FunctionLiteral* fun) {
842   CodeGenerator::RecordPositions(masm_, fun->end_position() - 1);
843 }
844
845
846 void FullCodeGenerator::SetStatementPosition(Statement* stmt) {
847   if (!info_->is_debug()) {
848     CodeGenerator::RecordPositions(masm_, stmt->position());
849   } else {
850     // Check if the statement will be breakable without adding a debug break
851     // slot.
852     BreakableStatementChecker checker(info_->isolate(), zone());
853     checker.Check(stmt);
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       DebugCodegen::GenerateSlot(masm_);
863     }
864   }
865 }
866
867
868 void FullCodeGenerator::VisitSuperReference(SuperReference* super) {
869   __ CallRuntime(Runtime::kThrowUnsupportedSuperError, 0);
870 }
871
872
873 void FullCodeGenerator::SetExpressionPosition(Expression* expr) {
874   if (!info_->is_debug()) {
875     CodeGenerator::RecordPositions(masm_, expr->position());
876   } else {
877     // Check if the expression will be breakable without adding a debug break
878     // slot.
879     BreakableStatementChecker checker(info_->isolate(), zone());
880     checker.Check(expr);
881     // Record a statement position right here if the expression is not
882     // breakable. For breakable expressions the actual recording of the
883     // position will be postponed to the breakable code (typically an IC).
884     // NOTE this will record a statement position for something which might
885     // not be a statement. As stepping in the debugger will only stop at
886     // statement positions this is used for e.g. the condition expression of
887     // a do while loop.
888     bool position_recorded = CodeGenerator::RecordPositions(
889         masm_, expr->position(), !checker.is_breakable());
890     // If the position recording did record a new position generate a debug
891     // break slot to make the statement breakable.
892     if (position_recorded) {
893       DebugCodegen::GenerateSlot(masm_);
894     }
895   }
896 }
897
898
899 void FullCodeGenerator::SetSourcePosition(int pos) {
900   if (pos != RelocInfo::kNoPosition) {
901     masm_->positions_recorder()->RecordPosition(pos);
902   }
903 }
904
905
906 void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
907   ZoneList<Expression*>* args = expr->arguments();
908   DCHECK(args->length() == 2);
909   EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
910 }
911
912
913 void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
914   ZoneList<Expression*>* args = expr->arguments();
915   DCHECK(args->length() == 2);
916   EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
917 }
918
919
920 void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
921   context()->Plug(handle(Smi::FromInt(0), isolate()));
922 }
923
924
925 void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
926   switch (expr->op()) {
927     case Token::COMMA:
928       return VisitComma(expr);
929     case Token::OR:
930     case Token::AND:
931       return VisitLogicalExpression(expr);
932     default:
933       return VisitArithmeticExpression(expr);
934   }
935 }
936
937
938 void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
939   if (context()->IsEffect()) {
940     VisitForEffect(expr);
941   } else if (context()->IsAccumulatorValue()) {
942     VisitForAccumulatorValue(expr);
943   } else if (context()->IsStackValue()) {
944     VisitForStackValue(expr);
945   } else if (context()->IsTest()) {
946     const TestContext* test = TestContext::cast(context());
947     VisitForControl(expr, test->true_label(), test->false_label(),
948                     test->fall_through());
949   }
950 }
951
952
953 void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
954   Comment cmnt(masm_, "[ Comma");
955   VisitForEffect(expr->left());
956   VisitInDuplicateContext(expr->right());
957 }
958
959
960 void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
961   bool is_logical_and = expr->op() == Token::AND;
962   Comment cmnt(masm_, is_logical_and ? "[ Logical AND" :  "[ Logical OR");
963   Expression* left = expr->left();
964   Expression* right = expr->right();
965   BailoutId right_id = expr->RightId();
966   Label done;
967
968   if (context()->IsTest()) {
969     Label eval_right;
970     const TestContext* test = TestContext::cast(context());
971     if (is_logical_and) {
972       VisitForControl(left, &eval_right, test->false_label(), &eval_right);
973     } else {
974       VisitForControl(left, test->true_label(), &eval_right, &eval_right);
975     }
976     PrepareForBailoutForId(right_id, NO_REGISTERS);
977     __ bind(&eval_right);
978
979   } else if (context()->IsAccumulatorValue()) {
980     VisitForAccumulatorValue(left);
981     // We want the value in the accumulator for the test, and on the stack in
982     // case we need it.
983     __ Push(result_register());
984     Label discard, restore;
985     if (is_logical_and) {
986       DoTest(left, &discard, &restore, &restore);
987     } else {
988       DoTest(left, &restore, &discard, &restore);
989     }
990     __ bind(&restore);
991     __ Pop(result_register());
992     __ jmp(&done);
993     __ bind(&discard);
994     __ Drop(1);
995     PrepareForBailoutForId(right_id, NO_REGISTERS);
996
997   } else if (context()->IsStackValue()) {
998     VisitForAccumulatorValue(left);
999     // We want the value in the accumulator for the test, and on the stack in
1000     // case we need it.
1001     __ Push(result_register());
1002     Label discard;
1003     if (is_logical_and) {
1004       DoTest(left, &discard, &done, &discard);
1005     } else {
1006       DoTest(left, &done, &discard, &discard);
1007     }
1008     __ bind(&discard);
1009     __ Drop(1);
1010     PrepareForBailoutForId(right_id, NO_REGISTERS);
1011
1012   } else {
1013     DCHECK(context()->IsEffect());
1014     Label eval_right;
1015     if (is_logical_and) {
1016       VisitForControl(left, &eval_right, &done, &eval_right);
1017     } else {
1018       VisitForControl(left, &done, &eval_right, &eval_right);
1019     }
1020     PrepareForBailoutForId(right_id, NO_REGISTERS);
1021     __ bind(&eval_right);
1022   }
1023
1024   VisitInDuplicateContext(right);
1025   __ bind(&done);
1026 }
1027
1028
1029 void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
1030   Token::Value op = expr->op();
1031   Comment cmnt(masm_, "[ ArithmeticExpression");
1032   Expression* left = expr->left();
1033   Expression* right = expr->right();
1034
1035   VisitForStackValue(left);
1036   VisitForAccumulatorValue(right);
1037
1038   SetSourcePosition(expr->position());
1039   if (ShouldInlineSmiCase(op)) {
1040     EmitInlineSmiBinaryOp(expr, op, left, right);
1041   } else {
1042     EmitBinaryOp(expr, op);
1043   }
1044 }
1045
1046
1047 void FullCodeGenerator::VisitBlock(Block* stmt) {
1048   Comment cmnt(masm_, "[ Block");
1049   NestedBlock nested_block(this, stmt);
1050   SetStatementPosition(stmt);
1051
1052   {
1053     EnterBlockScopeIfNeeded block_scope_state(
1054         this, stmt->scope(), stmt->EntryId(), stmt->DeclsId(), stmt->ExitId());
1055     VisitStatements(stmt->statements());
1056     __ bind(nested_block.break_label());
1057   }
1058 }
1059
1060
1061 void FullCodeGenerator::VisitModuleStatement(ModuleStatement* stmt) {
1062   Comment cmnt(masm_, "[ Module context");
1063
1064   DCHECK(stmt->body()->scope()->is_module_scope());
1065
1066   __ Push(Smi::FromInt(stmt->body()->scope()->module()->Index()));
1067   __ Push(Smi::FromInt(0));
1068   __ CallRuntime(Runtime::kPushModuleContext, 2);
1069   StoreToFrameField(
1070       StandardFrameConstants::kContextOffset, context_register());
1071
1072   Scope* saved_scope = scope_;
1073   scope_ = stmt->body()->scope();
1074   VisitStatements(stmt->body()->statements());
1075   scope_ = saved_scope;
1076   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1077   // Update local stack frame context field.
1078   StoreToFrameField(StandardFrameConstants::kContextOffset,
1079                     context_register());
1080 }
1081
1082
1083 void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
1084   Comment cmnt(masm_, "[ ExpressionStatement");
1085   SetStatementPosition(stmt);
1086   VisitForEffect(stmt->expression());
1087 }
1088
1089
1090 void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
1091   Comment cmnt(masm_, "[ EmptyStatement");
1092   SetStatementPosition(stmt);
1093 }
1094
1095
1096 void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
1097   Comment cmnt(masm_, "[ IfStatement");
1098   SetStatementPosition(stmt);
1099   Label then_part, else_part, done;
1100
1101   if (stmt->HasElseStatement()) {
1102     VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
1103     PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1104     __ bind(&then_part);
1105     Visit(stmt->then_statement());
1106     __ jmp(&done);
1107
1108     PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1109     __ bind(&else_part);
1110     Visit(stmt->else_statement());
1111   } else {
1112     VisitForControl(stmt->condition(), &then_part, &done, &then_part);
1113     PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1114     __ bind(&then_part);
1115     Visit(stmt->then_statement());
1116
1117     PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1118   }
1119   __ bind(&done);
1120   PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
1121 }
1122
1123
1124 void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
1125   Comment cmnt(masm_,  "[ ContinueStatement");
1126   SetStatementPosition(stmt);
1127   NestedStatement* current = nesting_stack_;
1128   int stack_depth = 0;
1129   int context_length = 0;
1130   // When continuing, we clobber the unpredictable value in the accumulator
1131   // with one that's safe for GC.  If we hit an exit from the try block of
1132   // try...finally on our way out, we will unconditionally preserve the
1133   // accumulator on the stack.
1134   ClearAccumulator();
1135   while (!current->IsContinueTarget(stmt->target())) {
1136     current = current->Exit(&stack_depth, &context_length);
1137   }
1138   __ Drop(stack_depth);
1139   if (context_length > 0) {
1140     while (context_length > 0) {
1141       LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1142       --context_length;
1143     }
1144     StoreToFrameField(StandardFrameConstants::kContextOffset,
1145                       context_register());
1146   }
1147
1148   __ jmp(current->AsIteration()->continue_label());
1149 }
1150
1151
1152 void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
1153   Comment cmnt(masm_,  "[ BreakStatement");
1154   SetStatementPosition(stmt);
1155   NestedStatement* current = nesting_stack_;
1156   int stack_depth = 0;
1157   int context_length = 0;
1158   // When breaking, we clobber the unpredictable value in the accumulator
1159   // with one that's safe for GC.  If we hit an exit from the try block of
1160   // try...finally on our way out, we will unconditionally preserve the
1161   // accumulator on the stack.
1162   ClearAccumulator();
1163   while (!current->IsBreakTarget(stmt->target())) {
1164     current = current->Exit(&stack_depth, &context_length);
1165   }
1166   __ Drop(stack_depth);
1167   if (context_length > 0) {
1168     while (context_length > 0) {
1169       LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1170       --context_length;
1171     }
1172     StoreToFrameField(StandardFrameConstants::kContextOffset,
1173                       context_register());
1174   }
1175
1176   __ jmp(current->AsBreakable()->break_label());
1177 }
1178
1179
1180 void FullCodeGenerator::EmitUnwindBeforeReturn() {
1181   NestedStatement* current = nesting_stack_;
1182   int stack_depth = 0;
1183   int context_length = 0;
1184   while (current != NULL) {
1185     current = current->Exit(&stack_depth, &context_length);
1186   }
1187   __ Drop(stack_depth);
1188 }
1189
1190
1191 void FullCodeGenerator::EmitPropertyKey(ObjectLiteralProperty* property,
1192                                         BailoutId bailout_id) {
1193   VisitForStackValue(property->key());
1194   __ InvokeBuiltin(Builtins::TO_NAME, CALL_FUNCTION);
1195   PrepareForBailoutForId(bailout_id, NO_REGISTERS);
1196   __ Push(result_register());
1197 }
1198
1199
1200 void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
1201   Comment cmnt(masm_, "[ ReturnStatement");
1202   SetStatementPosition(stmt);
1203   Expression* expr = stmt->expression();
1204   VisitForAccumulatorValue(expr);
1205   EmitUnwindBeforeReturn();
1206   EmitReturnSequence();
1207 }
1208
1209
1210 void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
1211   Comment cmnt(masm_, "[ WithStatement");
1212   SetStatementPosition(stmt);
1213
1214   VisitForStackValue(stmt->expression());
1215   PushFunctionArgumentForContextAllocation();
1216   __ CallRuntime(Runtime::kPushWithContext, 2);
1217   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1218   PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1219
1220   Scope* saved_scope = scope();
1221   scope_ = stmt->scope();
1222   { WithOrCatch body(this);
1223     Visit(stmt->statement());
1224   }
1225   scope_ = saved_scope;
1226
1227   // Pop context.
1228   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1229   // Update local stack frame context field.
1230   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1231 }
1232
1233
1234 void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
1235   Comment cmnt(masm_, "[ DoWhileStatement");
1236   SetStatementPosition(stmt);
1237   Label body, book_keeping;
1238
1239   Iteration loop_statement(this, stmt);
1240   increment_loop_depth();
1241
1242   __ bind(&body);
1243   Visit(stmt->body());
1244
1245   // Record the position of the do while condition and make sure it is
1246   // possible to break on the condition.
1247   __ bind(loop_statement.continue_label());
1248   PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1249   SetExpressionPosition(stmt->cond());
1250   VisitForControl(stmt->cond(),
1251                   &book_keeping,
1252                   loop_statement.break_label(),
1253                   &book_keeping);
1254
1255   // Check stack before looping.
1256   PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1257   __ bind(&book_keeping);
1258   EmitBackEdgeBookkeeping(stmt, &body);
1259   __ jmp(&body);
1260
1261   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1262   __ bind(loop_statement.break_label());
1263   decrement_loop_depth();
1264 }
1265
1266
1267 void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
1268   Comment cmnt(masm_, "[ WhileStatement");
1269   Label loop, body;
1270
1271   Iteration loop_statement(this, stmt);
1272   increment_loop_depth();
1273
1274   __ bind(&loop);
1275
1276   SetExpressionPosition(stmt->cond());
1277   VisitForControl(stmt->cond(),
1278                   &body,
1279                   loop_statement.break_label(),
1280                   &body);
1281
1282   PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1283   __ bind(&body);
1284   Visit(stmt->body());
1285
1286   __ bind(loop_statement.continue_label());
1287
1288   // Check stack before looping.
1289   EmitBackEdgeBookkeeping(stmt, &loop);
1290   __ jmp(&loop);
1291
1292   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1293   __ bind(loop_statement.break_label());
1294   decrement_loop_depth();
1295 }
1296
1297
1298 void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1299   Comment cmnt(masm_, "[ ForStatement");
1300   Label test, body;
1301
1302   Iteration loop_statement(this, stmt);
1303
1304   // Set statement position for a break slot before entering the for-body.
1305   SetStatementPosition(stmt);
1306
1307   if (stmt->init() != NULL) {
1308     SetStatementPosition(stmt->init());
1309     Visit(stmt->init());
1310   }
1311
1312   increment_loop_depth();
1313   // Emit the test at the bottom of the loop (even if empty).
1314   __ jmp(&test);
1315
1316   PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1317   __ bind(&body);
1318   Visit(stmt->body());
1319
1320   PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1321   __ bind(loop_statement.continue_label());
1322   if (stmt->next() != NULL) {
1323     SetStatementPosition(stmt->next());
1324     Visit(stmt->next());
1325   }
1326
1327   // Emit the statement position here as this is where the for
1328   // statement code starts.
1329   SetStatementPosition(stmt);
1330
1331   // Check stack before looping.
1332   EmitBackEdgeBookkeeping(stmt, &body);
1333
1334   __ bind(&test);
1335   if (stmt->cond() != NULL) {
1336     SetExpressionPosition(stmt->cond());
1337     VisitForControl(stmt->cond(),
1338                     &body,
1339                     loop_statement.break_label(),
1340                     loop_statement.break_label());
1341   } else {
1342     __ jmp(&body);
1343   }
1344
1345   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1346   __ bind(loop_statement.break_label());
1347   decrement_loop_depth();
1348 }
1349
1350
1351 void FullCodeGenerator::VisitForOfStatement(ForOfStatement* stmt) {
1352   Comment cmnt(masm_, "[ ForOfStatement");
1353   SetStatementPosition(stmt);
1354
1355   Iteration loop_statement(this, stmt);
1356   increment_loop_depth();
1357
1358   // var iterator = iterable[Symbol.iterator]();
1359   VisitForEffect(stmt->assign_iterator());
1360
1361   // Loop entry.
1362   __ bind(loop_statement.continue_label());
1363
1364   // result = iterator.next()
1365   SetExpressionPosition(stmt->next_result());
1366   VisitForEffect(stmt->next_result());
1367
1368   // if (result.done) break;
1369   Label result_not_done;
1370   VisitForControl(stmt->result_done(), loop_statement.break_label(),
1371                   &result_not_done, &result_not_done);
1372   __ bind(&result_not_done);
1373
1374   // each = result.value
1375   VisitForEffect(stmt->assign_each());
1376
1377   // Generate code for the body of the loop.
1378   Visit(stmt->body());
1379
1380   // Check stack before looping.
1381   PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1382   EmitBackEdgeBookkeeping(stmt, loop_statement.continue_label());
1383   __ jmp(loop_statement.continue_label());
1384
1385   // Exit and decrement the loop depth.
1386   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1387   __ bind(loop_statement.break_label());
1388   decrement_loop_depth();
1389 }
1390
1391
1392 void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1393   Comment cmnt(masm_, "[ TryCatchStatement");
1394   SetStatementPosition(stmt);
1395   // The try block adds a handler to the exception handler chain before
1396   // entering, and removes it again when exiting normally.  If an exception
1397   // is thrown during execution of the try block, the handler is consumed
1398   // and control is passed to the catch block with the exception in the
1399   // result register.
1400
1401   Label try_entry, handler_entry, exit;
1402   __ jmp(&try_entry);
1403   __ bind(&handler_entry);
1404   // Exception handler code, the exception is in the result register.
1405   // Extend the context before executing the catch block.
1406   { Comment cmnt(masm_, "[ Extend catch context");
1407     __ Push(stmt->variable()->name());
1408     __ Push(result_register());
1409     PushFunctionArgumentForContextAllocation();
1410     __ CallRuntime(Runtime::kPushCatchContext, 3);
1411     StoreToFrameField(StandardFrameConstants::kContextOffset,
1412                       context_register());
1413   }
1414
1415   Scope* saved_scope = scope();
1416   scope_ = stmt->scope();
1417   DCHECK(scope_->declarations()->is_empty());
1418   { WithOrCatch catch_body(this);
1419     Visit(stmt->catch_block());
1420   }
1421   // Restore the context.
1422   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1423   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1424   scope_ = saved_scope;
1425   __ jmp(&exit);
1426
1427   // Try block code. Sets up the exception handler chain.
1428   __ bind(&try_entry);
1429   EnterTryBlock(stmt->index(), &handler_entry);
1430   { TryCatch try_body(this);
1431     Visit(stmt->try_block());
1432   }
1433   ExitTryBlock(stmt->index());
1434   __ bind(&exit);
1435 }
1436
1437
1438 void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1439   Comment cmnt(masm_, "[ TryFinallyStatement");
1440   SetStatementPosition(stmt);
1441   // Try finally is compiled by setting up a try-handler on the stack while
1442   // executing the try body, and removing it again afterwards.
1443   //
1444   // The try-finally construct can enter the finally block in three ways:
1445   // 1. By exiting the try-block normally. This removes the try-handler and
1446   //    calls the finally block code before continuing.
1447   // 2. By exiting the try-block with a function-local control flow transfer
1448   //    (break/continue/return). The site of the, e.g., break removes the
1449   //    try handler and calls the finally block code before continuing
1450   //    its outward control transfer.
1451   // 3. By exiting the try-block with a thrown exception.
1452   //    This can happen in nested function calls. It traverses the try-handler
1453   //    chain and consumes the try-handler entry before jumping to the
1454   //    handler code. The handler code then calls the finally-block before
1455   //    rethrowing the exception.
1456   //
1457   // The finally block must assume a return address on top of the stack
1458   // (or in the link register on ARM chips) and a value (return value or
1459   // exception) in the result register (rax/eax/r0), both of which must
1460   // be preserved. The return address isn't GC-safe, so it should be
1461   // cooked before GC.
1462   Label try_entry, handler_entry, finally_entry;
1463
1464   // Jump to try-handler setup and try-block code.
1465   __ jmp(&try_entry);
1466   __ bind(&handler_entry);
1467   // Exception handler code.  This code is only executed when an exception
1468   // is thrown.  The exception is in the result register, and must be
1469   // preserved by the finally block.  Call the finally block and then
1470   // rethrow the exception if it returns.
1471   __ Call(&finally_entry);
1472   __ Push(result_register());
1473   __ CallRuntime(Runtime::kReThrow, 1);
1474
1475   // Finally block implementation.
1476   __ bind(&finally_entry);
1477   EnterFinallyBlock();
1478   { Finally finally_body(this);
1479     Visit(stmt->finally_block());
1480   }
1481   ExitFinallyBlock();  // Return to the calling code.
1482
1483   // Set up try handler.
1484   __ bind(&try_entry);
1485   EnterTryBlock(stmt->index(), &handler_entry);
1486   { TryFinally try_body(this, &finally_entry);
1487     Visit(stmt->try_block());
1488   }
1489   ExitTryBlock(stmt->index());
1490   // Execute the finally block on the way out.  Clobber the unpredictable
1491   // value in the result register with one that's safe for GC because the
1492   // finally block will unconditionally preserve the result register on the
1493   // stack.
1494   ClearAccumulator();
1495   __ Call(&finally_entry);
1496 }
1497
1498
1499 void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1500   Comment cmnt(masm_, "[ DebuggerStatement");
1501   SetStatementPosition(stmt);
1502
1503   __ DebugBreak();
1504   // Ignore the return value.
1505
1506   PrepareForBailoutForId(stmt->DebugBreakId(), NO_REGISTERS);
1507 }
1508
1509
1510 void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
1511   UNREACHABLE();
1512 }
1513
1514
1515 void FullCodeGenerator::VisitConditional(Conditional* expr) {
1516   Comment cmnt(masm_, "[ Conditional");
1517   Label true_case, false_case, done;
1518   VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1519
1520   PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1521   __ bind(&true_case);
1522   SetExpressionPosition(expr->then_expression());
1523   if (context()->IsTest()) {
1524     const TestContext* for_test = TestContext::cast(context());
1525     VisitForControl(expr->then_expression(),
1526                     for_test->true_label(),
1527                     for_test->false_label(),
1528                     NULL);
1529   } else {
1530     VisitInDuplicateContext(expr->then_expression());
1531     __ jmp(&done);
1532   }
1533
1534   PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1535   __ bind(&false_case);
1536   SetExpressionPosition(expr->else_expression());
1537   VisitInDuplicateContext(expr->else_expression());
1538   // If control flow falls through Visit, merge it with true case here.
1539   if (!context()->IsTest()) {
1540     __ bind(&done);
1541   }
1542 }
1543
1544
1545 void FullCodeGenerator::VisitLiteral(Literal* expr) {
1546   Comment cmnt(masm_, "[ Literal");
1547   context()->Plug(expr->value());
1548 }
1549
1550
1551 void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
1552   Comment cmnt(masm_, "[ FunctionLiteral");
1553
1554   // Build the function boilerplate and instantiate it.
1555   Handle<SharedFunctionInfo> function_info =
1556       Compiler::BuildFunctionInfo(expr, script(), info_);
1557   if (function_info.is_null()) {
1558     SetStackOverflow();
1559     return;
1560   }
1561   EmitNewClosure(function_info, expr->pretenure());
1562 }
1563
1564
1565 void FullCodeGenerator::VisitClassLiteral(ClassLiteral* lit) {
1566   Comment cmnt(masm_, "[ ClassLiteral");
1567
1568   {
1569     EnterBlockScopeIfNeeded block_scope_state(
1570         this, lit->scope(), lit->EntryId(), lit->DeclsId(), lit->ExitId());
1571
1572     if (lit->raw_name() != NULL) {
1573       __ Push(lit->name());
1574     } else {
1575       __ Push(isolate()->factory()->undefined_value());
1576     }
1577
1578     if (lit->extends() != NULL) {
1579       VisitForStackValue(lit->extends());
1580     } else {
1581       __ Push(isolate()->factory()->the_hole_value());
1582     }
1583
1584     VisitForStackValue(lit->constructor());
1585
1586     __ Push(script());
1587     __ Push(Smi::FromInt(lit->start_position()));
1588     __ Push(Smi::FromInt(lit->end_position()));
1589
1590     __ CallRuntime(Runtime::kDefineClass, 6);
1591     EmitClassDefineProperties(lit);
1592
1593     if (lit->scope() != NULL) {
1594       DCHECK_NOT_NULL(lit->class_variable_proxy());
1595       EmitVariableAssignment(lit->class_variable_proxy()->var(),
1596                              Token::INIT_CONST);
1597     }
1598   }
1599
1600   context()->Plug(result_register());
1601 }
1602
1603
1604 void FullCodeGenerator::VisitNativeFunctionLiteral(
1605     NativeFunctionLiteral* expr) {
1606   Comment cmnt(masm_, "[ NativeFunctionLiteral");
1607
1608   // Compute the function template for the native function.
1609   Handle<String> name = expr->name();
1610   v8::Handle<v8::FunctionTemplate> fun_template =
1611       expr->extension()->GetNativeFunctionTemplate(
1612           reinterpret_cast<v8::Isolate*>(isolate()), v8::Utils::ToLocal(name));
1613   DCHECK(!fun_template.IsEmpty());
1614
1615   // Instantiate the function and create a shared function info from it.
1616   Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
1617   const int literals = fun->NumberOfLiterals();
1618   Handle<Code> code = Handle<Code>(fun->shared()->code());
1619   Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
1620   Handle<SharedFunctionInfo> shared =
1621       isolate()->factory()->NewSharedFunctionInfo(
1622           name, literals, FunctionKind::kNormalFunction, code,
1623           Handle<ScopeInfo>(fun->shared()->scope_info()),
1624           Handle<TypeFeedbackVector>(fun->shared()->feedback_vector()));
1625   shared->set_construct_stub(*construct_stub);
1626
1627   // Copy the function data to the shared function info.
1628   shared->set_function_data(fun->shared()->function_data());
1629   int parameters = fun->shared()->internal_formal_parameter_count();
1630   shared->set_internal_formal_parameter_count(parameters);
1631
1632   EmitNewClosure(shared, false);
1633 }
1634
1635
1636 void FullCodeGenerator::VisitThrow(Throw* expr) {
1637   Comment cmnt(masm_, "[ Throw");
1638   VisitForStackValue(expr->exception());
1639   __ CallRuntime(Runtime::kThrow, 1);
1640   // Never returns here.
1641 }
1642
1643
1644 void FullCodeGenerator::EnterTryBlock(int index, Label* handler) {
1645   handler_table()->SetRangeStart(index, masm()->pc_offset());
1646   handler_table()->SetRangeHandler(index, handler->pos());
1647
1648   // Determine expression stack depth of try statement.
1649   int stack_depth = info_->scope()->num_stack_slots();  // Include stack locals.
1650   for (NestedStatement* current = nesting_stack_; current != NULL; /*nop*/) {
1651     current = current->AccumulateDepth(&stack_depth);
1652   }
1653   handler_table()->SetRangeDepth(index, stack_depth);
1654
1655   // Push context onto operand stack.
1656   STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
1657   __ Push(context_register());
1658 }
1659
1660
1661 void FullCodeGenerator::ExitTryBlock(int index) {
1662   handler_table()->SetRangeEnd(index, masm()->pc_offset());
1663
1664   // Drop context from operand stack.
1665   __ Drop(TryBlockConstant::kElementCount);
1666 }
1667
1668
1669 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryFinally::Exit(
1670     int* stack_depth, int* context_length) {
1671   // The macros used here must preserve the result register.
1672
1673   // Because the handler block contains the context of the finally
1674   // code, we can restore it directly from there for the finally code
1675   // rather than iteratively unwinding contexts via their previous
1676   // links.
1677   if (*context_length > 0) {
1678     __ Drop(*stack_depth);  // Down to the handler block.
1679     // Restore the context to its dedicated register and the stack.
1680     STATIC_ASSERT(TryFinally::kElementCount == 1);
1681     __ Pop(codegen_->context_register());
1682     codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1683                                 codegen_->context_register());
1684   } else {
1685     // Down to the handler block and also drop context.
1686     __ Drop(*stack_depth + kElementCount);
1687   }
1688   __ Call(finally_entry_);
1689
1690   *stack_depth = 0;
1691   *context_length = 0;
1692   return previous_;
1693 }
1694
1695
1696 bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1697   Expression* sub_expr;
1698   Handle<String> check;
1699   if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1700     EmitLiteralCompareTypeof(expr, sub_expr, check);
1701     return true;
1702   }
1703
1704   if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
1705     EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1706     return true;
1707   }
1708
1709   if (expr->IsLiteralCompareNull(&sub_expr)) {
1710     EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1711     return true;
1712   }
1713
1714   return false;
1715 }
1716
1717
1718 void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1719   DisallowHeapAllocation no_gc;
1720   Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1721
1722   // Increment loop nesting level by one and iterate over the back edge table
1723   // to find the matching loops to patch the interrupt
1724   // call to an unconditional call to the replacement code.
1725   int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level() + 1;
1726   if (loop_nesting_level > Code::kMaxLoopNestingMarker) return;
1727
1728   BackEdgeTable back_edges(unoptimized, &no_gc);
1729   for (uint32_t i = 0; i < back_edges.length(); i++) {
1730     if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1731       DCHECK_EQ(INTERRUPT, GetBackEdgeState(isolate,
1732                                             unoptimized,
1733                                             back_edges.pc(i)));
1734       PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1735     }
1736   }
1737
1738   unoptimized->set_allow_osr_at_loop_nesting_level(loop_nesting_level);
1739   DCHECK(Verify(isolate, unoptimized));
1740 }
1741
1742
1743 void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1744   DisallowHeapAllocation no_gc;
1745   Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1746
1747   // Iterate over the back edge table and revert the patched interrupt calls.
1748   int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1749
1750   BackEdgeTable back_edges(unoptimized, &no_gc);
1751   for (uint32_t i = 0; i < back_edges.length(); i++) {
1752     if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1753       DCHECK_NE(INTERRUPT, GetBackEdgeState(isolate,
1754                                             unoptimized,
1755                                             back_edges.pc(i)));
1756       PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1757     }
1758   }
1759
1760   unoptimized->set_allow_osr_at_loop_nesting_level(0);
1761   // Assert that none of the back edges are patched anymore.
1762   DCHECK(Verify(isolate, unoptimized));
1763 }
1764
1765
1766 void BackEdgeTable::AddStackCheck(Handle<Code> code, uint32_t pc_offset) {
1767   DisallowHeapAllocation no_gc;
1768   Isolate* isolate = code->GetIsolate();
1769   Address pc = code->instruction_start() + pc_offset;
1770   Code* patch = isolate->builtins()->builtin(Builtins::kOsrAfterStackCheck);
1771   PatchAt(*code, pc, OSR_AFTER_STACK_CHECK, patch);
1772 }
1773
1774
1775 void BackEdgeTable::RemoveStackCheck(Handle<Code> code, uint32_t pc_offset) {
1776   DisallowHeapAllocation no_gc;
1777   Isolate* isolate = code->GetIsolate();
1778   Address pc = code->instruction_start() + pc_offset;
1779
1780   if (OSR_AFTER_STACK_CHECK == GetBackEdgeState(isolate, *code, pc)) {
1781     Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1782     PatchAt(*code, pc, ON_STACK_REPLACEMENT, patch);
1783   }
1784 }
1785
1786
1787 #ifdef DEBUG
1788 bool BackEdgeTable::Verify(Isolate* isolate, Code* unoptimized) {
1789   DisallowHeapAllocation no_gc;
1790   int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1791   BackEdgeTable back_edges(unoptimized, &no_gc);
1792   for (uint32_t i = 0; i < back_edges.length(); i++) {
1793     uint32_t loop_depth = back_edges.loop_depth(i);
1794     CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
1795     // Assert that all back edges for shallower loops (and only those)
1796     // have already been patched.
1797     CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
1798              GetBackEdgeState(isolate,
1799                               unoptimized,
1800                               back_edges.pc(i)) != INTERRUPT);
1801   }
1802   return true;
1803 }
1804 #endif  // DEBUG
1805
1806
1807 FullCodeGenerator::EnterBlockScopeIfNeeded::EnterBlockScopeIfNeeded(
1808     FullCodeGenerator* codegen, Scope* scope, BailoutId entry_id,
1809     BailoutId declarations_id, BailoutId exit_id)
1810     : codegen_(codegen), scope_(scope), exit_id_(exit_id) {
1811   saved_scope_ = codegen_->scope();
1812
1813   if (scope == NULL) {
1814     codegen_->PrepareForBailoutForId(entry_id, NO_REGISTERS);
1815   } else {
1816     codegen_->scope_ = scope;
1817     {
1818       Comment cmnt(masm(), "[ Extend block context");
1819       __ Push(scope->GetScopeInfo(codegen->isolate()));
1820       codegen_->PushFunctionArgumentForContextAllocation();
1821       __ CallRuntime(Runtime::kPushBlockContext, 2);
1822
1823       // Replace the context stored in the frame.
1824       codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1825                                   codegen_->context_register());
1826       codegen_->PrepareForBailoutForId(entry_id, NO_REGISTERS);
1827     }
1828     {
1829       Comment cmnt(masm(), "[ Declarations");
1830       codegen_->VisitDeclarations(scope->declarations());
1831       codegen_->PrepareForBailoutForId(declarations_id, NO_REGISTERS);
1832     }
1833   }
1834 }
1835
1836
1837 FullCodeGenerator::EnterBlockScopeIfNeeded::~EnterBlockScopeIfNeeded() {
1838   if (scope_ != NULL) {
1839     codegen_->LoadContextField(codegen_->context_register(),
1840                                Context::PREVIOUS_INDEX);
1841     // Update local stack frame context field.
1842     codegen_->StoreToFrameField(StandardFrameConstants::kContextOffset,
1843                                 codegen_->context_register());
1844   }
1845   codegen_->PrepareForBailoutForId(exit_id_, NO_REGISTERS);
1846   codegen_->scope_ = saved_scope_;
1847 }
1848
1849
1850 #undef __
1851
1852
1853 } }  // namespace v8::internal