full-codegen.cc 54 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6
#include "src/v8.h"

7 8
#include "src/ast.h"
#include "src/ast-numbering.h"
9
#include "src/code-factory.h"
10 11 12 13 14 15 16 17
#include "src/codegen.h"
#include "src/compiler.h"
#include "src/debug.h"
#include "src/full-codegen.h"
#include "src/liveedit.h"
#include "src/macro-assembler.h"
#include "src/prettyprinter.h"
#include "src/scopeinfo.h"
18
#include "src/scopes.h"
19
#include "src/snapshot.h"
20 21 22 23

namespace v8 {
namespace internal {

24 25 26 27 28 29 30 31 32 33
void BreakableStatementChecker::Check(Statement* stmt) {
  Visit(stmt);
}


void BreakableStatementChecker::Check(Expression* expr) {
  Visit(expr);
}


34 35
void BreakableStatementChecker::VisitVariableDeclaration(
    VariableDeclaration* decl) {
36 37
}

arv@chromium.org's avatar
arv@chromium.org committed
38

39 40 41 42
void BreakableStatementChecker::VisitFunctionDeclaration(
    FunctionDeclaration* decl) {
}

arv@chromium.org's avatar
arv@chromium.org committed
43

44 45 46 47
void BreakableStatementChecker::VisitModuleDeclaration(
    ModuleDeclaration* decl) {
}

arv@chromium.org's avatar
arv@chromium.org committed
48

49 50 51 52
void BreakableStatementChecker::VisitImportDeclaration(
    ImportDeclaration* decl) {
}

arv@chromium.org's avatar
arv@chromium.org committed
53

54 55 56 57
void BreakableStatementChecker::VisitExportDeclaration(
    ExportDeclaration* decl) {
}

58 59 60 61

void BreakableStatementChecker::VisitModuleLiteral(ModuleLiteral* module) {
}

62

63 64 65
void BreakableStatementChecker::VisitModuleVariable(ModuleVariable* module) {
}

66

67 68 69
void BreakableStatementChecker::VisitModulePath(ModulePath* module) {
}

70

71 72 73
void BreakableStatementChecker::VisitModuleUrl(ModuleUrl* module) {
}

74

75 76 77 78
void BreakableStatementChecker::VisitModuleStatement(ModuleStatement* stmt) {
}


79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
void BreakableStatementChecker::VisitBlock(Block* stmt) {
}


void BreakableStatementChecker::VisitExpressionStatement(
    ExpressionStatement* stmt) {
  // Check if expression is breakable.
  Visit(stmt->expression());
}


void BreakableStatementChecker::VisitEmptyStatement(EmptyStatement* stmt) {
}


void BreakableStatementChecker::VisitIfStatement(IfStatement* stmt) {
  // If the condition is breakable the if statement is breakable.
  Visit(stmt->condition());
}


void BreakableStatementChecker::VisitContinueStatement(
    ContinueStatement* stmt) {
}


void BreakableStatementChecker::VisitBreakStatement(BreakStatement* stmt) {
}


void BreakableStatementChecker::VisitReturnStatement(ReturnStatement* stmt) {
  // Return is breakable if the expression is.
  Visit(stmt->expression());
}


115
void BreakableStatementChecker::VisitWithStatement(WithStatement* stmt) {
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
  Visit(stmt->expression());
}


void BreakableStatementChecker::VisitSwitchStatement(SwitchStatement* stmt) {
  // Switch statements breakable if the tag expression is.
  Visit(stmt->tag());
}


void BreakableStatementChecker::VisitDoWhileStatement(DoWhileStatement* stmt) {
  // Mark do while as breakable to avoid adding a break slot in front of it.
  is_breakable_ = true;
}


void BreakableStatementChecker::VisitWhileStatement(WhileStatement* stmt) {
  // Mark while statements breakable if the condition expression is.
  Visit(stmt->cond());
}


void BreakableStatementChecker::VisitForStatement(ForStatement* stmt) {
  // Mark for statements breakable if the condition expression is.
  if (stmt->cond() != NULL) {
    Visit(stmt->cond());
  }
}


void BreakableStatementChecker::VisitForInStatement(ForInStatement* stmt) {
  // Mark for in statements breakable if the enumerable expression is.
  Visit(stmt->enumerable());
}


152
void BreakableStatementChecker::VisitForOfStatement(ForOfStatement* stmt) {
153 154
  // For-of is breakable because of the next() call.
  is_breakable_ = true;
155 156 157
}


158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
void BreakableStatementChecker::VisitTryCatchStatement(
    TryCatchStatement* stmt) {
  // Mark try catch as breakable to avoid adding a break slot in front of it.
  is_breakable_ = true;
}


void BreakableStatementChecker::VisitTryFinallyStatement(
    TryFinallyStatement* stmt) {
  // Mark try finally as breakable to avoid adding a break slot in front of it.
  is_breakable_ = true;
}


void BreakableStatementChecker::VisitDebuggerStatement(
    DebuggerStatement* stmt) {
  // The debugger statement is breakable.
  is_breakable_ = true;
}


179 180 181 182
void BreakableStatementChecker::VisitCaseClause(CaseClause* clause) {
}


183 184 185 186
void BreakableStatementChecker::VisitFunctionLiteral(FunctionLiteral* expr) {
}


arv@chromium.org's avatar
arv@chromium.org committed
187 188 189 190 191 192 193
void BreakableStatementChecker::VisitClassLiteral(ClassLiteral* expr) {
  if (expr->extends() != NULL) {
    Visit(expr->extends());
  }
}


194 195
void BreakableStatementChecker::VisitNativeFunctionLiteral(
    NativeFunctionLiteral* expr) {
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
}


void BreakableStatementChecker::VisitConditional(Conditional* expr) {
}


void BreakableStatementChecker::VisitVariableProxy(VariableProxy* expr) {
}


void BreakableStatementChecker::VisitLiteral(Literal* expr) {
}


void BreakableStatementChecker::VisitRegExpLiteral(RegExpLiteral* expr) {
}


void BreakableStatementChecker::VisitObjectLiteral(ObjectLiteral* expr) {
}


void BreakableStatementChecker::VisitArrayLiteral(ArrayLiteral* expr) {
}


void BreakableStatementChecker::VisitAssignment(Assignment* expr) {
  // If assigning to a property (including a global property) the assignment is
  // breakable.
226
  VariableProxy* proxy = expr->target()->AsVariableProxy();
227
  Property* prop = expr->target()->AsProperty();
228
  if (prop != NULL || (proxy != NULL && proxy->var()->IsUnallocated())) {
229 230 231 232 233 234 235 236 237
    is_breakable_ = true;
    return;
  }

  // Otherwise the assignment is breakable if the assigned value is.
  Visit(expr->value());
}


238 239 240 241 242 243
void BreakableStatementChecker::VisitYield(Yield* expr) {
  // Yield is breakable if the expression is.
  Visit(expr->expression());
}


244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
void BreakableStatementChecker::VisitThrow(Throw* expr) {
  // Throw is breakable if the expression is.
  Visit(expr->exception());
}


void BreakableStatementChecker::VisitProperty(Property* expr) {
  // Property load is breakable.
  is_breakable_ = true;
}


void BreakableStatementChecker::VisitCall(Call* expr) {
  // Function calls both through IC and call stub are breakable.
  is_breakable_ = true;
}


void BreakableStatementChecker::VisitCallNew(CallNew* expr) {
  // Function calls through new are breakable.
  is_breakable_ = true;
}


void BreakableStatementChecker::VisitCallRuntime(CallRuntime* expr) {
}


void BreakableStatementChecker::VisitUnaryOperation(UnaryOperation* expr) {
  Visit(expr->expression());
}


void BreakableStatementChecker::VisitCountOperation(CountOperation* expr) {
  Visit(expr->expression());
}


void BreakableStatementChecker::VisitBinaryOperation(BinaryOperation* expr) {
  Visit(expr->left());
284 285 286 287
  if (expr->op() != Token::AND &&
      expr->op() != Token::OR) {
    Visit(expr->right());
  }
288 289 290 291 292 293 294 295 296 297 298 299 300
}


void BreakableStatementChecker::VisitCompareOperation(CompareOperation* expr) {
  Visit(expr->left());
  Visit(expr->right());
}


void BreakableStatementChecker::VisitThisFunction(ThisFunction* expr) {
}


301 302 303
void BreakableStatementChecker::VisitSuperReference(SuperReference* expr) {}


304
#define __ ACCESS_MASM(masm())
305

306
bool FullCodeGenerator::MakeCode(CompilationInfo* info) {
307
  Isolate* isolate = info->isolate();
308

309
  TimerEventScope<TimerEventCompileFullCode> timer(info->isolate());
310

311
  Handle<Script> script = info->script();
312 313
  if (!script->IsUndefined() && !script->source()->IsUndefined()) {
    int len = String::cast(script->source())->length();
314
    isolate->counters()->total_full_codegen_source_size()->Increment(len);
315
  }
316
  CodeGenerator::MakeCodePrologue(info, "full");
317
  const int kInitialBufferSize = 4 * KB;
318
  MacroAssembler masm(info->isolate(), NULL, kInitialBufferSize);
319
  if (info->will_serialize()) masm.enable_serializer();
320

321 322
  LOG_CODE_EVENT(isolate,
                 CodeStartLinePosInfoRecordEvent(masm.positions_recorder()));
323

324
  FullCodeGenerator cgen(&masm, info);
325
  cgen.Generate();
326
  if (cgen.HasStackOverflow()) {
327
    DCHECK(!isolate->has_pending_exception());
328
    return false;
329
  }
330
  unsigned table_offset = cgen.EmitBackEdgeTable();
331

332
  Code::Flags flags = Code::ComputeFlags(Code::FUNCTION);
333
  Handle<Code> code = CodeGenerator::MakeCodeEpilogue(&masm, flags, info);
334
  code->set_optimizable(info->IsOptimizable() &&
335
                        !info->function()->dont_optimize() &&
336
                        info->function()->scope()->AllowsLazyCompilation());
337
  cgen.PopulateDeoptimizationData(code);
338
  cgen.PopulateTypeFeedbackInfo(code);
339
  code->set_has_deoptimization_support(info->HasDeoptimizationSupport());
340
  code->set_handler_table(*cgen.handler_table());
341
  code->set_compiled_optimizable(info->IsOptimizable());
342
  code->set_allow_osr_at_loop_nesting_level(0);
343
  code->set_profiler_ticks(0);
344
  code->set_back_edge_table_offset(table_offset);
345
  CodeGenerator::PrintCode(code, info);
346 347 348
  info->SetCode(code);
  void* line_info = masm.positions_recorder()->DetachJITHandlerData();
  LOG_CODE_EVENT(isolate, CodeEndLinePosInfoRecordEvent(*code, line_info));
349 350 351 352 353

#ifdef DEBUG
  // Check that no context-specific object has been embedded.
  code->VerifyEmbeddedObjectsInFullCode();
#endif  // DEBUG
354
  return true;
355 356 357
}


358 359
unsigned FullCodeGenerator::EmitBackEdgeTable() {
  // The back edge table consists of a length (in number of entries)
360 361
  // field, and then a sequence of entries.  Each entry is a pair of AST id
  // and code-relative pc offset.
362
  masm()->Align(kPointerSize);
363
  unsigned offset = masm()->pc_offset();
364
  unsigned length = back_edges_.length();
365 366
  __ dd(length);
  for (unsigned i = 0; i < length; ++i) {
367 368
    __ dd(back_edges_[i].id.ToInt());
    __ dd(back_edges_[i].pc);
369
    __ dd(back_edges_[i].loop_depth);
370 371 372 373 374
  }
  return offset;
}


375 376
void FullCodeGenerator::EnsureSlotContainsAllocationSite(
    FeedbackVectorSlot slot) {
377 378
  Handle<TypeFeedbackVector> vector = FeedbackVector();
  if (!vector->Get(slot)->IsAllocationSite()) {
379 380
    Handle<AllocationSite> allocation_site =
        isolate()->factory()->NewAllocationSite();
381 382 383 384 385 386 387 388 389 390 391 392
    vector->Set(slot, *allocation_site);
  }
}


void FullCodeGenerator::EnsureSlotContainsAllocationSite(
    FeedbackVectorICSlot slot) {
  Handle<TypeFeedbackVector> vector = FeedbackVector();
  if (!vector->Get(slot)->IsAllocationSite()) {
    Handle<AllocationSite> allocation_site =
        isolate()->factory()->NewAllocationSite();
    vector->Set(slot, *allocation_site);
393 394 395 396
  }
}


397 398
void FullCodeGenerator::PopulateDeoptimizationData(Handle<Code> code) {
  // Fill in the deoptimization information.
399
  DCHECK(info_->HasDeoptimizationSupport() || bailout_entries_.is_empty());
400 401
  if (!info_->HasDeoptimizationSupport()) return;
  int length = bailout_entries_.length();
402 403
  Handle<DeoptimizationOutputData> data =
      DeoptimizationOutputData::New(isolate(), length, TENURED);
404
  for (int i = 0; i < length; i++) {
405
    data->SetAstId(i, bailout_entries_[i].id);
406 407 408 409 410 411
    data->SetPcAndState(i, Smi::FromInt(bailout_entries_[i].pc_and_state));
  }
  code->set_deoptimization_data(*data);
}


412 413 414
void FullCodeGenerator::PopulateTypeFeedbackInfo(Handle<Code> code) {
  Handle<TypeFeedbackInfo> info = isolate()->factory()->NewTypeFeedbackInfo();
  info->set_ic_total_count(ic_total_count_);
415
  DCHECK(!isolate()->heap()->InNewSpace(*info));
416 417 418 419
  code->set_type_feedback_info(*info);
}


420
void FullCodeGenerator::Initialize() {
421
  InitializeAstVisitor(info_->zone());
422 423 424 425 426 427
  // The generation of debug code must match between the snapshot code and the
  // code that is generated later.  This is assumed by the debugger when it is
  // calculating PC offsets after generating a debug version of code.  Therefore
  // we disable the production of debug code in the full compiler if we are
  // either generating a snapshot or we booted from a snapshot.
  generate_debug_code_ = FLAG_debug_code &&
428
                         !masm_->serializer_enabled() &&
429 430 431 432 433 434
                         !Snapshot::HaveASnapshotToStartFrom();
  masm_->set_emit_debug_code(generate_debug_code_);
  masm_->set_predictable_code_size(true);
}


435
void FullCodeGenerator::PrepareForBailout(Expression* node, State state) {
436 437 438 439
  PrepareForBailoutForId(node->id(), state);
}


verwaest@chromium.org's avatar
verwaest@chromium.org committed
440 441
void FullCodeGenerator::CallLoadIC(ContextualMode contextual_mode,
                                   TypeFeedbackId id) {
442
  Handle<Code> ic = CodeFactory::LoadIC(isolate(), contextual_mode).code();
443
  CallIC(ic, id);
444 445 446
}


447
void FullCodeGenerator::CallStoreIC(TypeFeedbackId id) {
448
  Handle<Code> ic = CodeFactory::StoreIC(isolate(), strict_mode()).code();
449
  CallIC(ic, id);
450 451 452
}


453 454 455 456 457 458 459 460 461 462 463
void FullCodeGenerator::RecordJSReturnSite(Call* call) {
  // We record the offset of the function return so we can rebuild the frame
  // if the function was inlined, i.e., this is the return address in the
  // inlined function's frame.
  //
  // The state is ignored.  We defensively set it to TOS_REG, which is the
  // real state of the unoptimized code at the return site.
  PrepareForBailoutForId(call->ReturnId(), TOS_REG);
#ifdef DEBUG
  // In debug builds, mark the return so we can verify that this function
  // was called.
464
  DCHECK(!call->return_is_recorded_);
465 466 467 468 469
  call->return_is_recorded_ = true;
#endif
}


470
void FullCodeGenerator::PrepareForBailoutForId(BailoutId id, State state) {
471 472
  // There's no need to prepare this code for bailouts from already optimized
  // code or code that can't be optimized.
473
  if (!info_->HasDeoptimizationSupport()) return;
474 475
  unsigned pc_and_state =
      StateField::encode(state) | PcField::encode(masm_->pc_offset());
476
  DCHECK(Smi::IsValid(pc_and_state));
477 478
#ifdef DEBUG
  for (int i = 0; i < bailout_entries_.length(); ++i) {
479
    DCHECK(bailout_entries_[i].id != id);
480 481
  }
#endif
482
  BailoutEntry entry = { id, pc_and_state };
483
  bailout_entries_.Add(entry, zone());
484 485 486
}


487 488
void FullCodeGenerator::RecordBackEdge(BailoutId ast_id) {
  // The pc offset does not need to be encoded and packed together with a state.
489 490
  DCHECK(masm_->pc_offset() > 0);
  DCHECK(loop_depth() > 0);
491 492 493 494
  uint8_t depth = Min(loop_depth(), Code::kMaxLoopNestingMarker);
  BackEdgeEntry entry =
      { ast_id, static_cast<unsigned>(masm_->pc_offset()), depth };
  back_edges_.Add(entry, zone());
495 496 497
}


498
bool FullCodeGenerator::ShouldInlineSmiCase(Token::Value op) {
499 500
  // Inline smi case inside loops, but not division and modulo which
  // are too complicated and take up too much space.
501 502 503
  if (op == Token::DIV ||op == Token::MOD) return false;
  if (FLAG_always_inline_smi_code) return true;
  return loop_depth_ > 0;
504 505 506
}


507 508 509 510 511 512 513 514 515 516
void FullCodeGenerator::EffectContext::Plug(Register reg) const {
}


void FullCodeGenerator::AccumulatorValueContext::Plug(Register reg) const {
  __ Move(result_register(), reg);
}


void FullCodeGenerator::StackValueContext::Plug(Register reg) const {
517
  __ Push(reg);
518 519 520 521 522 523
}


void FullCodeGenerator::TestContext::Plug(Register reg) const {
  // For simplicity we always test the accumulator register.
  __ Move(result_register(), reg);
524
  codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
525
  codegen()->DoTest(this);
526 527 528 529 530 531 532 533 534
}


void FullCodeGenerator::EffectContext::PlugTOS() const {
  __ Drop(1);
}


void FullCodeGenerator::AccumulatorValueContext::PlugTOS() const {
535
  __ Pop(result_register());
536 537 538 539 540 541 542 543 544
}


void FullCodeGenerator::StackValueContext::PlugTOS() const {
}


void FullCodeGenerator::TestContext::PlugTOS() const {
  // For simplicity we always test the accumulator register.
545
  __ Pop(result_register());
546
  codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
547
  codegen()->DoTest(this);
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
}


void FullCodeGenerator::EffectContext::PrepareTest(
    Label* materialize_true,
    Label* materialize_false,
    Label** if_true,
    Label** if_false,
    Label** fall_through) const {
  // In an effect context, the true and the false case branch to the
  // same label.
  *if_true = *if_false = *fall_through = materialize_true;
}


void FullCodeGenerator::AccumulatorValueContext::PrepareTest(
    Label* materialize_true,
    Label* materialize_false,
    Label** if_true,
    Label** if_false,
    Label** fall_through) const {
  *if_true = *fall_through = materialize_true;
  *if_false = materialize_false;
}


void FullCodeGenerator::StackValueContext::PrepareTest(
    Label* materialize_true,
    Label* materialize_false,
    Label** if_true,
    Label** if_false,
    Label** fall_through) const {
  *if_true = *fall_through = materialize_true;
  *if_false = materialize_false;
}


void FullCodeGenerator::TestContext::PrepareTest(
    Label* materialize_true,
    Label* materialize_false,
    Label** if_true,
    Label** if_false,
    Label** fall_through) const {
  *if_true = true_label_;
  *if_false = false_label_;
  *fall_through = fall_through_;
594 595 596
}


597 598 599 600 601 602 603 604
void FullCodeGenerator::DoTest(const TestContext* context) {
  DoTest(context->condition(),
         context->true_label(),
         context->false_label(),
         context->fall_through());
}


605
void FullCodeGenerator::AllocateModules(ZoneList<Declaration*>* declarations) {
606
  DCHECK(scope_->is_global_scope());
607 608 609 610 611 612 613 614 615

  for (int i = 0; i < declarations->length(); i++) {
    ModuleDeclaration* declaration = declarations->at(i)->AsModuleDeclaration();
    if (declaration != NULL) {
      ModuleLiteral* module = declaration->module()->AsModuleLiteral();
      if (module != NULL) {
        Comment cmnt(masm_, "[ Link nested modules");
        Scope* scope = module->body()->scope();
        Interface* interface = scope->interface();
616
        DCHECK(interface->IsModule() && interface->IsFrozen());
617 618 619 620

        interface->Allocate(scope->module_var()->index());

        // Set up module context.
621
        DCHECK(scope->interface()->Index() >= 0);
622 623
        __ Push(Smi::FromInt(scope->interface()->Index()));
        __ Push(scope->GetScopeInfo());
624
        __ CallRuntime(Runtime::kPushModuleContext, 2);
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
        StoreToFrameField(StandardFrameConstants::kContextOffset,
                          context_register());

        AllocateModules(scope->declarations());

        // Pop module context.
        LoadContextField(context_register(), Context::PREVIOUS_INDEX);
        // Update local stack frame context field.
        StoreToFrameField(StandardFrameConstants::kContextOffset,
                          context_register());
      }
    }
  }
}


// Modules have their own local scope, represented by their own context.
// Module instance objects have an accessor for every export that forwards
// access to the respective slot from the module's context. (Exports that are
// modules themselves, however, are simple data properties.)
//
// All modules have a _hosting_ scope/context, which (currently) is the
// (innermost) enclosing global scope. To deal with recursion, nested modules
// are hosted by the same scope as global ones.
//
// For every (global or nested) module literal, the hosting context has an
// internal slot that points directly to the respective module context. This
// enables quick access to (statically resolved) module members by 2-dimensional
// access through the hosting context. For example,
//
//   module A {
//     let x;
//     module B { let y; }
//   }
//   module C { let z; }
//
// allocates contexts as follows:
//
// [header| .A | .B | .C | A | C ]  (global)
//           |    |    |
//           |    |    +-- [header| z ]  (module)
//           |    |
//           |    +------- [header| y ]  (module)
//           |
//           +------------ [header| x | B ]  (module)
//
// Here, .A, .B, .C are the internal slots pointing to the hosted module
// contexts, whereas A, B, C hold the actual instance objects (note that every
// module context also points to the respective instance object through its
// extension slot in the header).
//
// To deal with arbitrary recursion and aliases between modules,
// they are created and initialized in several stages. Each stage applies to
// all modules in the hosting global scope, including nested ones.
//
// 1. Allocate: for each module _literal_, allocate the module contexts and
//    respective instance object and wire them up. This happens in the
//    PushModuleContext runtime function, as generated by AllocateModules
//    (invoked by VisitDeclarations in the hosting scope).
//
// 2. Bind: for each module _declaration_ (i.e. literals as well as aliases),
//    assign the respective instance object to respective local variables. This
//    happens in VisitModuleDeclaration, and uses the instance objects created
//    in the previous stage.
//    For each module _literal_, this phase also constructs a module descriptor
//    for the next stage. This happens in VisitModuleLiteral.
//
// 3. Populate: invoke the DeclareModules runtime function to populate each
//    _instance_ object with accessors for it exports. This is generated by
//    DeclareModules (invoked by VisitDeclarations in the hosting scope again),
//    and uses the descriptors generated in the previous stage.
//
// 4. Initialize: execute the module bodies (and other code) in sequence. This
//    happens by the separate statements generated for module bodies. To reenter
//    the module scopes properly, the parser inserted ModuleStatements.

701
void FullCodeGenerator::VisitDeclarations(
702
    ZoneList<Declaration*>* declarations) {
703 704
  Handle<FixedArray> saved_modules = modules_;
  int saved_module_index = module_index_;
705
  ZoneList<Handle<Object> >* saved_globals = globals_;
706
  ZoneList<Handle<Object> > inner_globals(10, zone());
707 708
  globals_ = &inner_globals;

709 710 711 712
  if (scope_->num_modules() != 0) {
    // This is a scope hosting modules. Allocate a descriptor array to pass
    // to the runtime for initialization.
    Comment cmnt(masm_, "[ Allocate modules");
713
    DCHECK(scope_->is_global_scope());
714 715 716 717 718 719 720 721 722
    modules_ =
        isolate()->factory()->NewFixedArray(scope_->num_modules(), TENURED);
    module_index_ = 0;

    // Generate code for allocating all modules, including nested ones.
    // The allocated contexts are stored in internal variables in this scope.
    AllocateModules(declarations);
  }

723
  AstVisitor::VisitDeclarations(declarations);
724 725 726

  if (scope_->num_modules() != 0) {
    // Initialize modules from descriptor array.
727
    DCHECK(module_index_ == modules_->length());
728 729 730 731 732
    DeclareModules(modules_);
    modules_ = saved_modules;
    module_index_ = saved_module_index;
  }

733
  if (!globals_->is_empty()) {
734
    // Invoke the platform-dependent code generator to do the actual
735
    // declaration of the global functions and variables.
736
    Handle<FixedArray> array =
737 738 739
       isolate()->factory()->NewFixedArray(globals_->length(), TENURED);
    for (int i = 0; i < globals_->length(); ++i)
      array->set(i, *globals_->at(i));
740
    DeclareGlobals(array);
741
  }
742 743

  globals_ = saved_globals;
744 745 746
}


747
void FullCodeGenerator::VisitModuleLiteral(ModuleLiteral* module) {
748 749 750
  Block* block = module->body();
  Scope* saved_scope = scope();
  scope_ = block->scope();
751
  Interface* interface = scope_->interface();
752 753 754 755

  Comment cmnt(masm_, "[ ModuleLiteral");
  SetStatementPosition(block);

756 757
  DCHECK(!modules_.is_null());
  DCHECK(module_index_ < modules_->length());
758 759
  int index = module_index_++;

760
  // Set up module context.
761
  DCHECK(interface->Index() >= 0);
762 763
  __ Push(Smi::FromInt(interface->Index()));
  __ Push(Smi::FromInt(0));
764
  __ CallRuntime(Runtime::kPushModuleContext, 2);
765
  StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
766 767 768 769 770 771

  {
    Comment cmnt(masm_, "[ Declarations");
    VisitDeclarations(scope_->declarations());
  }

772 773 774 775 776
  // Populate the module description.
  Handle<ModuleInfo> description =
      ModuleInfo::Create(isolate(), interface, scope_);
  modules_->set(index, *description);

777
  scope_ = saved_scope;
778 779 780 781
  // Pop module context.
  LoadContextField(context_register(), Context::PREVIOUS_INDEX);
  // Update local stack frame context field.
  StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
782 783 784 785
}


void FullCodeGenerator::VisitModuleVariable(ModuleVariable* module) {
786
  // Nothing to do.
787
  // The instance object is resolved statically through the module's interface.
788 789 790 791
}


void FullCodeGenerator::VisitModulePath(ModulePath* module) {
792
  // Nothing to do.
793
  // The instance object is resolved statically through the module's interface.
794 795 796
}


797 798 799 800 801
void FullCodeGenerator::VisitModuleUrl(ModuleUrl* module) {
  // TODO(rossberg): dummy allocation for now.
  Scope* scope = module->body()->scope();
  Interface* interface = scope_->interface();

802 803 804
  DCHECK(interface->IsModule() && interface->IsFrozen());
  DCHECK(!modules_.is_null());
  DCHECK(module_index_ < modules_->length());
805 806 807 808 809 810
  interface->Allocate(scope->module_var()->index());
  int index = module_index_++;

  Handle<ModuleInfo> description =
      ModuleInfo::Create(isolate(), interface, scope_);
  modules_->set(index, *description);
811 812 813
}


814
int FullCodeGenerator::DeclareGlobalsFlags() {
815
  DCHECK(DeclareGlobalsStrictMode::is_valid(strict_mode()));
816
  return DeclareGlobalsEvalFlag::encode(is_eval()) |
817
      DeclareGlobalsNativeFlag::encode(is_native()) |
818
      DeclareGlobalsStrictMode::encode(strict_mode());
819 820 821
}


822
void FullCodeGenerator::SetFunctionPosition(FunctionLiteral* fun) {
823
  CodeGenerator::RecordPositions(masm_, fun->start_position());
824 825 826
}


827
void FullCodeGenerator::SetReturnPosition(FunctionLiteral* fun) {
828
  CodeGenerator::RecordPositions(masm_, fun->end_position() - 1);
829 830 831
}


832
void FullCodeGenerator::SetStatementPosition(Statement* stmt) {
833
  if (!info_->is_debug()) {
834
    CodeGenerator::RecordPositions(masm_, stmt->position());
835 836 837
  } else {
    // Check if the statement will be breakable without adding a debug break
    // slot.
838
    BreakableStatementChecker checker(zone());
839 840 841 842 843
    checker.Check(stmt);
    // Record the statement position right here if the statement is not
    // breakable. For breakable statements the actual recording of the
    // position will be postponed to the breakable code (typically an IC).
    bool position_recorded = CodeGenerator::RecordPositions(
844
        masm_, stmt->position(), !checker.is_breakable());
845 846 847
    // If the position recording did record a new position generate a debug
    // break slot to make the statement breakable.
    if (position_recorded) {
848
      DebugCodegen::GenerateSlot(masm_);
849
    }
850
  }
851 852 853
}


854
void FullCodeGenerator::VisitSuperReference(SuperReference* super) {
855
  __ CallRuntime(Runtime::kThrowUnsupportedSuperError, 0);
856 857 858
}


859
void FullCodeGenerator::SetExpressionPosition(Expression* expr) {
860
  if (!info_->is_debug()) {
861
    CodeGenerator::RecordPositions(masm_, expr->position());
862 863 864
  } else {
    // Check if the expression will be breakable without adding a debug break
    // slot.
865
    BreakableStatementChecker checker(zone());
866 867 868 869 870 871 872 873 874
    checker.Check(expr);
    // Record a statement position right here if the expression is not
    // breakable. For breakable expressions the actual recording of the
    // position will be postponed to the breakable code (typically an IC).
    // NOTE this will record a statement position for something which might
    // not be a statement. As stepping in the debugger will only stop at
    // statement positions this is used for e.g. the condition expression of
    // a do while loop.
    bool position_recorded = CodeGenerator::RecordPositions(
875
        masm_, expr->position(), !checker.is_breakable());
876 877 878
    // If the position recording did record a new position generate a debug
    // break slot to make the statement breakable.
    if (position_recorded) {
879
      DebugCodegen::GenerateSlot(masm_);
880
    }
881
  }
882 883 884
}


885
void FullCodeGenerator::SetSourcePosition(int pos) {
886
  if (pos != RelocInfo::kNoPosition) {
887
    masm_->positions_recorder()->RecordPosition(pos);
888 889 890
  }
}

891

892 893 894 895 896 897 898 899 900 901 902 903 904 905
// Lookup table for code generators for  special runtime calls which are
// generated inline.
#define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize)          \
    &FullCodeGenerator::Emit##Name,

const FullCodeGenerator::InlineFunctionGenerator
  FullCodeGenerator::kInlineFunctionGenerators[] = {
    INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS)
  };
#undef INLINE_FUNCTION_GENERATOR_ADDRESS


FullCodeGenerator::InlineFunctionGenerator
  FullCodeGenerator::FindInlineFunctionGenerator(Runtime::FunctionId id) {
906 907
    int lookup_index =
        static_cast<int>(id) - static_cast<int>(Runtime::kFirstInlineFunction);
908 909
    DCHECK(lookup_index >= 0);
    DCHECK(static_cast<size_t>(lookup_index) <
910
           arraysize(kInlineFunctionGenerators));
911
    return kInlineFunctionGenerators[lookup_index];
912 913 914
}


915 916
void FullCodeGenerator::EmitInlineRuntimeCall(CallRuntime* expr) {
  const Runtime::Function* function = expr->function();
917 918
  DCHECK(function != NULL);
  DCHECK(function->intrinsic_type == Runtime::INLINE);
919 920
  InlineFunctionGenerator generator =
      FindInlineFunctionGenerator(function->function_id);
921
  ((*this).*(generator))(expr);
922 923 924
}


925
void FullCodeGenerator::EmitGeneratorNext(CallRuntime* expr) {
926
  ZoneList<Expression*>* args = expr->arguments();
927
  DCHECK(args->length() == 2);
928
  EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::NEXT);
929 930 931 932 933
}


