full-codegen-x87.cc 173 KB
Newer Older
danno@chromium.org's avatar
danno@chromium.org committed
1 2 3 4 5 6
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#if V8_TARGET_ARCH_X87

7
#include "src/code-factory.h"
8 9
#include "src/code-stubs.h"
#include "src/codegen.h"
10
#include "src/debug/debug.h"
11
#include "src/full-codegen/full-codegen.h"
12
#include "src/ic/ic.h"
13 14
#include "src/parser.h"
#include "src/scopes.h"
15
#include "src/x87/frames-x87.h"
danno@chromium.org's avatar
danno@chromium.org committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

namespace v8 {
namespace internal {

#define __ ACCESS_MASM(masm_)


class JumpPatchSite BASE_EMBEDDED {
 public:
  explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) {
#ifdef DEBUG
    info_emitted_ = false;
#endif
  }

  ~JumpPatchSite() {
32
    DCHECK(patch_site_.is_bound() == info_emitted_);
danno@chromium.org's avatar
danno@chromium.org committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
  }

  void EmitJumpIfNotSmi(Register reg,
                        Label* target,
                        Label::Distance distance = Label::kFar) {
    __ test(reg, Immediate(kSmiTagMask));
    EmitJump(not_carry, target, distance);  // Always taken before patched.
  }

  void EmitJumpIfSmi(Register reg,
                     Label* target,
                     Label::Distance distance = Label::kFar) {
    __ test(reg, Immediate(kSmiTagMask));
    EmitJump(carry, target, distance);  // Never taken before patched.
  }

  void EmitPatchInfo() {
    if (patch_site_.is_bound()) {
      int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(&patch_site_);
52
      DCHECK(is_uint8(delta_to_patch_site));
danno@chromium.org's avatar
danno@chromium.org committed
53 54 55 56 57 58 59 60 61 62 63 64
      __ test(eax, Immediate(delta_to_patch_site));
#ifdef DEBUG
      info_emitted_ = true;
#endif
    } else {
      __ nop();  // Signals no inlined code.
    }
  }

 private:
  // jc will be patched with jz, jnc will become jnz.
  void EmitJump(Condition cc, Label* target, Label::Distance distance) {
65 66
    DCHECK(!patch_site_.is_bound() && !info_emitted_);
    DCHECK(cc == carry || cc == not_carry);
danno@chromium.org's avatar
danno@chromium.org committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    __ bind(&patch_site_);
    __ j(cc, target, distance);
  }

  MacroAssembler* masm_;
  Label patch_site_;
#ifdef DEBUG
  bool info_emitted_;
#endif
};


// Generate code for a JS function.  On entry to the function the receiver
// and arguments have been pushed on the stack left to right, with the
// return address on top of them.  The actual argument count matches the
// formal parameter count expected by the function.
//
// The live registers are:
//   o edi: the JS function object being called (i.e. ourselves)
//   o esi: our context
//   o ebp: our caller's frame pointer
//   o esp: stack pointer (pointing to return address)
//
// The function builds a JS frame.  Please see JavaScriptFrameConstants in
// frames-x87.h for its layout.
void FullCodeGenerator::Generate() {
  CompilationInfo* info = info_;
  profiling_counter_ = isolate()->factory()->NewCell(
      Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate()));
96
  SetFunctionPosition(literal());
danno@chromium.org's avatar
danno@chromium.org committed
97 98 99 100 101 102
  Comment cmnt(masm_, "[ function compiled by full code generator");

  ProfileEntryHookStub::MaybeCallEntryHook(masm_);

#ifdef DEBUG
  if (strlen(FLAG_stop_at) > 0 &&
103
      literal()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) {
danno@chromium.org's avatar
danno@chromium.org committed
104 105 106 107 108 109 110
    __ int3();
  }
#endif

  // Sloppy mode functions and builtins need to replace the receiver with the
  // global proxy when called as functions (without an explicit receiver
  // object).
111
  if (info->MustReplaceUndefinedReceiverWithGlobalProxy()) {
danno@chromium.org's avatar
danno@chromium.org committed
112 113 114 115 116 117 118 119 120
    Label ok;
    // +1 for return address.
    int receiver_offset = (info->scope()->num_parameters() + 1) * kPointerSize;
    __ mov(ecx, Operand(esp, receiver_offset));

    __ cmp(ecx, isolate()->factory()->undefined_value());
    __ j(not_equal, &ok, Label::kNear);

    __ mov(ecx, GlobalObjectOperand());
121
    __ mov(ecx, FieldOperand(ecx, GlobalObject::kGlobalProxyOffset));
danno@chromium.org's avatar
danno@chromium.org committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

    __ mov(Operand(esp, receiver_offset), ecx);

    __ bind(&ok);
  }

  // Open a frame scope to indicate that there is a frame on the stack.  The
  // MANUAL indicates that the scope shouldn't actually generate code to set up
  // the frame (that is done below).
  FrameScope frame_scope(masm_, StackFrame::MANUAL);

  info->set_prologue_offset(masm_->pc_offset());
  __ Prologue(info->IsCodePreAgingActive());

  { Comment cmnt(masm_, "[ Allocate locals");
    int locals_count = info->scope()->num_stack_slots();
    // Generators allocate locals, if any, in context slots.
139
    DCHECK(!IsGeneratorFunction(literal()->kind()) || locals_count == 0);
danno@chromium.org's avatar
danno@chromium.org committed
140 141 142 143
    if (locals_count == 1) {
      __ push(Immediate(isolate()->factory()->undefined_value()));
    } else if (locals_count > 1) {
      if (locals_count >= 128) {
144 145 146 147 148 149 150
        Label ok;
        __ mov(ecx, esp);
        __ sub(ecx, Immediate(locals_count * kPointerSize));
        ExternalReference stack_limit =
            ExternalReference::address_of_real_stack_limit(isolate());
        __ cmp(ecx, Operand::StaticVariable(stack_limit));
        __ j(above_equal, &ok, Label::kNear);
151
        __ CallRuntime(Runtime::kThrowStackOverflow, 0);
152
        __ bind(&ok);
danno@chromium.org's avatar
danno@chromium.org committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
      }
      __ mov(eax, Immediate(isolate()->factory()->undefined_value()));
      const int kMaxPushes = 32;
      if (locals_count >= kMaxPushes) {
        int loop_iterations = locals_count / kMaxPushes;
        __ mov(ecx, loop_iterations);
        Label loop_header;
        __ bind(&loop_header);
        // Do pushes.
        for (int i = 0; i < kMaxPushes; i++) {
          __ push(eax);
        }
        __ dec(ecx);
        __ j(not_zero, &loop_header, Label::kNear);
      }
      int remaining = locals_count % kMaxPushes;
      // Emit the remaining pushes.
      for (int i  = 0; i < remaining; i++) {
        __ push(eax);
      }
    }
  }

  bool function_in_register = true;

  // Possibly allocate a local context.
179
  if (info->scope()->num_heap_slots() > 0) {
danno@chromium.org's avatar
danno@chromium.org committed
180
    Comment cmnt(masm_, "[ Allocate context");
181
    bool need_write_barrier = true;
182
    int slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
danno@chromium.org's avatar
danno@chromium.org committed
183
    // Argument to NewContext is the function, which is still in edi.
184
    if (info->scope()->is_script_scope()) {
danno@chromium.org's avatar
danno@chromium.org committed
185
      __ push(edi);
186
      __ Push(info->scope()->GetScopeInfo(info->isolate()));
187
      __ CallRuntime(Runtime::kNewScriptContext, 2);
188 189
    } else if (slots <= FastNewContextStub::kMaximumSlots) {
      FastNewContextStub stub(isolate(), slots);
danno@chromium.org's avatar
danno@chromium.org committed
190
      __ CallStub(&stub);
191 192
      // Result of FastNewContextStub is always in new space.
      need_write_barrier = false;
danno@chromium.org's avatar
danno@chromium.org committed
193 194
    } else {
      __ push(edi);
195
      __ CallRuntime(Runtime::kNewFunctionContext, 1);
danno@chromium.org's avatar
danno@chromium.org committed
196 197 198 199 200 201 202 203 204
    }
    function_in_register = false;
    // Context is returned in eax.  It replaces the context passed to us.
    // It's saved in the stack and kept live in esi.
    __ mov(esi, eax);
    __ mov(Operand(ebp, StandardFrameConstants::kContextOffset), eax);

    // Copy parameters into context if necessary.
    int num_parameters = info->scope()->num_parameters();
205 206 207
    int first_parameter = info->scope()->has_this_declaration() ? -1 : 0;
    for (int i = first_parameter; i < num_parameters; i++) {
      Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
danno@chromium.org's avatar
danno@chromium.org committed
208 209 210 211 212 213 214 215 216
      if (var->IsContextSlot()) {
        int parameter_offset = StandardFrameConstants::kCallerSPOffset +
            (num_parameters - 1 - i) * kPointerSize;
        // Load parameter from stack.
        __ mov(eax, Operand(ebp, parameter_offset));
        // Store it in the context.
        int context_offset = Context::SlotOffset(var->index());
        __ mov(Operand(esi, context_offset), eax);
        // Update the write barrier. This clobbers eax and ebx.
217
        if (need_write_barrier) {
218 219
          __ RecordWriteContextSlot(esi, context_offset, eax, ebx,
                                    kDontSaveFPRegs);
220 221 222 223 224 225
        } else if (FLAG_debug_code) {
          Label done;
          __ JumpIfInNewSpace(esi, eax, &done, Label::kNear);
          __ Abort(kExpectedNewSpaceObject);
          __ bind(&done);
        }
danno@chromium.org's avatar
danno@chromium.org committed
226 227 228 229
      }
    }
  }

230 231 232 233 234
  PrepareForBailoutForId(BailoutId::Prologue(), NO_REGISTERS);
  // Function register is trashed in case we bailout here. But since that
  // could happen only when we allocate a context the value of
  // |function_in_register| is correct.

235 236 237 238 239
  // Possibly set up a local binding to the this function which is used in
  // derived constructors with super calls.
  Variable* this_function_var = scope()->this_function_var();
  if (this_function_var != nullptr) {
    Comment cmnt(masm_, "[ This function");
240 241 242 243
    if (!function_in_register) {
      __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
      // The write barrier clobbers register again, keep is marked as such.
    }
244 245 246 247 248 249
    SetVar(this_function_var, edi, ebx, edx);
  }

  Variable* new_target_var = scope()->new_target_var();
  if (new_target_var != nullptr) {
    Comment cmnt(masm_, "[ new.target");
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
    __ mov(eax, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
    Label non_adaptor_frame;
    __ cmp(Operand(eax, StandardFrameConstants::kContextOffset),
           Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
    __ j(not_equal, &non_adaptor_frame);
    __ mov(eax, Operand(eax, StandardFrameConstants::kCallerFPOffset));

    __ bind(&non_adaptor_frame);
    __ cmp(Operand(eax, StandardFrameConstants::kMarkerOffset),
           Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));

    Label non_construct_frame, done;
    __ j(not_equal, &non_construct_frame);

    // Construct frame
265 266
    __ mov(eax,
           Operand(eax, ConstructFrameConstants::kOriginalConstructorOffset));
267 268 269 270 271 272 273
    __ jmp(&done);

    // Non-construct frame
    __ bind(&non_construct_frame);
    __ mov(eax, Immediate(isolate()->factory()->undefined_value()));

    __ bind(&done);
274 275 276
    SetVar(new_target_var, eax, ebx, edx);
  }

danno@chromium.org's avatar
danno@chromium.org committed
277 278 279 280
  Variable* arguments = scope()->arguments();
  if (arguments != NULL) {
    // Function uses arguments object.
    Comment cmnt(masm_, "[ Allocate arguments object");
281 282 283
    DCHECK(edi.is(ArgumentsAccessNewDescriptor::function()));
    if (!function_in_register) {
      __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
danno@chromium.org's avatar
danno@chromium.org committed
284 285 286 287
    }
    // Receiver is just before the parameters on the caller's stack.
    int num_parameters = info->scope()->num_parameters();
    int offset = num_parameters * kPointerSize;
288 289 290
    __ mov(ArgumentsAccessNewDescriptor::parameter_count(),
           Immediate(Smi::FromInt(num_parameters)));
    __ lea(ArgumentsAccessNewDescriptor::parameter_pointer(),
danno@chromium.org's avatar
danno@chromium.org committed
291
           Operand(ebp, StandardFrameConstants::kCallerSPOffset + offset));
292

293 294 295 296 297 298 299
    // Arguments to ArgumentsAccessStub:
    //   function, parameter pointer, parameter count.
    // The stub will rewrite parameter pointer and parameter count if the
    // previous stack frame was an arguments adapter frame.
    bool is_unmapped = is_strict(language_mode()) || !has_simple_parameters();
    ArgumentsAccessStub::Type type = ArgumentsAccessStub::ComputeType(
        is_unmapped, literal()->has_duplicate_parameters());
300
    ArgumentsAccessStub stub(isolate(), type);
danno@chromium.org's avatar
danno@chromium.org committed
301 302 303 304 305 306 307 308 309 310 311 312 313
    __ CallStub(&stub);

    SetVar(arguments, eax, ebx, edx);
  }

  if (FLAG_trace) {
    __ CallRuntime(Runtime::kTraceEnter, 0);
  }

  // Visit the declarations and body unless there is an illegal
  // redeclaration.
  if (scope()->HasIllegalRedeclaration()) {
    Comment cmnt(masm_, "[ Declarations");
314
    VisitForEffect(scope()->GetIllegalRedeclaration());
danno@chromium.org's avatar
danno@chromium.org committed
315 316 317 318 319 320 321

  } else {
    PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS);
    { Comment cmnt(masm_, "[ Declarations");
      VisitDeclarations(scope()->declarations());
    }

322 323 324 325 326
    // Assert that the declarations do not use ICs. Otherwise the debugger
    // won't be able to redirect a PC at an IC to the correct IC in newly
    // recompiled code.
    DCHECK_EQ(0, ic_total_count_);

danno@chromium.org's avatar
danno@chromium.org committed
327 328
    { Comment cmnt(masm_, "[ Stack check");
      PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS);
329 330 331 332 333 334 335
      Label ok;
      ExternalReference stack_limit
          = ExternalReference::address_of_stack_limit(isolate());
      __ cmp(esp, Operand::StaticVariable(stack_limit));
      __ j(above_equal, &ok, Label::kNear);
      __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET);
      __ bind(&ok);
danno@chromium.org's avatar
danno@chromium.org committed
336 337 338
    }

    { Comment cmnt(masm_, "[ Body");
339
      DCHECK(loop_depth() == 0);
340
      VisitStatements(literal()->body());
341
      DCHECK(loop_depth() == 0);
danno@chromium.org's avatar
danno@chromium.org committed
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    }
  }

  // Always emit a 'return undefined' in case control fell off the end of
  // the body.
  { Comment cmnt(masm_, "[ return <undefined>;");
    __ mov(eax, isolate()->factory()->undefined_value());
    EmitReturnSequence();
  }
}


void FullCodeGenerator::ClearAccumulator() {
  __ Move(eax, Immediate(Smi::FromInt(0)));
}


void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) {
  __ mov(ebx, Immediate(profiling_counter_));
  __ sub(FieldOperand(ebx, Cell::kValueOffset),
         Immediate(Smi::FromInt(delta)));
}


void FullCodeGenerator::EmitProfilingCounterReset() {
  int reset_value = FLAG_interrupt_budget;
  __ mov(ebx, Immediate(profiling_counter_));
  __ mov(FieldOperand(ebx, Cell::kValueOffset),
         Immediate(Smi::FromInt(reset_value)));
}


void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt,
                                                Label* back_edge_target) {
  Comment cmnt(masm_, "[ Back edge bookkeeping");
  Label ok;

379
  DCHECK(back_edge_target->is_bound());
danno@chromium.org's avatar
danno@chromium.org committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
  int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target);
  int weight = Min(kMaxBackEdgeWeight,
                   Max(1, distance / kCodeSizeMultiplier));
  EmitProfilingCounterDecrement(weight);
  __ j(positive, &ok, Label::kNear);
  __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET);

  // Record a mapping of this PC offset to the OSR id.  This is used to find
  // the AST id from the unoptimized code in order to use it as a key into
  // the deoptimization input data found in the optimized code.
  RecordBackEdge(stmt->OsrEntryId());

  EmitProfilingCounterReset();

  __ bind(&ok);
  PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);
  // Record a mapping of the OSR id to this PC.  This is used if the OSR
  // entry becomes the target of a bailout.  We don't expect it to be, but
  // we want it to work if it is.
  PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS);
}


void FullCodeGenerator::EmitReturnSequence() {
  Comment cmnt(masm_, "[ Return sequence");
  if (return_label_.is_bound()) {
    __ jmp(&return_label_);
  } else {
    // Common return label
    __ bind(&return_label_);
    if (FLAG_trace) {
      __ push(eax);
      __ CallRuntime(Runtime::kTraceExit, 1);
    }
    // Pretend that the exit is a backwards jump to the entry.
415 416 417 418 419 420 421 422
    int weight = 1;
    if (info_->ShouldSelfOptimize()) {
      weight = FLAG_interrupt_budget / FLAG_self_opt_count;
    } else {
      int distance = masm_->pc_offset();
      weight = Min(kMaxBackEdgeWeight,
                   Max(1, distance / kCodeSizeMultiplier));
    }
danno@chromium.org's avatar
danno@chromium.org committed
423 424 425 426 427 428 429 430 431
    EmitProfilingCounterDecrement(weight);
    Label ok;
    __ j(positive, &ok, Label::kNear);
    __ push(eax);
    __ call(isolate()->builtins()->InterruptCheck(),
            RelocInfo::CODE_TARGET);
    __ pop(eax);
    EmitProfilingCounterReset();
    __ bind(&ok);
432

433
    SetReturnPosition(literal());
434
    __ leave();
danno@chromium.org's avatar
danno@chromium.org committed
435

436 437
    int arg_count = info_->scope()->num_parameters() + 1;
    int arguments_bytes = arg_count * kPointerSize;
danno@chromium.org's avatar
danno@chromium.org committed
438 439 440 441 442 443
    __ Ret(arguments_bytes, ecx);
  }
}


void FullCodeGenerator::StackValueContext::Plug(Variable* var) const {
444
  DCHECK(var->IsStackAllocated() || var->IsContextSlot());
danno@chromium.org's avatar
danno@chromium.org committed
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
  MemOperand operand = codegen()->VarOperand(var, result_register());
  // Memory operands can be pushed directly.
  __ push(operand);
}


void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const {
  UNREACHABLE();  // Not used on X87.
}


void FullCodeGenerator::AccumulatorValueContext::Plug(
    Heap::RootListIndex index) const {
  UNREACHABLE();  // Not used on X87.
}


void FullCodeGenerator::StackValueContext::Plug(
    Heap::RootListIndex index) const {
  UNREACHABLE();  // Not used on X87.
}


void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const {
  UNREACHABLE();  // Not used on X87.
}


void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const {
}


void FullCodeGenerator::AccumulatorValueContext::Plug(
    Handle<Object> lit) const {
  if (lit->IsSmi()) {
    __ SafeMove(result_register(), Immediate(lit));
  } else {
    __ Move(result_register(), Immediate(lit));
  }
}


void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const {
  if (lit->IsSmi()) {
    __ SafePush(Immediate(lit));
  } else {
    __ push(Immediate(lit));
  }
}


void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const {
  codegen()->PrepareForBailoutBeforeSplit(condition(),
                                          true,
                                          true_label_,
                                          false_label_);
501
  DCHECK(!lit->IsUndetectableObject());  // There are no undetectable literals.
danno@chromium.org's avatar
danno@chromium.org committed
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
  if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) {
    if (false_label_ != fall_through_) __ jmp(false_label_);
  } else if (lit->IsTrue() || lit->IsJSObject()) {
    if (true_label_ != fall_through_) __ jmp(true_label_);
  } else if (lit->IsString()) {
    if (String::cast(*lit)->length() == 0) {
      if (false_label_ != fall_through_) __ jmp(false_label_);
    } else {
      if (true_label_ != fall_through_) __ jmp(true_label_);
    }
  } else if (lit->IsSmi()) {
    if (Smi::cast(*lit)->value() == 0) {
      if (false_label_ != fall_through_) __ jmp(false_label_);
    } else {
      if (true_label_ != fall_through_) __ jmp(true_label_);
    }
  } else {
    // For simplicity we always test the accumulator register.
    __ mov(result_register(), lit);
    codegen()->DoTest(this);
  }
}


void FullCodeGenerator::EffectContext::DropAndPlug(int count,
                                                   Register reg) const {
528
  DCHECK(count > 0);
danno@chromium.org's avatar
danno@chromium.org committed
529 530 531 532 533 534 535
  __ Drop(count);
}


void FullCodeGenerator::AccumulatorValueContext::DropAndPlug(
    int count,
    Register reg) const {
536
  DCHECK(count > 0);
danno@chromium.org's avatar
danno@chromium.org committed
537 538 539 540 541 542 543
  __ Drop(count);
  __ Move(result_register(), reg);
}


void FullCodeGenerator::StackValueContext::DropAndPlug(int count,
                                                       Register reg) const {
544
  DCHECK(count > 0);
danno@chromium.org's avatar
danno@chromium.org committed
545 546 547 548 549 550 551
  if (count > 1) __ Drop(count - 1);
  __ mov(Operand(esp, 0), reg);
}


void FullCodeGenerator::TestContext::DropAndPlug(int count,
                                                 Register reg) const {
552
  DCHECK(count > 0);
danno@chromium.org's avatar
danno@chromium.org committed
553 554 555 556 557 558 559 560 561 562
  // For simplicity we always test the accumulator register.
  __ Drop(count);
  __ Move(result_register(), reg);
  codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL);
  codegen()->DoTest(this);
}


void FullCodeGenerator::EffectContext::Plug(Label* materialize_true,
                                            Label* materialize_false) const {
563
  DCHECK(materialize_true == materialize_false);
danno@chromium.org's avatar
danno@chromium.org committed
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 594 595
  __ bind(materialize_true);
}


void FullCodeGenerator::AccumulatorValueContext::Plug(
    Label* materialize_true,
    Label* materialize_false) const {
  Label done;
  __ bind(materialize_true);
  __ mov(result_register(), isolate()->factory()->true_value());
  __ jmp(&done, Label::kNear);
  __ bind(materialize_false);
  __ mov(result_register(), isolate()->factory()->false_value());
  __ bind(&done);
}


void FullCodeGenerator::StackValueContext::Plug(
    Label* materialize_true,
    Label* materialize_false) const {
  Label done;
  __ bind(materialize_true);
  __ push(Immediate(isolate()->factory()->true_value()));
  __ jmp(&done, Label::kNear);
  __ bind(materialize_false);
  __ push(Immediate(isolate()->factory()->false_value()));
  __ bind(&done);
}


void FullCodeGenerator::TestContext::Plug(Label* materialize_true,
                                          Label* materialize_false) const {
596 597
  DCHECK(materialize_true == true_label_);
  DCHECK(materialize_false == false_label_);
danno@chromium.org's avatar
danno@chromium.org committed
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 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
}


void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const {
  Handle<Object> value = flag
      ? isolate()->factory()->true_value()
      : isolate()->factory()->false_value();
  __ mov(result_register(), value);
}


void FullCodeGenerator::StackValueContext::Plug(bool flag) const {
  Handle<Object> value = flag
      ? isolate()->factory()->true_value()
      : isolate()->factory()->false_value();
  __ push(Immediate(value));
}


void FullCodeGenerator::TestContext::Plug(bool flag) const {
  codegen()->PrepareForBailoutBeforeSplit(condition(),
                                          true,
                                          true_label_,
                                          false_label_);
  if (flag) {
    if (true_label_ != fall_through_) __ jmp(true_label_);
  } else {
    if (false_label_ != fall_through_) __ jmp(false_label_);
  }
}


void FullCodeGenerator::DoTest(Expression* condition,
                               Label* if_true,
                               Label* if_false,
                               Label* fall_through) {
  Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate());
  CallIC(ic, condition->test_id());
  __ test(result_register(), result_register());
  // The stub returns nonzero for true.
  Split(not_zero, if_true, if_false, fall_through);
}


void FullCodeGenerator::Split(Condition cc,
                              Label* if_true,
                              Label* if_false,
                              Label* fall_through) {
  if (if_false == fall_through) {
    __ j(cc, if_true);
  } else if (if_true == fall_through) {
    __ j(NegateCondition(cc), if_false);
  } else {
    __ j(cc, if_true);
    __ jmp(if_false);
  }
}


MemOperand FullCodeGenerator::StackOperand(Variable* var) {
658
  DCHECK(var->IsStackAllocated());
danno@chromium.org's avatar
danno@chromium.org committed
659 660 661 662 663 664 665 666 667 668 669 670 671
  // Offset is negative because higher indexes are at lower addresses.
  int offset = -var->index() * kPointerSize;
  // Adjust by a (parameter or local) base offset.
  if (var->IsParameter()) {
    offset += (info_->scope()->num_parameters() + 1) * kPointerSize;
  } else {
    offset += JavaScriptFrameConstants::kLocal0Offset;
  }
  return Operand(ebp, offset);
}


MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) {
672
  DCHECK(var->IsContextSlot() || var->IsStackAllocated());
danno@chromium.org's avatar
danno@chromium.org committed
673 674 675 676 677 678 679 680 681 682 683
  if (var->IsContextSlot()) {
    int context_chain_length = scope()->ContextChainLength(var->scope());
    __ LoadContext(scratch, context_chain_length);
    return ContextOperand(scratch, var->index());
  } else {
    return StackOperand(var);
  }
}


