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