void FullCodeGenerator::EmitGeneratorThrow(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
934
  DCHECK(args->length() == 2);
935 936 937 938
  EmitGeneratorResume(args->at(0), args->at(1), JSGeneratorObject::THROW);
}


939 940 941 942 943
void FullCodeGenerator::EmitDebugBreakInOptimizedCode(CallRuntime* expr) {
  context()->Plug(handle(Smi::FromInt(0), isolate()));
}


944
void FullCodeGenerator::VisitBinaryOperation(BinaryOperation* expr) {
945
  switch (expr->op()) {
946
    case Token::COMMA:
947
      return VisitComma(expr);
948 949
    case Token::OR:
    case Token::AND:
950
      return VisitLogicalExpression(expr);
951
    default:
952
      return VisitArithmeticExpression(expr);
953 954 955 956
  }
}


957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
void FullCodeGenerator::VisitInDuplicateContext(Expression* expr) {
  if (context()->IsEffect()) {
    VisitForEffect(expr);
  } else if (context()->IsAccumulatorValue()) {
    VisitForAccumulatorValue(expr);
  } else if (context()->IsStackValue()) {
    VisitForStackValue(expr);
  } else if (context()->IsTest()) {
    const TestContext* test = TestContext::cast(context());
    VisitForControl(expr, test->true_label(), test->false_label(),
                    test->fall_through());
  }
}