void FullCodeGenerator::GetVar(Register dest, Variable* var) {
684
  DCHECK(var->IsContextSlot() || var->IsStackAllocated());
danno@chromium.org's avatar
danno@chromium.org committed
685 686 687 688 689 690 691 692 693
  MemOperand location = VarOperand(var, dest);
  __ mov(dest, location);
}


void FullCodeGenerator::SetVar(Variable* var,
                               Register src,
                               Register scratch0,
                               Register scratch1) {
694 695 696 697
  DCHECK(var->IsContextSlot() || var->IsStackAllocated());
  DCHECK(!scratch0.is(src));
  DCHECK(!scratch0.is(scratch1));
  DCHECK(!scratch1.is(src));
danno@chromium.org's avatar
danno@chromium.org committed
698 699 700 701 702 703
  MemOperand location = VarOperand(var, scratch0);
  __ mov(location, src);

  // Emit the write barrier code if the location is in the heap.
  if (var->IsContextSlot()) {
    int offset = Context::SlotOffset(var->index());
704
    DCHECK(!scratch0.is(esi) && !src.is(esi) && !scratch1.is(esi));
705
    __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs);
danno@chromium.org's avatar
danno@chromium.org committed
706 707 708 709 710 711 712 713 714 715 716
  }
}


void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr,
                                                     bool should_normalize,
                                                     Label* if_true,
                                                     Label* if_false) {
  // Only prepare for bailouts before splits if we're in a test
  // context. Otherwise, we let the Visit function deal with the
  // preparation to avoid preparing with the same AST id twice.
717
  if (!context()->IsTest()) return;
danno@chromium.org's avatar
danno@chromium.org committed
718 719 720 721 722 723 724 725 726 727 728 729 730 731

  Label skip;
  if (should_normalize) __ jmp(&skip, Label::kNear);
  PrepareForBailout(expr, TOS_REG);
  if (should_normalize) {
    __ cmp(eax, isolate()->factory()->true_value());
    Split(equal, if_true, if_false, NULL);
    __ bind(&skip);
  }
}


void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) {
  // The variable in the declaration always resides in the current context.
732
  DCHECK_EQ(0, scope()->ContextChainLength(variable->scope()));
danno@chromium.org's avatar
danno@chromium.org committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
  if (generate_debug_code_) {
    // Check that we're not inside a with or catch context.
    __ mov(ebx, FieldOperand(esi, HeapObject::kMapOffset));
    __ cmp(ebx, isolate()->factory()->with_context_map());
    __ Check(not_equal, kDeclarationInWithContext);
    __ cmp(ebx, isolate()->factory()->catch_context_map());
    __ Check(not_equal, kDeclarationInCatchContext);
  }
}


void FullCodeGenerator::VisitVariableDeclaration(
    VariableDeclaration* declaration) {
  // If it was not possible to allocate the variable at compile time, we
  // need to "declare" it at runtime to make sure it actually exists in the
  // local context.
  VariableProxy* proxy = declaration->proxy();
  VariableMode mode = declaration->mode();
  Variable* variable = proxy->var();
  bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY;
  switch (variable->location()) {
754 755
    case VariableLocation::GLOBAL:
    case VariableLocation::UNALLOCATED:
danno@chromium.org's avatar
danno@chromium.org committed
756 757 758 759 760 761
      globals_->Add(variable->name(), zone());
      globals_->Add(variable->binding_needs_init()
                        ? isolate()->factory()->the_hole_value()
                        : isolate()->factory()->undefined_value(), zone());
      break;

762 763
    case VariableLocation::PARAMETER:
    case VariableLocation::LOCAL:
danno@chromium.org's avatar
danno@chromium.org committed
764 765 766 767 768 769 770
      if (hole_init) {
        Comment cmnt(masm_, "[ VariableDeclaration");
        __ mov(StackOperand(variable),
               Immediate(isolate()->factory()->the_hole_value()));
      }
      break;

771
    case VariableLocation::CONTEXT:
danno@chromium.org's avatar
danno@chromium.org committed
772 773 774 775 776 777 778 779 780 781
      if (hole_init) {
        Comment cmnt(masm_, "[ VariableDeclaration");
        EmitDebugCheckDeclarationContext(variable);
        __ mov(ContextOperand(esi, variable->index()),
               Immediate(isolate()->factory()->the_hole_value()));
        // No write barrier since the hole value is in old space.
        PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
      }
      break;

782
    case VariableLocation::LOOKUP: {
danno@chromium.org's avatar
danno@chromium.org committed
783 784 785
      Comment cmnt(masm_, "[ VariableDeclaration");
      __ push(Immediate(variable->name()));
      // VariableDeclaration nodes are always introduced in one of four modes.
786
      DCHECK(IsDeclaredVariableMode(mode));
danno@chromium.org's avatar
danno@chromium.org committed
787 788 789 790 791 792 793 794 795
      // Push initial value, if any.
      // Note: For variables we must not push an initial value (such as
      // 'undefined') because we may have a (legal) redeclaration and we
      // must not destroy the current value.
      if (hole_init) {
        __ push(Immediate(isolate()->factory()->the_hole_value()));
      } else {
        __ push(Immediate(Smi::FromInt(0)));  // Indicates no initial value.
      }
796 797 798 799
      __ CallRuntime(IsImmutableVariableMode(mode)
                         ? Runtime::kDeclareReadOnlyLookupSlot
                         : Runtime::kDeclareLookupSlot,
                     2);
danno@chromium.org's avatar
danno@chromium.org committed
800 801 802 803 804 805 806 807 808 809 810
      break;
    }
  }
}


void FullCodeGenerator::VisitFunctionDeclaration(
    FunctionDeclaration* declaration) {
  VariableProxy* proxy = declaration->proxy();
  Variable* variable = proxy->var();
  switch (variable->location()) {
811 812
    case VariableLocation::GLOBAL:
    case VariableLocation::UNALLOCATED: {
danno@chromium.org's avatar
danno@chromium.org committed
813 814
      globals_->Add(variable->name(), zone());
      Handle<SharedFunctionInfo> function =
815
          Compiler::GetSharedFunctionInfo(declaration->fun(), script(), info_);
danno@chromium.org's avatar
danno@chromium.org committed
816 817 818 819 820 821
      // Check for stack-overflow exception.
      if (function.is_null()) return SetStackOverflow();
      globals_->Add(function, zone());
      break;
    }

822 823
    case VariableLocation::PARAMETER:
    case VariableLocation::LOCAL: {
danno@chromium.org's avatar
danno@chromium.org committed
824 825 826 827 828 829
      Comment cmnt(masm_, "[ FunctionDeclaration");
      VisitForAccumulatorValue(declaration->fun());
      __ mov(StackOperand(variable), result_register());
      break;
    }

830
    case VariableLocation::CONTEXT: {
danno@chromium.org's avatar
danno@chromium.org committed
831 832 833 834 835
      Comment cmnt(masm_, "[ FunctionDeclaration");
      EmitDebugCheckDeclarationContext(variable);
      VisitForAccumulatorValue(declaration->fun());
      __ mov(ContextOperand(esi, variable->index()), result_register());
      // We know that we have written a function, which is not a smi.
836 837 838
      __ RecordWriteContextSlot(esi, Context::SlotOffset(variable->index()),
                                result_register(), ecx, kDontSaveFPRegs,
                                EMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
danno@chromium.org's avatar
danno@chromium.org committed
839 840 841 842
      PrepareForBailoutForId(proxy->id(), NO_REGISTERS);
      break;
    }

843
    case VariableLocation::LOOKUP: {
danno@chromium.org's avatar
danno@chromium.org committed
844 845 846
      Comment cmnt(masm_, "[ FunctionDeclaration");
      __ push(Immediate(variable->name()));
      VisitForStackValue(declaration->fun());
847
      __ CallRuntime(Runtime::kDeclareLookupSlot, 2);
danno@chromium.org's avatar
danno@chromium.org committed
848 849 850 851 852 853 854 855 856 857
      break;
    }
  }
}


void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) {
  // Call the runtime to declare the globals.
  __ Push(pairs);
  __ Push(Smi::FromInt(DeclareGlobalsFlags()));
858
  __ CallRuntime(Runtime::kDeclareGlobals, 2);
danno@chromium.org's avatar
danno@chromium.org committed
859 860 861 862 863 864 865
  // Return value is ignored.
}


void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) {
  // Call the runtime to declare the modules.
  __ Push(descriptions);
866
  __ CallRuntime(Runtime::kDeclareModules, 1);
danno@chromium.org's avatar
danno@chromium.org committed
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
  // Return value is ignored.
}


void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
  Comment cmnt(masm_, "[ SwitchStatement");
  Breakable nested_statement(this, stmt);
  SetStatementPosition(stmt);

  // Keep the switch value on the stack until a case matches.
  VisitForStackValue(stmt->tag());
  PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS);

  ZoneList<CaseClause*>* clauses = stmt->cases();
  CaseClause* default_clause = NULL;  // Can occur anywhere in the list.

  Label next_test;  // Recycled for each test.
  // Compile all the tests with branches to their bodies.
  for (int i = 0; i < clauses->length(); i++) {
    CaseClause* clause = clauses->at(i);
    clause->body_target()->Unuse();

    // The default is not a test, but remember it as final fall through.
    if (clause->is_default()) {
      default_clause = clause;
      continue;
    }

    Comment cmnt(masm_, "[ Case comparison");
    __ bind(&next_test);
    next_test.Unuse();

    // Compile the label expression.
    VisitForAccumulatorValue(clause->label());

    // Perform the comparison as if via '==='.
    __ mov(edx, Operand(esp, 0));  // Switch value.
    bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT);
    JumpPatchSite patch_site(masm_);
    if (inline_smi_code) {
      Label slow_case;
      __ mov(ecx, edx);
      __ or_(ecx, eax);
      patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);

      __ cmp(edx, eax);
      __ j(not_equal, &next_test);
      __ Drop(1);  // Switch value is no longer needed.
      __ jmp(clause->body_target());
      __ bind(&slow_case);
    }

919
    SetExpressionPosition(clause);
920
    Handle<Code> ic = CodeFactory::CompareIC(isolate(), Token::EQ_STRICT,
921
                                             strength(language_mode())).code();
danno@chromium.org's avatar
danno@chromium.org committed
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
    CallIC(ic, clause->CompareId());
    patch_site.EmitPatchInfo();

    Label skip;
    __ jmp(&skip, Label::kNear);
    PrepareForBailout(clause, TOS_REG);
    __ cmp(eax, isolate()->factory()->true_value());
    __ j(not_equal, &next_test);
    __ Drop(1);
    __ jmp(clause->body_target());
    __ bind(&skip);

    __ test(eax, eax);
    __ j(not_equal, &next_test);
    __ Drop(1);  // Switch value is no longer needed.
    __ jmp(clause->body_target());
  }

  // Discard the test value and jump to the default if present, otherwise to
  // the end of the statement.
  __ bind(&next_test);
  __ Drop(1);  // Switch value is no longer needed.
  if (default_clause == NULL) {
    __ jmp(nested_statement.break_label());
  } else {
    __ jmp(default_clause->body_target());
  }

  // Compile all the case bodies.
  for (int i = 0; i < clauses->length(); i++) {
    Comment cmnt(masm_, "[ Case body");
    CaseClause* clause = clauses->at(i);
    __ bind(clause->body_target());
    PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS);
    VisitStatements(clause->statements());
  }

  __ bind(nested_statement.break_label());
  PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
}


void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) {
  Comment cmnt(masm_, "[ ForInStatement");
966
  SetStatementPosition(stmt, SKIP_BREAK);
danno@chromium.org's avatar
danno@chromium.org committed
967

968
  FeedbackVectorSlot slot = stmt->ForInFeedbackSlot();
danno@chromium.org's avatar
danno@chromium.org committed
969 970 971 972 973 974 975

  Label loop, exit;
  ForIn loop_statement(this, stmt);
  increment_loop_depth();

  // Get the object to enumerate over. If the object is null or undefined, skip
  // over the loop.  See ECMA-262 version 5, section 12.6.4.
976
  SetExpressionAsStatementPosition(stmt->enumerable());
danno@chromium.org's avatar
danno@chromium.org committed
977 978 979 980 981 982 983 984 985 986 987 988 989 990
  VisitForAccumulatorValue(stmt->enumerable());
  __ cmp(eax, isolate()->factory()->undefined_value());
  __ j(equal, &exit);
  __ cmp(eax, isolate()->factory()->null_value());
  __ j(equal, &exit);

  PrepareForBailoutForId(stmt->PrepareId(), TOS_REG);

  // Convert the object to a JS object.
  Label convert, done_convert;
  __ JumpIfSmi(eax, &convert, Label::kNear);
  __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ecx);
  __ j(above_equal, &done_convert, Label::kNear);
  __ bind(&convert);
991 992
  ToObjectStub stub(isolate());
  __ CallStub(&stub);
danno@chromium.org's avatar
danno@chromium.org committed
993
  __ bind(&done_convert);
994
  PrepareForBailoutForId(stmt->ToObjectId(), TOS_REG);
danno@chromium.org's avatar
danno@chromium.org committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  __ push(eax);

  // Check for proxies.
  Label call_runtime, use_cache, fixed_array;
  STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
  __ CmpObjectType(eax, LAST_JS_PROXY_TYPE, ecx);
  __ j(below_equal, &call_runtime);

  // Check cache validity in generated code. This is a fast case for
  // the JSObject::IsSimpleEnum cache validity checks. If we cannot
  // guarantee cache validity, call the runtime system to check cache
  // validity or get the property names in a fixed array.
  __ CheckEnumCache(&call_runtime);

  __ mov(eax, FieldOperand(eax, HeapObject::kMapOffset));
  __ jmp(&use_cache, Label::kNear);

  // Get the set of properties to enumerate.
  __ bind(&call_runtime);
  __ push(eax);
  __ CallRuntime(Runtime::kGetPropertyNamesFast, 1);
1016
  PrepareForBailoutForId(stmt->EnumId(), TOS_REG);
danno@chromium.org's avatar
danno@chromium.org committed
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
  __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
         isolate()->factory()->meta_map());
  __ j(not_equal, &fixed_array);


  // We got a map in register eax. Get the enumeration cache from it.
  Label no_descriptors;
  __ bind(&use_cache);

  __ EnumLength(edx, eax);
  __ cmp(edx, Immediate(Smi::FromInt(0)));
  __ j(equal, &no_descriptors);

  __ LoadInstanceDescriptors(eax, ecx);
  __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheOffset));
  __ mov(ecx, FieldOperand(ecx, DescriptorArray::kEnumCacheBridgeCacheOffset));

  // Set up the four remaining stack slots.
  __ push(eax);  // Map.
  __ push(ecx);  // Enumeration cache.
  __ push(edx);  // Number of valid entries for the map in the enum cache.
  __ push(Immediate(Smi::FromInt(0)));  // Initial index.
  __ jmp(&loop);

  __ bind(&no_descriptors);
  __ add(esp, Immediate(kPointerSize));
  __ jmp(&exit);

  // We got a fixed array in register eax. Iterate through that.
  Label non_proxy;
  __ bind(&fixed_array);

  // No need for a write barrier, we are storing a Smi in the feedback vector.
1050 1051
  __ EmitLoadTypeFeedbackVector(ebx);
  int vector_index = SmiFromSlot(slot)->value();
1052
  __ mov(FieldOperand(ebx, FixedArray::OffsetOfElementAt(vector_index)),
1053
         Immediate(TypeFeedbackVector::MegamorphicSentinel(isolate())));
danno@chromium.org's avatar
danno@chromium.org committed
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

  __ mov(ebx, Immediate(Smi::FromInt(1)));  // Smi indicates slow check
  __ mov(ecx, Operand(esp, 0 * kPointerSize));  // Get enumerated object
  STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE);
  __ CmpObjectType(ecx, LAST_JS_PROXY_TYPE, ecx);
  __ j(above, &non_proxy);
  __ Move(ebx, Immediate(Smi::FromInt(0)));  // Zero indicates proxy
  __ bind(&non_proxy);
  __ push(ebx);  // Smi
  __ push(eax);  // Array
  __ mov(eax, FieldOperand(eax, FixedArray::kLengthOffset));
  __ push(eax);  // Fixed array length (as smi).
  __ push(Immediate(Smi::FromInt(0)));  // Initial index.

  // Generate code for doing the condition check.
  PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS);
  __ bind(&loop);
1071
  SetExpressionAsStatementPosition(stmt->each());
1072

danno@chromium.org's avatar
danno@chromium.org committed
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
  __ mov(eax, Operand(esp, 0 * kPointerSize));  // Get the current index.
  __ cmp(eax, Operand(esp, 1 * kPointerSize));  // Compare to the array length.
  __ j(above_equal, loop_statement.break_label());

  // Get the current entry of the array into register ebx.
  __ mov(ebx, Operand(esp, 2 * kPointerSize));
  __ mov(ebx, FieldOperand(ebx, eax, times_2, FixedArray::kHeaderSize));

  // Get the expected map from the stack or a smi in the
  // permanent slow case into register edx.
  __ mov(edx, Operand(esp, 3 * kPointerSize));

  // Check if the expected map still matches that of the enumerable.
  // If not, we may have to filter the key.
  Label update_each;
  __ mov(ecx, Operand(esp, 4 * kPointerSize));
  __ cmp(edx, FieldOperand(ecx, HeapObject::kMapOffset));
  __ j(equal, &update_each, Label::kNear);

  // For proxies, no filtering is done.
  // TODO(rossberg): What if only a prototype is a proxy? Not specified yet.
1094
  DCHECK(Smi::FromInt(0) == 0);
danno@chromium.org's avatar
danno@chromium.org committed
1095 1096 1097 1098 1099 1100 1101 1102
  __ test(edx, edx);
  __ j(zero, &update_each);

  // Convert the entry to a string or null if it isn't a property
  // anymore. If the property has been removed while iterating, we
  // just skip it.
  __ push(ecx);  // Enumerable.
  __ push(ebx);  // Current entry.
1103
  __ CallRuntime(Runtime::kForInFilter, 2);
1104
  PrepareForBailoutForId(stmt->FilterId(), TOS_REG);
1105
  __ cmp(eax, isolate()->factory()->undefined_value());
danno@chromium.org's avatar
danno@chromium.org committed
1106 1107 1108 1109 1110 1111 1112 1113 1114
  __ j(equal, loop_statement.continue_label());
  __ mov(ebx, eax);

  // Update the 'each' property or variable from the possibly filtered
  // entry in register ebx.
  __ bind(&update_each);
  __ mov(result_register(), ebx);
  // Perform the assignment as if via '='.
  { EffectContext context(this);
1115
    EmitAssignment(stmt->each(), stmt->EachFeedbackSlot());
1116
    PrepareForBailoutForId(stmt->AssignmentId(), NO_REGISTERS);
danno@chromium.org's avatar
danno@chromium.org committed
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
  }

  // Generate code for the body of the loop.
  Visit(stmt->body());

  // Generate code for going to the next element by incrementing the
  // index (smi) stored on top of the stack.
  __ bind(loop_statement.continue_label());
  __ add(Operand(esp, 0 * kPointerSize), Immediate(Smi::FromInt(1)));

  EmitBackEdgeBookkeeping(stmt, &loop);
  __ jmp(&loop);

  // Remove the pointers stored on the stack.
  __ bind(loop_statement.break_label());
  __ add(esp, Immediate(5 * kPointerSize));

  // Exit and decrement the loop depth.
  PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS);
  __ bind(&exit);
  decrement_loop_depth();
}


void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info,
                                       bool pretenure) {
  // Use the fast case closure allocation code that allocates in new
  // space for nested functions that don't need literals cloning. If
  // we're running with the --always-opt or the --prepare-always-opt
  // flag, we need to use the runtime function so that the new function
  // we are creating here gets a chance to have its code optimized and
  // doesn't just get a copy of the existing unoptimized code.
  if (!FLAG_always_opt &&
      !FLAG_prepare_always_opt &&
      !pretenure &&
      scope()->is_function_scope() &&
      info->num_literals() == 0) {
1154
    FastNewClosureStub stub(isolate(), info->language_mode(), info->kind());
danno@chromium.org's avatar
danno@chromium.org committed
1155 1156 1157 1158
    __ mov(ebx, Immediate(info));
    __ CallStub(&stub);
  } else {
    __ push(Immediate(info));
1159 1160
    __ CallRuntime(
        pretenure ? Runtime::kNewClosure_Tenured : Runtime::kNewClosure, 1);
danno@chromium.org's avatar
danno@chromium.org committed
1161 1162 1163 1164 1165
  }
  context()->Plug(eax);
}


1166
void FullCodeGenerator::EmitSetHomeObject(Expression* initializer, int offset,
1167
                                          FeedbackVectorSlot slot) {
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
  DCHECK(NeedsHomeObject(initializer));
  __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
  __ mov(StoreDescriptor::NameRegister(),
         Immediate(isolate()->factory()->home_object_symbol()));
  __ mov(StoreDescriptor::ValueRegister(), Operand(esp, offset * kPointerSize));
  if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
  CallStoreIC();
}


1178 1179 1180
void FullCodeGenerator::EmitSetHomeObjectAccumulator(Expression* initializer,
                                                     int offset,
                                                     FeedbackVectorSlot slot) {
1181 1182 1183 1184 1185 1186 1187
  DCHECK(NeedsHomeObject(initializer));
  __ mov(StoreDescriptor::ReceiverRegister(), eax);
  __ mov(StoreDescriptor::NameRegister(),
         Immediate(isolate()->factory()->home_object_symbol()));
  __ mov(StoreDescriptor::ValueRegister(), Operand(esp, offset * kPointerSize));
  if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
  CallStoreIC();
1188 1189 1190
}


1191
void FullCodeGenerator::EmitLoadGlobalCheckExtensions(VariableProxy* proxy,
1192
                                                      TypeofMode typeof_mode,
danno@chromium.org's avatar
danno@chromium.org committed
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
                                                      Label* slow) {
  Register context = esi;
  Register temp = edx;

  Scope* s = scope();
  while (s != NULL) {
    if (s->num_heap_slots() > 0) {
      if (s->calls_sloppy_eval()) {
        // Check that extension is NULL.
        __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
               Immediate(0));
        __ j(not_equal, slow);
      }
      // Load next context in chain.
      __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
      // Walk the rest of the chain without clobbering esi.
      context = temp;
    }
    // If no outer scope calls eval, we do not need to check more
    // context extensions.  If we have reached an eval scope, we check
    // all extensions from this point.
    if (!s->outer_scope_calls_sloppy_eval() || s->is_eval_scope()) break;
    s = s->outer_scope();
  }

  if (s != NULL && s->is_eval_scope()) {
    // Loop up the context chain.  There is no frame effect so it is
    // safe to use raw labels here.
    Label next, fast;
    if (!context.is(temp)) {
      __ mov(temp, context);
    }
    __ bind(&next);
    // Terminate at native context.
    __ cmp(FieldOperand(temp, HeapObject::kMapOffset),
           Immediate(isolate()->factory()->native_context_map()));
    __ j(equal, &fast, Label::kNear);
    // Check that extension is NULL.
    __ cmp(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0));
    __ j(not_equal, slow);
    // Load next context in chain.
    __ mov(temp, ContextOperand(temp, Context::PREVIOUS_INDEX));
    __ jmp(&next);
    __ bind(&fast);
  }

1239 1240
  // All extension objects were empty and it is safe to use a normal global
  // load machinery.
1241
  EmitGlobalVariableLoad(proxy, typeof_mode);
danno@chromium.org's avatar
danno@chromium.org committed
1242 1243 1244 1245 1246
}


MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var,
                                                                Label* slow) {
1247
  DCHECK(var->IsContextSlot());
danno@chromium.org's avatar
danno@chromium.org committed
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  Register context = esi;
  Register temp = ebx;

  for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) {
    if (s->num_heap_slots() > 0) {
      if (s->calls_sloppy_eval()) {
        // Check that extension is NULL.
        __ cmp(ContextOperand(context, Context::EXTENSION_INDEX),
               Immediate(0));
        __ j(not_equal, slow);
      }
      __ mov(temp, ContextOperand(context, Context::PREVIOUS_INDEX));
      // Walk the rest of the chain without clobbering esi.
      context = temp;
    }
  }
  // Check that last extension is NULL.
  __ cmp(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0));
  __ j(not_equal, slow);

  // This function is used only for loads, not stores, so it's safe to
  // return an esi-based operand (the write barrier cannot be allowed to
  // destroy the esi register).
  return ContextOperand(context, var->index());
}


1275
void FullCodeGenerator::EmitDynamicLookupFastCase(VariableProxy* proxy,
1276 1277
                                                  TypeofMode typeof_mode,
                                                  Label* slow, Label* done) {
danno@chromium.org's avatar
danno@chromium.org committed
1278 1279 1280 1281 1282
  // Generate fast-case code for variables that might be shadowed by
  // eval-introduced variables.  Eval is used a lot without
  // introducing variables.  In those cases, we do not want to
  // perform a runtime call for all variables in the scope
  // containing the eval.
1283
  Variable* var = proxy->var();
danno@chromium.org's avatar
danno@chromium.org committed
1284
  if (var->mode() == DYNAMIC_GLOBAL) {
1285
    EmitLoadGlobalCheckExtensions(proxy, typeof_mode, slow);
danno@chromium.org's avatar
danno@chromium.org committed
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
    __ jmp(done);
  } else if (var->mode() == DYNAMIC_LOCAL) {
    Variable* local = var->local_if_not_shadowed();
    __ mov(eax, ContextSlotOperandCheckExtensions(local, slow));
    if (local->mode() == LET || local->mode() == CONST ||
        local->mode() == CONST_LEGACY) {
      __ cmp(eax, isolate()->factory()->the_hole_value());
      __ j(not_equal, done);
      if (local->mode() == CONST_LEGACY) {
        __ mov(eax, isolate()->factory()->undefined_value());
      } else {  // LET || CONST
        __ push(Immediate(var->name()));
1298
        __ CallRuntime(Runtime::kThrowReferenceError, 1);
danno@chromium.org's avatar
danno@chromium.org committed
1299 1300 1301 1302 1303 1304 1305
      }
    }
    __ jmp(done);
  }
}


