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