972 973 974
void FullCodeGenerator::VisitComma(BinaryOperation* expr) {
  Comment cmnt(masm_, "[ Comma");
  VisitForEffect(expr->left());
975
  VisitInDuplicateContext(expr->right());
976 977 978
}


979 980 981 982 983
void FullCodeGenerator::VisitLogicalExpression(BinaryOperation* expr) {
  bool is_logical_and = expr->op() == Token::AND;
  Comment cmnt(masm_, is_logical_and ? "[ Logical AND" :  "[ Logical OR");
  Expression* left = expr->left();
  Expression* right = expr->right();
984
  BailoutId right_id = expr->RightId();
985
  Label done;
986

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
  if (context()->IsTest()) {
    Label eval_right;
    const TestContext* test = TestContext::cast(context());
    if (is_logical_and) {
      VisitForControl(left, &eval_right, test->false_label(), &eval_right);
    } else {
      VisitForControl(left, test->true_label(), &eval_right, &eval_right);
    }
    PrepareForBailoutForId(right_id, NO_REGISTERS);
    __ bind(&eval_right);

  } else if (context()->IsAccumulatorValue()) {
    VisitForAccumulatorValue(left);
    // We want the value in the accumulator for the test, and on the stack in
    // case we need it.
1002
    __ Push(result_register());
1003 1004
    Label discard, restore;
    if (is_logical_and) {
1005
      DoTest(left, &discard, &restore, &restore);
1006
    } else {
1007
      DoTest(left, &restore, &discard, &restore);
1008 1009
    }
    __ bind(&restore);
1010
    __ Pop(result_register());
1011 1012 1013 1014 1015 1016 1017 1018 1019
    __ jmp(&done);
    __ bind(&discard);
    __ Drop(1);
    PrepareForBailoutForId(right_id, NO_REGISTERS);

  } else if (context()->IsStackValue()) {
    VisitForAccumulatorValue(left);
    // We want the value in the accumulator for the test, and on the stack in
    // case we need it.
1020
    __ Push(result_register());
1021 1022
    Label discard;
    if (is_logical_and) {
1023
      DoTest(left, &discard, &done, &discard);
1024
    } else {
1025
      DoTest(left, &done, &discard, &discard);
1026 1027 1028 1029
    }
    __ bind(&discard);
    __ Drop(1);
    PrepareForBailoutForId(right_id, NO_REGISTERS);
1030 1031

  } else {
1032
    DCHECK(context()->IsEffect());
1033 1034 1035 1036 1037 1038 1039 1040
    Label eval_right;
    if (is_logical_and) {
      VisitForControl(left, &eval_right, &done, &eval_right);
    } else {
      VisitForControl(left, &done, &eval_right, &eval_right);
    }
    PrepareForBailoutForId(right_id, NO_REGISTERS);
    __ bind(&eval_right);
1041
  }
1042

1043
  VisitInDuplicateContext(right);
1044
  __ bind(&done);
1045
}
1046