1306
void FullCodeGenerator::EmitGlobalVariableLoad(VariableProxy* proxy,
1307
                                               TypeofMode typeof_mode) {
1308 1309 1310
  Variable* var = proxy->var();
  DCHECK(var->IsUnallocatedOrGlobalSlot() ||
         (var->IsLookupSlot() && var->mode() == DYNAMIC_GLOBAL));
1311 1312 1313
  if (var->IsGlobalSlot()) {
    DCHECK(var->index() > 0);
    DCHECK(var->IsStaticGlobalObjectProperty());
1314 1315 1316 1317 1318 1319 1320 1321
    int const slot = var->index();
    int const depth = scope()->ContextChainLength(var->scope());
    if (depth <= LoadGlobalViaContextStub::kMaximumDepth) {
      __ Move(LoadGlobalViaContextDescriptor::SlotRegister(), Immediate(slot));
      LoadGlobalViaContextStub stub(isolate(), depth);
      __ CallStub(&stub);
    } else {
      __ Push(Smi::FromInt(slot));
1322
      __ CallRuntime(Runtime::kLoadGlobalViaContext, 1);
1323
    }
1324 1325 1326 1327 1328 1329

  } else {
    __ mov(LoadDescriptor::ReceiverRegister(), GlobalObjectOperand());
    __ mov(LoadDescriptor::NameRegister(), var->name());
    __ mov(LoadDescriptor::SlotRegister(),
           Immediate(SmiFromSlot(proxy->VariableFeedbackSlot())));
1330
    CallLoadIC(typeof_mode);
1331
  }
1332 1333 1334 1335
}


void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy,
1336
                                         TypeofMode typeof_mode) {
1337
  SetExpressionPosition(proxy);
1338
  PrepareForBailoutForId(proxy->BeforeId(), NO_REGISTERS);
danno@chromium.org's avatar
danno@chromium.org committed
1339 1340 1341 1342 1343
  Variable* var = proxy->var();

  // Three cases: global variables, lookup variables, and all other types of
  // variables.
  switch (var->location()) {
1344 1345
    case VariableLocation::GLOBAL:
    case VariableLocation::UNALLOCATED: {
danno@chromium.org's avatar
danno@chromium.org committed
1346
      Comment cmnt(masm_, "[ Global variable");
1347
      EmitGlobalVariableLoad(proxy, typeof_mode);
danno@chromium.org's avatar
danno@chromium.org committed
1348 1349 1350 1351
      context()->Plug(eax);
      break;
    }

1352 1353 1354
    case VariableLocation::PARAMETER:
    case VariableLocation::LOCAL:
    case VariableLocation::CONTEXT: {
1355
      DCHECK_EQ(NOT_INSIDE_TYPEOF, typeof_mode);
danno@chromium.org's avatar
danno@chromium.org committed
1356 1357
      Comment cmnt(masm_, var->IsContextSlot() ? "[ Context variable"
                                               : "[ Stack variable");
1358

1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
      if (NeedsHoleCheckForLoad(proxy)) {
        // Let and const need a read barrier.
        Label done;
        GetVar(eax, var);
        __ cmp(eax, isolate()->factory()->the_hole_value());
        __ j(not_equal, &done, Label::kNear);
        if (var->mode() == LET || var->mode() == CONST) {
          // Throw a reference error when using an uninitialized let/const
          // binding in harmony mode.
          __ push(Immediate(var->name()));
          __ CallRuntime(Runtime::kThrowReferenceError, 1);
danno@chromium.org's avatar
danno@chromium.org committed
1370
        } else {
1371 1372 1373
          // Uninitialized legacy const bindings are unholed.
          DCHECK(var->mode() == CONST_LEGACY);
          __ mov(eax, isolate()->factory()->undefined_value());
danno@chromium.org's avatar
danno@chromium.org committed
1374
        }
1375 1376 1377
        __ bind(&done);
        context()->Plug(eax);
        break;
danno@chromium.org's avatar
danno@chromium.org committed
1378 1379 1380 1381 1382
      }
      context()->Plug(var);
      break;
    }

1383
    case VariableLocation::LOOKUP: {
danno@chromium.org's avatar
danno@chromium.org committed
1384 1385 1386 1387
      Comment cmnt(masm_, "[ Lookup variable");
      Label done, slow;
      // Generate code for loading from variables potentially shadowed
      // by eval-introduced variables.
1388
      EmitDynamicLookupFastCase(proxy, typeof_mode, &slow, &done);
danno@chromium.org's avatar
danno@chromium.org committed
1389 1390 1391
      __ bind(&slow);
      __ push(esi);  // Context.
      __ push(Immediate(var->name()));
1392
      Runtime::FunctionId function_id =
1393
          typeof_mode == NOT_INSIDE_TYPEOF
1394 1395 1396
              ? Runtime::kLoadLookupSlot
              : Runtime::kLoadLookupSlotNoReferenceError;
      __ CallRuntime(function_id, 2);
danno@chromium.org's avatar
danno@chromium.org committed
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
      __ bind(&done);
      context()->Plug(eax);
      break;
    }
  }
}


void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
  Comment cmnt(masm_, "[ RegExpLiteral");
  Label materialized;
  // Registers will be used as follows:
  // edi = JS function.
  // ecx = literals array.
  // ebx = regexp literal.
  // eax = regexp literal clone.
  __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
  __ mov(ecx, FieldOperand(edi, JSFunction::kLiteralsOffset));
1415
  int literal_offset = LiteralsArray::OffsetOfLiteralAt(expr->literal_index());
danno@chromium.org's avatar
danno@chromium.org committed
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
  __ mov(ebx, FieldOperand(ecx, literal_offset));
  __ cmp(ebx, isolate()->factory()->undefined_value());
  __ j(not_equal, &materialized, Label::kNear);

  // Create regexp literal using runtime function
  // Result will be in eax.
  __ push(ecx);
  __ push(Immediate(Smi::FromInt(expr->literal_index())));
  __ push(Immediate(expr->pattern()));
  __ push(Immediate(expr->flags()));
1426
  __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4);
danno@chromium.org's avatar
danno@chromium.org committed
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
  __ mov(ebx, eax);

  __ bind(&materialized);
  int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize;
  Label allocated, runtime_allocate;
  __ Allocate(size, eax, ecx, edx, &runtime_allocate, TAG_OBJECT);
  __ jmp(&allocated);

  __ bind(&runtime_allocate);
  __ push(ebx);
  __ push(Immediate(Smi::FromInt(size)));
1438
  __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
danno@chromium.org's avatar
danno@chromium.org committed
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
  __ pop(ebx);

  __ bind(&allocated);
  // Copy the content into the newly allocated memory.
  // (Unroll copy loop once for better throughput).
  for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) {
    __ mov(edx, FieldOperand(ebx, i));
    __ mov(ecx, FieldOperand(ebx, i + kPointerSize));
    __ mov(FieldOperand(eax, i), edx);
    __ mov(FieldOperand(eax, i + kPointerSize), ecx);
  }
  if ((size % (2 * kPointerSize)) != 0) {
    __ mov(edx, FieldOperand(ebx, size - kPointerSize));
    __ mov(FieldOperand(eax, size - kPointerSize), edx);
  }
  context()->Plug(eax);
}


1458 1459
void FullCodeGenerator::EmitAccessor(ObjectLiteralProperty* property) {
  Expression* expression = (property == NULL) ? NULL : property->value();
danno@chromium.org's avatar
danno@chromium.org committed
1460 1461 1462 1463
  if (expression == NULL) {
    __ push(Immediate(isolate()->factory()->null_value()));
  } else {
    VisitForStackValue(expression);
1464 1465 1466 1467 1468 1469
    if (NeedsHomeObject(expression)) {
      DCHECK(property->kind() == ObjectLiteral::Property::GETTER ||
             property->kind() == ObjectLiteral::Property::SETTER);
      int offset = property->kind() == ObjectLiteral::Property::GETTER ? 2 : 3;
      EmitSetHomeObject(expression, offset, property->GetSlot());
    }
danno@chromium.org's avatar
danno@chromium.org committed
1470 1471 1472 1473 1474 1475 1476 1477
  }
}


void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
  Comment cmnt(masm_, "[ ObjectLiteral");

  Handle<FixedArray> constant_properties = expr->constant_properties();
1478 1479 1480 1481
  int flags = expr->ComputeFlags();
  // If any of the keys would store to the elements array, then we shouldn't
  // allow it.
  if (MustCreateObjectLiteralWithRuntime(expr)) {
danno@chromium.org's avatar
danno@chromium.org committed
1482 1483 1484 1485 1486
    __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
    __ push(FieldOperand(edi, JSFunction::kLiteralsOffset));
    __ push(Immediate(Smi::FromInt(expr->literal_index())));
    __ push(Immediate(constant_properties));
    __ push(Immediate(Smi::FromInt(flags)));
1487
    __ CallRuntime(Runtime::kCreateObjectLiteral, 4);
danno@chromium.org's avatar
danno@chromium.org committed
1488 1489 1490 1491 1492 1493
  } else {
    __ mov(edi, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
    __ mov(eax, FieldOperand(edi, JSFunction::kLiteralsOffset));
    __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
    __ mov(ecx, Immediate(constant_properties));
    __ mov(edx, Immediate(Smi::FromInt(flags)));
1494
    FastCloneShallowObjectStub stub(isolate(), expr->properties_count());
danno@chromium.org's avatar
danno@chromium.org committed
1495 1496
    __ CallStub(&stub);
  }
1497
  PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
danno@chromium.org's avatar
danno@chromium.org committed
1498 1499 1500 1501 1502 1503

  // If result_saved is true the result is on top of the stack.  If
  // result_saved is false the result is in eax.
  bool result_saved = false;

  AccessorTable accessor_table(zone());
cdai2's avatar
cdai2 committed
1504 1505 1506 1507
  int property_index = 0;
  for (; property_index < expr->properties()->length(); property_index++) {
    ObjectLiteral::Property* property = expr->properties()->at(property_index);
    if (property->is_computed_name()) break;
danno@chromium.org's avatar
danno@chromium.org committed
1508 1509
    if (property->IsCompileTimeValue()) continue;

cdai2's avatar
cdai2 committed
1510
    Literal* key = property->key()->AsLiteral();
danno@chromium.org's avatar
danno@chromium.org committed
1511 1512 1513 1514 1515 1516 1517 1518 1519
    Expression* value = property->value();
    if (!result_saved) {
      __ push(eax);  // Save result on the stack
      result_saved = true;
    }
    switch (property->kind()) {
      case ObjectLiteral::Property::CONSTANT:
        UNREACHABLE();
      case ObjectLiteral::Property::MATERIALIZED_LITERAL:
1520
        DCHECK(!CompileTimeValue::IsCompileTimeValue(value));
danno@chromium.org's avatar
danno@chromium.org committed
1521 1522
        // Fall through.
      case ObjectLiteral::Property::COMPUTED:
1523 1524
        // It is safe to use [[Put]] here because the boilerplate already
        // contains computed properties with an uninitialized value.
danno@chromium.org's avatar
danno@chromium.org committed
1525 1526 1527
        if (key->value()->IsInternalizedString()) {
          if (property->emit_store()) {
            VisitForAccumulatorValue(value);
1528 1529 1530
            DCHECK(StoreDescriptor::ValueRegister().is(eax));
            __ mov(StoreDescriptor::NameRegister(), Immediate(key->value()));
            __ mov(StoreDescriptor::ReceiverRegister(), Operand(esp, 0));
1531
            if (FLAG_vector_stores) {
1532
              EmitLoadStoreICSlot(property->GetSlot(0));
1533 1534 1535 1536
              CallStoreIC();
            } else {
              CallStoreIC(key->LiteralFeedbackId());
            }
danno@chromium.org's avatar
danno@chromium.org committed
1537
            PrepareForBailoutForId(key->id(), NO_REGISTERS);
1538
            if (NeedsHomeObject(value)) {
1539
              EmitSetHomeObjectAccumulator(value, 0, property->GetSlot(1));
1540
            }
danno@chromium.org's avatar
danno@chromium.org committed
1541 1542 1543 1544 1545 1546 1547 1548 1549
          } else {
            VisitForEffect(value);
          }
          break;
        }
        __ push(Operand(esp, 0));  // Duplicate receiver.
        VisitForStackValue(key);
        VisitForStackValue(value);
        if (property->emit_store()) {
1550 1551 1552
          if (NeedsHomeObject(value)) {
            EmitSetHomeObject(value, 2, property->GetSlot());
          }
1553
          __ push(Immediate(Smi::FromInt(SLOPPY)));  // Language mode
1554
          __ CallRuntime(Runtime::kSetProperty, 4);
danno@chromium.org's avatar
danno@chromium.org committed
1555 1556 1557 1558 1559 1560 1561
        } else {
          __ Drop(3);
        }
        break;
      case ObjectLiteral::Property::PROTOTYPE:
        __ push(Operand(esp, 0));  // Duplicate receiver.
        VisitForStackValue(value);
1562 1563
        DCHECK(property->emit_store());
        __ CallRuntime(Runtime::kInternalSetPrototype, 2);
danno@chromium.org's avatar
danno@chromium.org committed
1564 1565
        break;
      case ObjectLiteral::Property::GETTER:
1566
        if (property->emit_store()) {
1567
          accessor_table.lookup(key)->second->getter = property;
1568
        }
danno@chromium.org's avatar
danno@chromium.org committed
1569 1570
        break;
      case ObjectLiteral::Property::SETTER:
1571
        if (property->emit_store()) {
1572
          accessor_table.lookup(key)->second->setter = property;
1573
        }
danno@chromium.org's avatar
danno@chromium.org committed
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
        break;
    }
  }

  // Emit code to define accessors, using only a single call to the runtime for
  // each pair of corresponding getters and setters.
  for (AccessorTable::Iterator it = accessor_table.begin();
       it != accessor_table.end();
       ++it) {
    __ push(Operand(esp, 0));  // Duplicate receiver.
    VisitForStackValue(it->first);
1585

1586
    EmitAccessor(it->second->getter);
danno@chromium.org's avatar
danno@chromium.org committed
1587
    EmitAccessor(it->second->setter);
1588

danno@chromium.org's avatar
danno@chromium.org committed
1589
    __ push(Immediate(Smi::FromInt(NONE)));
1590
    __ CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, 5);
danno@chromium.org's avatar
danno@chromium.org committed
1591 1592
  }

cdai2's avatar
cdai2 committed
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
  // Object literals have two parts. The "static" part on the left contains no
  // computed property names, and so we can compute its map ahead of time; see
  // runtime.cc::CreateObjectLiteralBoilerplate. The second "dynamic" part
  // starts with the first computed property name, and continues with all
  // properties to its right.  All the code from above initializes the static
  // component of the object literal, and arranges for the map of the result to
  // reflect the static order in which the keys appear. For the dynamic
  // properties, we compile them into a series of "SetOwnProperty" runtime
  // calls. This will preserve insertion order.
  for (; property_index < expr->properties()->length(); property_index++) {
    ObjectLiteral::Property* property = expr->properties()->at(property_index);

    Expression* value = property->value();
    if (!result_saved) {
      __ push(eax);  // Save result on the stack
      result_saved = true;
    }

    __ push(Operand(esp, 0));  // Duplicate receiver.

    if (property->kind() == ObjectLiteral::Property::PROTOTYPE) {
      DCHECK(!property->is_computed_name());
      VisitForStackValue(value);
1616 1617
      DCHECK(property->emit_store());
      __ CallRuntime(Runtime::kInternalSetPrototype, 2);
cdai2's avatar
cdai2 committed
1618
    } else {
1619
      EmitPropertyKey(property, expr->GetIdForProperty(property_index));
cdai2's avatar
cdai2 committed
1620
      VisitForStackValue(value);
1621 1622 1623
      if (NeedsHomeObject(value)) {
        EmitSetHomeObject(value, 2, property->GetSlot());
      }
cdai2's avatar
cdai2 committed
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641

      switch (property->kind()) {
        case ObjectLiteral::Property::CONSTANT:
        case ObjectLiteral::Property::MATERIALIZED_LITERAL:
        case ObjectLiteral::Property::COMPUTED:
          if (property->emit_store()) {
            __ push(Immediate(Smi::FromInt(NONE)));
            __ CallRuntime(Runtime::kDefineDataPropertyUnchecked, 4);
          } else {
            __ Drop(3);
          }
          break;

        case ObjectLiteral::Property::PROTOTYPE:
          UNREACHABLE();
          break;

        case ObjectLiteral::Property::GETTER:
1642 1643
          __ push(Immediate(Smi::FromInt(NONE)));
          __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
cdai2's avatar
cdai2 committed
1644 1645 1646
          break;

        case ObjectLiteral::Property::SETTER:
1647 1648
          __ push(Immediate(Smi::FromInt(NONE)));
          __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
cdai2's avatar
cdai2 committed
1649 1650 1651 1652 1653
          break;
      }
    }
  }

danno@chromium.org's avatar
danno@chromium.org committed
1654
  if (expr->has_function()) {
1655
    DCHECK(result_saved);
danno@chromium.org's avatar
danno@chromium.org committed
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
    __ push(Operand(esp, 0));
    __ CallRuntime(Runtime::kToFastProperties, 1);
  }

  if (result_saved) {
    context()->PlugTOS();
  } else {
    context()->Plug(eax);
  }
}


void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
  Comment cmnt(masm_, "[ ArrayLiteral");

  expr->BuildConstantElements(isolate());
  Handle<FixedArray> constant_elements = expr->constant_elements();
  bool has_constant_fast_elements =
1674
      IsFastObjectElementsKind(expr->constant_elements_kind());
danno@chromium.org's avatar
danno@chromium.org committed
1675 1676 1677 1678 1679 1680 1681 1682

  AllocationSiteMode allocation_site_mode = TRACK_ALLOCATION_SITE;
  if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) {
    // If the only customer of allocation sites is transitioning, then
    // we can turn it off if we don't have anywhere else to transition to.
    allocation_site_mode = DONT_TRACK_ALLOCATION_SITE;
  }

1683
  if (MustCreateArrayLiteralWithRuntime(expr)) {
danno@chromium.org's avatar
danno@chromium.org committed
1684 1685 1686 1687
    __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
    __ push(FieldOperand(ebx, JSFunction::kLiteralsOffset));
    __ push(Immediate(Smi::FromInt(expr->literal_index())));
    __ push(Immediate(constant_elements));
1688
    __ push(Immediate(Smi::FromInt(expr->ComputeFlags())));
1689
    __ CallRuntime(Runtime::kCreateArrayLiteral, 4);
danno@chromium.org's avatar
danno@chromium.org committed
1690 1691 1692 1693 1694 1695 1696 1697
  } else {
    __ mov(ebx, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
    __ mov(eax, FieldOperand(ebx, JSFunction::kLiteralsOffset));
    __ mov(ebx, Immediate(Smi::FromInt(expr->literal_index())));
    __ mov(ecx, Immediate(constant_elements));
    FastCloneShallowArrayStub stub(isolate(), allocation_site_mode);
    __ CallStub(&stub);
  }
1698
  PrepareForBailoutForId(expr->CreateLiteralId(), TOS_REG);
danno@chromium.org's avatar
danno@chromium.org committed
1699 1700

  bool result_saved = false;  // Is the result saved to the stack?
1701 1702
  ZoneList<Expression*>* subexprs = expr->values();
  int length = subexprs->length();
danno@chromium.org's avatar
danno@chromium.org committed
1703 1704 1705

  // Emit code to evaluate all the non-constant subexpressions and to store
  // them into the newly cloned array.
1706 1707 1708 1709 1710
  int array_index = 0;
  for (; array_index < length; array_index++) {
    Expression* subexpr = subexprs->at(array_index);
    if (subexpr->IsSpread()) break;

danno@chromium.org's avatar
danno@chromium.org committed
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
    // If the subexpression is a literal or a simple materialized literal it
    // is already set in the cloned array.
    if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;

    if (!result_saved) {
      __ push(eax);  // array literal.
      __ push(Immediate(Smi::FromInt(expr->literal_index())));
      result_saved = true;
    }
    VisitForAccumulatorValue(subexpr);

1722
    if (has_constant_fast_elements) {
danno@chromium.org's avatar
danno@chromium.org committed
1723 1724
      // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they
      // cannot transition and don't need to call the runtime stub.
1725
      int offset = FixedArray::kHeaderSize + (array_index * kPointerSize);
danno@chromium.org's avatar
danno@chromium.org committed
1726 1727 1728 1729 1730
      __ mov(ebx, Operand(esp, kPointerSize));  // Copy of array literal.
      __ mov(ebx, FieldOperand(ebx, JSObject::kElementsOffset));
      // Store the subexpression value in the array's elements.
      __ mov(FieldOperand(ebx, offset), result_register());
      // Update the write barrier for the array store.
1731 1732
      __ RecordWriteField(ebx, offset, result_register(), ecx, kDontSaveFPRegs,
                          EMIT_REMEMBERED_SET, INLINE_SMI_CHECK);
danno@chromium.org's avatar
danno@chromium.org committed
1733 1734
    } else {
      // Store the subexpression value in the array's elements.
1735
      __ mov(ecx, Immediate(Smi::FromInt(array_index)));
danno@chromium.org's avatar
danno@chromium.org committed
1736 1737 1738 1739
      StoreArrayLiteralElementStub stub(isolate());
      __ CallStub(&stub);
    }

1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
    PrepareForBailoutForId(expr->GetIdForElement(array_index), NO_REGISTERS);
  }

  // In case the array literal contains spread expressions it has two parts. The
  // first part is  the "static" array which has a literal index is  handled
  // above. The second part is the part after the first spread expression
  // (inclusive) and these elements gets appended to the array. Note that the
  // number elements an iterable produces is unknown ahead of time.
  if (array_index < length && result_saved) {
    __ Drop(1);  // literal index
    __ Pop(eax);
    result_saved = false;
  }
  for (; array_index < length; array_index++) {
    Expression* subexpr = subexprs->at(array_index);

    __ Push(eax);
    if (subexpr->IsSpread()) {
      VisitForStackValue(subexpr->AsSpread()->expression());
1759 1760
      __ InvokeBuiltin(Context::CONCAT_ITERABLE_TO_ARRAY_BUILTIN_INDEX,
                       CALL_FUNCTION);
1761 1762 1763 1764 1765 1766
    } else {
      VisitForStackValue(subexpr);
      __ CallRuntime(Runtime::kAppendElement, 2);
    }

    PrepareForBailoutForId(expr->GetIdForElement(array_index), NO_REGISTERS);
danno@chromium.org's avatar
danno@chromium.org committed
1767 1768 1769
  }

  if (result_saved) {
1770
    __ Drop(1);  // literal index
danno@chromium.org's avatar
danno@chromium.org committed
1771 1772 1773 1774 1775 1776 1777 1778
    context()->PlugTOS();
  } else {
    context()->Plug(eax);
  }
}


void FullCodeGenerator::VisitAssignment(Assignment* expr) {
1779
  DCHECK(expr->target()->IsValidReferenceExpressionOrThis());
danno@chromium.org's avatar
danno@chromium.org committed
1780 1781

  Comment cmnt(masm_, "[ Assignment");
1782
  SetExpressionPosition(expr, INSERT_BREAK);
danno@chromium.org's avatar
danno@chromium.org committed
1783 1784

  Property* property = expr->target()->AsProperty();
1785
  LhsKind assign_type = Property::GetAssignType(property);
danno@chromium.org's avatar
danno@chromium.org committed
1786 1787 1788 1789 1790 1791

  // Evaluate LHS expression.
  switch (assign_type) {
    case VARIABLE:
      // Nothing to do here.
      break;
1792
    case NAMED_SUPER_PROPERTY:
1793 1794
      VisitForStackValue(
          property->obj()->AsSuperPropertyReference()->this_var());
1795
      VisitForAccumulatorValue(
1796
          property->obj()->AsSuperPropertyReference()->home_object());
1797 1798 1799 1800 1801 1802
      __ push(result_register());
      if (expr->is_compound()) {
        __ push(MemOperand(esp, kPointerSize));
        __ push(result_register());
      }
      break;
danno@chromium.org's avatar
danno@chromium.org committed
1803 1804
    case NAMED_PROPERTY:
      if (expr->is_compound()) {
1805
        // We need the receiver both on the stack and in the register.
danno@chromium.org's avatar
danno@chromium.org committed
1806
        VisitForStackValue(property->obj());
1807
        __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
danno@chromium.org's avatar
danno@chromium.org committed
1808 1809 1810 1811
      } else {
        VisitForStackValue(property->obj());
      }
      break;
1812
    case KEYED_SUPER_PROPERTY:
1813 1814 1815
      VisitForStackValue(
          property->obj()->AsSuperPropertyReference()->this_var());
      VisitForStackValue(
1816
          property->obj()->AsSuperPropertyReference()->home_object());
1817 1818 1819 1820 1821 1822 1823 1824
      VisitForAccumulatorValue(property->key());
      __ Push(result_register());
      if (expr->is_compound()) {
        __ push(MemOperand(esp, 2 * kPointerSize));
        __ push(MemOperand(esp, 2 * kPointerSize));
        __ push(result_register());
      }
      break;
danno@chromium.org's avatar
danno@chromium.org committed
1825 1826 1827 1828
    case KEYED_PROPERTY: {
      if (expr->is_compound()) {
        VisitForStackValue(property->obj());
        VisitForStackValue(property->key());
1829 1830
        __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, kPointerSize));
        __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));
