Upstream version 9.38.204.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/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     masm_->positions_recorder()->WriteRecordedPositions();
852   }
853 }
854
855
856 // Lookup table for code generators for  special runtime calls which are
857 // generated inline.
858 #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize)          \
859     &FullCodeGenerator::Emit##Name,
860
861 const FullCodeGenerator::InlineFunctionGenerator
862   FullCodeGenerator::kInlineFunctionGenerators[] = {
863     INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
864   };
865 #undef INLINE_FUNCTION_GENERATOR_ADDRESS
866
867
868 FullCodeGenerator::InlineFunctionGenerator
869   FullCodeGenerator::FindInlineFunctionGenerator(Runtime::FunctionId id) {
870     int lookup_index =
871         static_cast<int>(id) - static_cast<int>(Runtime::kFirstInlineFunction);
872     DCHECK(lookup_index >= 0);
873     DCHECK(static_cast<size_t>(lookup_index) <
874            ARRAY_SIZE(kInlineFunctionGenerators));
875     return kInlineFunctionGenerators[lookup_index];
876 }
877
878
879 void FullCodeGenerator::EmitInlineRuntimeCall(CallRuntime* expr) {
880   const Runtime::Function* function = expr->function();
881   DCHECK(function != NULL);
882   DCHECK(function->intrinsic_type == Runtime::INLINE);
883   InlineFunctionGenerator generator =
884       FindInlineFunctionGenerator(function->function_id);
885   ((*this).*(generator))(expr);
886 }
887
888
889 void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
890   ZoneList<Expression*>* args = expr->arguments();
891   DCHECK(args->length() == 2);
892   EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
893 }
894
895
896 void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
897   ZoneList<Expression*>* args = expr->arguments();
898   DCHECK(args->length() == 2);
899   EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
900 }
901
902
903 void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
904   context()->Plug(handle(Smi::FromInt(0), isolate()));
905 }
906
907
908 void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
909   switch (expr->op()) {
910     case Token::COMMA:
911       return VisitComma(expr);
912     case Token::OR:
913     case Token::AND:
914       return VisitLogicalExpression(expr);
915     default:
916       return VisitArithmeticExpression(expr);
917   }
918 }
919
920
921 void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
922   if (context()->IsEffect()) {
923     VisitForEffect(expr);
924   } else if (context()->IsAccumulatorValue()) {
925     VisitForAccumulatorValue(expr);
926   } else if (context()->IsStackValue()) {
927     VisitForStackValue(expr);
928   } else if (context()->IsTest()) {
929     const TestContext* test = TestContext::cast(context());
930     VisitForControl(expr, test->true_label(), test->false_label(),
931                     test->fall_through());
932   }
933 }
934
935
936 void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
937   Comment cmnt(masm_, "[ Comma");
938   VisitForEffect(expr->left());
939   VisitInDuplicateContext(expr->right());
940 }
941
942
943 void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
944   bool is_logical_and = expr->op() == Token::AND;
945   Comment cmnt(masm_, is_logical_and ? "[ Logical AND" :  "[ Logical OR");
946   Expression* left = expr->left();
947   Expression* right = expr->right();
948   BailoutId right_id = expr->RightId();
949   Label done;
950
951   if (context()->IsTest()) {
952     Label eval_right;
953     const TestContext* test = TestContext::cast(context());
954     if (is_logical_and) {
955       VisitForControl(left, &eval_right, test->false_label(), &eval_right);
956     } else {
957       VisitForControl(left, test->true_label(), &eval_right, &eval_right);
958     }
959     PrepareForBailoutForId(right_id, NO_REGISTERS);
960     __ bind(&eval_right);
961
962   } else if (context()->IsAccumulatorValue()) {
963     VisitForAccumulatorValue(left);
964     // We want the value in the accumulator for the test, and on the stack in
965     // case we need it.
966     __ Push(result_register());
967     Label discard, restore;
968     if (is_logical_and) {
969       DoTest(left, &discard, &restore, &restore);
970     } else {
971       DoTest(left, &restore, &discard, &restore);
972     }
973     __ bind(&restore);
974     __ Pop(result_register());
975     __ jmp(&done);
976     __ bind(&discard);
977     __ Drop(1);
978     PrepareForBailoutForId(right_id, NO_REGISTERS);
979
980   } else if (context()->IsStackValue()) {
981     VisitForAccumulatorValue(left);
982     // We want the value in the accumulator for the test, and on the stack in
983     // case we need it.
984     __ Push(result_register());
985     Label discard;
986     if (is_logical_and) {
987       DoTest(left, &discard, &done, &discard);
988     } else {
989       DoTest(left, &done, &discard, &discard);
990     }
991     __ bind(&discard);
992     __ Drop(1);
993     PrepareForBailoutForId(right_id, NO_REGISTERS);
994
995   } else {
996     DCHECK(context()->IsEffect());
997     Label eval_right;
998     if (is_logical_and) {
999       VisitForControl(left, &eval_right, &done, &eval_right);
1000     } else {
1001       VisitForControl(left, &done, &eval_right, &eval_right);
1002     }
1003     PrepareForBailoutForId(right_id, NO_REGISTERS);
1004     __ bind(&eval_right);
1005   }
1006
1007   VisitInDuplicateContext(right);
1008   __ bind(&done);
1009 }
1010
1011
1012 void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
1013   Token::Value op = expr->op();
1014   Comment cmnt(masm_, "[ ArithmeticExpression");
1015   Expression* left = expr->left();
1016   Expression* right = expr->right();
1017   OverwriteMode mode =
1018       left->ResultOverwriteAllowed()
1019       ? OVERWRITE_LEFT
1020       : (right->ResultOverwriteAllowed() ? OVERWRITE_RIGHT : NO_OVERWRITE);
1021
1022   VisitForStackValue(left);
1023   VisitForAccumulatorValue(right);
1024
1025   SetSourcePosition(expr->position());
1026   if (ShouldInlineSmiCase(op)) {
1027     EmitInlineSmiBinaryOp(expr, op, mode, left, right);
1028   } else {
1029     EmitBinaryOp(expr, op, mode);
1030   }
1031 }
1032
1033
1034 void FullCodeGenerator::VisitBlock(Block* stmt) {
1035   Comment cmnt(masm_, "[ Block");
1036   NestedBlock nested_block(this, stmt);
1037   SetStatementPosition(stmt);
1038
1039   Scope* saved_scope = scope();
1040   // Push a block context when entering a block with block scoped variables.
1041   if (stmt->scope() == NULL) {
1042     PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1043   } else {
1044     scope_ = stmt->scope();
1045     DCHECK(!scope_->is_module_scope());
1046     { Comment cmnt(masm_, "[ Extend block context");
1047       __ Push(scope_->GetScopeInfo());
1048       PushFunctionArgumentForContextAllocation();
1049       __ CallRuntime(Runtime::kPushBlockContext, 2);
1050
1051       // Replace the context stored in the frame.
1052       StoreToFrameField(StandardFrameConstants::kContextOffset,
1053                         context_register());
1054       PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1055     }
1056     { Comment cmnt(masm_, "[ Declarations");
1057       VisitDeclarations(scope_->declarations());
1058       PrepareForBailoutForId(stmt->DeclsId(), NO_REGISTERS);
1059     }
1060   }
1061
1062   VisitStatements(stmt->statements());
1063   scope_ = saved_scope;
1064   __ bind(nested_block.break_label());
1065
1066   // Pop block context if necessary.
1067   if (stmt->scope() != NULL) {
1068     LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1069     // Update local stack frame context field.
1070     StoreToFrameField(StandardFrameConstants::kContextOffset,
1071                       context_register());
1072   }
1073   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1074 }
1075
1076
1077 void FullCodeGenerator::VisitModuleStatement(ModuleStatement* stmt) {
1078   Comment cmnt(masm_, "[ Module context");
1079
1080   __ Push(Smi::FromInt(stmt->proxy()->interface()->Index()));
1081   __ Push(Smi::FromInt(0));
1082   __ CallRuntime(Runtime::kPushModuleContext, 2);
1083   StoreToFrameField(
1084       StandardFrameConstants::kContextOffset, context_register());
1085
1086   Scope* saved_scope = scope_;
1087   scope_ = stmt->body()->scope();
1088   VisitStatements(stmt->body()->statements());
1089   scope_ = saved_scope;
1090   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1091   // Update local stack frame context field.
1092   StoreToFrameField(StandardFrameConstants::kContextOffset,
1093                     context_register());
1094 }
1095
1096
1097 void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
1098   Comment cmnt(masm_, "[ ExpressionStatement");
1099   SetStatementPosition(stmt);
1100   VisitForEffect(stmt->expression());
1101 }
1102
1103
1104 void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
1105   Comment cmnt(masm_, "[ EmptyStatement");
1106   SetStatementPosition(stmt);
1107 }
1108
1109
1110 void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
1111   Comment cmnt(masm_, "[ IfStatement");
1112   SetStatementPosition(stmt);
1113   Label then_part, else_part, done;
1114
1115   if (stmt->HasElseStatement()) {
1116     VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
1117     PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1118     __ bind(&then_part);
1119     Visit(stmt->then_statement());
1120     __ jmp(&done);
1121
1122     PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1123     __ bind(&else_part);
1124     Visit(stmt->else_statement());
1125   } else {
1126     VisitForControl(stmt->condition(), &then_part, &done, &then_part);
1127     PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1128     __ bind(&then_part);
1129     Visit(stmt->then_statement());
1130
1131     PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1132   }
1133   __ bind(&done);
1134   PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
1135 }
1136
1137
1138 void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
1139   Comment cmnt(masm_,  "[ ContinueStatement");
1140   SetStatementPosition(stmt);
1141   NestedStatement* current = nesting_stack_;
1142   int stack_depth = 0;
1143   int context_length = 0;
1144   // When continuing, we clobber the unpredictable value in the accumulator
1145   // with one that's safe for GC.  If we hit an exit from the try block of
1146   // try...finally on our way out, we will unconditionally preserve the
1147   // accumulator on the stack.
1148   ClearAccumulator();
1149   while (!current->IsContinueTarget(stmt->target())) {
1150     current = current->Exit(&stack_depth, &context_length);
1151   }
1152   __ Drop(stack_depth);
1153   if (context_length > 0) {
1154     while (context_length > 0) {
1155       LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1156       --context_length;
1157     }
1158     StoreToFrameField(StandardFrameConstants::kContextOffset,
1159                       context_register());
1160   }
1161
1162   __ jmp(current->AsIteration()->continue_label());
1163 }
1164
1165
1166 void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
1167   Comment cmnt(masm_,  "[ BreakStatement");
1168   SetStatementPosition(stmt);
1169   NestedStatement* current = nesting_stack_;
1170   int stack_depth = 0;
1171   int context_length = 0;
1172   // When breaking, we clobber the unpredictable value in the accumulator
1173   // with one that's safe for GC.  If we hit an exit from the try block of
1174   // try...finally on our way out, we will unconditionally preserve the
1175   // accumulator on the stack.
1176   ClearAccumulator();
1177   while (!current->IsBreakTarget(stmt->target())) {
1178     current = current->Exit(&stack_depth, &context_length);
1179   }
1180   __ Drop(stack_depth);
1181   if (context_length > 0) {
1182     while (context_length > 0) {
1183       LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1184       --context_length;
1185     }
1186     StoreToFrameField(StandardFrameConstants::kContextOffset,
1187                       context_register());
1188   }
1189
1190   __ jmp(current->AsBreakable()->break_label());
1191 }
1192
1193
1194 void FullCodeGenerator::EmitUnwindBeforeReturn() {
1195   NestedStatement* current = nesting_stack_;
1196   int stack_depth = 0;
1197   int context_length = 0;
1198   while (current != NULL) {
1199     current = current->Exit(&stack_depth, &context_length);
1200   }
1201   __ Drop(stack_depth);
1202 }
1203
1204
1205 void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
1206   Comment cmnt(masm_, "[ ReturnStatement");
1207   SetStatementPosition(stmt);
1208   Expression* expr = stmt->expression();
1209   VisitForAccumulatorValue(expr);
1210   EmitUnwindBeforeReturn();
1211   EmitReturnSequence();
1212 }
1213
1214
1215 void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
1216   Comment cmnt(masm_, "[ WithStatement");
1217   SetStatementPosition(stmt);
1218
1219   VisitForStackValue(stmt->expression());
1220   PushFunctionArgumentForContextAllocation();
1221   __ CallRuntime(Runtime::kPushWithContext, 2);
1222   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1223
1224   Scope* saved_scope = scope();
1225   scope_ = stmt->scope();
1226   { WithOrCatch body(this);
1227     Visit(stmt->statement());
1228   }
1229   scope_ = saved_scope;
1230
1231   // Pop context.
1232   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1233   // Update local stack frame context field.
1234   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1235 }
1236
1237
1238 void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
1239   Comment cmnt(masm_, "[ DoWhileStatement");
1240   SetStatementPosition(stmt);
1241   Label body, book_keeping;
1242
1243   Iteration loop_statement(this, stmt);
1244   increment_loop_depth();
1245
1246   __ bind(&body);
1247   Visit(stmt->body());
1248
1249   // Record the position of the do while condition and make sure it is
1250   // possible to break on the condition.
1251   __ bind(loop_statement.continue_label());
1252   PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1253   SetExpressionPosition(stmt->cond());
1254   VisitForControl(stmt->cond(),
1255                   &book_keeping,
1256                   loop_statement.break_label(),
1257                   &book_keeping);
1258
1259   // Check stack before looping.
1260   PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1261   __ bind(&book_keeping);
1262   EmitBackEdgeBookkeeping(stmt, &body);
1263   __ jmp(&body);
1264
1265   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1266   __ bind(loop_statement.break_label());
1267   decrement_loop_depth();
1268 }
1269
1270
1271 void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
1272   Comment cmnt(masm_, "[ WhileStatement");
1273   Label loop, body;
1274
1275   Iteration loop_statement(this, stmt);
1276   increment_loop_depth();
1277
1278   __ bind(&loop);
1279
1280   SetExpressionPosition(stmt->cond());
1281   VisitForControl(stmt->cond(),
1282                   &body,
1283                   loop_statement.break_label(),
1284                   &body);
1285
1286   PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1287   __ bind(&body);
1288   Visit(stmt->body());
1289
1290   __ bind(loop_statement.continue_label());
1291
1292   // Check stack before looping.
1293   EmitBackEdgeBookkeeping(stmt, &loop);
1294   __ jmp(&loop);
1295
1296   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1297   __ bind(loop_statement.break_label());
1298   decrement_loop_depth();
1299 }
1300
1301
1302 void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1303   Comment cmnt(masm_, "[ ForStatement");
1304   Label test, body;
1305
1306   Iteration loop_statement(this, stmt);
1307
1308   // Set statement position for a break slot before entering the for-body.
1309   SetStatementPosition(stmt);
1310
1311   if (stmt->init() != NULL) {
1312     Visit(stmt->init());
1313   }
1314
1315   increment_loop_depth();
1316   // Emit the test at the bottom of the loop (even if empty).
1317   __ jmp(&test);
1318
1319   PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1320   __ bind(&body);
1321   Visit(stmt->body());
1322
1323   PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1324   __ bind(loop_statement.continue_label());
1325   if (stmt->next() != NULL) {
1326     Visit(stmt->next());
1327   }
1328
1329   // Emit the statement position here as this is where the for
1330   // statement code starts.
1331   SetStatementPosition(stmt);
1332
1333   // Check stack before looping.
1334   EmitBackEdgeBookkeeping(stmt, &body);
1335
1336   __ bind(&test);
1337   if (stmt->cond() != NULL) {
1338     VisitForControl(stmt->cond(),
1339                     &body,
1340                     loop_statement.break_label(),
1341                     loop_statement.break_label());
1342   } else {
1343     __ jmp(&body);
1344   }
1345
1346   PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1347   __ bind(loop_statement.break_label());
1348   decrement_loop_depth();
1349 }
1350
1351
1352 void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1353   Comment cmnt(masm_, "[ TryCatchStatement");
1354   SetStatementPosition(stmt);
1355   // The try block adds a handler to the exception handler chain before
1356   // entering, and removes it again when exiting normally.  If an exception
1357   // is thrown during execution of the try block, the handler is consumed
1358   // and control is passed to the catch block with the exception in the
1359   // result register.
1360
1361   Label try_entry, handler_entry, exit;
1362   __ jmp(&try_entry);
1363   __ bind(&handler_entry);
1364   handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1365   // Exception handler code, the exception is in the result register.
1366   // Extend the context before executing the catch block.
1367   { Comment cmnt(masm_, "[ Extend catch context");
1368     __ Push(stmt->variable()->name());
1369     __ Push(result_register());
1370     PushFunctionArgumentForContextAllocation();
1371     __ CallRuntime(Runtime::kPushCatchContext, 3);
1372     StoreToFrameField(StandardFrameConstants::kContextOffset,
1373                       context_register());
1374   }
1375
1376   Scope* saved_scope = scope();
1377   scope_ = stmt->scope();
1378   DCHECK(scope_->declarations()->is_empty());
1379   { WithOrCatch catch_body(this);
1380     Visit(stmt->catch_block());
1381   }
1382   // Restore the context.
1383   LoadContextField(context_register(), Context::PREVIOUS_INDEX);
1384   StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1385   scope_ = saved_scope;
1386   __ jmp(&exit);
1387
1388   // Try block code. Sets up the exception handler chain.
1389   __ bind(&try_entry);
1390   __ PushTryHandler(StackHandler::CATCH, stmt->index());
1391   { TryCatch try_body(this);
1392     Visit(stmt->try_block());
1393   }
1394   __ PopTryHandler();
1395   __ bind(&exit);
1396 }
1397
1398
1399 void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1400   Comment cmnt(masm_, "[ TryFinallyStatement");
1401   SetStatementPosition(stmt);
1402   // Try finally is compiled by setting up a try-handler on the stack while
1403   // executing the try body, and removing it again afterwards.
1404   //
1405   // The try-finally construct can enter the finally block in three ways:
1406   // 1. By exiting the try-block normally. This removes the try-handler and
1407   //    calls the finally block code before continuing.
1408   // 2. By exiting the try-block with a function-local control flow transfer
1409   //    (break/continue/return). The site of the, e.g., break removes the
1410   //    try handler and calls the finally block code before continuing
1411   //    its outward control transfer.
1412   // 3. By exiting the try-block with a thrown exception.
1413   //    This can happen in nested function calls. It traverses the try-handler
1414   //    chain and consumes the try-handler entry before jumping to the
1415   //    handler code. The handler code then calls the finally-block before
1416   //    rethrowing the exception.
1417   //
1418   // The finally block must assume a return address on top of the stack
1419   // (or in the link register on ARM chips) and a value (return value or
1420   // exception) in the result register (rax/eax/r0), both of which must
1421   // be preserved. The return address isn't GC-safe, so it should be
1422   // cooked before GC.
1423   Label try_entry, handler_entry, finally_entry;
1424
1425   // Jump to try-handler setup and try-block code.
1426   __ jmp(&try_entry);
1427   __ bind(&handler_entry);
1428   handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
1429   // Exception handler code.  This code is only executed when an exception
1430   // is thrown.  The exception is in the result register, and must be
1431   // preserved by the finally block.  Call the finally block and then
1432   // rethrow the exception if it returns.
1433   __ Call(&finally_entry);
1434   __ Push(result_register());
1435   __ CallRuntime(Runtime::kReThrow, 1);
1436
1437   // Finally block implementation.
1438   __ bind(&finally_entry);
1439   EnterFinallyBlock();
1440   { Finally finally_body(this);
1441     Visit(stmt->finally_block());
1442   }
1443   ExitFinallyBlock();  // Return to the calling code.
1444
1445   // Set up try handler.
1446   __ bind(&try_entry);
1447   __ PushTryHandler(StackHandler::FINALLY, stmt->index());
1448   { TryFinally try_body(this, &finally_entry);
1449     Visit(stmt->try_block());
1450   }
1451   __ PopTryHandler();
1452   // Execute the finally block on the way out.  Clobber the unpredictable
1453   // value in the result register with one that's safe for GC because the
1454   // finally block will unconditionally preserve the result register on the
1455   // stack.
1456   ClearAccumulator();
1457   __ Call(&finally_entry);
1458 }
1459
1460
1461 void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1462   Comment cmnt(masm_, "[ DebuggerStatement");
1463   SetStatementPosition(stmt);
1464
1465   __ DebugBreak();
1466   // Ignore the return value.
1467 }
1468
1469
1470 void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
1471   UNREACHABLE();
1472 }
1473
1474
1475 void FullCodeGenerator::VisitConditional(Conditional* expr) {
1476   Comment cmnt(masm_, "[ Conditional");
1477   Label true_case, false_case, done;
1478   VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1479
1480   PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1481   __ bind(&true_case);
1482   SetExpressionPosition(expr->then_expression());
1483   if (context()->IsTest()) {
1484     const TestContext* for_test = TestContext::cast(context());
1485     VisitForControl(expr->then_expression(),
1486                     for_test->true_label(),
1487                     for_test->false_label(),
1488                     NULL);
1489   } else {
1490     VisitInDuplicateContext(expr->then_expression());
1491     __ jmp(&done);
1492   }
1493
1494   PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1495   __ bind(&false_case);
1496   SetExpressionPosition(expr->else_expression());
1497   VisitInDuplicateContext(expr->else_expression());
1498   // If control flow falls through Visit, merge it with true case here.
1499   if (!context()->IsTest()) {
1500     __ bind(&done);
1501   }
1502 }
1503
1504
1505 void FullCodeGenerator::VisitLiteral(Literal* expr) {
1506   Comment cmnt(masm_, "[ Literal");
1507   context()->Plug(expr->value());
1508 }
1509
1510
1511 void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
1512   Comment cmnt(masm_, "[ FunctionLiteral");
1513
1514   // Build the function boilerplate and instantiate it.
1515   Handle<SharedFunctionInfo> function_info =
1516       Compiler::BuildFunctionInfo(expr, script(), info_);
1517   if (function_info.is_null()) {
1518     SetStackOverflow();
1519     return;
1520   }
1521   EmitNewClosure(function_info, expr->pretenure());
1522 }
1523
1524
1525 void FullCodeGenerator::VisitNativeFunctionLiteral(
1526     NativeFunctionLiteral* expr) {
1527   Comment cmnt(masm_, "[ NativeFunctionLiteral");
1528
1529   // Compute the function template for the native function.
1530   Handle<String> name = expr->name();
1531   v8::Handle<v8::FunctionTemplate> fun_template =
1532       expr->extension()->GetNativeFunctionTemplate(
1533           reinterpret_cast<v8::Isolate*>(isolate()), v8::Utils::ToLocal(name));
1534   DCHECK(!fun_template.IsEmpty());
1535
1536   // Instantiate the function and create a shared function info from it.
1537   Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
1538   const int literals = fun->NumberOfLiterals();
1539   Handle<Code> code = Handle<Code>(fun->shared()->code());
1540   Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
1541   bool is_generator = false;
1542   bool is_arrow = false;
1543   Handle<SharedFunctionInfo> shared =
1544       isolate()->factory()->NewSharedFunctionInfo(
1545           name, literals, is_generator, is_arrow, code,
1546           Handle<ScopeInfo>(fun->shared()->scope_info()),
1547           Handle<FixedArray>(fun->shared()->feedback_vector()));
1548   shared->set_construct_stub(*construct_stub);
1549
1550   // Copy the function data to the shared function info.
1551   shared->set_function_data(fun->shared()->function_data());
1552   int parameters = fun->shared()->formal_parameter_count();
1553   shared->set_formal_parameter_count(parameters);
1554
1555   EmitNewClosure(shared, false);
1556 }
1557
1558
1559 void FullCodeGenerator::VisitThrow(Throw* expr) {
1560   Comment cmnt(masm_, "[ Throw");
1561   VisitForStackValue(expr->exception());
1562   __ CallRuntime(Runtime::kThrow, 1);
1563   // Never returns here.
1564 }
1565
1566
1567 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryCatch::Exit(
1568     int* stack_depth,
1569     int* context_length) {
1570   // The macros used here must preserve the result register.
1571   __ Drop(*stack_depth);
1572   __ PopTryHandler();
1573   *stack_depth = 0;
1574   return previous_;
1575 }
1576
1577
1578 bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1579   Expression* sub_expr;
1580   Handle<String> check;
1581   if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1582     EmitLiteralCompareTypeof(expr, sub_expr, check);
1583     return true;
1584   }
1585
1586   if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
1587     EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1588     return true;
1589   }
1590
1591   if (expr->IsLiteralCompareNull(&sub_expr)) {
1592     EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1593     return true;
1594   }
1595
1596   return false;
1597 }
1598
1599
1600 void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1601   DisallowHeapAllocation no_gc;
1602   Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1603
1604   // Increment loop nesting level by one and iterate over the back edge table
1605   // to find the matching loops to patch the interrupt
1606   // call to an unconditional call to the replacement code.
1607   int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level() + 1;
1608   if (loop_nesting_level > Code::kMaxLoopNestingMarker) return;
1609
1610   BackEdgeTable back_edges(unoptimized, &no_gc);
1611   for (uint32_t i = 0; i < back_edges.length(); i++) {
1612     if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1613       DCHECK_EQ(INTERRUPT, GetBackEdgeState(isolate,
1614                                             unoptimized,
1615                                             back_edges.pc(i)));
1616       PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1617     }
1618   }
1619
1620   unoptimized->set_allow_osr_at_loop_nesting_level(loop_nesting_level);
1621   DCHECK(Verify(isolate, unoptimized));
1622 }
1623
1624
1625 void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1626   DisallowHeapAllocation no_gc;
1627   Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1628
1629   // Iterate over the back edge table and revert the patched interrupt calls.
1630   int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1631
1632   BackEdgeTable back_edges(unoptimized, &no_gc);
1633   for (uint32_t i = 0; i < back_edges.length(); i++) {
1634     if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1635       DCHECK_NE(INTERRUPT, GetBackEdgeState(isolate,
1636                                             unoptimized,
1637                                             back_edges.pc(i)));
1638       PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1639     }
1640   }
1641
1642   unoptimized->set_allow_osr_at_loop_nesting_level(0);
1643   // Assert that none of the back edges are patched anymore.
1644   DCHECK(Verify(isolate, unoptimized));
1645 }
1646
1647
1648 void BackEdgeTable::AddStackCheck(Handle<Code> code, uint32_t pc_offset) {
1649   DisallowHeapAllocation no_gc;
1650   Isolate* isolate = code->GetIsolate();
1651   Address pc = code->instruction_start() + pc_offset;
1652   Code* patch = isolate->builtins()->builtin(Builtins::kOsrAfterStackCheck);
1653   PatchAt(*code, pc, OSR_AFTER_STACK_CHECK, patch);
1654 }
1655
1656
1657 void BackEdgeTable::RemoveStackCheck(Handle<Code> code, uint32_t pc_offset) {
1658   DisallowHeapAllocation no_gc;
1659   Isolate* isolate = code->GetIsolate();
1660   Address pc = code->instruction_start() + pc_offset;
1661
1662   if (OSR_AFTER_STACK_CHECK == GetBackEdgeState(isolate, *code, pc)) {
1663     Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1664     PatchAt(*code, pc, ON_STACK_REPLACEMENT, patch);
1665   }
1666 }
1667
1668
1669 #ifdef DEBUG
1670 bool BackEdgeTable::Verify(Isolate* isolate, Code* unoptimized) {
1671   DisallowHeapAllocation no_gc;
1672   int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1673   BackEdgeTable back_edges(unoptimized, &no_gc);
1674   for (uint32_t i = 0; i < back_edges.length(); i++) {
1675     uint32_t loop_depth = back_edges.loop_depth(i);
1676     CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
1677     // Assert that all back edges for shallower loops (and only those)
1678     // have already been patched.
1679     CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
1680              GetBackEdgeState(isolate,
1681                               unoptimized,
1682                               back_edges.pc(i)) != INTERRUPT);
1683   }
1684   return true;
1685 }
1686 #endif  // DEBUG
1687
1688
1689 #undef __
1690
1691
1692 } }  // namespace v8::internal