1047

1048 1049 1050 1051 1052 1053 1054 1055 1056
void FullCodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
  Token::Value op = expr->op();
  Comment cmnt(masm_, "[ ArithmeticExpression");
  Expression* left = expr->left();
  Expression* right = expr->right();
  OverwriteMode mode =
      left->ResultOverwriteAllowed()
      ? OVERWRITE_LEFT
      : (right->ResultOverwriteAllowed() ? OVERWRITE_RIGHT : NO_OVERWRITE);
1057

1058 1059
  VisitForStackValue(left);
  VisitForAccumulatorValue(right);
1060

1061 1062 1063
  SetSourcePosition(expr->position());
  if (ShouldInlineSmiCase(op)) {
    EmitInlineSmiBinaryOp(expr, op, mode, left, right);
1064
  } else {
1065
    EmitBinaryOp(expr, op, mode);
1066 1067 1068 1069
  }
}


1070
void FullCodeGenerator::VisitBlock(Block* stmt) {
1071
  Comment cmnt(masm_, "[ Block");
1072
  NestedBlock nested_block(this, stmt);
1073
  SetStatementPosition(stmt);
1074

1075
  Scope* saved_scope = scope();
1076
  // Push a block context when entering a block with block scoped variables.
1077 1078 1079
  if (stmt->scope() == NULL) {
    PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
  } else {
1080
    scope_ = stmt->scope();
1081
    DCHECK(!scope_->is_module_scope());
1082
    { Comment cmnt(masm_, "[ Extend block context");
1083
      __ Push(scope_->GetScopeInfo());
1084
      PushFunctionArgumentForContextAllocation();
1085
      __ CallRuntime(Runtime::kPushBlockContext, 2);
1086 1087 1088 1089

      // Replace the context stored in the frame.
      StoreToFrameField(StandardFrameConstants::kContextOffset,
                        context_register());
1090
      PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
1091 1092 1093
    }
    { Comment cmnt(masm_, "[ Declarations");
      VisitDeclarations(scope_->declarations());
1094
      PrepareForBailoutForId(stmt->DeclsId(), NO_REGISTERS);
1095 1096
    }
  }
1097

1098
  VisitStatements(stmt->statements());
1099
  scope_ = saved_scope;
1100
  __ bind(nested_block.break_label());
1101 1102

  // Pop block context if necessary.
1103
  if (stmt->scope() != NULL) {
1104 1105 1106 1107 1108
    LoadContextField(context_register(), Context::PREVIOUS_INDEX);
    // Update local stack frame context field.
    StoreToFrameField(StandardFrameConstants::kContextOffset,
                      context_register());
  }
1109
  PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1110 1111 1112
}