danno@chromium.org's avatar
danno@chromium.org committed
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
      } else {
        VisitForStackValue(property->obj());
        VisitForStackValue(property->key());
      }
      break;
    }
  }

  // For compound assignments we need another deoptimization point after the
  // variable/property load.
  if (expr->is_compound()) {
    AccumulatorValueContext result_context(this);
    { AccumulatorValueContext left_operand_context(this);
      switch (assign_type) {
        case VARIABLE:
          EmitVariableLoad(expr->target()->AsVariableProxy());
          PrepareForBailout(expr->target(), TOS_REG);
          break;
1849 1850 1851 1852
        case NAMED_SUPER_PROPERTY:
          EmitNamedSuperPropertyLoad(property);
          PrepareForBailoutForId(property->LoadId(), TOS_REG);
          break;
danno@chromium.org's avatar
danno@chromium.org committed
1853 1854 1855 1856
        case NAMED_PROPERTY:
          EmitNamedPropertyLoad(property);
          PrepareForBailoutForId(property->LoadId(), TOS_REG);
          break;
1857 1858 1859 1860
        case KEYED_SUPER_PROPERTY:
          EmitKeyedSuperPropertyLoad(property);
          PrepareForBailoutForId(property->LoadId(), TOS_REG);
          break;
danno@chromium.org's avatar
danno@chromium.org committed
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
        case KEYED_PROPERTY:
          EmitKeyedPropertyLoad(property);
          PrepareForBailoutForId(property->LoadId(), TOS_REG);
          break;
      }
    }

    Token::Value op = expr->binary_op();
    __ push(eax);  // Left operand goes on the stack.
    VisitForAccumulatorValue(expr->value());

    if (ShouldInlineSmiCase(op)) {
      EmitInlineSmiBinaryOp(expr->binary_operation(),
                            op,
                            expr->target(),
                            expr->value());
    } else {
1878
      EmitBinaryOp(expr->binary_operation(), op);
danno@chromium.org's avatar
danno@chromium.org committed
1879 1880 1881 1882 1883 1884 1885 1886
    }

    // Deoptimization point in case the binary operation may have side effects.
    PrepareForBailout(expr->binary_operation(), TOS_REG);
  } else {
    VisitForAccumulatorValue(expr->value());
  }

1887
  SetExpressionPosition(expr);
danno@chromium.org's avatar
danno@chromium.org committed
1888 1889 1890 1891 1892

  // Store the value.
  switch (assign_type) {
    case VARIABLE:
      EmitVariableAssignment(expr->target()->AsVariableProxy()->var(),
1893
                             expr->op(), expr->AssignmentSlot());
danno@chromium.org's avatar
danno@chromium.org committed
1894 1895 1896 1897 1898 1899
      PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
      context()->Plug(eax);
      break;
    case NAMED_PROPERTY:
      EmitNamedPropertyAssignment(expr);
      break;
1900
    case NAMED_SUPER_PROPERTY:
1901
      EmitNamedSuperPropertyStore(property);
1902 1903 1904 1905 1906
      context()->Plug(result_register());
      break;
    case KEYED_SUPER_PROPERTY:
      EmitKeyedSuperPropertyStore(property);
      context()->Plug(result_register());
1907
      break;
danno@chromium.org's avatar
danno@chromium.org committed
1908 1909 1910 1911 1912 1913 1914 1915 1916
    case KEYED_PROPERTY:
      EmitKeyedPropertyAssignment(expr);
      break;
  }
}


void FullCodeGenerator::VisitYield(Yield* expr) {
  Comment cmnt(masm_, "[ Yield");
1917 1918
  SetExpressionPosition(expr);

danno@chromium.org's avatar
danno@chromium.org committed
1919 1920 1921 1922 1923
  // Evaluate yielded value first; the initial iterator definition depends on
  // this.  It stays on the stack while we update the iterator.
  VisitForStackValue(expr->expression());

  switch (expr->yield_kind()) {
1924
    case Yield::kSuspend:
danno@chromium.org's avatar
danno@chromium.org committed
1925 1926 1927 1928
      // Pop value from top-of-stack slot; box result into result register.
      EmitCreateIteratorResult(false);
      __ push(result_register());
      // Fall through.
1929
    case Yield::kInitial: {
danno@chromium.org's avatar
danno@chromium.org committed
1930 1931 1932 1933
      Label suspend, continuation, post_runtime, resume;

      __ jmp(&suspend);
      __ bind(&continuation);
1934
      __ RecordGeneratorContinuation();
danno@chromium.org's avatar
danno@chromium.org committed
1935 1936 1937 1938
      __ jmp(&resume);

      __ bind(&suspend);
      VisitForAccumulatorValue(expr->generator_object());
1939
      DCHECK(continuation.pos() > 0 && Smi::IsValid(continuation.pos()));
danno@chromium.org's avatar
danno@chromium.org committed
1940 1941 1942 1943
      __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
             Immediate(Smi::FromInt(continuation.pos())));
      __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
      __ mov(ecx, esi);
1944 1945
      __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
                          kDontSaveFPRegs);
danno@chromium.org's avatar
danno@chromium.org committed
1946 1947 1948 1949
      __ lea(ebx, Operand(ebp, StandardFrameConstants::kExpressionsOffset));
      __ cmp(esp, ebx);
      __ j(equal, &post_runtime);
      __ push(eax);  // generator object
1950
      __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1);
danno@chromium.org's avatar
danno@chromium.org committed
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
      __ mov(context_register(),
             Operand(ebp, StandardFrameConstants::kContextOffset));
      __ bind(&post_runtime);
      __ pop(result_register());
      EmitReturnSequence();

      __ bind(&resume);
      context()->Plug(result_register());
      break;
    }

1962
    case Yield::kFinal: {
danno@chromium.org's avatar
danno@chromium.org committed
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
      VisitForAccumulatorValue(expr->generator_object());
      __ mov(FieldOperand(result_register(),
                          JSGeneratorObject::kContinuationOffset),
             Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorClosed)));
      // Pop value from top-of-stack slot, box result into result register.
      EmitCreateIteratorResult(true);
      EmitUnwindBeforeReturn();
      EmitReturnSequence();
      break;
    }

1974
    case Yield::kDelegating: {
danno@chromium.org's avatar
danno@chromium.org committed
1975 1976 1977 1978 1979 1980 1981 1982
      VisitForStackValue(expr->generator_object());

      // Initial stack layout is as follows:
      // [sp + 1 * kPointerSize] iter
      // [sp + 0 * kPointerSize] g

      Label l_catch, l_try, l_suspend, l_continuation, l_resume;
      Label l_next, l_call, l_loop;
1983 1984
      Register load_receiver = LoadDescriptor::ReceiverRegister();
      Register load_name = LoadDescriptor::NameRegister();
1985

danno@chromium.org's avatar
danno@chromium.org committed
1986 1987 1988 1989 1990 1991
      // Initial send value is undefined.
      __ mov(eax, isolate()->factory()->undefined_value());
      __ jmp(&l_next);

      // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; }
      __ bind(&l_catch);
1992 1993 1994 1995
      __ mov(load_name, isolate()->factory()->throw_string());  // "throw"
      __ push(load_name);                                       // "throw"
      __ push(Operand(esp, 2 * kPointerSize));                  // iter
      __ push(eax);                                             // exception
danno@chromium.org's avatar
danno@chromium.org committed
1996 1997 1998 1999 2000 2001 2002
      __ jmp(&l_call);

      // try { received = %yield result }
      // Shuffle the received result above a try handler and yield it without
      // re-boxing.
      __ bind(&l_try);
      __ pop(eax);                                       // result
2003 2004
      int handler_index = NewHandlerTableEntry();
      EnterTryBlock(handler_index, &l_catch);
2005
      const int try_block_size = TryCatch::kElementCount * kPointerSize;
danno@chromium.org's avatar
danno@chromium.org committed
2006
      __ push(eax);                                      // result
2007

danno@chromium.org's avatar
danno@chromium.org committed
2008 2009
      __ jmp(&l_suspend);
      __ bind(&l_continuation);
2010
      __ RecordGeneratorContinuation();
danno@chromium.org's avatar
danno@chromium.org committed
2011
      __ jmp(&l_resume);
2012

danno@chromium.org's avatar
danno@chromium.org committed
2013
      __ bind(&l_suspend);
2014
      const int generator_object_depth = kPointerSize + try_block_size;
danno@chromium.org's avatar
danno@chromium.org committed
2015 2016
      __ mov(eax, Operand(esp, generator_object_depth));
      __ push(eax);                                      // g
2017
      __ push(Immediate(Smi::FromInt(handler_index)));   // handler-index
2018
      DCHECK(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos()));
danno@chromium.org's avatar
danno@chromium.org committed
2019 2020 2021 2022
      __ mov(FieldOperand(eax, JSGeneratorObject::kContinuationOffset),
             Immediate(Smi::FromInt(l_continuation.pos())));
      __ mov(FieldOperand(eax, JSGeneratorObject::kContextOffset), esi);
      __ mov(ecx, esi);
2023 2024
      __ RecordWriteField(eax, JSGeneratorObject::kContextOffset, ecx, edx,
                          kDontSaveFPRegs);
2025
      __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 2);
danno@chromium.org's avatar
danno@chromium.org committed
2026 2027 2028 2029 2030
      __ mov(context_register(),
             Operand(ebp, StandardFrameConstants::kContextOffset));
      __ pop(eax);                                       // result
      EmitReturnSequence();
      __ bind(&l_resume);                                // received in eax
2031
      ExitTryBlock(handler_index);
danno@chromium.org's avatar
danno@chromium.org committed
2032 2033 2034

      // receiver = iter; f = iter.next; arg = received;
      __ bind(&l_next);
2035

2036 2037 2038 2039
      __ mov(load_name, isolate()->factory()->next_string());
      __ push(load_name);                           // "next"
      __ push(Operand(esp, 2 * kPointerSize));      // iter
      __ push(eax);                                 // received
danno@chromium.org's avatar
danno@chromium.org committed
2040 2041 2042

      // result = receiver[f](arg);
      __ bind(&l_call);
2043
      __ mov(load_receiver, Operand(esp, kPointerSize));
2044
      __ mov(LoadDescriptor::SlotRegister(),
2045
             Immediate(SmiFromSlot(expr->KeyedLoadFeedbackSlot())));
2046
      Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate(), SLOPPY).code();
danno@chromium.org's avatar
danno@chromium.org committed
2047 2048 2049
      CallIC(ic, TypeFeedbackId::None());
      __ mov(edi, eax);
      __ mov(Operand(esp, 2 * kPointerSize), edi);
2050
      SetCallPosition(expr, 1);
danno@chromium.org's avatar
danno@chromium.org committed
2051 2052 2053 2054 2055 2056 2057 2058 2059
      CallFunctionStub stub(isolate(), 1, CALL_AS_METHOD);
      __ CallStub(&stub);

      __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
      __ Drop(1);  // The function is still on the stack; drop it.

      // if (!result.done) goto l_try;
      __ bind(&l_loop);
      __ push(eax);                                      // save result
2060
      __ Move(load_receiver, eax);                       // result
2061 2062
      __ mov(load_name,
             isolate()->factory()->done_string());       // "done"
2063
      __ mov(LoadDescriptor::SlotRegister(),
2064
             Immediate(SmiFromSlot(expr->DoneFeedbackSlot())));
2065
      CallLoadIC(NOT_INSIDE_TYPEOF);  // result.done in eax
danno@chromium.org's avatar
danno@chromium.org committed
2066 2067 2068 2069 2070 2071
      Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate());
      CallIC(bool_ic);
      __ test(eax, eax);
      __ j(zero, &l_try);

      // result.value
2072 2073 2074
      __ pop(load_receiver);                              // result
      __ mov(load_name,
             isolate()->factory()->value_string());       // "value"
2075
      __ mov(LoadDescriptor::SlotRegister(),
2076
             Immediate(SmiFromSlot(expr->ValueFeedbackSlot())));
2077
      CallLoadIC(NOT_INSIDE_TYPEOF);                      // result.value in eax
danno@chromium.org's avatar
danno@chromium.org committed
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
      context()->DropAndPlug(2, eax);                     // drop iter and g
      break;
    }
  }
}


void FullCodeGenerator::EmitGeneratorResume(Expression *generator,
    Expression *value,
    JSGeneratorObject::ResumeMode resume_mode) {
  // The value stays in eax, and is ultimately read by the resumed generator, as
2089
  // if CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. Or it
danno@chromium.org's avatar
danno@chromium.org committed
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
  // is read to throw the value when the resumed generator is already closed.
  // ebx will hold the generator object until the activation has been resumed.
  VisitForStackValue(generator);
  VisitForAccumulatorValue(value);
  __ pop(ebx);

  // Load suspended function and context.
  __ mov(esi, FieldOperand(ebx, JSGeneratorObject::kContextOffset));
  __ mov(edi, FieldOperand(ebx, JSGeneratorObject::kFunctionOffset));

  // Push receiver.
  __ push(FieldOperand(ebx, JSGeneratorObject::kReceiverOffset));

  // Push holes for arguments to generator function.
  __ mov(edx, FieldOperand(edi, JSFunction::kSharedFunctionInfoOffset));
  __ mov(edx,
         FieldOperand(edx, SharedFunctionInfo::kFormalParameterCountOffset));
  __ mov(ecx, isolate()->factory()->the_hole_value());
  Label push_argument_holes, push_frame;
  __ bind(&push_argument_holes);
  __ sub(edx, Immediate(Smi::FromInt(1)));
  __ j(carry, &push_frame);
  __ push(ecx);
  __ jmp(&push_argument_holes);

  // Enter a new JavaScript frame, and initialize its slots as they were when
  // the generator was suspended.
2117
  Label resume_frame, done;
danno@chromium.org's avatar
danno@chromium.org committed
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
  __ bind(&push_frame);
  __ call(&resume_frame);
  __ jmp(&done);
  __ bind(&resume_frame);
  __ push(ebp);  // Caller's frame pointer.
  __ mov(ebp, esp);
  __ push(esi);  // Callee's context.
  __ push(edi);  // Callee's JS Function.

  // Load the operand stack size.
  __ mov(edx, FieldOperand(ebx, JSGeneratorObject::kOperandStackOffset));
  __ mov(edx, FieldOperand(edx, FixedArray::kLengthOffset));
  __ SmiUntag(edx);

  // If we are sending a value and there is no operand stack, we can jump back
  // in directly.
  if (resume_mode == JSGeneratorObject::NEXT) {
    Label slow_resume;
    __ cmp(edx, Immediate(0));
    __ j(not_zero, &slow_resume);
    __ mov(edx, FieldOperand(edi, JSFunction::kCodeEntryOffset));
    __ mov(ecx, FieldOperand(ebx, JSGeneratorObject::kContinuationOffset));
    __ SmiUntag(ecx);
    __ add(edx, ecx);
    __ mov(FieldOperand(ebx, JSGeneratorObject::kContinuationOffset),
           Immediate(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting)));
    __ jmp(edx);
    __ bind(&slow_resume);
  }

  // Otherwise, we push holes for the operand stack and call the runtime to fix
  // up the stack and the handlers.
  Label push_operand_holes, call_resume;
  __ bind(&push_operand_holes);
  __ sub(edx, Immediate(1));
  __ j(carry, &call_resume);
  __ push(ecx);
  __ jmp(&push_operand_holes);
  __ bind(&call_resume);
  __ push(ebx);
  __ push(result_register());
  __ Push(Smi::FromInt(resume_mode));
2160
  __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3);
danno@chromium.org's avatar
danno@chromium.org committed
2161 2162 2163 2164 2165 2166 2167 2168 2169
  // Not reached: the runtime call returns elsewhere.
  __ Abort(kGeneratorFailedToResume);

  __ bind(&done);
  context()->Plug(result_register());
}


void FullCodeGenerator::EmitCreateIteratorResult(bool done) {
2170
  Label allocate, done_allocate;
danno@chromium.org's avatar
danno@chromium.org committed
2171

2172 2173
  __ Allocate(JSIteratorResult::kSize, eax, ecx, edx, &allocate, TAG_OBJECT);
  __ jmp(&done_allocate, Label::kNear);
danno@chromium.org's avatar
danno@chromium.org committed
2174

2175 2176
  __ bind(&allocate);
  __ Push(Smi::FromInt(JSIteratorResult::kSize));
2177
  __ CallRuntime(Runtime::kAllocateInNewSpace, 1);
danno@chromium.org's avatar
danno@chromium.org committed
2178

2179 2180
  __ bind(&done_allocate);
  __ mov(ebx, GlobalObjectOperand());
2181 2182
  __ mov(ebx, FieldOperand(ebx, GlobalObject::kNativeContextOffset));
  __ mov(ebx, ContextOperand(ebx, Context::ITERATOR_RESULT_MAP_INDEX));
danno@chromium.org's avatar
danno@chromium.org committed
2183 2184 2185 2186 2187
  __ mov(FieldOperand(eax, HeapObject::kMapOffset), ebx);
  __ mov(FieldOperand(eax, JSObject::kPropertiesOffset),
         isolate()->factory()->empty_fixed_array());
  __ mov(FieldOperand(eax, JSObject::kElementsOffset),
         isolate()->factory()->empty_fixed_array());
2188 2189 2190 2191
  __ pop(FieldOperand(eax, JSIteratorResult::kValueOffset));
  __ mov(FieldOperand(eax, JSIteratorResult::kDoneOffset),
         isolate()->factory()->ToBoolean(done));
  STATIC_ASSERT(JSIteratorResult::kSize == 5 * kPointerSize);
danno@chromium.org's avatar
danno@chromium.org committed
2192 2193 2194 2195
}


void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) {
2196
  SetExpressionPosition(prop);
danno@chromium.org's avatar
danno@chromium.org committed
2197
  Literal* key = prop->key()->AsLiteral();
2198
  DCHECK(!key->value()->IsSmi());
2199 2200
  DCHECK(!prop->IsSuperAccess());

2201
  __ mov(LoadDescriptor::NameRegister(), Immediate(key->value()));
2202
  __ mov(LoadDescriptor::SlotRegister(),
2203
         Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
2204
  CallLoadIC(NOT_INSIDE_TYPEOF, language_mode());
danno@chromium.org's avatar
danno@chromium.org committed
2205 2206 2207
}


2208
void FullCodeGenerator::EmitNamedSuperPropertyLoad(Property* prop) {
2209
  // Stack: receiver, home_object.
2210
  SetExpressionPosition(prop);
2211 2212 2213 2214 2215
  Literal* key = prop->key()->AsLiteral();
  DCHECK(!key->value()->IsSmi());
  DCHECK(prop->IsSuperAccess());

  __ push(Immediate(key->value()));
2216 2217
  __ push(Immediate(Smi::FromInt(language_mode())));
  __ CallRuntime(Runtime::kLoadFromSuper, 4);
2218 2219 2220
}


danno@chromium.org's avatar
danno@chromium.org committed
2221
void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) {
2222
  SetExpressionPosition(prop);
2223
  Handle<Code> ic = CodeFactory::KeyedLoadIC(isolate(), language_mode()).code();
2224
  __ mov(LoadDescriptor::SlotRegister(),
2225 2226
         Immediate(SmiFromSlot(prop->PropertyFeedbackSlot())));
  CallIC(ic);
danno@chromium.org's avatar
danno@chromium.org committed
2227 2228 2229
}


2230 2231
void FullCodeGenerator::EmitKeyedSuperPropertyLoad(Property* prop) {
  // Stack: receiver, home_object, key.
2232
  SetExpressionPosition(prop);
2233 2234
  __ push(Immediate(Smi::FromInt(language_mode())));
  __ CallRuntime(Runtime::kLoadKeyedFromSuper, 4);
2235 2236 2237
}


danno@chromium.org's avatar
danno@chromium.org committed
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr,
                                              Token::Value op,
                                              Expression* left,
                                              Expression* right) {
  // Do combined smi check of the operands. Left operand is on the
  // stack. Right operand is in eax.
  Label smi_case, done, stub_call;
  __ pop(edx);
  __ mov(ecx, eax);
  __ or_(eax, edx);
  JumpPatchSite patch_site(masm_);
  patch_site.EmitJumpIfSmi(eax, &smi_case, Label::kNear);

  __ bind(&stub_call);
  __ mov(eax, ecx);
2253 2254
  Handle<Code> code =
      CodeFactory::BinaryOpIC(isolate(), op, strength(language_mode())).code();
2255
  CallIC(code, expr->BinaryOperationFeedbackId());
danno@chromium.org's avatar
danno@chromium.org committed
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
  patch_site.EmitPatchInfo();
  __ jmp(&done, Label::kNear);

  // Smi case.
  __ bind(&smi_case);
  __ mov(eax, edx);  // Copy left operand in case of a stub call.

  switch (op) {
    case Token::SAR:
      __ SmiUntag(ecx);
      __ sar_cl(eax);  // No checks of result necessary
      __ and_(eax, Immediate(~kSmiTagMask));
      break;
    case Token::SHL: {
      Label result_ok;
      __ SmiUntag(eax);
      __ SmiUntag(ecx);
      __ shl_cl(eax);
      // Check that the *signed* result fits in a smi.
      __ cmp(eax, 0xc0000000);
      __ j(positive, &result_ok);
      __ SmiTag(ecx);
      __ jmp(&stub_call);
      __ bind(&result_ok);
      __ SmiTag(eax);
      break;
    }
    case Token::SHR: {
      Label result_ok;
      __ SmiUntag(eax);
      __ SmiUntag(ecx);
      __ shr_cl(eax);
      __ test(eax, Immediate(0xc0000000));
      __ j(zero, &result_ok);
      __ SmiTag(ecx);
      __ jmp(&stub_call);
      __ bind(&result_ok);
      __ SmiTag(eax);
      break;
    }
    case Token::ADD:
      __ add(eax, ecx);
      __ j(overflow, &stub_call);
      break;
    case Token::SUB:
      __ sub(eax, ecx);
      __ j(overflow, &stub_call);
      break;
    case Token::MUL: {
      __ SmiUntag(eax);
      __ imul(eax, ecx);
      __ j(overflow, &stub_call);
      __ test(eax, eax);
      __ j(not_zero, &done, Label::kNear);
      __ mov(ebx, edx);
      __ or_(ebx, ecx);
      __ j(negative, &stub_call);
      break;
    }
    case Token::BIT_OR:
      __ or_(eax, ecx);
      break;
    case Token::BIT_AND:
      __ and_(eax, ecx);
      break;
    case Token::BIT_XOR:
      __ xor_(eax, ecx);
      break;
    default:
      UNREACHABLE();
  }

  __ bind(&done);
  context()->Plug(eax);
}


2333
void FullCodeGenerator::EmitClassDefineProperties(ClassLiteral* lit) {
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352
  // Constructor is in eax.
  DCHECK(lit != NULL);
  __ push(eax);

  // No access check is needed here since the constructor is created by the
  // class literal.
  Register scratch = ebx;
  __ mov(scratch, FieldOperand(eax, JSFunction::kPrototypeOrInitialMapOffset));
  __ Push(scratch);

  for (int i = 0; i < lit->properties()->length(); i++) {
    ObjectLiteral::Property* property = lit->properties()->at(i);
    Expression* value = property->value();

    if (property->is_static()) {
      __ push(Operand(esp, kPointerSize));  // constructor
    } else {
      __ push(Operand(esp, 0));  // prototype
    }
2353
    EmitPropertyKey(property, lit->GetIdForProperty(i));
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363

    // The static prototype property is read only. We handle the non computed
    // property name case in the parser. Since this is the only case where we
    // need to check for an own read only property we special case this so we do
    // not need to do this for every property.
    if (property->is_static() && property->is_computed_name()) {
      __ CallRuntime(Runtime::kThrowIfStaticPrototype, 1);
      __ push(eax);
    }

2364
    VisitForStackValue(value);
2365 2366 2367
    if (NeedsHomeObject(value)) {
      EmitSetHomeObject(value, 2, property->GetSlot());
    }
2368 2369 2370 2371 2372

    switch (property->kind()) {
      case ObjectLiteral::Property::CONSTANT:
      case ObjectLiteral::Property::MATERIALIZED_LITERAL:
      case ObjectLiteral::Property::PROTOTYPE:
2373 2374
        UNREACHABLE();
      case ObjectLiteral::Property::COMPUTED:
2375
        __ CallRuntime(Runtime::kDefineClassMethod, 3);
2376 2377 2378
        break;

      case ObjectLiteral::Property::GETTER:
2379 2380
        __ push(Immediate(Smi::FromInt(DONT_ENUM)));
        __ CallRuntime(Runtime::kDefineGetterPropertyUnchecked, 4);
2381 2382 2383
        break;

      case ObjectLiteral::Property::SETTER:
2384 2385
        __ push(Immediate(Smi::FromInt(DONT_ENUM)));
        __ CallRuntime(Runtime::kDefineSetterPropertyUnchecked, 4);
2386 2387 2388 2389
        break;
    }
  }

2390 2391
  // Set both the prototype and constructor to have fast properties, and also
  // freeze them in strong mode.
2392
  __ CallRuntime(Runtime::kFinalizeClassDefinition, 2);
2393 2394 2395
}