1113 1114 1115 1116 1117
void FullCodeGenerator::VisitModuleStatement(ModuleStatement* stmt) {
  Comment cmnt(masm_, "[ Module context");

  __ Push(Smi::FromInt(stmt->proxy()->interface()->Index()));
  __ Push(Smi::FromInt(0));
1118
  __ CallRuntime(Runtime::kPushModuleContext, 2);
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
  StoreToFrameField(
      StandardFrameConstants::kContextOffset, context_register());

  Scope* saved_scope = scope_;
  scope_ = stmt->body()->scope();
  VisitStatements(stmt->body()->statements());
  scope_ = saved_scope;
  LoadContextField(context_register(), Context::PREVIOUS_INDEX);
  // Update local stack frame context field.
  StoreToFrameField(StandardFrameConstants::kContextOffset,
                    context_register());
}


1133
void FullCodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
1134 1135
  Comment cmnt(masm_, "[ ExpressionStatement");
  SetStatementPosition(stmt);
1136
  VisitForEffect(stmt->expression());
1137 1138 1139
}


1140
void FullCodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
1141 1142
  Comment cmnt(masm_, "[ EmptyStatement");
  SetStatementPosition(stmt);
1143 1144 1145
}


1146
void FullCodeGenerator::VisitIfStatement(IfStatement* stmt) {
1147
  Comment cmnt(masm_, "[ IfStatement");
1148
  SetStatementPosition(stmt);
1149 1150
  Label then_part, else_part, done;

1151 1152
  if (stmt->HasElseStatement()) {
    VisitForControl(stmt->condition(), &then_part, &else_part, &then_part);
1153
    PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1154 1155 1156
    __ bind(&then_part);
    Visit(stmt->then_statement());
    __ jmp(&done);
1157

1158
    PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1159 1160 1161 1162
    __ bind(&else_part);
    Visit(stmt->else_statement());
  } else {
    VisitForControl(stmt->condition(), &then_part, &done, &then_part);
1163
    PrepareForBailoutForId(stmt->ThenId(), NO_REGISTERS);
1164 1165
    __ bind(&then_part);
    Visit(stmt->then_statement());
1166 1167

    PrepareForBailoutForId(stmt->ElseId(), NO_REGISTERS);
1168
  }
1169
  __ bind(&done);
1170
  PrepareForBailoutForId(stmt->IfId(), NO_REGISTERS);
1171 1172 1173
}


1174
void FullCodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
1175
  Comment cmnt(masm_,  "[ ContinueStatement");
1176
  SetStatementPosition(stmt);
1177 1178
  NestedStatement* current = nesting_stack_;
  int stack_depth = 0;
1179
  int context_length = 0;
kmillikin@chromium.org's avatar
kmillikin@chromium.org committed
1180 1181 1182 1183 1184
  // When continuing, we clobber the unpredictable value in the accumulator
  // with one that's safe for GC.  If we hit an exit from the try block of
  // try...finally on our way out, we will unconditionally preserve the
  // accumulator on the stack.
  ClearAccumulator();
1185
  while (!current->IsContinueTarget(stmt->target())) {
1186
    current = current->Exit(&stack_depth, &context_length);
1187 1188
  }
  __ Drop(stack_depth);
1189 1190 1191 1192 1193 1194 1195 1196
  if (context_length > 0) {
    while (context_length > 0) {
      LoadContextField(context_register(), Context::PREVIOUS_INDEX);
      --context_length;
    }
    StoreToFrameField(StandardFrameConstants::kContextOffset,
                      context_register());
  }
1197

1198
  __ jmp(current->AsIteration()->continue_label());
1199 1200 1201
}


1202
void FullCodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
1203
  Comment cmnt(masm_,  "[ BreakStatement");
1204
  SetStatementPosition(stmt);
1205 1206
  NestedStatement* current = nesting_stack_;
  int stack_depth = 0;
1207
  int context_length = 0;
kmillikin@chromium.org's avatar
kmillikin@chromium.org committed
1208 1209 1210 1211 1212
  // When breaking, we clobber the unpredictable value in the accumulator
  // with one that's safe for GC.  If we hit an exit from the try block of
  // try...finally on our way out, we will unconditionally preserve the
  // accumulator on the stack.
  ClearAccumulator();
1213
  while (!current->IsBreakTarget(stmt->target())) {
1214
    current = current->Exit(&stack_depth, &context_length);
1215 1216
  }
  __ Drop(stack_depth);
1217 1218 1219 1220 1221 1222 1223 1224
  if (context_length > 0) {
    while (context_length > 0) {
      LoadContextField(context_register(), Context::PREVIOUS_INDEX);
      --context_length;
    }
    StoreToFrameField(StandardFrameConstants::kContextOffset,
                      context_register());
  }
1225

1226
  __ jmp(current->AsBreakable()->break_label());
1227 1228 1229
}


1230
void FullCodeGenerator::EmitUnwindBeforeReturn() {
1231 1232
  NestedStatement* current = nesting_stack_;
  int stack_depth = 0;
1233
  int context_length = 0;
1234
  while (current != NULL) {
1235
    current = current->Exit(&stack_depth, &context_length);
1236 1237
  }
  __ Drop(stack_depth);
1238
}
1239

1240 1241 1242 1243 1244 1245 1246

void FullCodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
  Comment cmnt(masm_, "[ ReturnStatement");
  SetStatementPosition(stmt);
  Expression* expr = stmt->expression();
  VisitForAccumulatorValue(expr);
  EmitUnwindBeforeReturn();
1247
  EmitReturnSequence();
1248 1249 1250
}


1251 1252
void FullCodeGenerator::VisitWithStatement(WithStatement* stmt) {
  Comment cmnt(masm_, "[ WithStatement");
1253 1254
  SetStatementPosition(stmt);

1255
  VisitForStackValue(stmt->expression());
1256
  PushFunctionArgumentForContextAllocation();
1257
  __ CallRuntime(Runtime::kPushWithContext, 2);
1258
  StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1259

1260 1261
  Scope* saved_scope = scope();
  scope_ = stmt->scope();
1262 1263 1264
  { WithOrCatch body(this);
    Visit(stmt->statement());
  }
1265
  scope_ = saved_scope;
1266 1267 1268 1269 1270

  // Pop context.
  LoadContextField(context_register(), Context::PREVIOUS_INDEX);
  // Update local stack frame context field.
  StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1271 1272 1273
}


1274
void FullCodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
1275
  Comment cmnt(masm_, "[ DoWhileStatement");
1276
  SetStatementPosition(stmt);
1277
  Label body, book_keeping;
1278 1279

  Iteration loop_statement(this, stmt);
1280 1281 1282 1283 1284
  increment_loop_depth();

  __ bind(&body);
  Visit(stmt->body());

1285 1286
  // Record the position of the do while condition and make sure it is
  // possible to break on the condition.
1287
  __ bind(loop_statement.continue_label());
1288
  PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1289
  SetExpressionPosition(stmt->cond());
1290
  VisitForControl(stmt->cond(),
1291
                  &book_keeping,
1292
                  loop_statement.break_label(),
1293
                  &book_keeping);
1294

1295
  // Check stack before looping.
1296
  PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS);
1297
  __ bind(&book_keeping);
1298
  EmitBackEdgeBookkeeping(stmt, &body);
1299
  __ jmp(&body);
1300

1301
  PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1302
  __ bind(loop_statement.break_label());
1303
  decrement_loop_depth();
1304 1305 1306
}


1307
void FullCodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
1308
  Comment cmnt(masm_, "[ WhileStatement");
1309
  Label loop, body;
1310 1311

  Iteration loop_statement(this, stmt);
1312 1313
  increment_loop_depth();

1314 1315 1316 1317 1318 1319 1320
  __ bind(&loop);

  SetExpressionPosition(stmt->cond());
  VisitForControl(stmt->cond(),
                  &body,
                  loop_statement.break_label(),
                  &body);
1321

1322
  PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1323 1324
  __ bind(&body);
  Visit(stmt->body());
1325

1326
  __ bind(loop_statement.continue_label());
1327

1328
  // Check stack before looping.
1329 1330
  EmitBackEdgeBookkeeping(stmt, &loop);
  __ jmp(&loop);
1331

1332
  PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1333
  __ bind(loop_statement.break_label());
1334
  decrement_loop_depth();
1335 1336 1337
}


1338
void FullCodeGenerator::VisitForStatement(ForStatement* stmt) {
1339
  Comment cmnt(masm_, "[ ForStatement");
1340
  Label test, body;
1341 1342

  Iteration loop_statement(this, stmt);
1343 1344 1345 1346

  // Set statement position for a break slot before entering the for-body.
  SetStatementPosition(stmt);

1347 1348 1349 1350 1351 1352 1353 1354
  if (stmt->init() != NULL) {
    Visit(stmt->init());
  }

  increment_loop_depth();
  // Emit the test at the bottom of the loop (even if empty).
  __ jmp(&test);

1355
  PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
1356 1357 1358
  __ bind(&body);
  Visit(stmt->body());

1359
  PrepareForBailoutForId(stmt->ContinueId(), NO_REGISTERS);
1360
  __ bind(loop_statement.continue_label());
1361 1362 1363 1364
  if (stmt->next() != NULL) {
    Visit(stmt->next());
  }

1365 1366
  // Emit the statement position here as this is where the for
  // statement code starts.
1367
  SetStatementPosition(stmt);
1368 1369

  // Check stack before looping.
1370
  EmitBackEdgeBookkeeping(stmt, &body);
1371

1372
  __ bind(&test);
1373
  if (stmt->cond() != NULL) {
1374 1375
    VisitForControl(stmt->cond(),
                    &body,
1376 1377
                    loop_statement.break_label(),
                    loop_statement.break_label());
1378 1379 1380 1381
  } else {
    __ jmp(&body);
  }

1382
  PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
1383
  __ bind(loop_statement.break_label());
1384
  decrement_loop_depth();
1385 1386 1387
}