2396
void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, Token::Value op) {
danno@chromium.org's avatar
danno@chromium.org committed
2397
  __ pop(edx);
2398 2399
  Handle<Code> code =
      CodeFactory::BinaryOpIC(isolate(), op, strength(language_mode())).code();
danno@chromium.org's avatar
danno@chromium.org committed
2400
  JumpPatchSite patch_site(masm_);    // unbound, signals no inlined smi code.
2401
  CallIC(code, expr->BinaryOperationFeedbackId());
danno@chromium.org's avatar
danno@chromium.org committed
2402 2403 2404 2405 2406
  patch_site.EmitPatchInfo();
  context()->Plug(eax);
}


2407
void FullCodeGenerator::EmitAssignment(Expression* expr,
2408
                                       FeedbackVectorSlot slot) {
2409
  DCHECK(expr->IsValidReferenceExpressionOrThis());
danno@chromium.org's avatar
danno@chromium.org committed
2410 2411

  Property* prop = expr->AsProperty();
2412
  LhsKind assign_type = Property::GetAssignType(prop);
danno@chromium.org's avatar
danno@chromium.org committed
2413 2414 2415 2416 2417

  switch (assign_type) {
    case VARIABLE: {
      Variable* var = expr->AsVariableProxy()->var();
      EffectContext context(this);
2418
      EmitVariableAssignment(var, Token::ASSIGN, slot);
danno@chromium.org's avatar
danno@chromium.org committed
2419 2420 2421 2422 2423
      break;
    }
    case NAMED_PROPERTY: {
      __ push(eax);  // Preserve value.
      VisitForAccumulatorValue(prop->obj());
2424 2425 2426
      __ Move(StoreDescriptor::ReceiverRegister(), eax);
      __ pop(StoreDescriptor::ValueRegister());  // Restore value.
      __ mov(StoreDescriptor::NameRegister(),
2427
             prop->key()->AsLiteral()->value());
2428
      if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
danno@chromium.org's avatar
danno@chromium.org committed
2429 2430 2431
      CallStoreIC();
      break;
    }
2432 2433
    case NAMED_SUPER_PROPERTY: {
      __ push(eax);
2434 2435
      VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
      VisitForAccumulatorValue(
2436
          prop->obj()->AsSuperPropertyReference()->home_object());
2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450
      // stack: value, this; eax: home_object
      Register scratch = ecx;
      Register scratch2 = edx;
      __ mov(scratch, result_register());               // home_object
      __ mov(eax, MemOperand(esp, kPointerSize));       // value
      __ mov(scratch2, MemOperand(esp, 0));             // this
      __ mov(MemOperand(esp, kPointerSize), scratch2);  // this
      __ mov(MemOperand(esp, 0), scratch);              // home_object
      // stack: this, home_object. eax: value
      EmitNamedSuperPropertyStore(prop);
      break;
    }
    case KEYED_SUPER_PROPERTY: {
      __ push(eax);
2451 2452
      VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
      VisitForStackValue(
2453
          prop->obj()->AsSuperPropertyReference()->home_object());
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
      VisitForAccumulatorValue(prop->key());
      Register scratch = ecx;
      Register scratch2 = edx;
      __ mov(scratch2, MemOperand(esp, 2 * kPointerSize));  // value
      // stack: value, this, home_object; eax: key, edx: value
      __ mov(scratch, MemOperand(esp, kPointerSize));  // this
      __ mov(MemOperand(esp, 2 * kPointerSize), scratch);
      __ mov(scratch, MemOperand(esp, 0));  // home_object
      __ mov(MemOperand(esp, kPointerSize), scratch);
      __ mov(MemOperand(esp, 0), eax);
      __ mov(eax, scratch2);
      // stack: this, home_object, key; eax: value.
      EmitKeyedSuperPropertyStore(prop);
      break;
    }
danno@chromium.org's avatar
danno@chromium.org committed
2469 2470 2471 2472
    case KEYED_PROPERTY: {
      __ push(eax);  // Preserve value.
      VisitForStackValue(prop->obj());
      VisitForAccumulatorValue(prop->key());
2473 2474 2475
      __ Move(StoreDescriptor::NameRegister(), eax);
      __ pop(StoreDescriptor::ReceiverRegister());  // Receiver.
      __ pop(StoreDescriptor::ValueRegister());     // Restore value.
2476
      if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
2477
      Handle<Code> ic =
2478
          CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
danno@chromium.org's avatar
danno@chromium.org committed
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
      CallIC(ic);
      break;
    }
  }
  context()->Plug(eax);
}


void FullCodeGenerator::EmitStoreToStackLocalOrContextSlot(
    Variable* var, MemOperand location) {
  __ mov(location, eax);
  if (var->IsContextSlot()) {
    __ mov(edx, eax);
    int offset = Context::SlotOffset(var->index());
2493
    __ RecordWriteContextSlot(ecx, offset, edx, ebx, kDontSaveFPRegs);
danno@chromium.org's avatar
danno@chromium.org committed
2494 2495 2496 2497
  }
}


2498
void FullCodeGenerator::EmitVariableAssignment(Variable* var, Token::Value op,
2499
                                               FeedbackVectorSlot slot) {
2500
  if (var->IsUnallocated()) {
danno@chromium.org's avatar
danno@chromium.org committed
2501
    // Global var, const, or let.
2502 2503
    __ mov(StoreDescriptor::NameRegister(), var->name());
    __ mov(StoreDescriptor::ReceiverRegister(), GlobalObjectOperand());
2504
    if (FLAG_vector_stores) EmitLoadStoreICSlot(slot);
danno@chromium.org's avatar
danno@chromium.org committed
2505 2506
    CallStoreIC();

2507 2508 2509 2510
  } else if (var->IsGlobalSlot()) {
    // Global var, const, or let.
    DCHECK(var->index() > 0);
    DCHECK(var->IsStaticGlobalObjectProperty());
2511
    int const slot = var->index();
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
    int const depth = scope()->ContextChainLength(var->scope());
    if (depth <= StoreGlobalViaContextStub::kMaximumDepth) {
      __ Move(StoreGlobalViaContextDescriptor::SlotRegister(), Immediate(slot));
      DCHECK(StoreGlobalViaContextDescriptor::ValueRegister().is(eax));
      StoreGlobalViaContextStub stub(isolate(), depth, language_mode());
      __ CallStub(&stub);
    } else {
      __ Push(Smi::FromInt(slot));
      __ Push(eax);
      __ CallRuntime(is_strict(language_mode())
                         ? Runtime::kStoreGlobalViaContext_Strict
                         : Runtime::kStoreGlobalViaContext_Sloppy,
2524
                     2);
2525
    }
2526

danno@chromium.org's avatar
danno@chromium.org committed
2527 2528
  } else if (var->mode() == LET && op != Token::INIT_LET) {
    // Non-initializing assignment to let variable needs a write barrier.
2529 2530
    DCHECK(!var->IsLookupSlot());
    DCHECK(var->IsStackAllocated() || var->IsContextSlot());
2531 2532 2533 2534 2535 2536 2537 2538 2539
    Label assign;
    MemOperand location = VarOperand(var, ecx);
    __ mov(edx, location);
    __ cmp(edx, isolate()->factory()->the_hole_value());
    __ j(not_equal, &assign, Label::kNear);
    __ push(Immediate(var->name()));
    __ CallRuntime(Runtime::kThrowReferenceError, 1);
    __ bind(&assign);
    EmitStoreToStackLocalOrContextSlot(var, location);
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554

  } else if (var->mode() == CONST && op != Token::INIT_CONST) {
    // Assignment to const variable needs a write barrier.
    DCHECK(!var->IsLookupSlot());
    DCHECK(var->IsStackAllocated() || var->IsContextSlot());
    Label const_error;
    MemOperand location = VarOperand(var, ecx);
    __ mov(edx, location);
    __ cmp(edx, isolate()->factory()->the_hole_value());
    __ j(not_equal, &const_error, Label::kNear);
    __ push(Immediate(var->name()));
    __ CallRuntime(Runtime::kThrowReferenceError, 1);
    __ bind(&const_error);
    __ CallRuntime(Runtime::kThrowConstAssignError, 0);

2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
  } else if (var->is_this() && op == Token::INIT_CONST) {
    // Initializing assignment to const {this} needs a write barrier.
    DCHECK(var->IsStackAllocated() || var->IsContextSlot());
    Label uninitialized_this;
    MemOperand location = VarOperand(var, ecx);
    __ mov(edx, location);
    __ cmp(edx, isolate()->factory()->the_hole_value());
    __ j(equal, &uninitialized_this);
    __ push(Immediate(var->name()));
    __ CallRuntime(Runtime::kThrowReferenceError, 1);
    __ bind(&uninitialized_this);
    EmitStoreToStackLocalOrContextSlot(var, location);

danno@chromium.org's avatar
danno@chromium.org committed
2568 2569
  } else if (!var->is_const_mode() || op == Token::INIT_CONST) {
    if (var->IsLookupSlot()) {
2570 2571 2572 2573
      // Assignment to var.
      __ push(eax);  // Value.
      __ push(esi);  // Context.
      __ push(Immediate(var->name()));
2574
      __ push(Immediate(Smi::FromInt(language_mode())));
2575
      __ CallRuntime(Runtime::kStoreLookupSlot, 4);
danno@chromium.org's avatar
danno@chromium.org committed
2576
    } else {
2577 2578
      // Assignment to var or initializing assignment to let/const in harmony
      // mode.
2579
      DCHECK(var->IsStackAllocated() || var->IsContextSlot());
danno@chromium.org's avatar
danno@chromium.org committed
2580 2581 2582 2583 2584 2585 2586 2587 2588
      MemOperand location = VarOperand(var, ecx);
      if (generate_debug_code_ && op == Token::INIT_LET) {
        // Check for an uninitialized let binding.
        __ mov(edx, location);
        __ cmp(edx, isolate()->factory()->the_hole_value());
        __ Check(equal, kLetBindingReInitialization);
      }
      EmitStoreToStackLocalOrContextSlot(var, location);
    }
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615

  } else if (op == Token::INIT_CONST_LEGACY) {
    // Const initializers need a write barrier.
    DCHECK(var->mode() == CONST_LEGACY);
    DCHECK(!var->IsParameter());  // No const parameters.
    if (var->IsLookupSlot()) {
      __ push(eax);
      __ push(esi);
      __ push(Immediate(var->name()));
      __ CallRuntime(Runtime::kInitializeLegacyConstLookupSlot, 3);
    } else {
      DCHECK(var->IsStackLocal() || var->IsContextSlot());
      Label skip;
      MemOperand location = VarOperand(var, ecx);
      __ mov(edx, location);
      __ cmp(edx, isolate()->factory()->the_hole_value());
      __ j(not_equal, &skip, Label::kNear);
      EmitStoreToStackLocalOrContextSlot(var, location);
      __ bind(&skip);
    }

  } else {
    DCHECK(var->mode() == CONST_LEGACY && op != Token::INIT_CONST_LEGACY);
    if (is_strict(language_mode())) {
      __ CallRuntime(Runtime::kThrowConstAssignError, 0);
    }
    // Silently ignore store in sloppy mode.
danno@chromium.org's avatar
danno@chromium.org committed
2616 2617 2618 2619 2620 2621 2622 2623 2624
  }
}


void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) {
  // Assignment to a property, using a named store IC.
  // eax    : value
  // esp[0] : receiver
  Property* prop = expr->target()->AsProperty();
2625 2626
  DCHECK(prop != NULL);
  DCHECK(prop->key()->IsLiteral());
danno@chromium.org's avatar
danno@chromium.org committed
2627

2628 2629
  __ mov(StoreDescriptor::NameRegister(), prop->key()->AsLiteral()->value());
  __ pop(StoreDescriptor::ReceiverRegister());
2630 2631 2632 2633 2634 2635
  if (FLAG_vector_stores) {
    EmitLoadStoreICSlot(expr->AssignmentSlot());
    CallStoreIC();
  } else {
    CallStoreIC(expr->AssignmentFeedbackId());
  }
danno@chromium.org's avatar
danno@chromium.org committed
2636 2637 2638 2639 2640
  PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
  context()->Plug(eax);
}


2641
void FullCodeGenerator::EmitNamedSuperPropertyStore(Property* prop) {
2642 2643 2644 2645 2646 2647 2648 2649
  // Assignment to named property of super.
  // eax : value
  // stack : receiver ('this'), home_object
  DCHECK(prop != NULL);
  Literal* key = prop->key()->AsLiteral();
  DCHECK(key != NULL);

  __ push(Immediate(key->value()));
2650
  __ push(eax);
2651 2652
  __ CallRuntime((is_strict(language_mode()) ? Runtime::kStoreToSuper_Strict
                                             : Runtime::kStoreToSuper_Sloppy),
2653 2654 2655 2656
                 4);
}


2657 2658 2659 2660 2661 2662
void FullCodeGenerator::EmitKeyedSuperPropertyStore(Property* prop) {
  // Assignment to named property of super.
  // eax : value
  // stack : receiver ('this'), home_object, key

  __ push(eax);
2663 2664 2665 2666
  __ CallRuntime(
      (is_strict(language_mode()) ? Runtime::kStoreKeyedToSuper_Strict
                                  : Runtime::kStoreKeyedToSuper_Sloppy),
      4);
2667 2668 2669
}


danno@chromium.org's avatar
danno@chromium.org committed
2670 2671 2672 2673 2674 2675
void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) {
  // Assignment to a property, using a keyed store IC.
  // eax               : value
  // esp[0]            : key
  // esp[kPointerSize] : receiver

2676 2677 2678
  __ pop(StoreDescriptor::NameRegister());  // Key.
  __ pop(StoreDescriptor::ReceiverRegister());
  DCHECK(StoreDescriptor::ValueRegister().is(eax));
2679 2680
  Handle<Code> ic =
      CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
2681 2682 2683 2684 2685 2686
  if (FLAG_vector_stores) {
    EmitLoadStoreICSlot(expr->AssignmentSlot());
    CallIC(ic);
  } else {
    CallIC(ic, expr->AssignmentFeedbackId());
  }
danno@chromium.org's avatar
danno@chromium.org committed
2687 2688 2689 2690 2691 2692 2693 2694

  PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
  context()->Plug(eax);
}


void FullCodeGenerator::VisitProperty(Property* expr) {
  Comment cmnt(masm_, "[ Property");
2695 2696
  SetExpressionPosition(expr);

danno@chromium.org's avatar
danno@chromium.org committed
2697 2698 2699
  Expression* key = expr->key();

  if (key->IsPropertyName()) {
2700 2701 2702 2703 2704
    if (!expr->IsSuperAccess()) {
      VisitForAccumulatorValue(expr->obj());
      __ Move(LoadDescriptor::ReceiverRegister(), result_register());
      EmitNamedPropertyLoad(expr);
    } else {
2705 2706
      VisitForStackValue(expr->obj()->AsSuperPropertyReference()->this_var());
      VisitForStackValue(
2707
          expr->obj()->AsSuperPropertyReference()->home_object());
2708 2709
      EmitNamedSuperPropertyLoad(expr);
    }
danno@chromium.org's avatar
danno@chromium.org committed
2710
  } else {
2711 2712 2713 2714 2715 2716 2717
    if (!expr->IsSuperAccess()) {
      VisitForStackValue(expr->obj());
      VisitForAccumulatorValue(expr->key());
      __ pop(LoadDescriptor::ReceiverRegister());                  // Object.
      __ Move(LoadDescriptor::NameRegister(), result_register());  // Key.
      EmitKeyedPropertyLoad(expr);
    } else {
2718 2719
      VisitForStackValue(expr->obj()->AsSuperPropertyReference()->this_var());
      VisitForStackValue(
2720
          expr->obj()->AsSuperPropertyReference()->home_object());
2721 2722 2723
      VisitForStackValue(expr->key());
      EmitKeyedSuperPropertyLoad(expr);
    }
danno@chromium.org's avatar
danno@chromium.org committed
2724
  }
2725 2726
  PrepareForBailoutForId(expr->LoadId(), TOS_REG);
  context()->Plug(eax);
danno@chromium.org's avatar
danno@chromium.org committed
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740
}


void FullCodeGenerator::CallIC(Handle<Code> code,
                               TypeFeedbackId ast_id) {
  ic_total_count_++;
  __ call(code, RelocInfo::CODE_TARGET, ast_id);
}


// Code common for calls using the IC.
void FullCodeGenerator::EmitCallWithLoadIC(Call* expr) {
  Expression* callee = expr->expression();

2741 2742
  CallICState::CallType call_type =
      callee->IsVariableProxy() ? CallICState::FUNCTION : CallICState::METHOD;
danno@chromium.org's avatar
danno@chromium.org committed
2743
  // Get the target function.
2744
  if (call_type == CallICState::FUNCTION) {
danno@chromium.org's avatar
danno@chromium.org committed
2745 2746 2747 2748 2749 2750 2751 2752 2753
    { StackValueContext context(this);
      EmitVariableLoad(callee->AsVariableProxy());
      PrepareForBailout(callee, NO_REGISTERS);
    }
    // Push undefined as receiver. This is patched in the method prologue if it
    // is a sloppy mode method.
    __ push(Immediate(isolate()->factory()->undefined_value()));
  } else {
    // Load the function from the receiver.
2754
    DCHECK(callee->IsProperty());
2755
    DCHECK(!callee->AsProperty()->IsSuperAccess());
2756
    __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
danno@chromium.org's avatar
danno@chromium.org committed
2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767
    EmitNamedPropertyLoad(callee->AsProperty());
    PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);
    // Push the target function under the receiver.
    __ push(Operand(esp, 0));
    __ mov(Operand(esp, kPointerSize), eax);
  }

  EmitCall(expr, call_type);
}


2768
void FullCodeGenerator::EmitSuperCallWithLoadIC(Call* expr) {
2769
  SetExpressionPosition(expr);
2770 2771 2772 2773 2774 2775 2776 2777
  Expression* callee = expr->expression();
  DCHECK(callee->IsProperty());
  Property* prop = callee->AsProperty();
  DCHECK(prop->IsSuperAccess());

  Literal* key = prop->key()->AsLiteral();
  DCHECK(!key->value()->IsSmi());
  // Load the function from the receiver.
2778
  SuperPropertyReference* super_ref = prop->obj()->AsSuperPropertyReference();
2779
  VisitForStackValue(super_ref->home_object());
2780 2781 2782
  VisitForAccumulatorValue(super_ref->this_var());
  __ push(eax);
  __ push(eax);
2783
  __ push(Operand(esp, kPointerSize * 2));
2784
  __ push(Immediate(key->value()));
2785
  __ push(Immediate(Smi::FromInt(language_mode())));
2786 2787 2788
  // Stack here:
  //  - home_object
  //  - this (receiver)
2789 2790
  //  - this (receiver) <-- LoadFromSuper will pop here and below.
  //  - home_object
2791
  //  - key
2792 2793
  //  - language_mode
  __ CallRuntime(Runtime::kLoadFromSuper, 4);
2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804

  // Replace home_object with target function.
  __ mov(Operand(esp, kPointerSize), eax);

  // Stack here:
  // - target function
  // - this (receiver)
  EmitCall(expr, CallICState::METHOD);
}


danno@chromium.org's avatar
danno@chromium.org committed
2805 2806 2807 2808 2809 2810 2811 2812 2813
// Code common for calls using the IC.
void FullCodeGenerator::EmitKeyedCallWithLoadIC(Call* expr,
                                                Expression* key) {
  // Load the key.
  VisitForAccumulatorValue(key);

  Expression* callee = expr->expression();

  // Load the function from the receiver.
2814
  DCHECK(callee->IsProperty());
2815 2816
  __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
  __ mov(LoadDescriptor::NameRegister(), eax);
danno@chromium.org's avatar
danno@chromium.org committed
2817 2818 2819 2820 2821 2822 2823
  EmitKeyedPropertyLoad(callee->AsProperty());
  PrepareForBailoutForId(callee->AsProperty()->LoadId(), TOS_REG);

  // Push the target function under the receiver.
  __ push(Operand(esp, 0));
  __ mov(Operand(esp, kPointerSize), eax);

2824
  EmitCall(expr, CallICState::METHOD);
danno@chromium.org's avatar
danno@chromium.org committed
2825 2826 2827
}


2828 2829 2830 2831 2832 2833
void FullCodeGenerator::EmitKeyedSuperCallWithLoadIC(Call* expr) {
  Expression* callee = expr->expression();
  DCHECK(callee->IsProperty());
  Property* prop = callee->AsProperty();
  DCHECK(prop->IsSuperAccess());

2834
  SetExpressionPosition(prop);
2835
  // Load the function from the receiver.
2836
  SuperPropertyReference* super_ref = prop->obj()->AsSuperPropertyReference();
2837
  VisitForStackValue(super_ref->home_object());
2838 2839 2840 2841 2842
  VisitForAccumulatorValue(super_ref->this_var());
  __ push(eax);
  __ push(eax);
  __ push(Operand(esp, kPointerSize * 2));
  VisitForStackValue(prop->key());
2843
  __ push(Immediate(Smi::FromInt(language_mode())));
2844 2845 2846 2847 2848 2849
  // Stack here:
  //  - home_object
  //  - this (receiver)
  //  - this (receiver) <-- LoadKeyedFromSuper will pop here and below.
  //  - home_object
  //  - key
2850 2851
  //  - language_mode
  __ CallRuntime(Runtime::kLoadKeyedFromSuper, 4);
2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862

  // Replace home_object with target function.
  __ mov(Operand(esp, kPointerSize), eax);

  // Stack here:
  // - target function
  // - this (receiver)
  EmitCall(expr, CallICState::METHOD);
}


2863
void FullCodeGenerator::EmitCall(Call* expr, CallICState::CallType call_type) {
danno@chromium.org's avatar
danno@chromium.org committed
2864 2865 2866
  // Load the arguments.
  ZoneList<Expression*>* args = expr->arguments();
  int arg_count = args->length();
2867 2868
  for (int i = 0; i < arg_count; i++) {
    VisitForStackValue(args->at(i));
danno@chromium.org's avatar
danno@chromium.org committed
2869 2870
  }

2871
  SetCallPosition(expr, arg_count);
2872
  Handle<Code> ic = CodeFactory::CallIC(isolate(), arg_count, call_type).code();
2873
  __ Move(edx, Immediate(SmiFromSlot(expr->CallFeedbackICSlot())));
danno@chromium.org's avatar
danno@chromium.org committed
2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895
  __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
  // Don't assign a type feedback id to the IC, since type feedback is provided
  // by the vector above.
  CallIC(ic);

  RecordJSReturnSite(expr);

  // Restore context register.
  __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));

  context()->DropAndPlug(1, eax);
}


void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) {
  // Push copy of the first argument or undefined if it doesn't exist.
  if (arg_count > 0) {
    __ push(Operand(esp, arg_count * kPointerSize));
  } else {
    __ push(Immediate(isolate()->factory()->undefined_value()));
  }

2896 2897
  // Push the enclosing function.
  __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
2898

danno@chromium.org's avatar
danno@chromium.org committed
2899
  // Push the language mode.
2900
  __ push(Immediate(Smi::FromInt(language_mode())));
danno@chromium.org's avatar
danno@chromium.org committed
2901 2902 2903 2904 2905

  // Push the start position of the scope the calls resides in.
  __ push(Immediate(Smi::FromInt(scope()->start_position())));

  // Do the runtime call.
2906
  __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 5);
danno@chromium.org's avatar
danno@chromium.org committed
2907 2908 2909
}


2910 2911 2912 2913 2914
// See http://www.ecma-international.org/ecma-262/6.0/#sec-function-calls.
void FullCodeGenerator::PushCalleeAndWithBaseObject(Call* expr) {
  VariableProxy* callee = expr->expression()->AsVariableProxy();
  if (callee->var()->IsLookupSlot()) {
    Label slow, done;
2915 2916 2917 2918 2919
    SetExpressionPosition(callee);
    // Generate code for loading from variables potentially shadowed by
    // eval-introduced variables.
    EmitDynamicLookupFastCase(callee, NOT_INSIDE_TYPEOF, &slow, &done);

2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
    __ bind(&slow);
    // Call the runtime to find the function to call (returned in eax) and
    // the object holding it (returned in edx).
    __ push(context_register());
    __ push(Immediate(callee->name()));
    __ CallRuntime(Runtime::kLoadLookupSlot, 2);
    __ push(eax);  // Function.
    __ push(edx);  // Receiver.
    PrepareForBailoutForId(expr->LookupId(), NO_REGISTERS);

    // If fast case code has been generated, emit code to push the function
    // and receiver and have the slow path jump around this code.
    if (done.is_linked()) {
      Label call;
      __ jmp(&call, Label::kNear);
      __ bind(&done);
      // Push function.
      __ push(eax);
      // The receiver is implicitly the global receiver. Indicate this by
      // passing the hole to the call function stub.
      __ push(Immediate(isolate()->factory()->undefined_value()));
      __ bind(&call);
    }
  } else {
    VisitForStackValue(callee);
    // refEnv.WithBaseObject()
    __ push(Immediate(isolate()->factory()->undefined_value()));
  }
}