1388
void FullCodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
1389 1390
  Comment cmnt(masm_, "[ TryCatchStatement");
  SetStatementPosition(stmt);
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
  // The try block adds a handler to the exception handler chain before
  // entering, and removes it again when exiting normally.  If an exception
  // is thrown during execution of the try block, the handler is consumed
  // and control is passed to the catch block with the exception in the
  // result register.

  Label try_entry, handler_entry, exit;
  __ jmp(&try_entry);
  __ bind(&handler_entry);
  handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
  // Exception handler code, the exception is in the result register.
1402 1403
  // Extend the context before executing the catch block.
  { Comment cmnt(masm_, "[ Extend catch context");
1404
    __ Push(stmt->variable()->name());
1405
    __ Push(result_register());
1406
    PushFunctionArgumentForContextAllocation();
1407
    __ CallRuntime(Runtime::kPushCatchContext, 3);
1408 1409
    StoreToFrameField(StandardFrameConstants::kContextOffset,
                      context_register());
1410 1411
  }

1412 1413
  Scope* saved_scope = scope();
  scope_ = stmt->scope();
1414
  DCHECK(scope_->declarations()->is_empty());
1415
  { WithOrCatch catch_body(this);
1416 1417
    Visit(stmt->catch_block());
  }
1418 1419 1420
  // Restore the context.
  LoadContextField(context_register(), Context::PREVIOUS_INDEX);
  StoreToFrameField(StandardFrameConstants::kContextOffset, context_register());
1421
  scope_ = saved_scope;
1422
  __ jmp(&exit);
1423 1424

  // Try block code. Sets up the exception handler chain.
1425
  __ bind(&try_entry);
1426
  __ PushTryHandler(StackHandler::CATCH, stmt->index());
1427
  { TryCatch try_body(this);
1428 1429
    Visit(stmt->try_block());
  }
1430 1431
  __ PopTryHandler();
  __ bind(&exit);
1432 1433 1434
}


1435
void FullCodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
1436 1437
  Comment cmnt(masm_, "[ TryFinallyStatement");
  SetStatementPosition(stmt);
1438 1439 1440 1441 1442
  // Try finally is compiled by setting up a try-handler on the stack while
  // executing the try body, and removing it again afterwards.
  //
  // The try-finally construct can enter the finally block in three ways:
  // 1. By exiting the try-block normally. This removes the try-handler and
1443
  //    calls the finally block code before continuing.
1444 1445 1446 1447
  // 2. By exiting the try-block with a function-local control flow transfer
  //    (break/continue/return). The site of the, e.g., break removes the
  //    try handler and calls the finally block code before continuing
  //    its outward control transfer.
1448
  // 3. By exiting the try-block with a thrown exception.
1449
  //    This can happen in nested function calls. It traverses the try-handler
1450
  //    chain and consumes the try-handler entry before jumping to the
1451 1452 1453 1454 1455 1456 1457 1458
  //    handler code. The handler code then calls the finally-block before
  //    rethrowing the exception.
  //
  // The finally block must assume a return address on top of the stack
  // (or in the link register on ARM chips) and a value (return value or
  // exception) in the result register (rax/eax/r0), both of which must
  // be preserved. The return address isn't GC-safe, so it should be
  // cooked before GC.
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
  Label try_entry, handler_entry, finally_entry;

  // Jump to try-handler setup and try-block code.
  __ jmp(&try_entry);
  __ bind(&handler_entry);
  handler_table()->set(stmt->index(), Smi::FromInt(handler_entry.pos()));
  // Exception handler code.  This code is only executed when an exception
  // is thrown.  The exception is in the result register, and must be
  // preserved by the finally block.  Call the finally block and then
  // rethrow the exception if it returns.
  __ Call(&finally_entry);
1470
  __ Push(result_register());
1471
  __ CallRuntime(Runtime::kReThrow, 1);
1472

1473
  // Finally block implementation.
1474
  __ bind(&finally_entry);
1475 1476
  EnterFinallyBlock();
  { Finally finally_body(this);
1477 1478
    Visit(stmt->finally_block());
  }
1479
  ExitFinallyBlock();  // Return to the calling code.
1480

1481
  // Set up try handler.
1482
  __ bind(&try_entry);
1483
  __ PushTryHandler(StackHandler::FINALLY, stmt->index());
1484
  { TryFinally try_body(this, &finally_entry);
1485
    Visit(stmt->try_block());
1486
  }
1487
  __ PopTryHandler();
kmillikin@chromium.org's avatar
kmillikin@chromium.org committed
1488
  // Execute the finally block on the way out.  Clobber the unpredictable
1489 1490 1491
  // value in the result register with one that's safe for GC because the
  // finally block will unconditionally preserve the result register on the
  // stack.
kmillikin@chromium.org's avatar
kmillikin@chromium.org committed
1492
  ClearAccumulator();
1493
  __ Call(&finally_entry);
1494 1495 1496
}


1497
void FullCodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
1498 1499
  Comment cmnt(masm_, "[ DebuggerStatement");
  SetStatementPosition(stmt);
1500

serya@chromium.org's avatar
serya@chromium.org committed
1501
  __ DebugBreak();
1502
  // Ignore the return value.
1503 1504

  PrepareForBailoutForId(stmt->DebugBreakId(), NO_REGISTERS);
1505 1506 1507
}


1508 1509 1510 1511 1512
void FullCodeGenerator::VisitCaseClause(CaseClause* clause) {
  UNREACHABLE();
}


1513
void FullCodeGenerator::VisitConditional(Conditional* expr) {
1514
  Comment cmnt(masm_, "[ Conditional");
1515
  Label true_case, false_case, done;
1516
  VisitForControl(expr->condition(), &true_case, &false_case, &true_case);
1517

1518
  PrepareForBailoutForId(expr->ThenId(), NO_REGISTERS);
1519
  __ bind(&true_case);
1520
  SetExpressionPosition(expr->then_expression());
1521 1522 1523 1524 1525 1526 1527
  if (context()->IsTest()) {
    const TestContext* for_test = TestContext::cast(context());
    VisitForControl(expr->then_expression(),
                    for_test->true_label(),
                    for_test->false_label(),
                    NULL);
  } else {
1528
    VisitInDuplicateContext(expr->then_expression());
1529 1530 1531
    __ jmp(&done);
  }

1532
  PrepareForBailoutForId(expr->ElseId(), NO_REGISTERS);
1533
  __ bind(&false_case);
1534
  SetExpressionPosition(expr->else_expression());
1535
  VisitInDuplicateContext(expr->else_expression());
1536
  // If control flow falls through Visit, merge it with true case here.
1537
  if (!context()->IsTest()) {
1538 1539
    __ bind(&done);
  }
1540 1541 1542
}


1543
void FullCodeGenerator::VisitLiteral(Literal* expr) {
1544
  Comment cmnt(masm_, "[ Literal");
1545
  context()->Plug(expr->value());
1546 1547 1548
}


1549 1550 1551 1552 1553
void FullCodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
  Comment cmnt(masm_, "[ FunctionLiteral");

  // Build the function boilerplate and instantiate it.
  Handle<SharedFunctionInfo> function_info =
1554
      Compiler::BuildFunctionInfo(expr, script(), info_);
1555 1556 1557 1558
  if (function_info.is_null()) {
    SetStackOverflow();
    return;
  }
1559
  EmitNewClosure(function_info, expr->pretenure());
1560 1561 1562
}