danno@chromium.org's avatar
danno@chromium.org committed
2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
void FullCodeGenerator::VisitCall(Call* expr) {
#ifdef DEBUG
  // We want to verify that RecordJSReturnSite gets called on all paths
  // through this function.  Avoid early returns.
  expr->return_is_recorded_ = false;
#endif

  Comment cmnt(masm_, "[ Call");
  Expression* callee = expr->expression();
  Call::CallType call_type = expr->GetCallType(isolate());

  if (call_type == Call::POSSIBLY_EVAL_CALL) {
    // In a call to eval, we first call RuntimeHidden_ResolvePossiblyDirectEval
2964 2965
    // to resolve the function we need to call.  Then we call the resolved
    // function using the given arguments.
danno@chromium.org's avatar
danno@chromium.org committed
2966 2967
    ZoneList<Expression*>* args = expr->arguments();
    int arg_count = args->length();
2968

2969
    PushCalleeAndWithBaseObject(expr);
danno@chromium.org's avatar
danno@chromium.org committed
2970

2971 2972 2973 2974
    // Push the arguments.
    for (int i = 0; i < arg_count; i++) {
      VisitForStackValue(args->at(i));
    }
danno@chromium.org's avatar
danno@chromium.org committed
2975

2976 2977 2978 2979
    // Push a copy of the function (found below the arguments) and
    // resolve eval.
    __ push(Operand(esp, (arg_count + 1) * kPointerSize));
    EmitResolvePossiblyDirectEval(arg_count);
2980

2981 2982 2983 2984 2985
    // Touch up the stack with the resolved function.
    __ mov(Operand(esp, (arg_count + 1) * kPointerSize), eax);

    PrepareForBailoutForId(expr->EvalId(), NO_REGISTERS);

2986
    SetCallPosition(expr, arg_count);
danno@chromium.org's avatar
danno@chromium.org committed
2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998
    CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
    __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
    __ CallStub(&stub);
    RecordJSReturnSite(expr);
    // Restore context register.
    __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
    context()->DropAndPlug(1, eax);

  } else if (call_type == Call::GLOBAL_CALL) {
    EmitCallWithLoadIC(expr);
  } else if (call_type == Call::LOOKUP_SLOT_CALL) {
    // Call to a lookup slot (dynamically introduced variable).
2999
    PushCalleeAndWithBaseObject(expr);
danno@chromium.org's avatar
danno@chromium.org committed
3000 3001 3002
    EmitCall(expr);
  } else if (call_type == Call::PROPERTY_CALL) {
    Property* property = callee->AsProperty();
3003
    bool is_named_call = property->key()->IsPropertyName();
3004 3005 3006 3007 3008 3009
    if (property->IsSuperAccess()) {
      if (is_named_call) {
        EmitSuperCallWithLoadIC(expr);
      } else {
        EmitKeyedSuperCallWithLoadIC(expr);
      }
danno@chromium.org's avatar
danno@chromium.org committed
3010
    } else {
3011
      VisitForStackValue(property->obj());
3012 3013 3014 3015 3016
      if (is_named_call) {
        EmitCallWithLoadIC(expr);
      } else {
        EmitKeyedCallWithLoadIC(expr, property->key());
      }
danno@chromium.org's avatar
danno@chromium.org committed
3017
    }
3018
  } else if (call_type == Call::SUPER_CALL) {
3019
    EmitSuperConstructorCall(expr);
danno@chromium.org's avatar
danno@chromium.org committed
3020
  } else {
3021
    DCHECK(call_type == Call::OTHER_CALL);
danno@chromium.org's avatar
danno@chromium.org committed
3022
    // Call to an arbitrary expression not handled specially above.
3023
    VisitForStackValue(callee);
danno@chromium.org's avatar
danno@chromium.org committed
3024 3025 3026 3027 3028 3029 3030
    __ push(Immediate(isolate()->factory()->undefined_value()));
    // Emit function call.
    EmitCall(expr);
  }

#ifdef DEBUG
  // RecordJSReturnSite should have been called.
3031
  DCHECK(expr->return_is_recorded_);
danno@chromium.org's avatar
danno@chromium.org committed
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044
#endif
}


void FullCodeGenerator::VisitCallNew(CallNew* expr) {
  Comment cmnt(masm_, "[ CallNew");
  // According to ECMA-262, section 11.2.2, page 44, the function
  // expression in new calls must be evaluated before the
  // arguments.

  // Push constructor on the stack.  If it's not a function it's used as
  // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is
  // ignored.
3045
  DCHECK(!expr->expression()->IsSuperPropertyReference());
3046
  VisitForStackValue(expr->expression());
danno@chromium.org's avatar
danno@chromium.org committed
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056

  // Push the arguments ("left-to-right") on the stack.
  ZoneList<Expression*>* args = expr->arguments();
  int arg_count = args->length();
  for (int i = 0; i < arg_count; i++) {
    VisitForStackValue(args->at(i));
  }

  // Call the construct call builtin that handles allocation and
  // constructor invocation.
3057
  SetConstructCallPosition(expr);
danno@chromium.org's avatar
danno@chromium.org committed
3058 3059 3060 3061 3062 3063

  // Load function and argument count into edi and eax.
  __ Move(eax, Immediate(arg_count));
  __ mov(edi, Operand(esp, arg_count * kPointerSize));

  // Record call targets in unoptimized code.
3064
  __ EmitLoadTypeFeedbackVector(ebx);
3065
  __ mov(edx, Immediate(SmiFromSlot(expr->CallNewFeedbackSlot())));
danno@chromium.org's avatar
danno@chromium.org committed
3066 3067 3068 3069

  CallConstructStub stub(isolate(), RECORD_CONSTRUCTOR_TARGET);
  __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);
  PrepareForBailoutForId(expr->ReturnId(), TOS_REG);
3070 3071
  // Restore context register.
  __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
danno@chromium.org's avatar
danno@chromium.org committed
3072 3073 3074 3075
  context()->Plug(eax);
}


3076
void FullCodeGenerator::EmitSuperConstructorCall(Call* expr) {
3077 3078 3079 3080 3081
  SuperCallReference* super_call_ref =
      expr->expression()->AsSuperCallReference();
  DCHECK_NOT_NULL(super_call_ref);

  EmitLoadSuperConstructor(super_call_ref);
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092
  __ push(result_register());

  // Push the arguments ("left-to-right") on the stack.
  ZoneList<Expression*>* args = expr->arguments();
  int arg_count = args->length();
  for (int i = 0; i < arg_count; i++) {
    VisitForStackValue(args->at(i));
  }

  // Call the construct call builtin that handles allocation and
  // constructor invocation.
3093
  SetConstructCallPosition(expr);
3094

3095 3096 3097 3098
  // Load original constructor into ecx.
  VisitForAccumulatorValue(super_call_ref->new_target_var());
  __ mov(ecx, result_register());

3099 3100 3101 3102 3103
  // Load function and argument count into edi and eax.
  __ Move(eax, Immediate(arg_count));
  __ mov(edi, Operand(esp, arg_count * kPointerSize));

  // Record call targets in unoptimized code.
3104
  __ EmitLoadTypeFeedbackVector(ebx);
3105 3106
  __ mov(edx, Immediate(SmiFromSlot(expr->CallFeedbackSlot())));

3107
  CallConstructStub stub(isolate(), SUPER_CALL_RECORD_TARGET);
3108 3109 3110 3111
  __ call(stub.GetCode(), RelocInfo::CONSTRUCT_CALL);

  RecordJSReturnSite(expr);

3112 3113
  // Restore context register.
  __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3114 3115 3116 3117
  context()->Plug(eax);
}


danno@chromium.org's avatar
danno@chromium.org committed
3118 3119
void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3120
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  __ test(eax, Immediate(kSmiTagMask));
  Split(zero, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3141
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  __ JumpIfSmi(eax, if_false);
  __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, ebx);
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(above_equal, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


3161
void FullCodeGenerator::EmitIsSimdValue(CallRuntime* expr) {
3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK(args->length() == 1);

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
                         &if_false, &fall_through);

  __ JumpIfSmi(eax, if_false);
3175
  __ CmpObjectType(eax, SIMD128_VALUE_TYPE, ebx);
3176
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
3177
  Split(equal, if_true, if_false, fall_through);
3178

danno@chromium.org's avatar
danno@chromium.org committed
3179 3180 3181 3182 3183 3184
  context()->Plug(if_true, if_false);
}


void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3185
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  __ JumpIfSmi(eax, if_false);
  __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(equal, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3207
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  Handle<Map> map = masm()->isolate()->factory()->heap_number_map();
  __ CheckMap(eax, map, if_false, DO_SMI_CHECK);
  // Check if the exponent half is 0x80000000. Comparing against 1 and
  // checking for overflow is the shortest possible encoding.
  __ cmp(FieldOperand(eax, HeapNumber::kExponentOffset), Immediate(0x1));
  __ j(no_overflow, if_false);
  __ cmp(FieldOperand(eax, HeapNumber::kMantissaOffset), Immediate(0x0));
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(equal, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


void FullCodeGenerator::EmitIsArray(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3234
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  __ JumpIfSmi(eax, if_false);
  __ CmpObjectType(eax, JS_ARRAY_TYPE, ebx);
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(equal, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
void FullCodeGenerator::EmitIsTypedArray(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK(args->length() == 1);

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
                         &if_false, &fall_through);

  __ JumpIfSmi(eax, if_false);
  __ CmpObjectType(eax, JS_TYPED_ARRAY_TYPE, ebx);
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(equal, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


danno@chromium.org's avatar
danno@chromium.org committed
3276 3277
void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3278
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  __ JumpIfSmi(eax, if_false);
  __ CmpObjectType(eax, JS_REGEXP_TYPE, ebx);
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(equal, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322
void FullCodeGenerator::EmitIsJSProxy(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK(args->length() == 1);

  VisitForAccumulatorValue(args->at(0));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
                         &if_false, &fall_through);

  __ JumpIfSmi(eax, if_false);
  Register map = ebx;
  __ mov(map, FieldOperand(eax, HeapObject::kMapOffset));
  __ CmpInstanceType(map, FIRST_JS_PROXY_TYPE);
  __ j(less, if_false);
  __ CmpInstanceType(map, LAST_JS_PROXY_TYPE);
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(less_equal, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}

danno@chromium.org's avatar
danno@chromium.org committed
3323 3324

void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) {
3325
  DCHECK(expr->arguments()->length() == 0);
danno@chromium.org's avatar
danno@chromium.org committed
3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  // Get the frame pointer for the calling frame.
  __ mov(eax, Operand(ebp, StandardFrameConstants::kCallerFPOffset));

  // Skip the arguments adaptor frame if it exists.
  Label check_frame_marker;
  __ cmp(Operand(eax, StandardFrameConstants::kContextOffset),
         Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
  __ j(not_equal, &check_frame_marker);
  __ mov(eax, Operand(eax, StandardFrameConstants::kCallerFPOffset));

  // Check the marker in the calling frame.
  __ bind(&check_frame_marker);
  __ cmp(Operand(eax, StandardFrameConstants::kMarkerOffset),
         Immediate(Smi::FromInt(StackFrame::CONSTRUCT)));
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(equal, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3357
  DCHECK(args->length() == 2);
danno@chromium.org's avatar
danno@chromium.org committed
3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380

  // Load the two objects into registers and perform the comparison.
  VisitForStackValue(args->at(0));
  VisitForAccumulatorValue(args->at(1));

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  __ pop(ebx);
  __ cmp(eax, ebx);
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(equal, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


void FullCodeGenerator::EmitArguments(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3381
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394

  // ArgumentsAccessStub expects the key in edx and the formal
  // parameter count in eax.
  VisitForAccumulatorValue(args->at(0));
  __ mov(edx, eax);
  __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));
  ArgumentsAccessStub stub(isolate(), ArgumentsAccessStub::READ_ELEMENT);
  __ CallStub(&stub);
  context()->Plug(eax);
}


void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) {
3395
  DCHECK(expr->arguments()->length() == 0);
danno@chromium.org's avatar
danno@chromium.org committed
3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418

  Label exit;
  // Get the number of formal parameters.
  __ Move(eax, Immediate(Smi::FromInt(info_->scope()->num_parameters())));

  // Check if the calling frame is an arguments adaptor frame.
  __ mov(ebx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
  __ cmp(Operand(ebx, StandardFrameConstants::kContextOffset),
         Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
  __ j(not_equal, &exit);

  // Arguments adaptor case: Read the arguments length from the
  // adaptor frame.
  __ mov(eax, Operand(ebx, ArgumentsAdaptorFrameConstants::kLengthOffset));

  __ bind(&exit);
  __ AssertSmi(eax);
  context()->Plug(eax);
}


void FullCodeGenerator::EmitClassOf(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3419
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446
  Label done, null, function, non_function_constructor;

  VisitForAccumulatorValue(args->at(0));

  // If the object is a smi, we return null.
  __ JumpIfSmi(eax, &null);

  // Check that the object is a JS object but take special care of JS
  // functions to make sure they have 'Function' as their class.
  // Assume that there are only two callable types, and one of them is at
  // either end of the type range for JS object types. Saves extra comparisons.
  STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2);
  __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, eax);
  // Map is now in eax.
  __ j(below, &null);
  STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE ==
                FIRST_SPEC_OBJECT_TYPE + 1);
  __ j(equal, &function);

  __ CmpInstanceType(eax, LAST_SPEC_OBJECT_TYPE);
  STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE ==
                LAST_SPEC_OBJECT_TYPE - 1);
  __ j(equal, &function);
  // Assume that there is no larger type.
  STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1);

  // Check if the constructor in the map is a JS function.
3447 3448
  __ GetMapConstructor(eax, eax, ebx);
  __ CmpInstanceType(ebx, JS_FUNCTION_TYPE);
danno@chromium.org's avatar
danno@chromium.org committed
3449 3450 3451 3452 3453 3454 3455 3456 3457 3458
  __ j(not_equal, &non_function_constructor);

  // eax now contains the constructor function. Grab the
  // instance class name from there.
  __ mov(eax, FieldOperand(eax, JSFunction::kSharedFunctionInfoOffset));
  __ mov(eax, FieldOperand(eax, SharedFunctionInfo::kInstanceClassNameOffset));
  __ jmp(&done);

  // Functions have class 'Function'.
  __ bind(&function);
3459
  __ mov(eax, isolate()->factory()->Function_string());
danno@chromium.org's avatar
danno@chromium.org committed
3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479
  __ jmp(&done);

  // Objects with a non-function constructor have class 'Object'.
  __ bind(&non_function_constructor);
  __ mov(eax, isolate()->factory()->Object_string());
  __ jmp(&done);

  // Non-JS objects have class null.
  __ bind(&null);
  __ mov(eax, isolate()->factory()->null_value());

  // All done.
  __ bind(&done);

  context()->Plug(eax);
}


void FullCodeGenerator::EmitValueOf(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3480
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496

  VisitForAccumulatorValue(args->at(0));  // Load the object.

  Label done;
  // If the object is a smi return the object.
  __ JumpIfSmi(eax, &done, Label::kNear);
  // If the object is not a value type, return the object.
  __ CmpObjectType(eax, JS_VALUE_TYPE, ebx);
  __ j(not_equal, &done, Label::kNear);
  __ mov(eax, FieldOperand(eax, JSValue::kValueOffset));

  __ bind(&done);
  context()->Plug(eax);
}


3497
void FullCodeGenerator::EmitIsDate(CallRuntime* expr) {
3498 3499 3500
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_EQ(1, args->length());

3501
  VisitForAccumulatorValue(args->at(0));
3502

3503 3504 3505 3506 3507 3508
  Label materialize_true, materialize_false;
  Label* if_true = nullptr;
  Label* if_false = nullptr;
  Label* fall_through = nullptr;
  context()->PrepareTest(&materialize_true, &materialize_false, &if_true,
                         &if_false, &fall_through);
3509

3510 3511 3512 3513
  __ JumpIfSmi(eax, if_false);
  __ CmpObjectType(eax, JS_DATE_TYPE, ebx);
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(equal, if_true, if_false, fall_through);
3514

3515
  context()->Plug(if_true, if_false);
3516 3517 3518
}


danno@chromium.org's avatar
danno@chromium.org committed
3519 3520
void FullCodeGenerator::EmitDateField(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3521
  DCHECK(args->length() == 2);
3522
  DCHECK_NOT_NULL(args->at(1)->AsLiteral());
danno@chromium.org's avatar
danno@chromium.org committed
3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
  Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value()));

  VisitForAccumulatorValue(args->at(0));  // Load the object.

  Register object = eax;
  Register result = eax;
  Register scratch = ecx;

  if (index->value() == 0) {
    __ mov(result, FieldOperand(object, JSDate::kValueOffset));
  } else {
3534
    Label runtime, done;
danno@chromium.org's avatar
danno@chromium.org committed
3535 3536 3537 3538 3539 3540 3541
    if (index->value() < JSDate::kFirstUncachedField) {
      ExternalReference stamp = ExternalReference::date_cache_stamp(isolate());
      __ mov(scratch, Operand::StaticVariable(stamp));
      __ cmp(scratch, FieldOperand(object, JSDate::kCacheStampOffset));
      __ j(not_equal, &runtime, Label::kNear);
      __ mov(result, FieldOperand(object, JSDate::kValueOffset +
                                          kPointerSize * index->value()));
3542
      __ jmp(&done, Label::kNear);
danno@chromium.org's avatar
danno@chromium.org committed
3543 3544 3545 3546 3547 3548
    }
    __ bind(&runtime);
    __ PrepareCallCFunction(2, scratch);
    __ mov(Operand(esp, 0), object);
    __ mov(Operand(esp, 1 * kPointerSize), Immediate(index));
    __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2);
3549
    __ bind(&done);
danno@chromium.org's avatar
danno@chromium.org committed
3550 3551 3552 3553 3554 3555 3556 3557
  }

  context()->Plug(result);
}


void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3558
  DCHECK_EQ(3, args->length());
danno@chromium.org's avatar
danno@chromium.org committed
3559 3560 3561 3562 3563

  Register string = eax;
  Register index = ebx;
  Register value = ecx;

3564 3565 3566
  VisitForStackValue(args->at(0));        // index
  VisitForStackValue(args->at(1));        // value
  VisitForAccumulatorValue(args->at(2));  // string
danno@chromium.org's avatar
danno@chromium.org committed
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593

  __ pop(value);
  __ pop(index);

  if (FLAG_debug_code) {
    __ test(value, Immediate(kSmiTagMask));
    __ Check(zero, kNonSmiValue);
    __ test(index, Immediate(kSmiTagMask));
    __ Check(zero, kNonSmiValue);
  }

  __ SmiUntag(value);
  __ SmiUntag(index);

  if (FLAG_debug_code) {
    static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
    __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type);
  }

  __ mov_b(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize),
           value);
  context()->Plug(string);
}


void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3594
  DCHECK_EQ(3, args->length());
danno@chromium.org's avatar
danno@chromium.org committed
3595 3596 3597 3598 3599

  Register string = eax;
  Register index = ebx;
  Register value = ecx;

3600 3601 3602
  VisitForStackValue(args->at(0));        // index
  VisitForStackValue(args->at(1));        // value
  VisitForAccumulatorValue(args->at(2));  // string
danno@chromium.org's avatar
danno@chromium.org committed
3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626
  __ pop(value);
  __ pop(index);

  if (FLAG_debug_code) {
    __ test(value, Immediate(kSmiTagMask));
    __ Check(zero, kNonSmiValue);
    __ test(index, Immediate(kSmiTagMask));
    __ Check(zero, kNonSmiValue);
    __ SmiUntag(index);
    static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
    __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type);
    __ SmiTag(index);
  }

  __ SmiUntag(value);
  // No need to untag a smi for two-byte addressing.
  __ mov_w(FieldOperand(string, index, times_1, SeqTwoByteString::kHeaderSize),
           value);
  context()->Plug(string);
}


void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3627
  DCHECK(args->length() == 2);
danno@chromium.org's avatar
danno@chromium.org committed
3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646

  VisitForStackValue(args->at(0));  // Load the object.
  VisitForAccumulatorValue(args->at(1));  // Load the value.
  __ pop(ebx);  // eax = value. ebx = object.

  Label done;
  // If the object is a smi, return the value.
  __ JumpIfSmi(ebx, &done, Label::kNear);

  // If the object is not a value type, return the value.
  __ CmpObjectType(ebx, JS_VALUE_TYPE, ecx);
  __ j(not_equal, &done, Label::kNear);

  // Store the value.
  __ mov(FieldOperand(ebx, JSValue::kValueOffset), eax);

  // Update the write barrier.  Save the value as it will be
  // overwritten by the write barrier code and is needed afterward.
  __ mov(edx, eax);
3647
  __ RecordWriteField(ebx, JSValue::kValueOffset, edx, ecx, kDontSaveFPRegs);
danno@chromium.org's avatar
danno@chromium.org committed
3648 3649 3650 3651 3652 3653

  __ bind(&done);
  context()->Plug(eax);
}


3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670
void FullCodeGenerator::EmitToInteger(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_EQ(1, args->length());

  // Load the argument into eax and convert it.
  VisitForAccumulatorValue(args->at(0));

  // Convert the object to an integer.
  Label done_convert;
  __ JumpIfSmi(eax, &done_convert, Label::kNear);
  __ Push(eax);
  __ CallRuntime(Runtime::kToInteger, 1);
  __ bind(&done_convert);
  context()->Plug(eax);
}


3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_EQ(args->length(), 1);

  // Load the argument into eax and call the stub.
  VisitForAccumulatorValue(args->at(0));

  NumberToStringStub stub(isolate());
  __ CallStub(&stub);
  context()->Plug(eax);
}


3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696
void FullCodeGenerator::EmitToString(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_EQ(1, args->length());

  // Load the argument into eax and convert it.
  VisitForAccumulatorValue(args->at(0));

  ToStringStub stub(isolate());
  __ CallStub(&stub);
  context()->Plug(eax);
}


3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709
void FullCodeGenerator::EmitToNumber(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_EQ(1, args->length());

  // Load the argument into eax and convert it.
  VisitForAccumulatorValue(args->at(0));

  ToNumberStub stub(isolate());
  __ CallStub(&stub);
  context()->Plug(eax);
}


3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723
void FullCodeGenerator::EmitToName(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_EQ(1, args->length());

  // Load the argument into eax and convert it.
  VisitForAccumulatorValue(args->at(0));

  // Convert the object to a name.
  Label convert, done_convert;
  __ JumpIfSmi(eax, &convert, Label::kNear);
  STATIC_ASSERT(FIRST_NAME_TYPE == FIRST_TYPE);
  __ CmpObjectType(eax, LAST_NAME_TYPE, ecx);
  __ j(below_equal, &done_convert, Label::kNear);
  __ bind(&convert);
3724 3725
  __ Push(eax);
  __ CallRuntime(Runtime::kToName, 1);
3726 3727 3728 3729 3730
  __ bind(&done_convert);
  context()->Plug(eax);
}


3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
void FullCodeGenerator::EmitToObject(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_EQ(1, args->length());

  // Load the argument into eax and convert it.
  VisitForAccumulatorValue(args->at(0));

  ToObjectStub stub(isolate());
  __ CallStub(&stub);
  context()->Plug(eax);
}


danno@chromium.org's avatar
danno@chromium.org committed
3744 3745
void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3746
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764

  VisitForAccumulatorValue(args->at(0));

  Label done;
  StringCharFromCodeGenerator generator(eax, ebx);
  generator.GenerateFast(masm_);
  __ jmp(&done);

  NopRuntimeCallHelper call_helper;
  generator.GenerateSlow(masm_, call_helper);

  __ bind(&done);
  context()->Plug(ebx);
}


void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3765
  DCHECK(args->length() == 2);
danno@chromium.org's avatar
danno@chromium.org committed
3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801

  VisitForStackValue(args->at(0));
  VisitForAccumulatorValue(args->at(1));

  Register object = ebx;
  Register index = eax;
  Register result = edx;

  __ pop(object);

  Label need_conversion;
  Label index_out_of_range;
  Label done;
  StringCharCodeAtGenerator generator(object,
                                      index,
                                      result,
                                      &need_conversion,
                                      &need_conversion,
                                      &index_out_of_range,
                                      STRING_INDEX_IS_NUMBER);
  generator.GenerateFast(masm_);
  __ jmp(&done);

  __ bind(&index_out_of_range);
  // When the index is out of range, the spec requires us to return
  // NaN.
  __ Move(result, Immediate(isolate()->factory()->nan_value()));
  __ jmp(&done);

  __ bind(&need_conversion);
  // Move the undefined value into the result register, which will
  // trigger conversion.
  __ Move(result, Immediate(isolate()->factory()->undefined_value()));
  __ jmp(&done);

  NopRuntimeCallHelper call_helper;
3802
  generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
danno@chromium.org's avatar
danno@chromium.org committed
3803 3804 3805 3806 3807 3808 3809 3810

  __ bind(&done);
  context()->Plug(result);
}


void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3811
  DCHECK(args->length() == 2);
danno@chromium.org's avatar
danno@chromium.org committed
3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849

  VisitForStackValue(args->at(0));
  VisitForAccumulatorValue(args->at(1));

  Register object = ebx;
  Register index = eax;
  Register scratch = edx;
  Register result = eax;

  __ pop(object);

  Label need_conversion;
  Label index_out_of_range;
  Label done;
  StringCharAtGenerator generator(object,
                                  index,
                                  scratch,
                                  result,
                                  &need_conversion,
                                  &need_conversion,
                                  &index_out_of_range,
                                  STRING_INDEX_IS_NUMBER);
  generator.GenerateFast(masm_);
  __ jmp(&done);

  __ bind(&index_out_of_range);
  // When the index is out of range, the spec requires us to return
  // the empty string.
  __ Move(result, Immediate(isolate()->factory()->empty_string()));
  __ jmp(&done);

  __ bind(&need_conversion);
  // Move smi zero into the result register, which will trigger
  // conversion.
  __ Move(result, Immediate(Smi::FromInt(0)));
  __ jmp(&done);

  NopRuntimeCallHelper call_helper;
3850
  generator.GenerateSlow(masm_, NOT_PART_OF_IC_HANDLER, call_helper);
danno@chromium.org's avatar
danno@chromium.org committed
3851 3852 3853 3854 3855 3856 3857 3858

  __ bind(&done);
  context()->Plug(result);
}


void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3859
  DCHECK_EQ(2, args->length());
danno@chromium.org's avatar
danno@chromium.org committed
3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
  VisitForStackValue(args->at(0));
  VisitForAccumulatorValue(args->at(1));

  __ pop(edx);
  StringAddStub stub(isolate(), STRING_ADD_CHECK_BOTH, NOT_TENURED);
  __ CallStub(&stub);
  context()->Plug(eax);
}


3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889
void FullCodeGenerator::EmitCall(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_LE(2, args->length());
  // Push target, receiver and arguments onto the stack.
  for (Expression* const arg : *args) {
    VisitForStackValue(arg);
  }
  // Move target to edi.
  int const argc = args->length() - 2;
  __ mov(edi, Operand(esp, (argc + 1) * kPointerSize));
  // Call the target.
  __ mov(eax, Immediate(argc));
  __ Call(isolate()->builtins()->Call(), RelocInfo::CODE_TARGET);
  // Restore context register.
  __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
  // Discard the function left on TOS.
  context()->DropAndPlug(1, eax);
}


danno@chromium.org's avatar
danno@chromium.org committed
3890 3891
void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3892
  DCHECK(args->length() >= 2);
danno@chromium.org's avatar
danno@chromium.org committed
3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914

  int arg_count = args->length() - 2;  // 2 ~ receiver and function.
  for (int i = 0; i < arg_count + 1; ++i) {
    VisitForStackValue(args->at(i));
  }
  VisitForAccumulatorValue(args->last());  // Function.

  Label runtime, done;
  // Check for non-function argument (including proxy).
  __ JumpIfSmi(eax, &runtime);
  __ CmpObjectType(eax, JS_FUNCTION_TYPE, ebx);
  __ j(not_equal, &runtime);

  // InvokeFunction requires the function in edi. Move it in there.
  __ mov(edi, result_register());
  ParameterCount count(arg_count);
  __ InvokeFunction(edi, count, CALL_FUNCTION, NullCallWrapper());
  __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
  __ jmp(&done);

  __ bind(&runtime);
  __ push(eax);
3915
  __ CallRuntime(Runtime::kCallFunction, args->length());
danno@chromium.org's avatar
danno@chromium.org committed
3916 3917 3918 3919 3920 3921
  __ bind(&done);

  context()->Plug(eax);
}


3922
void FullCodeGenerator::EmitDefaultConstructorCallSuper(CallRuntime* expr) {
3923 3924
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK(args->length() == 2);
3925

3926
  // Evaluate new.target and super constructor.
3927 3928
  VisitForStackValue(args->at(0));
  VisitForStackValue(args->at(1));
3929 3930 3931 3932

  // Check if the calling frame is an arguments adaptor frame.
  Label adaptor_frame, args_set_up, runtime;
  __ mov(edx, Operand(ebp, StandardFrameConstants::kCallerFPOffset));
3933 3934
  __ mov(ebx, Operand(edx, StandardFrameConstants::kContextOffset));
  __ cmp(ebx, Immediate(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3935 3936 3937 3938 3939 3940 3941 3942
  __ j(equal, &adaptor_frame);
  // default constructor has no arguments, so no adaptor frame means no args.
  __ mov(eax, Immediate(0));
  __ jmp(&args_set_up);

  // Copy arguments from adaptor frame.
  {
    __ bind(&adaptor_frame);
3943 3944
    __ mov(ebx, Operand(edx, ArgumentsAdaptorFrameConstants::kLengthOffset));
    __ SmiUntag(ebx);
3945

3946 3947
    __ mov(eax, ebx);
    __ lea(edx, Operand(edx, ebx, times_pointer_size,
3948 3949 3950 3951 3952
                        StandardFrameConstants::kCallerSPOffset));
    Label loop;
    __ bind(&loop);
    __ push(Operand(edx, -1 * kPointerSize));
    __ sub(edx, Immediate(kPointerSize));
3953
    __ dec(ebx);
3954 3955 3956 3957
    __ j(not_zero, &loop);
  }

  __ bind(&args_set_up);
3958

3959 3960 3961
  __ mov(edx, Operand(esp, eax, times_pointer_size, 1 * kPointerSize));
  __ mov(edi, Operand(esp, eax, times_pointer_size, 0 * kPointerSize));
  __ Call(isolate()->builtins()->Construct(), RelocInfo::CONSTRUCT_CALL);
3962

3963 3964
  // Restore context register.
  __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
3965

3966
  context()->DropAndPlug(1, eax);
3967 3968 3969
}


danno@chromium.org's avatar
danno@chromium.org committed
3970 3971 3972 3973
void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) {
  // Load the arguments on the stack and call the stub.
  RegExpConstructResultStub stub(isolate());
  ZoneList<Expression*>* args = expr->arguments();
3974
  DCHECK(args->length() == 3);
danno@chromium.org's avatar
danno@chromium.org committed
3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986
  VisitForStackValue(args->at(0));
  VisitForStackValue(args->at(1));
  VisitForAccumulatorValue(args->at(2));
  __ pop(ebx);
  __ pop(ecx);
  __ CallStub(&stub);
  context()->Plug(eax);
}


void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
3987
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010

  VisitForAccumulatorValue(args->at(0));

  __ AssertString(eax);

  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  __ test(FieldOperand(eax, String::kHashFieldOffset),
          Immediate(String::kContainsCachedArrayIndexMask));
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
  Split(zero, if_true, if_false, fall_through);

  context()->Plug(if_true, if_false);
}


void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
4011
  DCHECK(args->length() == 1);
danno@chromium.org's avatar
danno@chromium.org committed
4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022
  VisitForAccumulatorValue(args->at(0));

  __ AssertString(eax);

  __ mov(eax, FieldOperand(eax, String::kHashFieldOffset));
  __ IndexFromHash(eax, eax);

  context()->Plug(eax);
}


4023
void FullCodeGenerator::EmitFastOneByteArrayJoin(CallRuntime* expr) {
danno@chromium.org's avatar
danno@chromium.org committed
4024 4025 4026 4027 4028
  Label bailout, done, one_char_separator, long_separator,
      non_trivial_array, not_size_one_array, loop,
      loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry;

  ZoneList<Expression*>* args = expr->arguments();
4029
  DCHECK(args->length() == 2);
danno@chromium.org's avatar
danno@chromium.org committed
4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080
  // We will leave the separator on the stack until the end of the function.
  VisitForStackValue(args->at(1));
  // Load this to eax (= array)
  VisitForAccumulatorValue(args->at(0));
  // All aliases of the same register have disjoint lifetimes.
  Register array = eax;
  Register elements = no_reg;  // Will be eax.

  Register index = edx;

  Register string_length = ecx;

  Register string = esi;

  Register scratch = ebx;

  Register array_length = edi;
  Register result_pos = no_reg;  // Will be edi.

  // Separator operand is already pushed.
  Operand separator_operand = Operand(esp, 2 * kPointerSize);
  Operand result_operand = Operand(esp, 1 * kPointerSize);
  Operand array_length_operand = Operand(esp, 0);
  __ sub(esp, Immediate(2 * kPointerSize));
  __ cld();
  // Check that the array is a JSArray
  __ JumpIfSmi(array, &bailout);
  __ CmpObjectType(array, JS_ARRAY_TYPE, scratch);
  __ j(not_equal, &bailout);

  // Check that the array has fast elements.
  __ CheckFastElements(scratch, &bailout);

  // If the array has length zero, return the empty string.
  __ mov(array_length, FieldOperand(array, JSArray::kLengthOffset));
  __ SmiUntag(array_length);
  __ j(not_zero, &non_trivial_array);
  __ mov(result_operand, isolate()->factory()->empty_string());
  __ jmp(&done);

  // Save the array length.
  __ bind(&non_trivial_array);
  __ mov(array_length_operand, array_length);

  // Save the FixedArray containing array's elements.
  // End of array's live range.
  elements = array;
  __ mov(elements, FieldOperand(array, JSArray::kElementsOffset));
  array = no_reg;


4081
  // Check that all array elements are sequential one-byte strings, and
danno@chromium.org's avatar
danno@chromium.org committed
4082 4083 4084 4085 4086 4087 4088 4089
  // accumulate the sum of their lengths, as a smi-encoded value.
  __ Move(index, Immediate(0));
  __ Move(string_length, Immediate(0));
  // Loop condition: while (index < length).
  // Live loop registers: index, array_length, string,
  //                      scratch, string_length, elements.
  if (generate_debug_code_) {
    __ cmp(index, array_length);
4090
    __ Assert(less, kNoEmptyArraysHereInEmitFastOneByteArrayJoin);
danno@chromium.org's avatar
danno@chromium.org committed
4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
  }
  __ bind(&loop);
  __ mov(string, FieldOperand(elements,
                              index,
                              times_pointer_size,
                              FixedArray::kHeaderSize));
  __ JumpIfSmi(string, &bailout);
  __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
  __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
  __ and_(scratch, Immediate(
      kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
  __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
  __ j(not_equal, &bailout);
  __ add(string_length,
         FieldOperand(string, SeqOneByteString::kLengthOffset));
  __ j(overflow, &bailout);
  __ add(index, Immediate(1));
  __ cmp(index, array_length);
  __ j(less, &loop);

  // If array_length is 1, return elements[0], a string.
  __ cmp(array_length, 1);
  __ j(not_equal, &not_size_one_array);
  __ mov(scratch, FieldOperand(elements, FixedArray::kHeaderSize));
  __ mov(result_operand, scratch);
  __ jmp(&done);

  __ bind(&not_size_one_array);

  // End of array_length live range.
  result_pos = array_length;
  array_length = no_reg;

  // Live registers:
  // string_length: Sum of string lengths, as a smi.
  // elements: FixedArray of strings.

4128
  // Check that the separator is a flat one-byte string.
danno@chromium.org's avatar
danno@chromium.org committed
4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151
  __ mov(string, separator_operand);
  __ JumpIfSmi(string, &bailout);
  __ mov(scratch, FieldOperand(string, HeapObject::kMapOffset));
  __ movzx_b(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset));
  __ and_(scratch, Immediate(
      kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask));
  __ cmp(scratch, kStringTag | kOneByteStringTag | kSeqStringTag);
  __ j(not_equal, &bailout);

  // Add (separator length times array_length) - separator length
  // to string_length.
  __ mov(scratch, separator_operand);
  __ mov(scratch, FieldOperand(scratch, SeqOneByteString::kLengthOffset));
  __ sub(string_length, scratch);  // May be negative, temporarily.
  __ imul(scratch, array_length_operand);
  __ j(overflow, &bailout);
  __ add(string_length, scratch);
  __ j(overflow, &bailout);

  __ shr(string_length, 1);
  // Live registers and stack values:
  //   string_length
  //   elements
4152 4153
  __ AllocateOneByteString(result_pos, string_length, scratch, index, string,
                           &bailout);
danno@chromium.org's avatar
danno@chromium.org committed
4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195
  __ mov(result_operand, result_pos);
  __ lea(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize));


  __ mov(string, separator_operand);
  __ cmp(FieldOperand(string, SeqOneByteString::kLengthOffset),
         Immediate(Smi::FromInt(1)));
  __ j(equal, &one_char_separator);
  __ j(greater, &long_separator);


  // Empty separator case
  __ mov(index, Immediate(0));
  __ jmp(&loop_1_condition);
  // Loop condition: while (index < length).
  __ bind(&loop_1);
  // Each iteration of the loop concatenates one string to the result.
  // Live values in registers:
  //   index: which element of the elements array we are adding to the result.
  //   result_pos: the position to which we are currently copying characters.
  //   elements: the FixedArray of strings we are joining.

  // Get string = array[index].
  __ mov(string, FieldOperand(elements, index,
                              times_pointer_size,
                              FixedArray::kHeaderSize));
  __ mov(string_length,
         FieldOperand(string, String::kLengthOffset));
  __ shr(string_length, 1);
  __ lea(string,
         FieldOperand(string, SeqOneByteString::kHeaderSize));
  __ CopyBytes(string, result_pos, string_length, scratch);
  __ add(index, Immediate(1));
  __ bind(&loop_1_condition);
  __ cmp(index, array_length_operand);
  __ j(less, &loop_1);  // End while (index < length).
  __ jmp(&done);



  // One-character separator case
  __ bind(&one_char_separator);
4196
  // Replace separator with its one-byte character value.
danno@chromium.org's avatar
danno@chromium.org committed
4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286
  __ mov_b(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize));
  __ mov_b(separator_operand, scratch);

  __ Move(index, Immediate(0));
  // Jump into the loop after the code that copies the separator, so the first
  // element is not preceded by a separator
  __ jmp(&loop_2_entry);
  // Loop condition: while (index < length).
  __ bind(&loop_2);
  // Each iteration of the loop concatenates one string to the result.
  // Live values in registers:
  //   index: which element of the elements array we are adding to the result.
  //   result_pos: the position to which we are currently copying characters.

  // Copy the separator character to the result.
  __ mov_b(scratch, separator_operand);
  __ mov_b(Operand(result_pos, 0), scratch);
  __ inc(result_pos);

  __ bind(&loop_2_entry);
  // Get string = array[index].
  __ mov(string, FieldOperand(elements, index,
                              times_pointer_size,
                              FixedArray::kHeaderSize));
  __ mov(string_length,
         FieldOperand(string, String::kLengthOffset));
  __ shr(string_length, 1);
  __ lea(string,
         FieldOperand(string, SeqOneByteString::kHeaderSize));
  __ CopyBytes(string, result_pos, string_length, scratch);
  __ add(index, Immediate(1));

  __ cmp(index, array_length_operand);
  __ j(less, &loop_2);  // End while (index < length).
  __ jmp(&done);


  // Long separator case (separator is more than one character).
  __ bind(&long_separator);

  __ Move(index, Immediate(0));
  // Jump into the loop after the code that copies the separator, so the first
  // element is not preceded by a separator
  __ jmp(&loop_3_entry);
  // Loop condition: while (index < length).
  __ bind(&loop_3);
  // Each iteration of the loop concatenates one string to the result.
  // Live values in registers:
  //   index: which element of the elements array we are adding to the result.
  //   result_pos: the position to which we are currently copying characters.

  // Copy the separator to the result.
  __ mov(string, separator_operand);
  __ mov(string_length,
         FieldOperand(string, String::kLengthOffset));
  __ shr(string_length, 1);
  __ lea(string,
         FieldOperand(string, SeqOneByteString::kHeaderSize));
  __ CopyBytes(string, result_pos, string_length, scratch);

  __ bind(&loop_3_entry);
  // Get string = array[index].
  __ mov(string, FieldOperand(elements, index,
                              times_pointer_size,
                              FixedArray::kHeaderSize));
  __ mov(string_length,
         FieldOperand(string, String::kLengthOffset));
  __ shr(string_length, 1);
  __ lea(string,
         FieldOperand(string, SeqOneByteString::kHeaderSize));
  __ CopyBytes(string, result_pos, string_length, scratch);
  __ add(index, Immediate(1));

  __ cmp(index, array_length_operand);
  __ j(less, &loop_3);  // End while (index < length).
  __ jmp(&done);


  __ bind(&bailout);
  __ mov(result_operand, isolate()->factory()->undefined_value());
  __ bind(&done);
  __ mov(eax, result_operand);
  // Drop temp values from the stack, and restore context register.
  __ add(esp, Immediate(3 * kPointerSize));

  __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
  context()->Plug(eax);
}


4287
void FullCodeGenerator::EmitDebugIsActive(CallRuntime* expr) {
4288
  DCHECK(expr->arguments()->length() == 0);
4289 4290 4291 4292 4293 4294 4295 4296
  ExternalReference debug_is_active =
      ExternalReference::debug_is_active_address(isolate());
  __ movzx_b(eax, Operand::StaticVariable(debug_is_active));
  __ SmiTag(eax);
  context()->Plug(eax);
}


4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326
void FullCodeGenerator::EmitCreateIterResultObject(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  DCHECK_EQ(2, args->length());
  VisitForStackValue(args->at(0));
  VisitForStackValue(args->at(1));

  Label runtime, done;

  __ Allocate(JSIteratorResult::kSize, eax, ecx, edx, &runtime, TAG_OBJECT);
  __ mov(ebx, GlobalObjectOperand());
  __ mov(ebx, FieldOperand(ebx, GlobalObject::kNativeContextOffset));
  __ mov(ebx, ContextOperand(ebx, Context::ITERATOR_RESULT_MAP_INDEX));
  __ mov(FieldOperand(eax, HeapObject::kMapOffset), ebx);
  __ mov(FieldOperand(eax, JSObject::kPropertiesOffset),
         isolate()->factory()->empty_fixed_array());
  __ mov(FieldOperand(eax, JSObject::kElementsOffset),
         isolate()->factory()->empty_fixed_array());
  __ pop(FieldOperand(eax, JSIteratorResult::kDoneOffset));
  __ pop(FieldOperand(eax, JSIteratorResult::kValueOffset));
  STATIC_ASSERT(JSIteratorResult::kSize == 5 * kPointerSize);
  __ jmp(&done, Label::kNear);

  __ bind(&runtime);
  __ CallRuntime(Runtime::kCreateIterResultObject, 2);

  __ bind(&done);
  context()->Plug(eax);
}


4327
void FullCodeGenerator::EmitLoadJSRuntimeFunction(CallRuntime* expr) {
4328 4329
  // Push undefined as receiver.
  __ push(Immediate(isolate()->factory()->undefined_value()));
4330

4331 4332 4333
  __ mov(eax, GlobalObjectOperand());
  __ mov(eax, FieldOperand(eax, GlobalObject::kNativeContextOffset));
  __ mov(eax, ContextOperand(eax, expr->context_index()));
4334 4335 4336 4337 4338 4339 4340
}


void FullCodeGenerator::EmitCallJSRuntimeFunction(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
  int arg_count = args->length();

4341
  SetCallPosition(expr, arg_count);
4342 4343 4344 4345 4346 4347
  CallFunctionStub stub(isolate(), arg_count, NO_CALL_FUNCTION_FLAGS);
  __ mov(edi, Operand(esp, (arg_count + 1) * kPointerSize));
  __ CallStub(&stub);
}


danno@chromium.org's avatar
danno@chromium.org committed
4348 4349
void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) {
  ZoneList<Expression*>* args = expr->arguments();
4350
  int arg_count = args->length();
danno@chromium.org's avatar
danno@chromium.org committed
4351 4352

  if (expr->is_jsruntime()) {
4353
    Comment cmnt(masm_, "[ CallRuntime");
4354
    EmitLoadJSRuntimeFunction(expr);
danno@chromium.org's avatar
danno@chromium.org committed
4355 4356 4357 4358 4359

    // Push the target function under the receiver.
    __ push(Operand(esp, 0));
    __ mov(Operand(esp, kPointerSize), eax);

4360
    // Push the arguments ("left-to-right").
danno@chromium.org's avatar
danno@chromium.org committed
4361 4362 4363 4364
    for (int i = 0; i < arg_count; i++) {
      VisitForStackValue(args->at(i));
    }

4365
    PrepareForBailoutForId(expr->CallId(), NO_REGISTERS);
4366 4367
    EmitCallJSRuntimeFunction(expr);

danno@chromium.org's avatar
danno@chromium.org committed
4368 4369 4370 4371 4372
    // Restore context register.
    __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
    context()->DropAndPlug(1, eax);

  } else {
4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387
    const Runtime::Function* function = expr->function();
    switch (function->function_id) {
#define CALL_INTRINSIC_GENERATOR(Name)     \
  case Runtime::kInline##Name: {           \
    Comment cmnt(masm_, "[ Inline" #Name); \
    return Emit##Name(expr);               \
  }
      FOR_EACH_FULL_CODE_INTRINSIC(CALL_INTRINSIC_GENERATOR)
#undef CALL_INTRINSIC_GENERATOR
      default: {
        Comment cmnt(masm_, "[ CallRuntime for unhandled intrinsic");
        // Push the arguments ("left-to-right").
        for (int i = 0; i < arg_count; i++) {
          VisitForStackValue(args->at(i));
        }
danno@chromium.org's avatar
danno@chromium.org committed
4388

4389
        // Call the C runtime function.
4390
        PrepareForBailoutForId(expr->CallId(), NO_REGISTERS);
4391 4392 4393 4394
        __ CallRuntime(expr->function(), arg_count);
        context()->Plug(eax);
      }
    }
danno@chromium.org's avatar
danno@chromium.org committed
4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408
  }
}


void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
  switch (expr->op()) {
    case Token::DELETE: {
      Comment cmnt(masm_, "[ UnaryOperation (DELETE)");
      Property* property = expr->expression()->AsProperty();
      VariableProxy* proxy = expr->expression()->AsVariableProxy();

      if (property != NULL) {
        VisitForStackValue(property->obj());
        VisitForStackValue(property->key());
4409 4410 4411 4412
        __ CallRuntime(is_strict(language_mode())
                           ? Runtime::kDeleteProperty_Strict
                           : Runtime::kDeleteProperty_Sloppy,
                       2);
danno@chromium.org's avatar
danno@chromium.org committed
4413 4414 4415
        context()->Plug(eax);
      } else if (proxy != NULL) {
        Variable* var = proxy->var();
4416 4417 4418 4419
        // Delete of an unqualified identifier is disallowed in strict mode but
        // "delete this" is allowed.
        bool is_this = var->HasThisName(isolate());
        DCHECK(is_sloppy(language_mode()) || is_this);
4420
        if (var->IsUnallocatedOrGlobalSlot()) {
danno@chromium.org's avatar
danno@chromium.org committed
4421 4422
          __ push(GlobalObjectOperand());
          __ push(Immediate(var->name()));
4423
          __ CallRuntime(Runtime::kDeleteProperty_Sloppy, 2);
danno@chromium.org's avatar
danno@chromium.org committed
4424 4425 4426 4427 4428
          context()->Plug(eax);
        } else if (var->IsStackAllocated() || var->IsContextSlot()) {
          // Result of deleting non-global variables is false.  'this' is
          // not really a variable, though we implement it as one.  The
          // subexpression does not have side effects.
4429
          context()->Plug(is_this);
danno@chromium.org's avatar
danno@chromium.org committed
4430 4431 4432 4433 4434
        } else {
          // Non-global variable.  Call the runtime to try to delete from the
          // context where the variable was introduced.
          __ push(context_register());
          __ push(Immediate(var->name()));
4435
          __ CallRuntime(Runtime::kDeleteLookupSlot, 2);
danno@chromium.org's avatar
danno@chromium.org committed
4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472
          context()->Plug(eax);
        }
      } else {
        // Result of deleting non-property, non-variable reference is true.
        // The subexpression may have side effects.
        VisitForEffect(expr->expression());
        context()->Plug(true);
      }
      break;
    }

    case Token::VOID: {
      Comment cmnt(masm_, "[ UnaryOperation (VOID)");
      VisitForEffect(expr->expression());
      context()->Plug(isolate()->factory()->undefined_value());
      break;
    }

    case Token::NOT: {
      Comment cmnt(masm_, "[ UnaryOperation (NOT)");
      if (context()->IsEffect()) {
        // Unary NOT has no side effects so it's only necessary to visit the
        // subexpression.  Match the optimizing compiler by not branching.
        VisitForEffect(expr->expression());
      } else if (context()->IsTest()) {
        const TestContext* test = TestContext::cast(context());
        // The labels are swapped for the recursive call.
        VisitForControl(expr->expression(),
                        test->false_label(),
                        test->true_label(),
                        test->fall_through());
        context()->Plug(test->true_label(), test->false_label());
      } else {
        // We handle value contexts explicitly rather than simply visiting
        // for control and plugging the control flow into the context,
        // because we need to prepare a pair of extra administrative AST ids
        // for the optimizing compiler.
4473
        DCHECK(context()->IsAccumulatorValue() || context()->IsStackValue());
danno@chromium.org's avatar
danno@chromium.org committed
4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500
        Label materialize_true, materialize_false, done;
        VisitForControl(expr->expression(),
                        &materialize_false,
                        &materialize_true,
                        &materialize_true);
        __ bind(&materialize_true);
        PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS);
        if (context()->IsAccumulatorValue()) {
          __ mov(eax, isolate()->factory()->true_value());
        } else {
          __ Push(isolate()->factory()->true_value());
        }
        __ jmp(&done, Label::kNear);
        __ bind(&materialize_false);
        PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS);
        if (context()->IsAccumulatorValue()) {
          __ mov(eax, isolate()->factory()->false_value());
        } else {
          __ Push(isolate()->factory()->false_value());
        }
        __ bind(&done);
      }
      break;
    }

    case Token::TYPEOF: {
      Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)");
4501 4502
      {
        AccumulatorValueContext context(this);
danno@chromium.org's avatar
danno@chromium.org committed
4503 4504
        VisitForTypeofValue(expr->expression());
      }
4505 4506 4507
      __ mov(ebx, eax);
      TypeofStub typeof_stub(isolate());
      __ CallStub(&typeof_stub);