1563
void FullCodeGenerator::VisitClassLiteral(ClassLiteral* lit) {
arv@chromium.org's avatar
arv@chromium.org committed
1564
  Comment cmnt(masm_, "[ ClassLiteral");
1565

1566 1567
  if (lit->raw_name() != NULL) {
    __ Push(lit->name());
1568 1569 1570 1571
  } else {
    __ Push(isolate()->factory()->undefined_value());
  }

1572 1573
  if (lit->extends() != NULL) {
    VisitForStackValue(lit->extends());
1574 1575
  } else {
    __ Push(isolate()->factory()->the_hole_value());
arv@chromium.org's avatar
arv@chromium.org committed
1576
  }
1577

1578 1579
  if (lit->constructor() != NULL) {
    VisitForStackValue(lit->constructor());
1580 1581 1582 1583
  } else {
    __ Push(isolate()->factory()->undefined_value());
  }

1584 1585 1586 1587 1588
  __ Push(script());
  __ Push(Smi::FromInt(lit->start_position()));
  __ Push(Smi::FromInt(lit->end_position()));

  __ CallRuntime(Runtime::kDefineClass, 6);
1589 1590
  EmitClassDefineProperties(lit);

1591
  context()->Plug(result_register());
arv@chromium.org's avatar
arv@chromium.org committed
1592 1593 1594
}


1595 1596 1597 1598 1599 1600 1601
void FullCodeGenerator::VisitNativeFunctionLiteral(
    NativeFunctionLiteral* expr) {
  Comment cmnt(masm_, "[ NativeFunctionLiteral");

  // Compute the function template for the native function.
  Handle<String> name = expr->name();
  v8::Handle<v8::FunctionTemplate> fun_template =
1602 1603
      expr->extension()->GetNativeFunctionTemplate(
          reinterpret_cast<v8::Isolate*>(isolate()), v8::Utils::ToLocal(name));
1604
  DCHECK(!fun_template.IsEmpty());
1605 1606 1607 1608 1609 1610 1611

  // Instantiate the function and create a shared function info from it.
  Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
  const int literals = fun->NumberOfLiterals();
  Handle<Code> code = Handle<Code>(fun->shared()->code());
  Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
  Handle<SharedFunctionInfo> shared =
1612
      isolate()->factory()->NewSharedFunctionInfo(
1613
          name, literals, FunctionKind::kNormalFunction, code,
1614
          Handle<ScopeInfo>(fun->shared()->scope_info()),
1615
          Handle<TypeFeedbackVector>(fun->shared()->feedback_vector()));
1616 1617 1618 1619 1620 1621 1622 1623
  shared->set_construct_stub(*construct_stub);

  // Copy the function data to the shared function info.
  shared->set_function_data(fun->shared()->function_data());
  int parameters = fun->shared()->formal_parameter_count();
  shared->set_formal_parameter_count(parameters);

  EmitNewClosure(shared, false);
1624 1625 1626
}


1627
void FullCodeGenerator::VisitThrow(Throw* expr) {
1628
  Comment cmnt(masm_, "[ Throw");
1629
  VisitForStackValue(expr->exception());
1630
  __ CallRuntime(Runtime::kThrow, 1);
1631
  // Never returns here.
1632 1633 1634
}


1635 1636 1637
FullCodeGenerator::NestedStatement* FullCodeGenerator::TryCatch::Exit(
    int* stack_depth,
    int* context_length) {
1638
  // The macros used here must preserve the result register.
1639
  __ Drop(*stack_depth);
1640
  __ PopTryHandler();
1641 1642
  *stack_depth = 0;
  return previous_;
1643 1644
}

1645

1646
bool FullCodeGenerator::TryLiteralCompare(CompareOperation* expr) {
1647
  Expression* sub_expr;
1648
  Handle<String> check;
1649
  if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) {
1650
    EmitLiteralCompareTypeof(expr, sub_expr, check);
1651 1652 1653
    return true;
  }

1654
  if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) {
1655
    EmitLiteralCompareNil(expr, sub_expr, kUndefinedValue);
1656 1657 1658
    return true;
  }

1659 1660
  if (expr->IsLiteralCompareNull(&sub_expr)) {
    EmitLiteralCompareNil(expr, sub_expr, kNullValue);
1661 1662 1663
    return true;
  }

1664 1665 1666 1667
  return false;
}


1668
void BackEdgeTable::Patch(Isolate* isolate, Code* unoptimized) {
1669
  DisallowHeapAllocation no_gc;
1670
  Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1671

1672 1673
  // Increment loop nesting level by one and iterate over the back edge table
  // to find the matching loops to patch the interrupt
1674
  // call to an unconditional call to the replacement code.
1675 1676
  int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level() + 1;
  if (loop_nesting_level > Code::kMaxLoopNestingMarker) return;
1677 1678 1679 1680

  BackEdgeTable back_edges(unoptimized, &no_gc);
  for (uint32_t i = 0; i < back_edges.length(); i++) {
    if (static_cast<int>(back_edges.loop_depth(i)) == loop_nesting_level) {
1681
      DCHECK_EQ(INTERRUPT, GetBackEdgeState(isolate,
1682 1683
                                            unoptimized,
                                            back_edges.pc(i)));
1684
      PatchAt(unoptimized, back_edges.pc(i), ON_STACK_REPLACEMENT, patch);
1685 1686 1687
    }
  }

1688
  unoptimized->set_allow_osr_at_loop_nesting_level(loop_nesting_level);
1689
  DCHECK(Verify(isolate, unoptimized));
1690 1691 1692
}


1693
void BackEdgeTable::Revert(Isolate* isolate, Code* unoptimized) {
1694
  DisallowHeapAllocation no_gc;
1695
  Code* patch = isolate->builtins()->builtin(Builtins::kInterruptCheck);
1696 1697 1698 1699 1700 1701 1702

  // Iterate over the back edge table and revert the patched interrupt calls.
  int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();

  BackEdgeTable back_edges(unoptimized, &no_gc);
  for (uint32_t i = 0; i < back_edges.length(); i++) {
    if (static_cast<int>(back_edges.loop_depth(i)) <= loop_nesting_level) {
1703
      DCHECK_NE(INTERRUPT, GetBackEdgeState(isolate,
1704 1705 1706
                                            unoptimized,
                                            back_edges.pc(i)));
      PatchAt(unoptimized, back_edges.pc(i), INTERRUPT, patch);
1707 1708 1709 1710 1711
    }
  }

  unoptimized->set_allow_osr_at_loop_nesting_level(0);
  // Assert that none of the back edges are patched anymore.
1712
  DCHECK(Verify(isolate, unoptimized));
1713 1714 1715
}


1716
void BackEdgeTable::AddStackCheck(Handle<Code> code, uint32_t pc_offset) {
1717
  DisallowHeapAllocation no_gc;
1718 1719
  Isolate* isolate = code->GetIsolate();
  Address pc = code->instruction_start() + pc_offset;
1720
  Code* patch = isolate->builtins()->builtin(Builtins::kOsrAfterStackCheck);
1721
  PatchAt(*code, pc, OSR_AFTER_STACK_CHECK, patch);
1722 1723 1724
}


1725
void BackEdgeTable::RemoveStackCheck(Handle<Code> code, uint32_t pc_offset) {
1726
  DisallowHeapAllocation no_gc;
1727 1728 1729 1730
  Isolate* isolate = code->GetIsolate();
  Address pc = code->instruction_start() + pc_offset;

  if (OSR_AFTER_STACK_CHECK == GetBackEdgeState(isolate, *code, pc)) {
1731
    Code* patch = isolate->builtins()->builtin(Builtins::kOnStackReplacement);
1732
    PatchAt(*code, pc, ON_STACK_REPLACEMENT, patch);
1733 1734 1735 1736
  }
}


1737
#ifdef DEBUG
1738
bool BackEdgeTable::Verify(Isolate* isolate, Code* unoptimized) {
1739
  DisallowHeapAllocation no_gc;
1740
  int loop_nesting_level = unoptimized->allow_osr_at_loop_nesting_level();
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
  BackEdgeTable back_edges(unoptimized, &no_gc);
  for (uint32_t i = 0; i < back_edges.length(); i++) {
    uint32_t loop_depth = back_edges.loop_depth(i);
    CHECK_LE(static_cast<int>(loop_depth), Code::kMaxLoopNestingMarker);
    // Assert that all back edges for shallower loops (and only those)
    // have already been patched.
    CHECK_EQ((static_cast<int>(loop_depth) <= loop_nesting_level),
             GetBackEdgeState(isolate,
                              unoptimized,
                              back_edges.pc(i)) != INTERRUPT);
  }
  return true;
}
#endif  // DEBUG


1757 1758 1759
#undef __


1760
} }  // namespace v8::internal