danno@chromium.org's avatar
danno@chromium.org committed
4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518
      context()->Plug(eax);
      break;
    }

    default:
      UNREACHABLE();
  }
}


void FullCodeGenerator::VisitCountOperation(CountOperation* expr) {
4519
  DCHECK(expr->expression()->IsValidReferenceExpressionOrThis());
danno@chromium.org's avatar
danno@chromium.org committed
4520 4521 4522 4523

  Comment cmnt(masm_, "[ CountOperation");

  Property* prop = expr->expression()->AsProperty();
4524
  LhsKind assign_type = Property::GetAssignType(prop);
danno@chromium.org's avatar
danno@chromium.org committed
4525 4526 4527

  // Evaluate expression and get value.
  if (assign_type == VARIABLE) {
4528
    DCHECK(expr->expression()->AsVariableProxy()->var() != NULL);
danno@chromium.org's avatar
danno@chromium.org committed
4529 4530 4531 4532 4533 4534 4535
    AccumulatorValueContext context(this);
    EmitVariableLoad(expr->expression()->AsVariableProxy());
  } else {
    // Reserve space for result of postfix operation.
    if (expr->is_postfix() && !context()->IsEffect()) {
      __ push(Immediate(Smi::FromInt(0)));
    }
4536 4537 4538 4539 4540 4541 4542 4543 4544 4545
    switch (assign_type) {
      case NAMED_PROPERTY: {
        // Put the object both on the stack and in the register.
        VisitForStackValue(prop->obj());
        __ mov(LoadDescriptor::ReceiverRegister(), Operand(esp, 0));
        EmitNamedPropertyLoad(prop);
        break;
      }

      case NAMED_SUPER_PROPERTY: {
4546
        VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
4547
        VisitForAccumulatorValue(
4548
            prop->obj()->AsSuperPropertyReference()->home_object());
4549 4550 4551 4552 4553 4554 4555 4556
        __ push(result_register());
        __ push(MemOperand(esp, kPointerSize));
        __ push(result_register());
        EmitNamedSuperPropertyLoad(prop);
        break;
      }

      case KEYED_SUPER_PROPERTY: {
4557 4558
        VisitForStackValue(prop->obj()->AsSuperPropertyReference()->this_var());
        VisitForStackValue(
4559
            prop->obj()->AsSuperPropertyReference()->home_object());
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580
        VisitForAccumulatorValue(prop->key());
        __ push(result_register());
        __ push(MemOperand(esp, 2 * kPointerSize));
        __ push(MemOperand(esp, 2 * kPointerSize));
        __ push(result_register());
        EmitKeyedSuperPropertyLoad(prop);
        break;
      }

      case KEYED_PROPERTY: {
        VisitForStackValue(prop->obj());
        VisitForStackValue(prop->key());
        __ mov(LoadDescriptor::ReceiverRegister(),
               Operand(esp, kPointerSize));                       // Object.
        __ mov(LoadDescriptor::NameRegister(), Operand(esp, 0));  // Key.
        EmitKeyedPropertyLoad(prop);
        break;
      }

      case VARIABLE:
        UNREACHABLE();
danno@chromium.org's avatar
danno@chromium.org committed
4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611
    }
  }

  // We need a second deoptimization point after loading the value
  // in case evaluating the property load my have a side effect.
  if (assign_type == VARIABLE) {
    PrepareForBailout(expr->expression(), TOS_REG);
  } else {
    PrepareForBailoutForId(prop->LoadId(), TOS_REG);
  }

  // Inline smi case if we are in a loop.
  Label done, stub_call;
  JumpPatchSite patch_site(masm_);
  if (ShouldInlineSmiCase(expr->op())) {
    Label slow;
    patch_site.EmitJumpIfNotSmi(eax, &slow, Label::kNear);

    // Save result for postfix expressions.
    if (expr->is_postfix()) {
      if (!context()->IsEffect()) {
        // Save the result on the stack. If we have a named or keyed property
        // we store the result under the receiver that is currently on top
        // of the stack.
        switch (assign_type) {
          case VARIABLE:
            __ push(eax);
            break;
          case NAMED_PROPERTY:
            __ mov(Operand(esp, kPointerSize), eax);
            break;
4612 4613 4614
          case NAMED_SUPER_PROPERTY:
            __ mov(Operand(esp, 2 * kPointerSize), eax);
            break;
danno@chromium.org's avatar
danno@chromium.org committed
4615 4616 4617
          case KEYED_PROPERTY:
            __ mov(Operand(esp, 2 * kPointerSize), eax);
            break;
4618 4619 4620
          case KEYED_SUPER_PROPERTY:
            __ mov(Operand(esp, 3 * kPointerSize), eax);
            break;
danno@chromium.org's avatar
danno@chromium.org committed
4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639
        }
      }
    }

    if (expr->op() == Token::INC) {
      __ add(eax, Immediate(Smi::FromInt(1)));
    } else {
      __ sub(eax, Immediate(Smi::FromInt(1)));
    }
    __ j(no_overflow, &done, Label::kNear);
    // Call stub. Undo operation first.
    if (expr->op() == Token::INC) {
      __ sub(eax, Immediate(Smi::FromInt(1)));
    } else {
      __ add(eax, Immediate(Smi::FromInt(1)));
    }
    __ jmp(&stub_call, Label::kNear);
    __ bind(&slow);
  }
4640 4641 4642 4643 4644
  if (!is_strong(language_mode())) {
    ToNumberStub convert_stub(isolate());
    __ CallStub(&convert_stub);
    PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
  }
danno@chromium.org's avatar
danno@chromium.org committed
4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658

  // Save result for postfix expressions.
  if (expr->is_postfix()) {
    if (!context()->IsEffect()) {
      // Save the result on the stack. If we have a named or keyed property
      // we store the result under the receiver that is currently on top
      // of the stack.
      switch (assign_type) {
        case VARIABLE:
          __ push(eax);
          break;
        case NAMED_PROPERTY:
          __ mov(Operand(esp, kPointerSize), eax);
          break;
4659 4660 4661
        case NAMED_SUPER_PROPERTY:
          __ mov(Operand(esp, 2 * kPointerSize), eax);
          break;
danno@chromium.org's avatar
danno@chromium.org committed
4662 4663 4664
        case KEYED_PROPERTY:
          __ mov(Operand(esp, 2 * kPointerSize), eax);
          break;
4665 4666 4667
        case KEYED_SUPER_PROPERTY:
          __ mov(Operand(esp, 3 * kPointerSize), eax);
          break;
danno@chromium.org's avatar
danno@chromium.org committed
4668 4669 4670 4671
      }
    }
  }

4672
  SetExpressionPosition(expr);
danno@chromium.org's avatar
danno@chromium.org committed
4673 4674 4675 4676 4677

  // Call stub for +1/-1.
  __ bind(&stub_call);
  __ mov(edx, eax);
  __ mov(eax, Immediate(Smi::FromInt(1)));
4678 4679
  Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), expr->binary_op(),
                                              strength(language_mode())).code();
4680
  CallIC(code, expr->CountBinOpFeedbackId());
danno@chromium.org's avatar
danno@chromium.org committed
4681 4682 4683
  patch_site.EmitPatchInfo();
  __ bind(&done);

4684 4685 4686
  if (is_strong(language_mode())) {
    PrepareForBailoutForId(expr->ToNumberId(), TOS_REG);
  }
danno@chromium.org's avatar
danno@chromium.org committed
4687 4688 4689 4690 4691 4692 4693
  // Store the value returned in eax.
  switch (assign_type) {
    case VARIABLE:
      if (expr->is_postfix()) {
        // Perform the assignment as if via '='.
        { EffectContext context(this);
          EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4694
                                 Token::ASSIGN, expr->CountSlot());
danno@chromium.org's avatar
danno@chromium.org committed
4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705
          PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
          context.Plug(eax);
        }
        // For all contexts except EffectContext We have the result on
        // top of the stack.
        if (!context()->IsEffect()) {
          context()->PlugTOS();
        }
      } else {
        // Perform the assignment as if via '='.
        EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(),
4706
                               Token::ASSIGN, expr->CountSlot());
danno@chromium.org's avatar
danno@chromium.org committed
4707 4708 4709 4710 4711
        PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
        context()->Plug(eax);
      }
      break;
    case NAMED_PROPERTY: {
4712
      __ mov(StoreDescriptor::NameRegister(),
4713
             prop->key()->AsLiteral()->value());
4714
      __ pop(StoreDescriptor::ReceiverRegister());
4715 4716 4717 4718 4719 4720
      if (FLAG_vector_stores) {
        EmitLoadStoreICSlot(expr->CountSlot());
        CallStoreIC();
      } else {
        CallStoreIC(expr->CountStoreFeedbackId());
      }
danno@chromium.org's avatar
danno@chromium.org committed
4721 4722 4723 4724 4725 4726 4727 4728 4729 4730
      PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
      if (expr->is_postfix()) {
        if (!context()->IsEffect()) {
          context()->PlugTOS();
        }
      } else {
        context()->Plug(eax);
      }
      break;
    }
4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741
    case NAMED_SUPER_PROPERTY: {
      EmitNamedSuperPropertyStore(prop);
      if (expr->is_postfix()) {
        if (!context()->IsEffect()) {
          context()->PlugTOS();
        }
      } else {
        context()->Plug(eax);
      }
      break;
    }
4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752
    case KEYED_SUPER_PROPERTY: {
      EmitKeyedSuperPropertyStore(prop);
      if (expr->is_postfix()) {
        if (!context()->IsEffect()) {
          context()->PlugTOS();
        }
      } else {
        context()->Plug(eax);
      }
      break;
    }
danno@chromium.org's avatar
danno@chromium.org committed
4753
    case KEYED_PROPERTY: {
4754 4755
      __ pop(StoreDescriptor::NameRegister());
      __ pop(StoreDescriptor::ReceiverRegister());
4756
      Handle<Code> ic =
4757
          CodeFactory::KeyedStoreIC(isolate(), language_mode()).code();
4758 4759 4760 4761 4762 4763
      if (FLAG_vector_stores) {
        EmitLoadStoreICSlot(expr->CountSlot());
        CallIC(ic);
      } else {
        CallIC(ic, expr->CountStoreFeedbackId());
      }
danno@chromium.org's avatar
danno@chromium.org committed
4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802
      PrepareForBailoutForId(expr->AssignmentId(), TOS_REG);
      if (expr->is_postfix()) {
        // Result is on the stack
        if (!context()->IsEffect()) {
          context()->PlugTOS();
        }
      } else {
        context()->Plug(eax);
      }
      break;
    }
  }
}


void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr,
                                                 Expression* sub_expr,
                                                 Handle<String> check) {
  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  { AccumulatorValueContext context(this);
    VisitForTypeofValue(sub_expr);
  }
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);

  Factory* factory = isolate()->factory();
  if (String::Equals(check, factory->number_string())) {
    __ JumpIfSmi(eax, if_true);
    __ cmp(FieldOperand(eax, HeapObject::kMapOffset),
           isolate()->factory()->heap_number_map());
    Split(equal, if_true, if_false, fall_through);
  } else if (String::Equals(check, factory->string_string())) {
    __ JumpIfSmi(eax, if_false);
    __ CmpObjectType(eax, FIRST_NONSTRING_TYPE, edx);
4803
    Split(below, if_true, if_false, fall_through);
danno@chromium.org's avatar
danno@chromium.org committed
4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818
  } else if (String::Equals(check, factory->symbol_string())) {
    __ JumpIfSmi(eax, if_false);
    __ CmpObjectType(eax, SYMBOL_TYPE, edx);
    Split(equal, if_true, if_false, fall_through);
  } else if (String::Equals(check, factory->boolean_string())) {
    __ cmp(eax, isolate()->factory()->true_value());
    __ j(equal, if_true);
    __ cmp(eax, isolate()->factory()->false_value());
    Split(equal, if_true, if_false, fall_through);
  } else if (String::Equals(check, factory->undefined_string())) {
    __ cmp(eax, isolate()->factory()->undefined_value());
    __ j(equal, if_true);
    __ JumpIfSmi(eax, if_false);
    // Check for undetectable objects => true.
    __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
4819 4820
    __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
              1 << Map::kIsUndetectable);
danno@chromium.org's avatar
danno@chromium.org committed
4821 4822 4823
    Split(not_zero, if_true, if_false, fall_through);
  } else if (String::Equals(check, factory->function_string())) {
    __ JumpIfSmi(eax, if_false);
4824 4825 4826 4827 4828
    // Check for callable and not undetectable objects => true.
    __ mov(edx, FieldOperand(eax, HeapObject::kMapOffset));
    __ movzx_b(ecx, FieldOperand(edx, Map::kBitFieldOffset));
    __ and_(ecx, (1 << Map::kIsCallable) | (1 << Map::kIsUndetectable));
    __ cmp(ecx, 1 << Map::kIsCallable);
danno@chromium.org's avatar
danno@chromium.org committed
4829 4830 4831
    Split(equal, if_true, if_false, fall_through);
  } else if (String::Equals(check, factory->object_string())) {
    __ JumpIfSmi(eax, if_false);
4832 4833
    __ cmp(eax, isolate()->factory()->null_value());
    __ j(equal, if_true);
4834 4835
    STATIC_ASSERT(LAST_SPEC_OBJECT_TYPE == LAST_TYPE);
    __ CmpObjectType(eax, FIRST_SPEC_OBJECT_TYPE, edx);
danno@chromium.org's avatar
danno@chromium.org committed
4836
    __ j(below, if_false);
4837
    // Check for callable or undetectable objects => false.
danno@chromium.org's avatar
danno@chromium.org committed
4838
    __ test_b(FieldOperand(edx, Map::kBitFieldOffset),
4839
              (1 << Map::kIsCallable) | (1 << Map::kIsUndetectable));
danno@chromium.org's avatar
danno@chromium.org committed
4840
    Split(zero, if_true, if_false, fall_through);
4841 4842 4843 4844 4845 4846 4847 4848 4849 4850
// clang-format off
#define SIMD128_TYPE(TYPE, Type, type, lane_count, lane_type)   \
  } else if (String::Equals(check, factory->type##_string())) { \
    __ JumpIfSmi(eax, if_false);                                \
    __ cmp(FieldOperand(eax, HeapObject::kMapOffset),           \
           isolate()->factory()->type##_map());                 \
    Split(equal, if_true, if_false, fall_through);
  SIMD128_TYPES(SIMD128_TYPE)
#undef SIMD128_TYPE
    // clang-format on
danno@chromium.org's avatar
danno@chromium.org committed
4851 4852 4853 4854 4855 4856 4857 4858 4859
  } else {
    if (if_false != fall_through) __ jmp(if_false);
  }
  context()->Plug(if_true, if_false);
}


void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) {
  Comment cmnt(masm_, "[ CompareOperation");
4860
  SetExpressionPosition(expr);
danno@chromium.org's avatar
danno@chromium.org committed
4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879

  // First we try a fast inlined version of the compare when one of
  // the operands is a literal.
  if (TryLiteralCompare(expr)) return;

  // Always perform the comparison for its control flow.  Pack the result
  // into the expression's context after the comparison is performed.
  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  Token::Value op = expr->op();
  VisitForStackValue(expr->left());
  switch (op) {
    case Token::IN:
      VisitForStackValue(expr->right());
4880
      __ CallRuntime(Runtime::kHasProperty, 2);
danno@chromium.org's avatar
danno@chromium.org committed
4881 4882 4883 4884 4885 4886
      PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
      __ cmp(eax, isolate()->factory()->true_value());
      Split(equal, if_true, if_false, fall_through);
      break;

    case Token::INSTANCEOF: {
4887 4888 4889
      VisitForAccumulatorValue(expr->right());
      __ Pop(edx);
      InstanceOfStub stub(isolate());
danno@chromium.org's avatar
danno@chromium.org committed
4890
      __ CallStub(&stub);
4891 4892 4893
      PrepareForBailoutBeforeSplit(expr, false, NULL, NULL);
      __ cmp(eax, isolate()->factory()->true_value());
      Split(equal, if_true, if_false, fall_through);
danno@chromium.org's avatar
danno@chromium.org committed
4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913
      break;
    }

    default: {
      VisitForAccumulatorValue(expr->right());
      Condition cc = CompareIC::ComputeCondition(op);
      __ pop(edx);

      bool inline_smi_code = ShouldInlineSmiCase(op);
      JumpPatchSite patch_site(masm_);
      if (inline_smi_code) {
        Label slow_case;
        __ mov(ecx, edx);
        __ or_(ecx, eax);
        patch_site.EmitJumpIfNotSmi(ecx, &slow_case, Label::kNear);
        __ cmp(edx, eax);
        Split(cc, if_true, if_false, NULL);
        __ bind(&slow_case);
      }

4914 4915
      Handle<Code> ic = CodeFactory::CompareIC(
                            isolate(), op, strength(language_mode())).code();
danno@chromium.org's avatar
danno@chromium.org committed
4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976
      CallIC(ic, expr->CompareOperationFeedbackId());
      patch_site.EmitPatchInfo();

      PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);
      __ test(eax, eax);
      Split(cc, if_true, if_false, fall_through);
    }
  }

  // Convert the result of the comparison into one expected for this
  // expression's context.
  context()->Plug(if_true, if_false);
}


void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr,
                                              Expression* sub_expr,
                                              NilValue nil) {
  Label materialize_true, materialize_false;
  Label* if_true = NULL;
  Label* if_false = NULL;
  Label* fall_through = NULL;
  context()->PrepareTest(&materialize_true, &materialize_false,
                         &if_true, &if_false, &fall_through);

  VisitForAccumulatorValue(sub_expr);
  PrepareForBailoutBeforeSplit(expr, true, if_true, if_false);

  Handle<Object> nil_value = nil == kNullValue
      ? isolate()->factory()->null_value()
      : isolate()->factory()->undefined_value();
  if (expr->op() == Token::EQ_STRICT) {
    __ cmp(eax, nil_value);
    Split(equal, if_true, if_false, fall_through);
  } else {
    Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil);
    CallIC(ic, expr->CompareOperationFeedbackId());
    __ test(eax, eax);
    Split(not_zero, if_true, if_false, fall_through);
  }
  context()->Plug(if_true, if_false);
}


void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) {
  __ mov(eax, Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
  context()->Plug(eax);
}


Register FullCodeGenerator::result_register() {
  return eax;
}


Register FullCodeGenerator::context_register() {
  return esi;
}


void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) {
4977
  DCHECK_EQ(POINTER_SIZE_ALIGN(frame_offset), frame_offset);
danno@chromium.org's avatar
danno@chromium.org committed
4978 4979 4980 4981 4982 4983 4984 4985 4986 4987
  __ mov(Operand(ebp, frame_offset), value);
}


void FullCodeGenerator::LoadContextField(Register dst, int context_index) {
  __ mov(dst, ContextOperand(esi, context_index));
}


void FullCodeGenerator::PushFunctionArgumentForContextAllocation() {
4988 4989 4990
  Scope* closure_scope = scope()->ClosureScope();
  if (closure_scope->is_script_scope() ||
      closure_scope->is_module_scope()) {
danno@chromium.org's avatar
danno@chromium.org committed
4991 4992 4993 4994 4995
    // Contexts nested in the native context have a canonical empty function
    // as their closure, not the anonymous closure containing the global
    // code.  Pass a smi sentinel and let the runtime look up the empty
    // function.
    __ push(Immediate(Smi::FromInt(0)));
4996
  } else if (closure_scope->is_eval_scope()) {
danno@chromium.org's avatar
danno@chromium.org committed
4997 4998 4999 5000 5001
    // Contexts nested inside eval code have the same closure as the context
    // calling eval, not the anonymous closure containing the eval code.
    // Fetch it from the context.
    __ push(ContextOperand(esi, Context::CLOSURE_INDEX));
  } else {
5002
    DCHECK(closure_scope->is_function_scope());
danno@chromium.org's avatar
danno@chromium.org committed
5003 5004 5005 5006 5007 5008 5009 5010 5011 5012
    __ push(Operand(ebp, JavaScriptFrameConstants::kFunctionOffset));
  }
}


// ----------------------------------------------------------------------------
// Non-local control flow support.

void FullCodeGenerator::EnterFinallyBlock() {
  // Cook return address on top of stack (smi encoded Code* delta)
5013
  DCHECK(!result_register().is(edx));
danno@chromium.org's avatar
danno@chromium.org committed
5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028
  __ pop(edx);
  __ sub(edx, Immediate(masm_->CodeObject()));
  STATIC_ASSERT(kSmiTagSize + kSmiShiftSize == 1);
  STATIC_ASSERT(kSmiTag == 0);
  __ SmiTag(edx);
  __ push(edx);

  // Store result register while executing finally block.
  __ push(result_register());

  // Store pending message while executing finally block.
  ExternalReference pending_message_obj =
      ExternalReference::address_of_pending_message_obj(isolate());
  __ mov(edx, Operand::StaticVariable(pending_message_obj));
  __ push(edx);
5029 5030

  ClearPendingMessage();
danno@chromium.org's avatar
danno@chromium.org committed
5031 5032 5033 5034
}


void FullCodeGenerator::ExitFinallyBlock() {
5035
  DCHECK(!result_register().is(edx));
danno@chromium.org's avatar
danno@chromium.org committed
5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052
  // Restore pending message from stack.
  __ pop(edx);
  ExternalReference pending_message_obj =
      ExternalReference::address_of_pending_message_obj(isolate());
  __ mov(Operand::StaticVariable(pending_message_obj), edx);

  // Restore result register from stack.
  __ pop(result_register());

  // Uncook return address.
  __ pop(edx);
  __ SmiUntag(edx);
  __ add(edx, Immediate(masm_->CodeObject()));
  __ jmp(edx);
}


5053 5054 5055 5056 5057 5058 5059 5060 5061
void FullCodeGenerator::ClearPendingMessage() {
  DCHECK(!result_register().is(edx));
  ExternalReference pending_message_obj =
      ExternalReference::address_of_pending_message_obj(isolate());
  __ mov(edx, Immediate(isolate()->factory()->the_hole_value()));
  __ mov(Operand::StaticVariable(pending_message_obj), edx);
}


5062
void FullCodeGenerator::EmitLoadStoreICSlot(FeedbackVectorSlot slot) {
5063 5064 5065 5066 5067 5068
  DCHECK(FLAG_vector_stores && !slot.IsInvalid());
  __ mov(VectorStoreICTrampolineDescriptor::SlotRegister(),
         Immediate(SmiFromSlot(slot)));
}


danno@chromium.org's avatar
danno@chromium.org committed
5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123
#undef __


static const byte kJnsInstruction = 0x79;
static const byte kJnsOffset = 0x11;
static const byte kNopByteOne = 0x66;
static const byte kNopByteTwo = 0x90;
#ifdef DEBUG
static const byte kCallInstruction = 0xe8;
#endif


void BackEdgeTable::PatchAt(Code* unoptimized_code,
                            Address pc,
                            BackEdgeState target_state,
                            Code* replacement_code) {
  Address call_target_address = pc - kIntSize;
  Address jns_instr_address = call_target_address - 3;
  Address jns_offset_address = call_target_address - 2;

  switch (target_state) {
    case INTERRUPT:
      //     sub <profiling_counter>, <delta>  ;; Not changed
      //     jns ok
      //     call <interrupt stub>
      //   ok:
      *jns_instr_address = kJnsInstruction;
      *jns_offset_address = kJnsOffset;
      break;
    case ON_STACK_REPLACEMENT:
    case OSR_AFTER_STACK_CHECK:
      //     sub <profiling_counter>, <delta>  ;; Not changed
      //     nop
      //     nop
      //     call <on-stack replacment>
      //   ok:
      *jns_instr_address = kNopByteOne;
      *jns_offset_address = kNopByteTwo;
      break;
  }

  Assembler::set_target_address_at(call_target_address,
                                   unoptimized_code,
                                   replacement_code->entry());
  unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch(
      unoptimized_code, call_target_address, replacement_code);
}


BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState(
    Isolate* isolate,
    Code* unoptimized_code,
    Address pc) {
  Address call_target_address = pc - kIntSize;
  Address jns_instr_address = call_target_address - 3;
5124
  DCHECK_EQ(kCallInstruction, *(call_target_address - 1));
danno@chromium.org's avatar
danno@chromium.org committed
5125 5126

  if (*jns_instr_address == kJnsInstruction) {
5127 5128
    DCHECK_EQ(kJnsOffset, *(call_target_address - 2));
    DCHECK_EQ(isolate->builtins()->InterruptCheck()->entry(),
danno@chromium.org's avatar
danno@chromium.org committed
5129 5130 5131 5132 5133
              Assembler::target_address_at(call_target_address,
                                           unoptimized_code));
    return INTERRUPT;
  }

5134 5135
  DCHECK_EQ(kNopByteOne, *jns_instr_address);
  DCHECK_EQ(kNopByteTwo, *(call_target_address - 2));
danno@chromium.org's avatar
danno@chromium.org committed
5136 5137 5138 5139 5140 5141

  if (Assembler::target_address_at(call_target_address, unoptimized_code) ==
      isolate->builtins()->OnStackReplacement()->entry()) {
    return ON_STACK_REPLACEMENT;
  }

5142
  DCHECK_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(),
danno@chromium.org's avatar
danno@chromium.org committed
5143 5144 5145 5146 5147 5148
            Assembler::target_address_at(call_target_address,
                                         unoptimized_code));
  return OSR_AFTER_STACK_CHECK;
}


5149 5150
}  // namespace internal
}  // namespace v8
danno@chromium.org's avatar
danno@chromium.org committed
5151 5152

#endif  // V8_TARGET_ARCH_X87