lithium-ia32.cc 94 KB
Newer Older
1
// Copyright 2012 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

28 29
#include "v8.h"

30
#if V8_TARGET_ARCH_IA32
31

32
#include "lithium-allocator-inl.h"
33 34
#include "ia32/lithium-ia32.h"
#include "ia32/lithium-codegen-ia32.h"
35
#include "hydrogen-osr.h"
36 37 38 39 40 41 42 43 44 45 46 47

namespace v8 {
namespace internal {

#define DEFINE_COMPILE(type)                            \
  void L##type::CompileToNative(LCodeGen* generator) {  \
    generator->Do##type(this);                          \
  }
LITHIUM_CONCRETE_INSTRUCTION_LIST(DEFINE_COMPILE)
#undef DEFINE_COMPILE


48 49
#ifdef DEBUG
void LInstruction::VerifyCall() {
50 51 52 53
  // Call instructions can use only fixed registers as temporaries and
  // outputs because all registers are blocked by the calling convention.
  // Inputs operands must use a fixed register or use-at-start policy or
  // a non-register policy.
54 55 56
  ASSERT(Output() == NULL ||
         LUnallocated::cast(Output())->HasFixedPolicy() ||
         !LUnallocated::cast(Output())->HasRegisterPolicy());
57 58
  for (UseIterator it(this); !it.Done(); it.Advance()) {
    LUnallocated* operand = LUnallocated::cast(it.Current());
59 60
    ASSERT(operand->HasFixedPolicy() ||
           operand->IsUsedAtStart());
61
  }
62 63
  for (TempIterator it(this); !it.Done(); it.Advance()) {
    LUnallocated* operand = LUnallocated::cast(it.Current());
64
    ASSERT(operand->HasFixedPolicy() ||!operand->HasRegisterPolicy());
65 66 67 68 69
  }
}
#endif


70 71 72 73 74 75 76 77
bool LInstruction::HasDoubleRegisterResult() {
  return HasResult() && result()->IsDoubleRegister();
}


bool LInstruction::HasDoubleRegisterInput() {
  for (int i = 0; i < InputCount(); i++) {
    LOperand* op = InputAt(i);
78
    if (op != NULL && op->IsDoubleRegister()) {
79 80 81 82 83 84 85
      return true;
    }
  }
  return false;
}


86 87 88 89 90 91 92 93 94 95 96
bool LInstruction::IsDoubleInput(X87Register reg, LCodeGen* cgen) {
  for (int i = 0; i < InputCount(); i++) {
    LOperand* op = InputAt(i);
    if (op != NULL && op->IsDoubleRegister()) {
      if (cgen->ToX87Register(op).is(reg)) return true;
    }
  }
  return false;
}


97
void LInstruction::PrintTo(StringStream* stream) {
98
  stream->Add("%s ", this->Mnemonic());
99 100

  PrintOutputOperandTo(stream);
101

102 103 104 105 106 107 108 109 110 111 112 113 114 115
  PrintDataTo(stream);

  if (HasEnvironment()) {
    stream->Add(" ");
    environment()->PrintTo(stream);
  }

  if (HasPointerMap()) {
    stream->Add(" ");
    pointer_map()->PrintTo(stream);
  }
}


116
void LInstruction::PrintDataTo(StringStream* stream) {
117
  stream->Add("= ");
118
  for (int i = 0; i < InputCount(); i++) {
119
    if (i > 0) stream->Add(" ");
120 121 122 123 124
    if (InputAt(i) == NULL) {
      stream->Add("NULL");
    } else {
      InputAt(i)->PrintTo(stream);
    }
125
  }
126 127 128
}


129 130
void LInstruction::PrintOutputOperandTo(StringStream* stream) {
  if (HasResult()) result()->PrintTo(stream);
131 132 133
}


134
void LLabel::PrintDataTo(StringStream* stream) {
fschneider@chromium.org's avatar
fschneider@chromium.org committed
135
  LGap::PrintDataTo(stream);
136 137 138 139 140 141 142 143 144 145 146 147 148
  LLabel* rep = replacement();
  if (rep != NULL) {
    stream->Add(" Dead block replaced with B%d", rep->block_id());
  }
}


bool LGap::IsRedundant() const {
  for (int i = 0; i < 4; i++) {
    if (parallel_moves_[i] != NULL && !parallel_moves_[i]->IsRedundant()) {
      return false;
    }
  }
fschneider@chromium.org's avatar
fschneider@chromium.org committed
149

150 151 152 153
  return true;
}


154
void LGap::PrintDataTo(StringStream* stream) {
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
  for (int i = 0; i < 4; i++) {
    stream->Add("(");
    if (parallel_moves_[i] != NULL) {
      parallel_moves_[i]->PrintDataTo(stream);
    }
    stream->Add(") ");
  }
}


const char* LArithmeticD::Mnemonic() const {
  switch (op()) {
    case Token::ADD: return "add-d";
    case Token::SUB: return "sub-d";
    case Token::MUL: return "mul-d";
    case Token::DIV: return "div-d";
    case Token::MOD: return "mod-d";
    default:
      UNREACHABLE();
      return NULL;
  }
}


const char* LArithmeticT::Mnemonic() const {
  switch (op()) {
    case Token::ADD: return "add-t";
    case Token::SUB: return "sub-t";
    case Token::MUL: return "mul-t";
    case Token::MOD: return "mod-t";
    case Token::DIV: return "div-t";
186 187 188
    case Token::BIT_AND: return "bit-and-t";
    case Token::BIT_OR: return "bit-or-t";
    case Token::BIT_XOR: return "bit-xor-t";
189
    case Token::ROR: return "ror-t";
190 191 192
    case Token::SHL: return "sal-t";
    case Token::SAR: return "sar-t";
    case Token::SHR: return "shr-t";
193 194 195 196 197 198 199
    default:
      UNREACHABLE();
      return NULL;
  }
}


200 201 202 203 204
bool LGoto::HasInterestingComment(LCodeGen* gen) const {
  return !gen->IsNextEmittedBlock(block_id());
}


205
void LGoto::PrintDataTo(StringStream* stream) {
206 207 208 209
  stream->Add("B%d", block_id());
}


210
void LBranch::PrintDataTo(StringStream* stream) {
211
  stream->Add("B%d | B%d on ", true_block_id(), false_block_id());
212
  value()->PrintTo(stream);
213 214 215
}


216
void LCompareNumericAndBranch::PrintDataTo(StringStream* stream) {
217
  stream->Add("if ");
218
  left()->PrintTo(stream);
219
  stream->Add(" %s ", Token::String(op()));
220
  right()->PrintTo(stream);
221 222 223 224
  stream->Add(" then B%d else B%d", true_block_id(), false_block_id());
}


225
void LIsObjectAndBranch::PrintDataTo(StringStream* stream) {
226
  stream->Add("if is_object(");
227
  value()->PrintTo(stream);
228 229 230 231
  stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}


232 233
void LIsStringAndBranch::PrintDataTo(StringStream* stream) {
  stream->Add("if is_string(");
234
  value()->PrintTo(stream);
235 236 237 238
  stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}


239
void LIsSmiAndBranch::PrintDataTo(StringStream* stream) {
240
  stream->Add("if is_smi(");
241
  value()->PrintTo(stream);
242 243 244 245
  stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}


246 247
void LIsUndetectableAndBranch::PrintDataTo(StringStream* stream) {
  stream->Add("if is_undetectable(");
248
  value()->PrintTo(stream);
249 250 251 252
  stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}


253 254
void LStringCompareAndBranch::PrintDataTo(StringStream* stream) {
  stream->Add("if string_compare(");
255 256
  left()->PrintTo(stream);
  right()->PrintTo(stream);
257 258 259 260
  stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}


261
void LHasInstanceTypeAndBranch::PrintDataTo(StringStream* stream) {
262
  stream->Add("if has_instance_type(");
263
  value()->PrintTo(stream);
264 265 266 267
  stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}


268
void LHasCachedArrayIndexAndBranch::PrintDataTo(StringStream* stream) {
269
  stream->Add("if has_cached_array_index(");
270
  value()->PrintTo(stream);
271 272 273 274
  stream->Add(") then B%d else B%d", true_block_id(), false_block_id());
}


275
void LClassOfTestAndBranch::PrintDataTo(StringStream* stream) {
276
  stream->Add("if class_of_test(");
277
  value()->PrintTo(stream);
278 279 280 281 282 283 284
  stream->Add(", \"%o\") then B%d else B%d",
              *hydrogen()->class_name(),
              true_block_id(),
              false_block_id());
}


285
void LTypeofIsAndBranch::PrintDataTo(StringStream* stream) {
286
  stream->Add("if typeof ");
287
  value()->PrintTo(stream);
288 289 290 291 292 293
  stream->Add(" == \"%s\" then B%d else B%d",
              *hydrogen()->type_literal()->ToCString(),
              true_block_id(), false_block_id());
}


294 295 296 297 298 299 300 301
void LStoreCodeEntry::PrintDataTo(StringStream* stream) {
  stream->Add(" = ");
  function()->PrintTo(stream);
  stream->Add(".code_entry = ");
  code_object()->PrintTo(stream);
}


302 303 304
void LInnerAllocatedObject::PrintDataTo(StringStream* stream) {
  stream->Add(" = ");
  base_object()->PrintTo(stream);
305 306
  stream->Add(" + ");
  offset()->PrintTo(stream);
307 308 309
}


310
void LCallConstantFunction::PrintDataTo(StringStream* stream) {
311 312 313 314
  stream->Add("#%d / ", arity());
}


315
void LLoadContextSlot::PrintDataTo(StringStream* stream) {
316
  context()->PrintTo(stream);
317 318 319 320 321
  stream->Add("[%d]", slot_index());
}


void LStoreContextSlot::PrintDataTo(StringStream* stream) {
322
  context()->PrintTo(stream);
323
  stream->Add("[%d] <- ", slot_index());
324
  value()->PrintTo(stream);
325 326 327
}


328 329
void LInvokeFunction::PrintDataTo(StringStream* stream) {
  stream->Add("= ");
330
  context()->PrintTo(stream);
331
  stream->Add(" ");
332
  function()->PrintTo(stream);
333 334 335 336
  stream->Add(" #%d / ", arity());
}


337
void LCallKeyed::PrintDataTo(StringStream* stream) {
338 339 340 341
  stream->Add("[ecx] #%d / ", arity());
}


342
void LCallNamed::PrintDataTo(StringStream* stream) {
343
  SmartArrayPointer<char> name_string = name()->ToCString();
344 345 346 347
  stream->Add("%s #%d / ", *name_string, arity());
}


348
void LCallGlobal::PrintDataTo(StringStream* stream) {
349
  SmartArrayPointer<char> name_string = name()->ToCString();
350 351 352 353
  stream->Add("%s #%d / ", *name_string, arity());
}


354
void LCallKnownGlobal::PrintDataTo(StringStream* stream) {
355 356 357 358
  stream->Add("#%d / ", arity());
}


359
void LCallNew::PrintDataTo(StringStream* stream) {
360
  stream->Add("= ");
361 362 363
  context()->PrintTo(stream);
  stream->Add(" ");
  constructor()->PrintTo(stream);
364 365 366 367
  stream->Add(" #%d / ", arity());
}


368 369 370 371 372 373
void LCallNewArray::PrintDataTo(StringStream* stream) {
  stream->Add("= ");
  context()->PrintTo(stream);
  stream->Add(" ");
  constructor()->PrintTo(stream);
  stream->Add(" #%d / ", arity());
374
  ElementsKind kind = hydrogen()->elements_kind();
375 376 377 378
  stream->Add(" (%s) ", ElementsKindToString(kind));
}


379
void LAccessArgumentsAt::PrintDataTo(StringStream* stream) {
380 381 382 383 384 385 386 387 388 389
  arguments()->PrintTo(stream);

  stream->Add(" length ");
  length()->PrintTo(stream);

  stream->Add(" index ");
  index()->PrintTo(stream);
}


390
int LPlatformChunk::GetNextSpillIndex(RegisterKind kind) {
391
  // Skip a slot if for a double-width slot.
392
  if (kind == DOUBLE_REGISTERS) {
393 394 395 396
    spill_slot_count_++;
    spill_slot_count_ |= 1;
    num_double_slots_++;
  }
397 398 399 400
  return spill_slot_count_++;
}


401 402 403
LOperand* LPlatformChunk::GetNextSpillSlot(RegisterKind kind) {
  int index = GetNextSpillIndex(kind);
  if (kind == DOUBLE_REGISTERS) {
404
    return LDoubleStackSlot::Create(index, zone());
405
  } else {
406
    ASSERT(kind == GENERAL_REGISTERS);
407
    return LStackSlot::Create(index, zone());
408 409 410 411
  }
}


412
void LStoreNamedField::PrintDataTo(StringStream* stream) {
413
  object()->PrintTo(stream);
414
  hydrogen()->access().PrintTo(stream);
415 416 417 418 419
  stream->Add(" <- ");
  value()->PrintTo(stream);
}


420 421 422 423 424 425 426 427 428
void LStoreNamedGeneric::PrintDataTo(StringStream* stream) {
  object()->PrintTo(stream);
  stream->Add(".");
  stream->Add(*String::cast(*name())->ToCString());
  stream->Add(" <- ");
  value()->PrintTo(stream);
}


429 430 431 432 433 434 435 436 437 438 439 440
void LLoadKeyed::PrintDataTo(StringStream* stream) {
  elements()->PrintTo(stream);
  stream->Add("[");
  key()->PrintTo(stream);
  if (hydrogen()->IsDehoisted()) {
    stream->Add(" + %d]", additional_index());
  } else {
    stream->Add("]");
  }
}


441
void LStoreKeyed::PrintDataTo(StringStream* stream) {
442 443 444
  elements()->PrintTo(stream);
  stream->Add("[");
  key()->PrintTo(stream);
445 446 447 448 449
  if (hydrogen()->IsDehoisted()) {
    stream->Add(" + %d] <-", additional_index());
  } else {
    stream->Add("] <- ");
  }
450 451 452 453 454 455 456 457

  if (value() == NULL) {
    ASSERT(hydrogen()->IsConstantHoleStore() &&
           hydrogen()->value()->representation().IsDouble());
    stream->Add("<the hole(nan)>");
  } else {
    value()->PrintTo(stream);
  }
458 459 460
}


461
void LStoreKeyedGeneric::PrintDataTo(StringStream* stream) {
462 463 464 465 466 467 468 469
  object()->PrintTo(stream);
  stream->Add("[");
  key()->PrintTo(stream);
  stream->Add("] <- ");
  value()->PrintTo(stream);
}


470 471 472 473 474 475
void LTransitionElementsKind::PrintDataTo(StringStream* stream) {
  object()->PrintTo(stream);
  stream->Add(" %p -> %p", *original_map(), *transitioned_map());
}


476
LPlatformChunk* LChunkBuilder::Build() {
477
  ASSERT(is_unused());
478
  chunk_ = new(zone()) LPlatformChunk(info(), graph());
479
  LPhase phase("L_Building chunk", chunk_);
480
  status_ = BUILDING;
481 482

  // Reserve the first spill slot for the state of dynamic alignment.
483
  if (info()->IsOptimizing()) {
484
    int alignment_state_index = chunk_->GetNextSpillIndex(GENERAL_REGISTERS);
485 486 487
    ASSERT_EQ(alignment_state_index, 0);
    USE(alignment_state_index);
  }
488

489 490 491 492
  // If compiling for OSR, reserve space for the unoptimized frame,
  // which will be subsumed into this frame.
  if (graph()->has_osr()) {
    for (int i = graph()->osr()->UnoptimizedFrameSlots(); i > 0; i--) {
493
      chunk_->GetNextSpillIndex(GENERAL_REGISTERS);
494 495 496
    }
  }

497 498 499 500 501 502 503 504 505 506 507 508
  const ZoneList<HBasicBlock*>* blocks = graph()->blocks();
  for (int i = 0; i < blocks->length(); i++) {
    HBasicBlock* next = NULL;
    if (i < blocks->length() - 1) next = blocks->at(i + 1);
    DoBasicBlock(blocks->at(i), next);
    if (is_aborted()) return NULL;
  }
  status_ = DONE;
  return chunk_;
}


509
void LChunkBuilder::Abort(BailoutReason reason) {
510
  info()->set_bailout_reason(reason);
511 512 513 514 515
  status_ = ABORTED;
}


LUnallocated* LChunkBuilder::ToUnallocated(Register reg) {
516 517
  return new(zone()) LUnallocated(LUnallocated::FIXED_REGISTER,
                                  Register::ToAllocationIndex(reg));
518 519 520 521
}


LUnallocated* LChunkBuilder::ToUnallocated(XMMRegister reg) {
522 523
  return new(zone()) LUnallocated(LUnallocated::FIXED_DOUBLE_REGISTER,
                                  XMMRegister::ToAllocationIndex(reg));
524 525 526 527 528 529 530 531 532 533 534 535 536 537
}


LOperand* LChunkBuilder::UseFixed(HValue* value, Register fixed_register) {
  return Use(value, ToUnallocated(fixed_register));
}


LOperand* LChunkBuilder::UseFixedDouble(HValue* value, XMMRegister reg) {
  return Use(value, ToUnallocated(reg));
}


LOperand* LChunkBuilder::UseRegister(HValue* value) {
538
  return Use(value, new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER));
539 540 541 542 543
}


LOperand* LChunkBuilder::UseRegisterAtStart(HValue* value) {
  return Use(value,
544 545
             new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER,
                                      LUnallocated::USED_AT_START));
546 547 548 549
}


LOperand* LChunkBuilder::UseTempRegister(HValue* value) {
550
  return Use(value, new(zone()) LUnallocated(LUnallocated::WRITABLE_REGISTER));
551 552 553 554
}


LOperand* LChunkBuilder::Use(HValue* value) {
555
  return Use(value, new(zone()) LUnallocated(LUnallocated::NONE));
556 557 558 559
}


LOperand* LChunkBuilder::UseAtStart(HValue* value) {
560 561
  return Use(value, new(zone()) LUnallocated(LUnallocated::NONE,
                                             LUnallocated::USED_AT_START));
562 563 564
}


565 566 567 568 569
static inline bool CanBeImmediateConstant(HValue* value) {
  return value->IsConstant() && HConstant::cast(value)->NotInNewSpace();
}


570
LOperand* LChunkBuilder::UseOrConstant(HValue* value) {
571
  return CanBeImmediateConstant(value)
572 573 574 575 576 577
      ? chunk_->DefineConstantOperand(HConstant::cast(value))
      : Use(value);
}


LOperand* LChunkBuilder::UseOrConstantAtStart(HValue* value) {
578
  return CanBeImmediateConstant(value)
579 580 581 582 583
      ? chunk_->DefineConstantOperand(HConstant::cast(value))
      : UseAtStart(value);
}


584 585 586 587 588 589 590 591
LOperand* LChunkBuilder::UseFixedOrConstant(HValue* value,
                                            Register fixed_register) {
  return CanBeImmediateConstant(value)
      ? chunk_->DefineConstantOperand(HConstant::cast(value))
      : UseFixed(value, fixed_register);
}


592
LOperand* LChunkBuilder::UseRegisterOrConstant(HValue* value) {
593
  return CanBeImmediateConstant(value)
594 595 596 597 598 599
      ? chunk_->DefineConstantOperand(HConstant::cast(value))
      : UseRegister(value);
}


LOperand* LChunkBuilder::UseRegisterOrConstantAtStart(HValue* value) {
600
  return CanBeImmediateConstant(value)
601 602 603 604 605
      ? chunk_->DefineConstantOperand(HConstant::cast(value))
      : UseRegisterAtStart(value);
}


606 607 608 609 610
LOperand* LChunkBuilder::UseConstant(HValue* value) {
  return chunk_->DefineConstantOperand(HConstant::cast(value));
}


611 612 613
LOperand* LChunkBuilder::UseAny(HValue* value) {
  return value->IsConstant()
      ? chunk_->DefineConstantOperand(HConstant::cast(value))
614
      :  Use(value, new(zone()) LUnallocated(LUnallocated::ANY));
615 616 617
}


618 619 620 621 622
LOperand* LChunkBuilder::Use(HValue* value, LUnallocated* operand) {
  if (value->EmitAtUses()) {
    HInstruction* instr = HInstruction::cast(value);
    VisitInstruction(instr);
  }
623
  operand->set_virtual_register(value->id());
624 625 626 627
  return operand;
}


628 629 630
template<int I, int T>
LInstruction* LChunkBuilder::Define(LTemplateInstruction<1, I, T>* instr,
                                    LUnallocated* result) {
631
  result->set_virtual_register(current_instruction_->id());
632 633 634 635 636 637 638 639
  instr->set_result(result);
  return instr;
}


template<int I, int T>
LInstruction* LChunkBuilder::DefineAsRegister(
    LTemplateInstruction<1, I, T>* instr) {
640 641
  return Define(instr,
                new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER));
642 643 644
}


645 646 647 648
template<int I, int T>
LInstruction* LChunkBuilder::DefineAsSpilled(
    LTemplateInstruction<1, I, T>* instr,
    int index) {
649 650
  return Define(instr,
                new(zone()) LUnallocated(LUnallocated::FIXED_SLOT, index));
651 652 653
}


654 655 656
template<int I, int T>
LInstruction* LChunkBuilder::DefineSameAsFirst(
    LTemplateInstruction<1, I, T>* instr) {
657 658
  return Define(instr,
                new(zone()) LUnallocated(LUnallocated::SAME_AS_FIRST_INPUT));
659 660 661
}


662 663
template<int I, int T>
LInstruction* LChunkBuilder::DefineFixed(LTemplateInstruction<1, I, T>* instr,
664
                                         Register reg) {
665 666 667 668
  return Define(instr, ToUnallocated(reg));
}


669 670 671 672
template<int I, int T>
LInstruction* LChunkBuilder::DefineFixedDouble(
    LTemplateInstruction<1, I, T>* instr,
    XMMRegister reg) {
673 674 675 676 677 678
  return Define(instr, ToUnallocated(reg));
}


LInstruction* LChunkBuilder::AssignEnvironment(LInstruction* instr) {
  HEnvironment* hydrogen_env = current_block_->last_environment();
679
  int argument_index_accumulator = 0;
680
  ZoneList<HValue*> objects_to_materialize(0, zone());
681
  instr->set_environment(CreateEnvironment(hydrogen_env,
682 683
                                           &argument_index_accumulator,
                                           &objects_to_materialize));
684 685 686 687 688 689 690
  return instr;
}


LInstruction* LChunkBuilder::MarkAsCall(LInstruction* instr,
                                        HInstruction* hinstr,
                                        CanDeoptimize can_deoptimize) {
691 692
  info()->MarkAsNonDeferredCalling();

693 694 695 696
#ifdef DEBUG
  instr->VerifyCall();
#endif
  instr->MarkAsCall();
697 698
  instr = AssignPointerMap(instr);

699
  if (hinstr->HasObservableSideEffects()) {
700 701
    ASSERT(hinstr->next()->IsSimulate());
    HSimulate* sim = HSimulate::cast(hinstr->next());
702
    ASSERT(instruction_pending_deoptimization_environment_ == NULL);
703
    ASSERT(pending_deoptimization_ast_id_.IsNone());
704
    instruction_pending_deoptimization_environment_ = instr;
705
    pending_deoptimization_ast_id_ = sim->ast_id();
706 707 708 709 710 711 712
  }

  // If instruction does not have side-effects lazy deoptimization
  // after the call will try to deoptimize to the point before the call.
  // Thus we still need to attach environment to this call even if
  // call sequence can not deoptimize eagerly.
  bool needs_environment =
713 714
      (can_deoptimize == CAN_DEOPTIMIZE_EAGERLY) ||
      !hinstr->HasObservableSideEffects();
715 716 717 718 719 720 721 722 723 724
  if (needs_environment && !instr->HasEnvironment()) {
    instr = AssignEnvironment(instr);
  }

  return instr;
}


LInstruction* LChunkBuilder::AssignPointerMap(LInstruction* instr) {
  ASSERT(!instr->HasPointerMap());
725
  instr->set_pointer_map(new(zone()) LPointerMap(zone()));
726 727 728 729 730
  return instr;
}


LUnallocated* LChunkBuilder::TempRegister() {
731 732
  LUnallocated* operand =
      new(zone()) LUnallocated(LUnallocated::MUST_HAVE_REGISTER);
733
  int vreg = allocator_->GetVirtualRegister();
734
  if (!allocator_->AllocationOk()) {
735
    Abort(kOutOfVirtualRegistersWhileTryingToAllocateTempRegister);
736
    vreg = 0;
737
  }
738
  operand->set_virtual_register(vreg);
739 740 741 742 743 744
  return operand;
}


LOperand* LChunkBuilder::FixedTemp(Register reg) {
  LUnallocated* operand = ToUnallocated(reg);
745
  ASSERT(operand->HasFixedPolicy());
746 747 748 749 750 751
  return operand;
}


LOperand* LChunkBuilder::FixedTemp(XMMRegister reg) {
  LUnallocated* operand = ToUnallocated(reg);
752
  ASSERT(operand->HasFixedPolicy());
753 754 755 756 757
  return operand;
}


LInstruction* LChunkBuilder::DoBlockEntry(HBlockEntry* instr) {
758
  return new(zone()) LLabel(instr->block());
759 760 761
}


762 763 764 765 766
LInstruction* LChunkBuilder::DoDummyUse(HDummyUse* instr) {
  return DefineAsRegister(new(zone()) LDummyUse(UseAny(instr->value())));
}


767 768 769 770 771 772
LInstruction* LChunkBuilder::DoEnvironmentMarker(HEnvironmentMarker* instr) {
  UNREACHABLE();
  return NULL;
}


773
LInstruction* LChunkBuilder::DoDeoptimize(HDeoptimize* instr) {
774
  return AssignEnvironment(new(zone()) LDeoptimize);
775 776 777 778 779
}


LInstruction* LChunkBuilder::DoShift(Token::Value op,
                                     HBitwiseBinaryOperation* instr) {
780 781 782 783
  if (instr->representation().IsSmiOrInteger32()) {
    ASSERT(instr->left()->representation().Equals(instr->representation()));
    ASSERT(instr->right()->representation().Equals(instr->representation()));
    LOperand* left = UseRegisterAtStart(instr->left());
784

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    HValue* right_value = instr->right();
    LOperand* right = NULL;
    int constant_value = 0;
    bool does_deopt = false;
    if (right_value->IsConstant()) {
      HConstant* constant = HConstant::cast(right_value);
      right = chunk_->DefineConstantOperand(constant);
      constant_value = constant->Integer32Value() & 0x1f;
      // Left shifts can deoptimize if we shift by > 0 and the result cannot be
      // truncated to smi.
      if (instr->representation().IsSmi() && constant_value > 0) {
        does_deopt = !instr->CheckUsesForFlag(HValue::kTruncatingToSmi);
      }
    } else {
      right = UseFixed(right_value, ecx);
800
    }
801

802 803 804 805 806 807 808 809
    // Shift operations can only deoptimize if we do a logical shift by 0 and
    // the result cannot be truncated to int32.
    if (op == Token::SHR && constant_value == 0) {
      if (FLAG_opt_safe_uint32_operations) {
        does_deopt = !instr->CheckFlag(HInstruction::kUint32);
      } else {
        does_deopt = !instr->CheckUsesForFlag(HValue::kTruncatingToInt32);
      }
810 811
    }

812 813 814 815 816 817
    LInstruction* result =
        DefineSameAsFirst(new(zone()) LShiftI(op, left, right, does_deopt));
    return does_deopt ? AssignEnvironment(result) : result;
  } else {
    return DoArithmeticT(op, instr);
  }
818 819 820 821 822 823 824 825
}


LInstruction* LChunkBuilder::DoArithmeticD(Token::Value op,
                                           HArithmeticBinaryOperation* instr) {
  ASSERT(instr->representation().IsDouble());
  ASSERT(instr->left()->representation().IsDouble());
  ASSERT(instr->right()->representation().IsDouble());
826 827 828 829 830 831 832 833 834 835 836
  if (op == Token::MOD) {
    LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
    LOperand* right = UseRegisterAtStart(instr->BetterRightOperand());
    LArithmeticD* result = new(zone()) LArithmeticD(op, left, right);
    return MarkAsCall(DefineSameAsFirst(result), instr);
  } else {
    LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
    LOperand* right = UseRegisterAtStart(instr->BetterRightOperand());
    LArithmeticD* result = new(zone()) LArithmeticD(op, left, right);
    return DefineSameAsFirst(result);
  }
837 838 839 840
}


LInstruction* LChunkBuilder::DoArithmeticT(Token::Value op,
841
                                           HBinaryOperation* instr) {
842 843
  HValue* left = instr->left();
  HValue* right = instr->right();
844 845
  ASSERT(left->representation().IsTagged());
  ASSERT(right->representation().IsTagged());
846
  LOperand* context = UseFixed(instr->context(), esi);
847 848
  LOperand* left_operand = UseFixed(left, edx);
  LOperand* right_operand = UseFixed(right, eax);
849
  LArithmeticT* result =
850
      new(zone()) LArithmeticT(op, context, left_operand, right_operand);
851 852 853
  return MarkAsCall(DefineFixed(result, eax), instr);
}

854

855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
void LChunkBuilder::DoBasicBlock(HBasicBlock* block, HBasicBlock* next_block) {
  ASSERT(is_building());
  current_block_ = block;
  next_block_ = next_block;
  if (block->IsStartBlock()) {
    block->UpdateEnvironment(graph_->start_environment());
    argument_count_ = 0;
  } else if (block->predecessors()->length() == 1) {
    // We have a single predecessor => copy environment and outgoing
    // argument count from the predecessor.
    ASSERT(block->phis()->length() == 0);
    HBasicBlock* pred = block->predecessors()->at(0);
    HEnvironment* last_environment = pred->last_environment();
    ASSERT(last_environment != NULL);
    // Only copy the environment, if it is later used again.
    if (pred->end()->SecondSuccessor() == NULL) {
      ASSERT(pred->end()->FirstSuccessor() == block);
    } else {
      if (pred->end()->FirstSuccessor()->block_id() > block->block_id() ||
          pred->end()->SecondSuccessor()->block_id() > block->block_id()) {
        last_environment = last_environment->Copy();
      }
    }
    block->UpdateEnvironment(last_environment);
    ASSERT(pred->argument_count() >= 0);
    argument_count_ = pred->argument_count();
  } else {
    // We are at a state join => process phis.
    HBasicBlock* pred = block->predecessors()->at(0);
    // No need to copy the environment, it cannot be used later.
    HEnvironment* last_environment = pred->last_environment();
    for (int i = 0; i < block->phis()->length(); ++i) {
      HPhi* phi = block->phis()->at(i);
888
      if (phi->HasMergedIndex()) {
889 890
        last_environment->SetValueAt(phi->merged_index(), phi);
      }
891 892
    }
    for (int i = 0; i < block->deleted_phis()->length(); ++i) {
893 894 895 896
      if (block->deleted_phis()->at(i) < last_environment->length()) {
        last_environment->SetValueAt(block->deleted_phis()->at(i),
                                     graph_->GetConstantUndefined());
      }
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    }
    block->UpdateEnvironment(last_environment);
    // Pick up the outgoing argument count of one of the predecessors.
    argument_count_ = pred->argument_count();
  }
  HInstruction* current = block->first();
  int start = chunk_->instructions()->length();
  while (current != NULL && !is_aborted()) {
    // Code for constants in registers is generated lazily.
    if (!current->EmitAtUses()) {
      VisitInstruction(current);
    }
    current = current->next();
  }
  int end = chunk_->instructions()->length() - 1;
  if (end >= start) {
    block->set_first_instruction_index(start);
    block->set_last_instruction_index(end);
  }
  block->set_argument_count(argument_count_);
  next_block_ = NULL;
  current_block_ = NULL;
}


void LChunkBuilder::VisitInstruction(HInstruction* current) {
  HInstruction* old_current = current_instruction_;
  current_instruction_ = current;
925 926 927

  LInstruction* instr = NULL;
  if (current->CanReplaceWithDummyUses()) {
928 929 930 931 932 933
    if (current->OperandCount() == 0) {
      instr = DefineAsRegister(new(zone()) LDummy());
    } else {
      instr = DefineAsRegister(new(zone())
          LDummyUse(UseAny(current->OperandAt(0))));
    }
934 935 936 937 938 939 940 941 942
    for (int i = 1; i < current->OperandCount(); ++i) {
      LInstruction* dummy =
          new(zone()) LDummyUse(UseAny(current->OperandAt(i)));
      dummy->set_hydrogen_value(current);
      chunk_->AddInstruction(dummy, current_block_);
    }
  } else {
    instr = current->CompileToLithium(this);
  }
943

944 945 946
  argument_count_ += current->argument_delta();
  ASSERT(argument_count_ >= 0);

947
  if (instr != NULL) {
948 949 950 951
    // Associate the hydrogen instruction first, since we may need it for
    // the ClobbersRegisters() or ClobbersDoubleRegisters() calls below.
    instr->set_hydrogen_value(current);

952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
#if DEBUG
    // Make sure that the lithium instruction has either no fixed register
    // constraints in temps or the result OR no uses that are only used at
    // start. If this invariant doesn't hold, the register allocator can decide
    // to insert a split of a range immediately before the instruction due to an
    // already allocated register needing to be used for the instruction's fixed
    // register constraint. In this case, The register allocator won't see an
    // interference between the split child and the use-at-start (it would if
    // the it was just a plain use), so it is free to move the split child into
    // the same register that is used for the use-at-start.
    // See https://code.google.com/p/chromium/issues/detail?id=201590
    if (!(instr->ClobbersRegisters() && instr->ClobbersDoubleRegisters())) {
      int fixed = 0;
      int used_at_start = 0;
      for (UseIterator it(instr); !it.Done(); it.Advance()) {
        LUnallocated* operand = LUnallocated::cast(it.Current());
        if (operand->IsUsedAtStart()) ++used_at_start;
      }
      if (instr->Output() != NULL) {
        if (LUnallocated::cast(instr->Output())->HasFixedPolicy()) ++fixed;
      }
      for (TempIterator it(instr); !it.Done(); it.Advance()) {
        LUnallocated* operand = LUnallocated::cast(it.Current());
        if (operand->HasFixedPolicy()) ++fixed;
      }
      ASSERT(fixed == 0 || used_at_start == 0);
    }
#endif

981 982 983 984 985 986
    if (FLAG_stress_pointer_maps && !instr->HasPointerMap()) {
      instr = AssignPointerMap(instr);
    }
    if (FLAG_stress_environments && !instr->HasEnvironment()) {
      instr = AssignEnvironment(instr);
    }
987 988 989 990 991 992 993 994 995 996
    if (!CpuFeatures::IsSafeForSnapshot(SSE2) && instr->IsGoto() &&
        LGoto::cast(instr)->jumps_to_join()) {
      // TODO(olivf) Since phis of spilled values are joined as registers
      // (not in the stack slot), we need to allow the goto gaps to keep one
      // x87 register alive. To ensure all other values are still spilled, we
      // insert a fpu register barrier right before.
      LClobberDoubles* clobber = new(zone()) LClobberDoubles();
      clobber->set_hydrogen_value(current);
      chunk_->AddInstruction(clobber, current_block_);
    }
997
    chunk_->AddInstruction(instr, current_block_);
998 999 1000 1001 1002
  }
  current_instruction_ = old_current;
}


1003 1004
LEnvironment* LChunkBuilder::CreateEnvironment(
    HEnvironment* hydrogen_env,
1005 1006
    int* argument_index_accumulator,
    ZoneList<HValue*>* objects_to_materialize) {
1007 1008
  if (hydrogen_env == NULL) return NULL;

1009 1010 1011
  LEnvironment* outer = CreateEnvironment(hydrogen_env->outer(),
                                          argument_index_accumulator,
                                          objects_to_materialize);
1012 1013
  BailoutId ast_id = hydrogen_env->ast_id();
  ASSERT(!ast_id.IsNone() ||
1014
         hydrogen_env->frame_type() != JS_FUNCTION);
1015
  int value_count = hydrogen_env->length() - hydrogen_env->specials_count();
1016 1017
  LEnvironment* result =
      new(zone()) LEnvironment(hydrogen_env->closure(),
1018
                               hydrogen_env->frame_type(),
1019 1020 1021 1022
                               ast_id,
                               hydrogen_env->parameter_count(),
                               argument_count_,
                               value_count,
1023
                               outer,
1024
                               hydrogen_env->entry(),
1025
                               zone());
1026
  int argument_index = *argument_index_accumulator;
1027
  int object_index = objects_to_materialize->length();
1028
  for (int i = 0; i < hydrogen_env->length(); ++i) {
1029 1030
    if (hydrogen_env->is_special_index(i)) continue;

1031
    LOperand* op;
1032
    HValue* value = hydrogen_env->values()->at(i);
1033 1034 1035
    if (value->IsArgumentsObject() || value->IsCapturedObject()) {
      objects_to_materialize->Add(value, zone());
      op = LEnvironment::materialization_marker();
1036
    } else if (value->IsPushArgument()) {
1037
      op = new(zone()) LArgument(argument_index++);
1038
    } else {
1039
      op = UseAny(value);
1040
    }
1041 1042 1043
    result->AddValue(op,
                     value->representation(),
                     value->CheckFlag(HInstruction::kUint32));
1044 1045
  }

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
  for (int i = object_index; i < objects_to_materialize->length(); ++i) {
    HValue* object_to_materialize = objects_to_materialize->at(i);
    int previously_materialized_object = -1;
    for (int prev = 0; prev < i; ++prev) {
      if (objects_to_materialize->at(prev) == objects_to_materialize->at(i)) {
        previously_materialized_object = prev;
        break;
      }
    }
    int length = object_to_materialize->OperandCount();
    bool is_arguments = object_to_materialize->IsArgumentsObject();
    if (previously_materialized_object >= 0) {
      result->AddDuplicateObject(previously_materialized_object);
      continue;
    } else {
      result->AddNewObject(is_arguments ? length - 1 : length, is_arguments);
    }
    for (int i = is_arguments ? 1 : 0; i < length; ++i) {
      LOperand* op;
      HValue* value = object_to_materialize->OperandAt(i);
      if (value->IsArgumentsObject() || value->IsCapturedObject()) {
        objects_to_materialize->Add(value, zone());
        op = LEnvironment::materialization_marker();
      } else {
        ASSERT(!value->IsPushArgument());
        op = UseAny(value);
      }
1073 1074 1075 1076 1077 1078
      result->AddValue(op,
                       value->representation(),
                       value->CheckFlag(HInstruction::kUint32));
    }
  }

1079
  if (hydrogen_env->frame_type() == JS_FUNCTION) {
1080 1081 1082
    *argument_index_accumulator = argument_index;
  }

1083 1084 1085 1086 1087
  return result;
}


LInstruction* LChunkBuilder::DoGoto(HGoto* instr) {
1088
  return new(zone()) LGoto(instr->FirstSuccessor());
1089 1090 1091
}


1092
LInstruction* LChunkBuilder::DoBranch(HBranch* instr) {
1093 1094
  LInstruction* goto_instr = CheckElideControlInstruction(instr);
  if (goto_instr != NULL) return goto_instr;
1095

1096 1097 1098 1099 1100
  ToBooleanStub::Types expected = instr->expected_input_types();

  // Tagged values that are not known smis or booleans require a
  // deoptimization environment. If the instruction is generic no
  // environment is needed since all cases are handled.
1101
  HValue* value = instr->value();
1102 1103 1104 1105 1106 1107
  Representation rep = value->representation();
  HType type = value->type();
  if (!rep.IsTagged() || type.IsSmi() || type.IsBoolean()) {
    return new(zone()) LBranch(UseRegister(value), NULL);
  }

1108 1109 1110 1111 1112 1113 1114 1115
  bool needs_temp = expected.NeedsMap() || expected.IsEmpty();
  LOperand* temp = needs_temp ? TempRegister() : NULL;

  // The Generic stub does not have a deopt, so we need no environment.
  if (expected.IsGeneric()) {
    return new(zone()) LBranch(UseRegister(value), temp);
  }

1116 1117 1118
  // We need a temporary register when we have to access the map *or* we have
  // no type info yet, in which case we handle all cases (including the ones
  // involving maps).
1119
  return AssignEnvironment(new(zone()) LBranch(UseRegister(value), temp));
1120 1121 1122
}


1123 1124 1125 1126 1127
LInstruction* LChunkBuilder::DoDebugBreak(HDebugBreak* instr) {
  return new(zone()) LDebugBreak();
}


1128
LInstruction* LChunkBuilder::DoCompareMap(HCompareMap* instr) {
1129 1130
  ASSERT(instr->value()->representation().IsTagged());
  LOperand* value = UseRegisterAtStart(instr->value());
1131
  return new(zone()) LCmpMapAndBranch(value);
1132 1133 1134 1135
}


LInstruction* LChunkBuilder::DoArgumentsLength(HArgumentsLength* length) {
1136
  info()->MarkAsRequiresFrame();
1137
  return DefineAsRegister(new(zone()) LArgumentsLength(Use(length->value())));
1138 1139 1140 1141
}


LInstruction* LChunkBuilder::DoArgumentsElements(HArgumentsElements* elems) {
1142
  info()->MarkAsRequiresFrame();
1143
  return DefineAsRegister(new(zone()) LArgumentsElements);
1144 1145 1146 1147
}


LInstruction* LChunkBuilder::DoInstanceOf(HInstanceOf* instr) {
1148 1149 1150
  LOperand* left = UseFixed(instr->left(), InstanceofStub::left());
  LOperand* right = UseFixed(instr->right(), InstanceofStub::right());
  LOperand* context = UseFixed(instr->context(), esi);
1151
  LInstanceOf* result = new(zone()) LInstanceOf(context, left, right);
1152 1153 1154 1155
  return MarkAsCall(DefineFixed(result, eax), instr);
}


1156 1157
LInstruction* LChunkBuilder::DoInstanceOfKnownGlobal(
    HInstanceOfKnownGlobal* instr) {
1158
  LInstanceOfKnownGlobal* result =
1159
      new(zone()) LInstanceOfKnownGlobal(
1160 1161
          UseFixed(instr->context(), esi),
          UseFixed(instr->left(), InstanceofStub::left()),
1162
          FixedTemp(edi));
1163
  return MarkAsCall(DefineFixed(result, eax), instr);
1164 1165 1166
}


1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
LInstruction* LChunkBuilder::DoWrapReceiver(HWrapReceiver* instr) {
  LOperand* receiver = UseRegister(instr->receiver());
  LOperand* function = UseRegisterAtStart(instr->function());
  LOperand* temp = TempRegister();
  LWrapReceiver* result =
      new(zone()) LWrapReceiver(receiver, function, temp);
  return AssignEnvironment(DefineSameAsFirst(result));
}


1177 1178 1179
LInstruction* LChunkBuilder::DoApplyArguments(HApplyArguments* instr) {
  LOperand* function = UseFixed(instr->function(), edi);
  LOperand* receiver = UseFixed(instr->receiver(), eax);
1180 1181
  LOperand* length = UseFixed(instr->length(), ebx);
  LOperand* elements = UseFixed(instr->elements(), ecx);
1182 1183 1184
  LApplyArguments* result = new(zone()) LApplyArguments(function,
                                                        receiver,
                                                        length,
1185
                                                        elements);
1186 1187 1188 1189 1190
  return MarkAsCall(DefineFixed(result, eax), instr, CAN_DEOPTIMIZE_EAGERLY);
}


LInstruction* LChunkBuilder::DoPushArgument(HPushArgument* instr) {
1191
  LOperand* argument = UseAny(instr->argument());
1192
  return new(zone()) LPushArgument(argument);
1193 1194 1195
}


1196 1197 1198 1199 1200 1201 1202 1203
LInstruction* LChunkBuilder::DoStoreCodeEntry(
    HStoreCodeEntry* store_code_entry) {
  LOperand* function = UseRegister(store_code_entry->function());
  LOperand* code_object = UseTempRegister(store_code_entry->code_object());
  return new(zone()) LStoreCodeEntry(function, code_object);
}


1204
LInstruction* LChunkBuilder::DoInnerAllocatedObject(
1205 1206 1207 1208 1209
    HInnerAllocatedObject* instr) {
  LOperand* base_object = UseRegisterAtStart(instr->base_object());
  LOperand* offset = UseRegisterOrConstantAtStart(instr->offset());
  return DefineAsRegister(
      new(zone()) LInnerAllocatedObject(base_object, offset));
1210 1211 1212
}


1213
LInstruction* LChunkBuilder::DoThisFunction(HThisFunction* instr) {
1214 1215 1216
  return instr->HasNoUses()
      ? NULL
      : DefineAsRegister(new(zone()) LThisFunction);
1217 1218 1219
}


1220
LInstruction* LChunkBuilder::DoContext(HContext* instr) {
1221 1222 1223 1224 1225 1226 1227
  if (instr->HasNoUses()) return NULL;

  if (info()->IsStub()) {
    return DefineFixed(new(zone()) LContext, esi);
  }

  return DefineAsRegister(new(zone()) LContext);
1228 1229 1230 1231 1232
}


LInstruction* LChunkBuilder::DoOuterContext(HOuterContext* instr) {
  LOperand* context = UseRegisterAtStart(instr->value());
1233
  return DefineAsRegister(new(zone()) LOuterContext(context));
1234 1235 1236
}


1237 1238 1239 1240 1241 1242
LInstruction* LChunkBuilder::DoDeclareGlobals(HDeclareGlobals* instr) {
  LOperand* context = UseFixed(instr->context(), esi);
  return MarkAsCall(new(zone()) LDeclareGlobals(context), instr);
}


1243
LInstruction* LChunkBuilder::DoGlobalObject(HGlobalObject* instr) {
1244
  LOperand* context = UseRegisterAtStart(instr->value());
1245
  return DefineAsRegister(new(zone()) LGlobalObject(context));
1246 1247 1248 1249
}


LInstruction* LChunkBuilder::DoGlobalReceiver(HGlobalReceiver* instr) {
1250
  LOperand* global_object = UseRegisterAtStart(instr->value());
1251
  return DefineAsRegister(new(zone()) LGlobalReceiver(global_object));
1252 1253 1254 1255 1256
}


LInstruction* LChunkBuilder::DoCallConstantFunction(
    HCallConstantFunction* instr) {
1257
  return MarkAsCall(DefineFixed(new(zone()) LCallConstantFunction, eax), instr);
1258 1259 1260
}


1261 1262 1263
LInstruction* LChunkBuilder::DoInvokeFunction(HInvokeFunction* instr) {
  LOperand* context = UseFixed(instr->context(), esi);
  LOperand* function = UseFixed(instr->function(), edi);
1264
  LInvokeFunction* result = new(zone()) LInvokeFunction(context, function);
1265 1266 1267 1268
  return MarkAsCall(DefineFixed(result, eax), instr, CANNOT_DEOPTIMIZE_EAGERLY);
}


1269
LInstruction* LChunkBuilder::DoUnaryMathOperation(HUnaryMathOperation* instr) {
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
  switch (instr->op()) {
    case kMathFloor: return DoMathFloor(instr);
    case kMathRound: return DoMathRound(instr);
    case kMathAbs: return DoMathAbs(instr);
    case kMathLog: return DoMathLog(instr);
    case kMathSin: return DoMathSin(instr);
    case kMathCos: return DoMathCos(instr);
    case kMathTan: return DoMathTan(instr);
    case kMathExp: return DoMathExp(instr);
    case kMathSqrt: return DoMathSqrt(instr);
    case kMathPowHalf: return DoMathPowHalf(instr);
    default:
      UNREACHABLE();
      return NULL;
1284 1285 1286 1287
  }
}


1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
LInstruction* LChunkBuilder::DoMathFloor(HUnaryMathOperation* instr) {
  LOperand* input = UseRegisterAtStart(instr->value());
  LMathFloor* result = new(zone()) LMathFloor(input);
  return AssignEnvironment(DefineAsRegister(result));
}


LInstruction* LChunkBuilder::DoMathRound(HUnaryMathOperation* instr) {
  LOperand* input = UseRegister(instr->value());
  LOperand* temp = FixedTemp(xmm4);
1298
  LMathRound* result = new(zone()) LMathRound(input, temp);
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
  return AssignEnvironment(DefineAsRegister(result));
}


LInstruction* LChunkBuilder::DoMathAbs(HUnaryMathOperation* instr) {
  LOperand* context = UseAny(instr->context());  // Deferred use.
  LOperand* input = UseRegisterAtStart(instr->value());
  LMathAbs* result = new(zone()) LMathAbs(context, input);
  return AssignEnvironment(AssignPointerMap(DefineSameAsFirst(result)));
}


LInstruction* LChunkBuilder::DoMathLog(HUnaryMathOperation* instr) {
  ASSERT(instr->representation().IsDouble());
  ASSERT(instr->value()->representation().IsDouble());
  LOperand* input = UseRegisterAtStart(instr->value());
  LMathLog* result = new(zone()) LMathLog(input);
  return DefineSameAsFirst(result);
}


LInstruction* LChunkBuilder::DoMathSin(HUnaryMathOperation* instr) {
  LOperand* input = UseFixedDouble(instr->value(), xmm1);
  LMathSin* result = new(zone()) LMathSin(input);
  return MarkAsCall(DefineFixedDouble(result, xmm1), instr);
}


LInstruction* LChunkBuilder::DoMathCos(HUnaryMathOperation* instr) {
  LOperand* input = UseFixedDouble(instr->value(), xmm1);
  LMathCos* result = new(zone()) LMathCos(input);
  return MarkAsCall(DefineFixedDouble(result, xmm1), instr);
}


LInstruction* LChunkBuilder::DoMathTan(HUnaryMathOperation* instr) {
  LOperand* input = UseFixedDouble(instr->value(), xmm1);
  LMathTan* result = new(zone()) LMathTan(input);
  return MarkAsCall(DefineFixedDouble(result, xmm1), instr);
}


LInstruction* LChunkBuilder::DoMathExp(HUnaryMathOperation* instr) {
  ASSERT(instr->representation().IsDouble());
  ASSERT(instr->value()->representation().IsDouble());
  LOperand* value = UseTempRegister(instr->value());
  LOperand* temp1 = TempRegister();
  LOperand* temp2 = TempRegister();
  LMathExp* result = new(zone()) LMathExp(value, temp1, temp2);
  return DefineAsRegister(result);
}


LInstruction* LChunkBuilder::DoMathSqrt(HUnaryMathOperation* instr) {
  LOperand* input = UseRegisterAtStart(instr->value());
  LMathSqrt* result = new(zone()) LMathSqrt(input);
  return DefineSameAsFirst(result);
}


LInstruction* LChunkBuilder::DoMathPowHalf(HUnaryMathOperation* instr) {
  LOperand* input = UseRegisterAtStart(instr->value());
  LOperand* temp = TempRegister();
1362
  LMathPowHalf* result = new(zone()) LMathPowHalf(input, temp);
1363 1364 1365 1366
  return DefineSameAsFirst(result);
}


1367 1368
LInstruction* LChunkBuilder::DoCallKeyed(HCallKeyed* instr) {
  ASSERT(instr->key()->representation().IsTagged());
1369
  LOperand* context = UseFixed(instr->context(), esi);
1370
  LOperand* key = UseFixed(instr->key(), ecx);
1371
  LCallKeyed* result = new(zone()) LCallKeyed(context, key);
1372
  return MarkAsCall(DefineFixed(result, eax), instr);
1373 1374 1375 1376
}


LInstruction* LChunkBuilder::DoCallNamed(HCallNamed* instr) {
1377
  LOperand* context = UseFixed(instr->context(), esi);
1378
  LCallNamed* result = new(zone()) LCallNamed(context);
1379
  return MarkAsCall(DefineFixed(result, eax), instr);
1380 1381 1382 1383
}


LInstruction* LChunkBuilder::DoCallGlobal(HCallGlobal* instr) {
1384
  LOperand* context = UseFixed(instr->context(), esi);
1385
  LCallGlobal* result = new(zone()) LCallGlobal(context);
1386
  return MarkAsCall(DefineFixed(result, eax), instr);
1387 1388 1389 1390
}


LInstruction* LChunkBuilder::DoCallKnownGlobal(HCallKnownGlobal* instr) {
1391
  return MarkAsCall(DefineFixed(new(zone()) LCallKnownGlobal, eax), instr);
1392 1393 1394 1395
}


LInstruction* LChunkBuilder::DoCallNew(HCallNew* instr) {
1396
  LOperand* context = UseFixed(instr->context(), esi);
1397
  LOperand* constructor = UseFixed(instr->constructor(), edi);
1398
  LCallNew* result = new(zone()) LCallNew(context, constructor);
1399 1400 1401 1402
  return MarkAsCall(DefineFixed(result, eax), instr);
}


1403 1404 1405 1406 1407 1408 1409 1410
LInstruction* LChunkBuilder::DoCallNewArray(HCallNewArray* instr) {
  LOperand* context = UseFixed(instr->context(), esi);
  LOperand* constructor = UseFixed(instr->constructor(), edi);
  LCallNewArray* result = new(zone()) LCallNewArray(context, constructor);
  return MarkAsCall(DefineFixed(result, eax), instr);
}


1411
LInstruction* LChunkBuilder::DoCallFunction(HCallFunction* instr) {
1412
  LOperand* context = UseFixed(instr->context(), esi);
1413
  LOperand* function = UseFixed(instr->function(), edi);
1414 1415 1416 1417
  LCallFunction* call = new(zone()) LCallFunction(context, function);
  LInstruction* result = DefineFixed(call, eax);
  if (instr->IsTailCall()) return result;
  return MarkAsCall(result, instr);
1418 1419 1420 1421
}


LInstruction* LChunkBuilder::DoCallRuntime(HCallRuntime* instr) {
1422
  LOperand* context = UseFixed(instr->context(), esi);
1423
  return MarkAsCall(DefineFixed(new(zone()) LCallRuntime(context), eax), instr);
1424 1425 1426
}


1427 1428 1429 1430 1431
LInstruction* LChunkBuilder::DoRor(HRor* instr) {
  return DoShift(Token::ROR, instr);
}


1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
LInstruction* LChunkBuilder::DoShr(HShr* instr) {
  return DoShift(Token::SHR, instr);
}


LInstruction* LChunkBuilder::DoSar(HSar* instr) {
  return DoShift(Token::SAR, instr);
}


LInstruction* LChunkBuilder::DoShl(HShl* instr) {
  return DoShift(Token::SHL, instr);
}


1447
LInstruction* LChunkBuilder::DoBitwise(HBitwise* instr) {
1448
  if (instr->representation().IsSmiOrInteger32()) {
1449 1450
    ASSERT(instr->left()->representation().Equals(instr->representation()));
    ASSERT(instr->right()->representation().Equals(instr->representation()));
1451
    ASSERT(instr->CheckFlag(HValue::kTruncatingToInt32));
1452

1453 1454
    LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
    LOperand* right = UseOrConstantAtStart(instr->BetterRightOperand());
1455
    return DefineSameAsFirst(new(zone()) LBitI(left, right));
1456
  } else {
1457
    return DoArithmeticT(instr->op(), instr);
1458
  }
1459 1460 1461 1462
}


LInstruction* LChunkBuilder::DoDiv(HDiv* instr) {
1463
  if (instr->representation().IsSmiOrInteger32()) {
1464 1465
    ASSERT(instr->left()->representation().Equals(instr->representation()));
    ASSERT(instr->right()->representation().Equals(instr->representation()));
1466 1467 1468 1469 1470 1471 1472
    if (instr->HasPowerOf2Divisor()) {
      ASSERT(!instr->CheckFlag(HValue::kCanBeDivByZero));
      LOperand* value = UseRegisterAtStart(instr->left());
      LDivI* div =
          new(zone()) LDivI(value, UseOrConstant(instr->right()), NULL);
      return AssignEnvironment(DefineSameAsFirst(div));
    }
1473 1474
    // The temporary operand is necessary to ensure that right is not allocated
    // into edx.
1475
    LOperand* temp = FixedTemp(edx);
1476
    LOperand* dividend = UseFixed(instr->left(), eax);
1477
    LOperand* divisor = UseRegister(instr->right());
1478
    LDivI* result = new(zone()) LDivI(dividend, divisor, temp);
1479
    return AssignEnvironment(DefineFixed(result, eax));
1480 1481
  } else if (instr->representation().IsDouble()) {
    return DoArithmeticD(Token::DIV, instr);
1482 1483 1484 1485 1486 1487
  } else {
    return DoArithmeticT(Token::DIV, instr);
  }
}


1488 1489 1490 1491 1492 1493 1494
HValue* LChunkBuilder::SimplifiedDivisorForMathFloorOfDiv(HValue* divisor) {
  if (divisor->IsConstant() &&
      HConstant::cast(divisor)->HasInteger32Value()) {
    HConstant* constant_val = HConstant::cast(divisor);
    return constant_val->CopyToRepresentation(Representation::Integer32(),
                                              divisor->block()->zone());
  }
1495 1496 1497 1498 1499 1500 1501 1502
  // A value with an integer representation does not need to be transformed.
  if (divisor->representation().IsInteger32()) {
    return divisor;
  // A change from an integer32 can be replaced by the integer32 value.
  } else if (divisor->IsChange() &&
             HChange::cast(divisor)->from().IsInteger32()) {
    return HChange::cast(divisor)->value();
  }
1503 1504 1505 1506
  return NULL;
}


1507 1508
LInstruction* LChunkBuilder::DoMathFloorOfDiv(HMathFloorOfDiv* instr) {
  HValue* right = instr->right();
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
  if (!right->IsConstant()) {
    ASSERT(right->representation().IsInteger32());
    // The temporary operand is necessary to ensure that right is not allocated
    // into edx.
    LOperand* temp = FixedTemp(edx);
    LOperand* dividend = UseFixed(instr->left(), eax);
    LOperand* divisor = UseRegister(instr->right());
    LDivI* flooring_div = new(zone()) LDivI(dividend, divisor, temp);
    return AssignEnvironment(DefineFixed(flooring_div, eax));
  }

1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
  ASSERT(right->IsConstant() && HConstant::cast(right)->HasInteger32Value());
  LOperand* divisor = chunk_->DefineConstantOperand(HConstant::cast(right));
  int32_t divisor_si = HConstant::cast(right)->Integer32Value();
  if (divisor_si == 0) {
    LOperand* dividend = UseRegister(instr->left());
    return AssignEnvironment(DefineAsRegister(
        new(zone()) LMathFloorOfDiv(dividend, divisor, NULL)));
  } else if (IsPowerOf2(abs(divisor_si))) {
    // use dividend as temp if divisor < 0 && divisor != -1
    LOperand* dividend = divisor_si < -1 ? UseTempRegister(instr->left()) :
                         UseRegisterAtStart(instr->left());
    LInstruction* result = DefineAsRegister(
        new(zone()) LMathFloorOfDiv(dividend, divisor, NULL));
    return divisor_si < 0 ? AssignEnvironment(result) : result;
  } else {
    // needs edx:eax, plus a temp
    LOperand* dividend = UseFixed(instr->left(), eax);
    LOperand* temp = TempRegister();
    LInstruction* result = DefineFixed(
        new(zone()) LMathFloorOfDiv(dividend, divisor, temp), edx);
    return divisor_si < 0 ? AssignEnvironment(result) : result;
  }
}


1545
LInstruction* LChunkBuilder::DoMod(HMod* instr) {
1546 1547
  HValue* left = instr->left();
  HValue* right = instr->right();
1548
  if (instr->representation().IsSmiOrInteger32()) {
1549 1550
    ASSERT(instr->left()->representation().Equals(instr->representation()));
    ASSERT(instr->right()->representation().Equals(instr->representation()));
1551

1552
    if (instr->HasPowerOf2Divisor()) {
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
      ASSERT(!right->CanBeZero());
      LModI* mod = new(zone()) LModI(UseRegisterAtStart(left),
                                     UseOrConstant(right),
                                     NULL);
      LInstruction* result = DefineSameAsFirst(mod);
      return (left->CanBeNegative() &&
              instr->CheckFlag(HValue::kBailoutOnMinusZero))
          ? AssignEnvironment(result)
          : result;
      return AssignEnvironment(DefineSameAsFirst(mod));
1563
    } else {
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
      // The temporary operand is necessary to ensure that right is not
      // allocated into edx.
      LModI* mod = new(zone()) LModI(UseFixed(left, eax),
                                     UseRegister(right),
                                     FixedTemp(edx));
      LInstruction* result = DefineFixed(mod, edx);
      return (right->CanBeZero() ||
              (left->RangeCanInclude(kMinInt) &&
               right->RangeCanInclude(-1) &&
               instr->CheckFlag(HValue::kBailoutOnMinusZero)) ||
              (left->CanBeNegative() &&
               instr->CanBeZero() &&
               instr->CheckFlag(HValue::kBailoutOnMinusZero)))
          ? AssignEnvironment(result)
          : result;
1579
    }
1580 1581
  } else if (instr->representation().IsDouble()) {
    return DoArithmeticD(Token::MOD, instr);
1582
  } else {
1583
    return DoArithmeticT(Token::MOD, instr);
1584 1585 1586 1587 1588
  }
}


LInstruction* LChunkBuilder::DoMul(HMul* instr) {
1589 1590 1591
  if (instr->representation().IsSmiOrInteger32()) {
    ASSERT(instr->left()->representation().Equals(instr->representation()));
    ASSERT(instr->right()->representation().Equals(instr->representation()));
1592 1593
    LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
    LOperand* right = UseOrConstant(instr->BetterRightOperand());
1594 1595 1596 1597
    LOperand* temp = NULL;
    if (instr->CheckFlag(HValue::kBailoutOnMinusZero)) {
      temp = TempRegister();
    }
1598
    LMulI* mul = new(zone()) LMulI(left, right, temp);
1599 1600 1601 1602 1603
    if (instr->CheckFlag(HValue::kCanOverflow) ||
        instr->CheckFlag(HValue::kBailoutOnMinusZero)) {
      AssignEnvironment(mul);
    }
    return DefineSameAsFirst(mul);
1604
  } else if (instr->representation().IsDouble()) {
1605
    return DoArithmeticD(Token::MUL, instr);
1606 1607 1608 1609 1610 1611 1612
  } else {
    return DoArithmeticT(Token::MUL, instr);
  }
}


LInstruction* LChunkBuilder::DoSub(HSub* instr) {
1613
  if (instr->representation().IsSmiOrInteger32()) {
1614 1615
    ASSERT(instr->left()->representation().Equals(instr->representation()));
    ASSERT(instr->right()->representation().Equals(instr->representation()));
1616 1617
    LOperand* left = UseRegisterAtStart(instr->left());
    LOperand* right = UseOrConstantAtStart(instr->right());
1618
    LSubI* sub = new(zone()) LSubI(left, right);
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
    LInstruction* result = DefineSameAsFirst(sub);
    if (instr->CheckFlag(HValue::kCanOverflow)) {
      result = AssignEnvironment(result);
    }
    return result;
  } else if (instr->representation().IsDouble()) {
    return DoArithmeticD(Token::SUB, instr);
  } else {
    return DoArithmeticT(Token::SUB, instr);
  }
}


LInstruction* LChunkBuilder::DoAdd(HAdd* instr) {
1633
  if (instr->representation().IsSmiOrInteger32()) {
1634 1635
    ASSERT(instr->left()->representation().Equals(instr->representation()));
    ASSERT(instr->right()->representation().Equals(instr->representation()));
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
    // Check to see if it would be advantageous to use an lea instruction rather
    // than an add. This is the case when no overflow check is needed and there
    // are multiple uses of the add's inputs, so using a 3-register add will
    // preserve all input values for later uses.
    bool use_lea = LAddI::UseLea(instr);
    LOperand* left = UseRegisterAtStart(instr->BetterLeftOperand());
    HValue* right_candidate = instr->BetterRightOperand();
    LOperand* right = use_lea
        ? UseRegisterOrConstantAtStart(right_candidate)
        : UseOrConstantAtStart(right_candidate);
1646
    LAddI* add = new(zone()) LAddI(left, right);
1647 1648 1649 1650 1651
    bool can_overflow = instr->CheckFlag(HValue::kCanOverflow);
    LInstruction* result = use_lea
        ? DefineAsRegister(add)
        : DefineSameAsFirst(add);
    if (can_overflow) {
1652 1653 1654 1655 1656
      result = AssignEnvironment(result);
    }
    return result;
  } else if (instr->representation().IsDouble()) {
    return DoArithmeticD(Token::ADD, instr);
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
  } else if (instr->representation().IsExternal()) {
    ASSERT(instr->left()->representation().IsExternal());
    ASSERT(instr->right()->representation().IsInteger32());
    ASSERT(!instr->CheckFlag(HValue::kCanOverflow));
    bool use_lea = LAddI::UseLea(instr);
    LOperand* left = UseRegisterAtStart(instr->left());
    HValue* right_candidate = instr->right();
    LOperand* right = use_lea
        ? UseRegisterOrConstantAtStart(right_candidate)
        : UseOrConstantAtStart(right_candidate);
    LAddI* add = new(zone()) LAddI(left, right);
    LInstruction* result = use_lea
        ? DefineAsRegister(add)
        : DefineSameAsFirst(add);
    return result;
1672 1673 1674 1675 1676 1677
  } else {
    return DoArithmeticT(Token::ADD, instr);
  }
}


1678 1679 1680
LInstruction* LChunkBuilder::DoMathMinMax(HMathMinMax* instr) {
  LOperand* left = NULL;
  LOperand* right = NULL;
1681
  if (instr->representation().IsSmiOrInteger32()) {
1682 1683
    ASSERT(instr->left()->representation().Equals(instr->representation()));
    ASSERT(instr->right()->representation().Equals(instr->representation()));
1684 1685
    left = UseRegisterAtStart(instr->BetterLeftOperand());
    right = UseOrConstantAtStart(instr->BetterRightOperand());
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
  } else {
    ASSERT(instr->representation().IsDouble());
    ASSERT(instr->left()->representation().IsDouble());
    ASSERT(instr->right()->representation().IsDouble());
    left = UseRegisterAtStart(instr->left());
    right = UseRegisterAtStart(instr->right());
  }
  LMathMinMax* minmax = new(zone()) LMathMinMax(left, right);
  return DefineSameAsFirst(minmax);
}


1698 1699 1700 1701 1702 1703
LInstruction* LChunkBuilder::DoPower(HPower* instr) {
  ASSERT(instr->representation().IsDouble());
  // We call a C function for double power. It can't trigger a GC.
  // We need to use fixed result register for the call.
  Representation exponent_type = instr->right()->representation();
  ASSERT(instr->left()->representation().IsDouble());
1704
  LOperand* left = UseFixedDouble(instr->left(), xmm2);
1705
  LOperand* right = exponent_type.IsDouble() ?
1706
      UseFixedDouble(instr->right(), xmm1) :
1707
      UseFixed(instr->right(), eax);
1708
  LPower* result = new(zone()) LPower(left, right);
1709
  return MarkAsCall(DefineFixedDouble(result, xmm3), instr,
1710 1711 1712 1713
                    CAN_DEOPTIMIZE_EAGERLY);
}


1714
LInstruction* LChunkBuilder::DoCompareGeneric(HCompareGeneric* instr) {
1715 1716
  ASSERT(instr->left()->representation().IsSmiOrTagged());
  ASSERT(instr->right()->representation().IsSmiOrTagged());
1717
  LOperand* context = UseFixed(instr->context(), esi);
1718 1719
  LOperand* left = UseFixed(instr->left(), edx);
  LOperand* right = UseFixed(instr->right(), eax);
1720 1721
  LCmpT* result = new(zone()) LCmpT(context, left, right);
  return MarkAsCall(DefineFixed(result, eax), instr);
1722 1723 1724
}


1725 1726
LInstruction* LChunkBuilder::DoCompareNumericAndBranch(
    HCompareNumericAndBranch* instr) {
1727
  Representation r = instr->representation();
1728
  if (r.IsSmiOrInteger32()) {
1729 1730
    ASSERT(instr->left()->representation().Equals(r));
    ASSERT(instr->right()->representation().Equals(r));
1731
    LOperand* left = UseRegisterOrConstantAtStart(instr->left());
1732
    LOperand* right = UseOrConstantAtStart(instr->right());
1733
    return new(zone()) LCompareNumericAndBranch(left, right);
1734 1735
  } else {
    ASSERT(r.IsDouble());
1736
    ASSERT(instr->left()->representation().IsDouble());
1737
    ASSERT(instr->right()->representation().IsDouble());
1738 1739
    LOperand* left;
    LOperand* right;
1740 1741 1742 1743 1744 1745
    if (CanBeImmediateConstant(instr->left()) &&
        CanBeImmediateConstant(instr->right())) {
      // The code generator requires either both inputs to be constant
      // operands, or neither.
      left = UseConstant(instr->left());
      right = UseConstant(instr->right());
1746 1747 1748 1749
    } else {
      left = UseRegisterAtStart(instr->left());
      right = UseRegisterAtStart(instr->right());
    }
1750
    return new(zone()) LCompareNumericAndBranch(left, right);
1751 1752 1753 1754
  }
}


1755 1756
LInstruction* LChunkBuilder::DoCompareObjectEqAndBranch(
    HCompareObjectEqAndBranch* instr) {
1757 1758
  LInstruction* goto_instr = CheckElideControlInstruction(instr);
  if (goto_instr != NULL) return goto_instr;
1759
  LOperand* left = UseRegisterAtStart(instr->left());
1760
  LOperand* right = UseOrConstantAtStart(instr->right());
1761
  return new(zone()) LCmpObjectEqAndBranch(left, right);
1762 1763 1764
}


1765 1766
LInstruction* LChunkBuilder::DoCompareHoleAndBranch(
    HCompareHoleAndBranch* instr) {
1767 1768
  LOperand* value = UseRegisterAtStart(instr->value());
  return new(zone()) LCmpHoleAndBranch(value);
1769 1770 1771
}


1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
LInstruction* LChunkBuilder::DoCompareMinusZeroAndBranch(
    HCompareMinusZeroAndBranch* instr) {
  LInstruction* goto_instr = CheckElideControlInstruction(instr);
  if (goto_instr != NULL) return goto_instr;
  LOperand* value = UseRegister(instr->value());
  LOperand* scratch = TempRegister();
  return new(zone()) LCompareMinusZeroAndBranch(value, scratch);
}


1782
LInstruction* LChunkBuilder::DoIsObjectAndBranch(HIsObjectAndBranch* instr) {
1783
  ASSERT(instr->value()->representation().IsSmiOrTagged());
1784
  LOperand* temp = TempRegister();
1785
  return new(zone()) LIsObjectAndBranch(UseRegister(instr->value()), temp);
1786 1787 1788
}


1789 1790 1791
LInstruction* LChunkBuilder::DoIsStringAndBranch(HIsStringAndBranch* instr) {
  ASSERT(instr->value()->representation().IsTagged());
  LOperand* temp = TempRegister();
1792
  return new(zone()) LIsStringAndBranch(UseRegister(instr->value()), temp);
1793 1794 1795
}


1796
LInstruction* LChunkBuilder::DoIsSmiAndBranch(HIsSmiAndBranch* instr) {
1797
  ASSERT(instr->value()->representation().IsTagged());
1798
  return new(zone()) LIsSmiAndBranch(Use(instr->value()));
1799 1800 1801
}


1802 1803
LInstruction* LChunkBuilder::DoIsUndetectableAndBranch(
    HIsUndetectableAndBranch* instr) {
1804
  ASSERT(instr->value()->representation().IsTagged());
1805 1806
  return new(zone()) LIsUndetectableAndBranch(
      UseRegisterAtStart(instr->value()), TempRegister());
1807 1808 1809
}


1810 1811 1812 1813 1814 1815 1816 1817
LInstruction* LChunkBuilder::DoStringCompareAndBranch(
    HStringCompareAndBranch* instr) {
  ASSERT(instr->left()->representation().IsTagged());
  ASSERT(instr->right()->representation().IsTagged());
  LOperand* context = UseFixed(instr->context(), esi);
  LOperand* left = UseFixed(instr->left(), edx);
  LOperand* right = UseFixed(instr->right(), eax);

1818
  LStringCompareAndBranch* result = new(zone())
1819 1820 1821 1822 1823 1824
      LStringCompareAndBranch(context, left, right);

  return MarkAsCall(result, instr);
}


1825 1826
LInstruction* LChunkBuilder::DoHasInstanceTypeAndBranch(
    HHasInstanceTypeAndBranch* instr) {
1827
  ASSERT(instr->value()->representation().IsTagged());
1828 1829 1830
  return new(zone()) LHasInstanceTypeAndBranch(
      UseRegisterAtStart(instr->value()),
      TempRegister());
1831 1832 1833
}


1834 1835
LInstruction* LChunkBuilder::DoGetCachedArrayIndex(
    HGetCachedArrayIndex* instr)  {
1836 1837 1838
  ASSERT(instr->value()->representation().IsTagged());
  LOperand* value = UseRegisterAtStart(instr->value());

1839
  return DefineAsRegister(new(zone()) LGetCachedArrayIndex(value));
1840 1841 1842
}


1843 1844
LInstruction* LChunkBuilder::DoHasCachedArrayIndexAndBranch(
    HHasCachedArrayIndexAndBranch* instr) {
1845
  ASSERT(instr->value()->representation().IsTagged());
1846
  return new(zone()) LHasCachedArrayIndexAndBranch(
1847
      UseRegisterAtStart(instr->value()));
1848 1849 1850
}


1851 1852
LInstruction* LChunkBuilder::DoClassOfTestAndBranch(
    HClassOfTestAndBranch* instr) {
1853
  ASSERT(instr->value()->representation().IsTagged());
1854 1855 1856
  return new(zone()) LClassOfTestAndBranch(UseRegister(instr->value()),
                                           TempRegister(),
                                           TempRegister());
1857 1858 1859
}


1860 1861 1862 1863 1864 1865
LInstruction* LChunkBuilder::DoMapEnumLength(HMapEnumLength* instr) {
  LOperand* map = UseRegisterAtStart(instr->value());
  return DefineAsRegister(new(zone()) LMapEnumLength(map));
}


1866 1867
LInstruction* LChunkBuilder::DoElementsKind(HElementsKind* instr) {
  LOperand* object = UseRegisterAtStart(instr->value());
1868
  return DefineAsRegister(new(zone()) LElementsKind(object));
1869 1870 1871
}


1872 1873
LInstruction* LChunkBuilder::DoValueOf(HValueOf* instr) {
  LOperand* object = UseRegister(instr->value());
1874
  LValueOf* result = new(zone()) LValueOf(object, TempRegister());
1875
  return DefineSameAsFirst(result);
1876 1877 1878
}


1879
LInstruction* LChunkBuilder::DoDateField(HDateField* instr) {
1880
  LOperand* date = UseFixed(instr->value(), eax);
1881
  LDateField* result =
1882
      new(zone()) LDateField(date, FixedTemp(ecx), instr->index());
1883
  return MarkAsCall(DefineFixed(result, eax), instr, CAN_DEOPTIMIZE_EAGERLY);
1884 1885 1886
}


1887 1888 1889 1890 1891 1892 1893
LInstruction* LChunkBuilder::DoSeqStringGetChar(HSeqStringGetChar* instr) {
  LOperand* string = UseRegisterAtStart(instr->string());
  LOperand* index = UseRegisterOrConstantAtStart(instr->index());
  return DefineAsRegister(new(zone()) LSeqStringGetChar(string, index));
}


1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
LOperand* LChunkBuilder::GetSeqStringSetCharOperand(HSeqStringSetChar* instr) {
  if (instr->encoding() == String::ONE_BYTE_ENCODING) {
    if (FLAG_debug_code) {
      return UseFixed(instr->value(), eax);
    } else {
      return UseFixedOrConstant(instr->value(), eax);
    }
  } else {
    if (FLAG_debug_code) {
      return UseRegisterAtStart(instr->value());
    } else {
      return UseRegisterOrConstantAtStart(instr->value());
    }
  }
}


1911
LInstruction* LChunkBuilder::DoSeqStringSetChar(HSeqStringSetChar* instr) {
1912
  LOperand* string = UseRegisterAtStart(instr->string());
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
  LOperand* index = FLAG_debug_code
      ? UseRegisterAtStart(instr->index())
      : UseRegisterOrConstantAtStart(instr->index());
  LOperand* value = GetSeqStringSetCharOperand(instr);
  LOperand* context = FLAG_debug_code ? UseFixed(instr->context(), esi) : NULL;
  LInstruction* result = new(zone()) LSeqStringSetChar(context, string,
                                                       index, value);
  if (FLAG_debug_code) {
    result = MarkAsCall(result, instr);
  }
  return result;
1924 1925 1926
}


1927
LInstruction* LChunkBuilder::DoBoundsCheck(HBoundsCheck* instr) {
1928
  return AssignEnvironment(new(zone()) LBoundsCheck(
1929 1930
      UseRegisterOrConstantAtStart(instr->index()),
      UseAtStart(instr->length())));
1931 1932 1933
}


1934 1935 1936 1937 1938 1939 1940
LInstruction* LChunkBuilder::DoBoundsCheckBaseIndexInformation(
    HBoundsCheckBaseIndexInformation* instr) {
  UNREACHABLE();
  return NULL;
}


1941 1942 1943 1944 1945 1946 1947
LInstruction* LChunkBuilder::DoAbnormalExit(HAbnormalExit* instr) {
  // The control instruction marking the end of a block that completed
  // abruptly (e.g., threw an exception).  There is nothing specific to do.
  return NULL;
}


1948
LInstruction* LChunkBuilder::DoThrow(HThrow* instr) {
1949
  LOperand* context = UseFixed(instr->context(), esi);
1950
  LOperand* value = UseFixed(instr->value(), eax);
1951
  return MarkAsCall(new(zone()) LThrow(context, value), instr);
1952 1953 1954
}


1955 1956 1957 1958 1959
LInstruction* LChunkBuilder::DoUseConst(HUseConst* instr) {
  return NULL;
}


1960 1961 1962 1963 1964 1965 1966 1967
LInstruction* LChunkBuilder::DoForceRepresentation(HForceRepresentation* bad) {
  // All HForceRepresentation instructions should be eliminated in the
  // representation change phase of Hydrogen.
  UNREACHABLE();
  return NULL;
}


1968 1969 1970
LInstruction* LChunkBuilder::DoChange(HChange* instr) {
  Representation from = instr->from();
  Representation to = instr->to();
1971 1972 1973
  if (from.IsSmi()) {
    if (to.IsTagged()) {
      LOperand* value = UseRegister(instr->value());
1974
      return DefineSameAsFirst(new(zone()) LDummyUse(value));
1975 1976 1977
    }
    from = Representation::Tagged();
  }
1978 1979 1980
  // Only mark conversions that might need to allocate as calling rather than
  // all changes. This makes simple, non-allocating conversion not have to force
  // building a stack frame.
1981 1982 1983
  if (from.IsTagged()) {
    if (to.IsDouble()) {
      LOperand* value = UseRegister(instr->value());
1984
      // Temp register only necessary for minus zero check.
1985
      LOperand* temp = TempRegister();
1986
      LNumberUntagD* res = new(zone()) LNumberUntagD(value, temp);
1987
      return AssignEnvironment(DefineAsRegister(res));
1988 1989
    } else if (to.IsSmi()) {
      HValue* val = instr->value();
1990
      LOperand* value = UseRegister(val);
1991 1992 1993
      if (val->type().IsSmi()) {
        return DefineSameAsFirst(new(zone()) LDummyUse(value));
      }
1994
      return AssignEnvironment(DefineSameAsFirst(new(zone()) LCheckSmi(value)));
1995 1996
    } else {
      ASSERT(to.IsInteger32());
1997 1998 1999
      HValue* val = instr->value();
      if (val->type().IsSmi() || val->representation().IsSmi()) {
        LOperand* value = UseRegister(val);
2000
        return DefineSameAsFirst(new(zone()) LSmiUntag(value, false));
2001
      } else {
2002
        bool truncating = instr->CanTruncateToInt32();
2003 2004 2005 2006 2007
        LOperand* xmm_temp =
            (CpuFeatures::IsSafeForSnapshot(SSE2) && !truncating)
                ? FixedTemp(xmm1) : NULL;
        LTaggedToI* res = new(zone()) LTaggedToI(UseRegister(val), xmm_temp);
        return AssignEnvironment(DefineSameAsFirst(res));
2008 2009 2010 2011
      }
    }
  } else if (from.IsDouble()) {
    if (to.IsTagged()) {
2012
      info()->MarkAsDeferredCalling();
2013
      LOperand* value = UseRegisterAtStart(instr->value());
2014
      LOperand* temp = FLAG_inline_new ? TempRegister() : NULL;
2015 2016 2017

      // Make sure that temp and result_temp are different registers.
      LUnallocated* result_temp = TempRegister();
2018
      LNumberTagD* result = new(zone()) LNumberTagD(value, temp);
2019
      return AssignPointerMap(Define(result, result_temp));
2020 2021 2022 2023
    } else if (to.IsSmi()) {
      LOperand* value = UseRegister(instr->value());
      return AssignEnvironment(
          DefineAsRegister(new(zone()) LDoubleToSmi(value)));
2024 2025
    } else {
      ASSERT(to.IsInteger32());
2026
      bool truncating = instr->CanTruncateToInt32();
2027
      bool needs_temp = CpuFeatures::IsSafeForSnapshot(SSE2) && !truncating;
2028 2029 2030
      LOperand* value = needs_temp ?
          UseTempRegister(instr->value()) : UseRegister(instr->value());
      LOperand* temp = needs_temp ? TempRegister() : NULL;
2031 2032
      return AssignEnvironment(
          DefineAsRegister(new(zone()) LDoubleToI(value, temp)));
2033 2034
    }
  } else if (from.IsInteger32()) {
2035
    info()->MarkAsDeferredCalling();
2036 2037 2038 2039
    if (to.IsTagged()) {
      HValue* val = instr->value();
      LOperand* value = UseRegister(val);
      if (val->HasRange() && val->range()->IsInSmiRange()) {
2040
        return DefineSameAsFirst(new(zone()) LSmiTag(value));
2041
      } else if (val->CheckFlag(HInstruction::kUint32)) {
2042 2043 2044
        LOperand* temp = CpuFeatures::IsSupported(SSE2) ? FixedTemp(xmm1)
                                                        : NULL;
        LNumberTagU* result = new(zone()) LNumberTagU(value, temp);
2045
        return AssignEnvironment(AssignPointerMap(DefineSameAsFirst(result)));
2046
      } else {
2047
        LNumberTagI* result = new(zone()) LNumberTagI(value);
2048 2049
        return AssignEnvironment(AssignPointerMap(DefineSameAsFirst(result)));
      }
2050 2051 2052
    } else if (to.IsSmi()) {
      HValue* val = instr->value();
      LOperand* value = UseRegister(val);
2053 2054 2055
      LInstruction* result = val->CheckFlag(HInstruction::kUint32)
           ? DefineSameAsFirst(new(zone()) LUint32ToSmi(value))
           : DefineSameAsFirst(new(zone()) LInteger32ToSmi(value));
2056 2057 2058 2059
      if (val->HasRange() && val->range()->IsInSmiRange()) {
        return result;
      }
      return AssignEnvironment(result);
2060 2061
    } else {
      ASSERT(to.IsDouble());
2062 2063 2064 2065 2066 2067 2068 2069
      if (instr->value()->CheckFlag(HInstruction::kUint32)) {
        LOperand* temp = FixedTemp(xmm1);
        return DefineAsRegister(
            new(zone()) LUint32ToDouble(UseRegister(instr->value()), temp));
      } else {
        return DefineAsRegister(
            new(zone()) LInteger32ToDouble(Use(instr->value())));
      }
2070 2071 2072 2073 2074 2075 2076
    }
  }
  UNREACHABLE();
  return NULL;
}


2077
LInstruction* LChunkBuilder::DoCheckHeapObject(HCheckHeapObject* instr) {
2078
  LOperand* value = UseAtStart(instr->value());
2079
  return AssignEnvironment(new(zone()) LCheckNonSmi(value));
2080 2081 2082
}


2083 2084 2085 2086 2087 2088
LInstruction* LChunkBuilder::DoCheckSmi(HCheckSmi* instr) {
  LOperand* value = UseRegisterAtStart(instr->value());
  return AssignEnvironment(new(zone()) LCheckSmi(value));
}


2089 2090 2091
LInstruction* LChunkBuilder::DoCheckInstanceType(HCheckInstanceType* instr) {
  LOperand* value = UseRegisterAtStart(instr->value());
  LOperand* temp = TempRegister();
2092
  LCheckInstanceType* result = new(zone()) LCheckInstanceType(value, temp);
2093 2094 2095 2096
  return AssignEnvironment(result);
}


2097 2098 2099
LInstruction* LChunkBuilder::DoCheckValue(HCheckValue* instr) {
  // If the object is in new space, we'll emit a global cell compare and so
  // want the value in a register.  If the object gets promoted before we
2100 2101
  // emit code, we will still get the register but will do an immediate
  // compare instead of the cell compare.  This is safe.
2102
  LOperand* value = instr->object_in_new_space()
2103
      ? UseRegisterAtStart(instr->value()) : UseAtStart(instr->value());
2104
  return AssignEnvironment(new(zone()) LCheckValue(value));
2105 2106 2107
}


2108
LInstruction* LChunkBuilder::DoCheckMaps(HCheckMaps* instr) {
2109
  LOperand* value = NULL;
2110 2111 2112 2113
  if (!instr->CanOmitMapChecks()) {
    value = UseRegisterAtStart(instr->value());
    if (instr->has_migration_target()) info()->MarkAsDeferredCalling();
  }
2114
  LCheckMaps* result = new(zone()) LCheckMaps(value);
2115 2116 2117 2118 2119
  if (!instr->CanOmitMapChecks()) {
    AssignEnvironment(result);
    if (instr->has_migration_target()) return AssignPointerMap(result);
  }
  return result;
2120 2121 2122
}


2123 2124 2125 2126 2127
LInstruction* LChunkBuilder::DoClampToUint8(HClampToUint8* instr) {
  HValue* value = instr->value();
  Representation input_rep = value->representation();
  if (input_rep.IsDouble()) {
    LOperand* reg = UseRegister(value);
2128
    return DefineFixed(new(zone()) LClampDToUint8(reg), eax);
2129 2130
  } else if (input_rep.IsInteger32()) {
    LOperand* reg = UseFixed(value, eax);
2131
    return DefineFixed(new(zone()) LClampIToUint8(reg), eax);
2132
  } else {
2133
    ASSERT(input_rep.IsSmiOrTagged());
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
    if (CpuFeatures::IsSupported(SSE2)) {
      LOperand* reg = UseFixed(value, eax);
      // Register allocator doesn't (yet) support allocation of double
      // temps. Reserve xmm1 explicitly.
      LOperand* temp = FixedTemp(xmm1);
      LClampTToUint8* result = new(zone()) LClampTToUint8(reg, temp);
      return AssignEnvironment(DefineFixed(result, eax));
    } else {
      LOperand* value = UseRegister(instr->value());
      LClampTToUint8NoSSE2* res =
          new(zone()) LClampTToUint8NoSSE2(value, TempRegister(),
                                           TempRegister(), TempRegister());
      return AssignEnvironment(DefineFixed(res, ecx));
    }
2148 2149 2150 2151
  }
}


2152
LInstruction* LChunkBuilder::DoReturn(HReturn* instr) {
2153
  LOperand* context = info()->IsStub() ? UseFixed(instr->context(), esi) : NULL;
2154
  LOperand* parameter_count = UseRegisterOrConstant(instr->parameter_count());
2155 2156
  return new(zone()) LReturn(
      UseFixed(instr->value(), eax), context, parameter_count);
2157 2158 2159 2160 2161
}


LInstruction* LChunkBuilder::DoConstant(HConstant* instr) {
  Representation r = instr->representation();
2162 2163 2164
  if (r.IsSmi()) {
    return DefineAsRegister(new(zone()) LConstantS);
  } else if (r.IsInteger32()) {
2165
    return DefineAsRegister(new(zone()) LConstantI);
2166
  } else if (r.IsDouble()) {
2167
    double value = instr->DoubleValue();
2168
    bool value_is_zero = BitCast<uint64_t, double>(value) == 0;
2169 2170
    LOperand* temp = value_is_zero ? NULL : TempRegister();
    return DefineAsRegister(new(zone()) LConstantD(temp));
2171 2172
  } else if (r.IsExternal()) {
    return DefineAsRegister(new(zone()) LConstantE);
2173
  } else if (r.IsTagged()) {
2174
    return DefineAsRegister(new(zone()) LConstantT);
2175
  } else {
2176
    UNREACHABLE();
2177 2178 2179 2180 2181
    return NULL;
  }
}


2182
LInstruction* LChunkBuilder::DoLoadGlobalCell(HLoadGlobalCell* instr) {
2183
  LLoadGlobalCell* result = new(zone()) LLoadGlobalCell;
2184
  return instr->RequiresHoleCheck()
2185 2186 2187 2188 2189
      ? AssignEnvironment(DefineAsRegister(result))
      : DefineAsRegister(result);
}


2190 2191
LInstruction* LChunkBuilder::DoLoadGlobalGeneric(HLoadGlobalGeneric* instr) {
  LOperand* context = UseFixed(instr->context(), esi);
2192
  LOperand* global_object = UseFixed(instr->global_object(), edx);
2193 2194
  LLoadGlobalGeneric* result =
      new(zone()) LLoadGlobalGeneric(context, global_object);
2195 2196 2197 2198
  return MarkAsCall(DefineFixed(result, eax), instr);
}


2199 2200
LInstruction* LChunkBuilder::DoStoreGlobalCell(HStoreGlobalCell* instr) {
  LStoreGlobalCell* result =
2201
      new(zone()) LStoreGlobalCell(UseRegister(instr->value()));
2202
  return instr->RequiresHoleCheck() ? AssignEnvironment(result) : result;
2203 2204 2205
}


2206 2207 2208 2209 2210
LInstruction* LChunkBuilder::DoStoreGlobalGeneric(HStoreGlobalGeneric* instr) {
  LOperand* context = UseFixed(instr->context(), esi);
  LOperand* global_object = UseFixed(instr->global_object(), edx);
  LOperand* value = UseFixed(instr->value(), eax);
  LStoreGlobalGeneric* result =
2211
      new(zone()) LStoreGlobalGeneric(context, global_object, value);
2212 2213 2214 2215
  return MarkAsCall(result, instr);
}


2216
LInstruction* LChunkBuilder::DoLoadContextSlot(HLoadContextSlot* instr) {
2217
  LOperand* context = UseRegisterAtStart(instr->value());
2218 2219 2220
  LInstruction* result =
      DefineAsRegister(new(zone()) LLoadContextSlot(context));
  return instr->RequiresHoleCheck() ? AssignEnvironment(result) : result;
2221 2222 2223 2224 2225 2226
}


LInstruction* LChunkBuilder::DoStoreContextSlot(HStoreContextSlot* instr) {
  LOperand* value;
  LOperand* temp;
2227
  LOperand* context = UseRegister(instr->context());
2228 2229 2230 2231 2232 2233 2234
  if (instr->NeedsWriteBarrier()) {
    value = UseTempRegister(instr->value());
    temp = TempRegister();
  } else {
    value = UseRegister(instr->value());
    temp = NULL;
  }
2235 2236
  LInstruction* result = new(zone()) LStoreContextSlot(context, value, temp);
  return instr->RequiresHoleCheck() ? AssignEnvironment(result) : result;
2237 2238 2239
}


2240
LInstruction* LChunkBuilder::DoLoadNamedField(HLoadNamedField* instr) {
2241 2242 2243 2244
  LOperand* obj = (instr->access().IsExternalMemory() &&
                   instr->access().offset() == 0)
      ? UseRegisterOrConstantAtStart(instr->object())
      : UseRegisterAtStart(instr->object());
2245
  return DefineAsRegister(new(zone()) LLoadNamedField(obj));
2246 2247 2248 2249
}


LInstruction* LChunkBuilder::DoLoadNamedGeneric(HLoadNamedGeneric* instr) {
2250
  LOperand* context = UseFixed(instr->context(), esi);
2251
  LOperand* object = UseFixed(instr->object(), edx);
2252
  LLoadNamedGeneric* result = new(zone()) LLoadNamedGeneric(context, object);
2253
  return MarkAsCall(DefineFixed(result, eax), instr);
2254 2255 2256
}


2257 2258 2259
LInstruction* LChunkBuilder::DoLoadFunctionPrototype(
    HLoadFunctionPrototype* instr) {
  return AssignEnvironment(DefineAsRegister(
2260 2261
      new(zone()) LLoadFunctionPrototype(UseRegister(instr->function()),
                                         TempRegister())));
2262 2263 2264
}


2265 2266 2267 2268 2269
LInstruction* LChunkBuilder::DoLoadRoot(HLoadRoot* instr) {
  return DefineAsRegister(new(zone()) LLoadRoot);
}


2270 2271
LInstruction* LChunkBuilder::DoLoadExternalArrayPointer(
    HLoadExternalArrayPointer* instr) {
2272
  LOperand* input = UseRegisterAtStart(instr->value());
2273
  return DefineAsRegister(new(zone()) LLoadExternalArrayPointer(input));
2274 2275 2276
}


2277
LInstruction* LChunkBuilder::DoLoadKeyed(HLoadKeyed* instr) {
2278
  ASSERT(instr->key()->representation().IsSmiOrInteger32());
2279
  ElementsKind elements_kind = instr->elements_kind();
2280 2281 2282
  bool clobbers_key = ExternalArrayOpRequiresTemp(
      instr->key()->representation(), elements_kind);
  LOperand* key = clobbers_key
2283
      ? UseTempRegister(instr->key())
2284
      : UseRegisterOrConstantAtStart(instr->key());
2285
  LLoadKeyed* result = NULL;
2286

2287 2288 2289 2290
  if (!instr->is_external()) {
    LOperand* obj = UseRegisterAtStart(instr->elements());
    result = new(zone()) LLoadKeyed(obj, key);
  } else {
2291 2292 2293 2294 2295 2296 2297
    ASSERT(
        (instr->representation().IsInteger32() &&
         (elements_kind != EXTERNAL_FLOAT_ELEMENTS) &&
         (elements_kind != EXTERNAL_DOUBLE_ELEMENTS)) ||
        (instr->representation().IsDouble() &&
         ((elements_kind == EXTERNAL_FLOAT_ELEMENTS) ||
          (elements_kind == EXTERNAL_DOUBLE_ELEMENTS))));
2298 2299
    LOperand* external_pointer = UseRegister(instr->elements());
    result = new(zone()) LLoadKeyed(external_pointer, key);
2300
  }
2301

2302 2303 2304
  DefineAsRegister(result);
  bool can_deoptimize = instr->RequiresHoleCheck() ||
      (elements_kind == EXTERNAL_UNSIGNED_INT_ELEMENTS);
2305 2306
  // An unsigned int array load might overflow and cause a deopt, make sure it
  // has an environment.
2307
  return can_deoptimize ? AssignEnvironment(result) : result;
2308 2309 2310
}


2311
LInstruction* LChunkBuilder::DoLoadKeyedGeneric(HLoadKeyedGeneric* instr) {
2312
  LOperand* context = UseFixed(instr->context(), esi);
2313
  LOperand* object = UseFixed(instr->object(), edx);
2314
  LOperand* key = UseFixed(instr->key(), ecx);
2315

2316 2317
  LLoadKeyedGeneric* result =
      new(zone()) LLoadKeyedGeneric(context, object, key);
2318
  return MarkAsCall(DefineFixed(result, eax), instr);
2319 2320 2321
}


2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
LOperand* LChunkBuilder::GetStoreKeyedValueOperand(HStoreKeyed* instr) {
  ElementsKind elements_kind = instr->elements_kind();

  // Determine if we need a byte register in this case for the value.
  bool val_is_fixed_register =
      elements_kind == EXTERNAL_BYTE_ELEMENTS ||
      elements_kind == EXTERNAL_UNSIGNED_BYTE_ELEMENTS ||
      elements_kind == EXTERNAL_PIXEL_ELEMENTS;
  if (val_is_fixed_register) {
    return UseFixed(instr->value(), eax);
  }

  if (!CpuFeatures::IsSafeForSnapshot(SSE2) &&
      IsDoubleOrFloatElementsKind(elements_kind)) {
    return UseRegisterAtStart(instr->value());
  }

  return UseRegister(instr->value());
}


2343 2344 2345 2346
LInstruction* LChunkBuilder::DoStoreKeyed(HStoreKeyed* instr) {
  if (!instr->is_external()) {
    ASSERT(instr->elements()->representation().IsTagged());
    ASSERT(instr->key()->representation().IsInteger32() ||
2347
           instr->key()->representation().IsSmi());
2348

2349 2350
    if (instr->value()->representation().IsDouble()) {
      LOperand* object = UseRegisterAtStart(instr->elements());
2351
      LOperand* val = NULL;
2352
      val = UseRegisterAtStart(instr->value());
2353
      LOperand* key = UseRegisterOrConstantAtStart(instr->key());
2354
      return new(zone()) LStoreKeyed(object, key, val);
2355
    } else {
2356
      ASSERT(instr->value()->representation().IsSmiOrTagged());
2357 2358 2359
      bool needs_write_barrier = instr->NeedsWriteBarrier();

      LOperand* obj = UseRegister(instr->elements());
2360 2361 2362 2363 2364 2365
      LOperand* val;
      LOperand* key;
      if (needs_write_barrier) {
        val = UseTempRegister(instr->value());
        key = UseTempRegister(instr->key());
      } else {
2366 2367
        val = UseRegisterOrConstantAtStart(instr->value());
        key = UseRegisterOrConstantAtStart(instr->key());
2368
      }
2369
      return new(zone()) LStoreKeyed(obj, key, val);
2370
    }
2371
  }
2372

2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
  ElementsKind elements_kind = instr->elements_kind();
  ASSERT(
      (instr->value()->representation().IsInteger32() &&
       (elements_kind != EXTERNAL_FLOAT_ELEMENTS) &&
       (elements_kind != EXTERNAL_DOUBLE_ELEMENTS)) ||
      (instr->value()->representation().IsDouble() &&
       ((elements_kind == EXTERNAL_FLOAT_ELEMENTS) ||
        (elements_kind == EXTERNAL_DOUBLE_ELEMENTS))));
  ASSERT(instr->elements()->representation().IsExternal());

  LOperand* external_pointer = UseRegister(instr->elements());
2384
  LOperand* val = GetStoreKeyedValueOperand(instr);
2385 2386 2387 2388 2389 2390 2391 2392
  bool clobbers_key = ExternalArrayOpRequiresTemp(
      instr->key()->representation(), elements_kind);
  LOperand* key = clobbers_key
      ? UseTempRegister(instr->key())
      : UseRegisterOrConstantAtStart(instr->key());
  return new(zone()) LStoreKeyed(external_pointer,
                                 key,
                                 val);
2393 2394 2395
}


2396
LInstruction* LChunkBuilder::DoStoreKeyedGeneric(HStoreKeyedGeneric* instr) {
2397 2398
  LOperand* context = UseFixed(instr->context(), esi);
  LOperand* object = UseFixed(instr->object(), edx);
2399
  LOperand* key = UseFixed(instr->key(), ecx);
2400
  LOperand* value = UseFixed(instr->value(), eax);
2401 2402 2403 2404 2405

  ASSERT(instr->object()->representation().IsTagged());
  ASSERT(instr->key()->representation().IsTagged());
  ASSERT(instr->value()->representation().IsTagged());

2406
  LStoreKeyedGeneric* result =
2407
      new(zone()) LStoreKeyedGeneric(context, object, key, value);
2408
  return MarkAsCall(result, instr);
2409 2410 2411
}


2412 2413
LInstruction* LChunkBuilder::DoTransitionElementsKind(
    HTransitionElementsKind* instr) {
2414
  LOperand* object = UseRegister(instr->object());
2415
  if (IsSimpleMapChangeTransition(instr->from_kind(), instr->to_kind())) {
2416 2417 2418 2419
    LOperand* object = UseRegister(instr->object());
    LOperand* new_map_reg = TempRegister();
    LOperand* temp_reg = TempRegister();
    LTransitionElementsKind* result =
2420 2421 2422
        new(zone()) LTransitionElementsKind(object, NULL,
                                            new_map_reg, temp_reg);
    return result;
2423
  } else {
2424
    LOperand* context = UseFixed(instr->context(), esi);
2425 2426 2427
    LTransitionElementsKind* result =
        new(zone()) LTransitionElementsKind(object, context, NULL, NULL);
    return AssignPointerMap(result);
2428 2429 2430 2431
  }
}


2432 2433 2434 2435 2436 2437 2438 2439 2440 2441
LInstruction* LChunkBuilder::DoTrapAllocationMemento(
    HTrapAllocationMemento* instr) {
  LOperand* object = UseRegister(instr->object());
  LOperand* temp = TempRegister();
  LTrapAllocationMemento* result =
      new(zone()) LTrapAllocationMemento(object, temp);
  return AssignEnvironment(result);
}


2442
LInstruction* LChunkBuilder::DoStoreNamedField(HStoreNamedField* instr) {
2443
  bool is_in_object = instr->access().IsInobject();
2444 2445
  bool is_external_location = instr->access().IsExternalMemory() &&
      instr->access().offset() == 0;
2446
  bool needs_write_barrier = instr->NeedsWriteBarrier();
2447
  bool needs_write_barrier_for_map = instr->has_transition() &&
2448
      instr->NeedsWriteBarrierForMap();
2449

2450 2451
  LOperand* obj;
  if (needs_write_barrier) {
2452
    obj = is_in_object
2453 2454
        ? UseRegister(instr->object())
        : UseTempRegister(instr->object());
2455 2456 2457 2458 2459
  } else if (is_external_location) {
    ASSERT(!is_in_object);
    ASSERT(!needs_write_barrier);
    ASSERT(!needs_write_barrier_for_map);
    obj = UseRegisterOrConstant(instr->object());
2460
  } else {
2461 2462 2463
    obj = needs_write_barrier_for_map
        ? UseRegister(instr->object())
        : UseRegisterAtStart(instr->object());
2464
  }
2465

2466
  bool can_be_constant = instr->value()->IsConstant() &&
2467
      HConstant::cast(instr->value())->NotInNewSpace() &&
2468
      !(FLAG_track_double_fields && instr->field_representation().IsDouble());
2469

2470
  LOperand* val;
2471 2472
  if (instr->field_representation().IsInteger8() ||
      instr->field_representation().IsUInteger8()) {
2473 2474 2475 2476
    // mov_b requires a byte register (i.e. any of eax, ebx, ecx, edx).
    // Just force the value to be in eax and we're safe here.
    val = UseFixed(instr->value(), eax);
  } else if (needs_write_barrier) {
2477
    val = UseTempRegister(instr->value());
2478
  } else if (can_be_constant) {
2479
    val = UseRegisterOrConstant(instr->value());
2480 2481
  } else if (FLAG_track_fields && instr->field_representation().IsSmi()) {
    val = UseTempRegister(instr->value());
2482 2483
  } else if (FLAG_track_double_fields &&
             instr->field_representation().IsDouble()) {
2484
    val = UseRegisterAtStart(instr->value());
2485 2486 2487
  } else {
    val = UseRegister(instr->value());
  }
2488 2489 2490

  // We only need a scratch register if we have a write barrier or we
  // have a store into the properties array (not in-object-property).
2491
  LOperand* temp = (!is_in_object || needs_write_barrier ||
2492
                    needs_write_barrier_for_map) ? TempRegister() : NULL;
2493 2494 2495

  // We need a temporary register for write barrier of the map field.
  LOperand* temp_map = needs_write_barrier_for_map ? TempRegister() : NULL;
2496

2497 2498
  LStoreNamedField* result =
      new(zone()) LStoreNamedField(obj, val, temp, temp_map);
2499 2500 2501 2502 2503
  if (FLAG_track_heap_object_fields &&
      instr->field_representation().IsHeapObject()) {
    if (!instr->value()->type().IsHeapObject()) {
      return AssignEnvironment(result);
    }
2504 2505
  }
  return result;
2506 2507 2508 2509
}


LInstruction* LChunkBuilder::DoStoreNamedGeneric(HStoreNamedGeneric* instr) {
2510 2511 2512
  LOperand* context = UseFixed(instr->context(), esi);
  LOperand* object = UseFixed(instr->object(), edx);
  LOperand* value = UseFixed(instr->value(), eax);
2513

2514 2515
  LStoreNamedGeneric* result =
      new(zone()) LStoreNamedGeneric(context, object, value);
2516 2517 2518 2519
  return MarkAsCall(result, instr);
}


2520
LInstruction* LChunkBuilder::DoStringAdd(HStringAdd* instr) {
2521
  LOperand* context = UseFixed(instr->context(), esi);
2522 2523 2524 2525 2526 2527
  LOperand* left = FLAG_new_string_add
      ? UseFixed(instr->left(), edx)
      : UseOrConstantAtStart(instr->left());
  LOperand* right = FLAG_new_string_add
      ? UseFixed(instr->right(), eax)
      : UseOrConstantAtStart(instr->right());
2528
  LStringAdd* string_add = new(zone()) LStringAdd(context, left, right);
2529
  return MarkAsCall(DefineFixed(string_add, eax), instr);
2530 2531 2532
}


2533
LInstruction* LChunkBuilder::DoStringCharCodeAt(HStringCharCodeAt* instr) {
2534 2535
  LOperand* string = UseTempRegister(instr->string());
  LOperand* index = UseTempRegister(instr->index());
2536
  LOperand* context = UseAny(instr->context());
2537 2538
  LStringCharCodeAt* result =
      new(zone()) LStringCharCodeAt(context, string, index);
2539
  return AssignEnvironment(AssignPointerMap(DefineAsRegister(result)));
2540 2541 2542
}


2543 2544
LInstruction* LChunkBuilder::DoStringCharFromCode(HStringCharFromCode* instr) {
  LOperand* char_code = UseRegister(instr->value());
2545
  LOperand* context = UseAny(instr->context());
2546 2547
  LStringCharFromCode* result =
      new(zone()) LStringCharFromCode(context, char_code);
2548 2549 2550 2551
  return AssignPointerMap(DefineAsRegister(result));
}


2552 2553 2554
LInstruction* LChunkBuilder::DoAllocate(HAllocate* instr) {
  info()->MarkAsDeferredCalling();
  LOperand* context = UseAny(instr->context());
2555 2556 2557
  LOperand* size = instr->size()->IsConstant()
      ? UseConstant(instr->size())
      : UseTempRegister(instr->size());
2558 2559 2560 2561 2562 2563
  LOperand* temp = TempRegister();
  LAllocate* result = new(zone()) LAllocate(context, size, temp);
  return AssignPointerMap(DefineAsRegister(result));
}


2564
LInstruction* LChunkBuilder::DoRegExpLiteral(HRegExpLiteral* instr) {
2565
  LOperand* context = UseFixed(instr->context(), esi);
2566 2567
  return MarkAsCall(
      DefineFixed(new(zone()) LRegExpLiteral(context), eax), instr);
2568 2569 2570 2571
}


LInstruction* LChunkBuilder::DoFunctionLiteral(HFunctionLiteral* instr) {
2572
  LOperand* context = UseFixed(instr->context(), esi);
2573 2574
  return MarkAsCall(
      DefineFixed(new(zone()) LFunctionLiteral(context), eax), instr);
2575 2576 2577 2578
}


LInstruction* LChunkBuilder::DoOsrEntry(HOsrEntry* instr) {
2579
  ASSERT(argument_count_ == 0);
2580 2581
  allocator_->MarkAsOsrEntry();
  current_block_->last_environment()->set_ast_id(instr->ast_id());
2582
  return AssignEnvironment(new(zone()) LOsrEntry);
2583 2584 2585 2586
}


LInstruction* LChunkBuilder::DoParameter(HParameter* instr) {
2587
  LParameter* result = new(zone()) LParameter;
2588
  if (instr->kind() == HParameter::STACK_PARAMETER) {
2589 2590 2591 2592 2593 2594
    int spill_index = chunk()->GetParameterStackSlot(instr->index());
    return DefineAsSpilled(result, spill_index);
  } else {
    ASSERT(info()->IsStub());
    CodeStubInterfaceDescriptor* descriptor =
        info()->code_stub()->GetInterfaceDescriptor(info()->isolate());
2595
    int index = static_cast<int>(instr->index());
2596
    Register reg = descriptor->GetParameterRegister(index);
2597 2598
    return DefineFixed(result, reg);
  }
2599 2600 2601 2602
}


LInstruction* LChunkBuilder::DoUnknownOSRValue(HUnknownOSRValue* instr) {
2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
  // Use an index that corresponds to the location in the unoptimized frame,
  // which the optimized frame will subsume.
  int env_index = instr->index();
  int spill_index = 0;
  if (instr->environment()->is_parameter_index(env_index)) {
    spill_index = chunk()->GetParameterStackSlot(env_index);
  } else {
    spill_index = env_index - instr->environment()->first_local_index();
    if (spill_index > LUnallocated::kMaxFixedSlotIndex) {
      Abort(kNotEnoughSpillSlotsForOsr);
      spill_index = 0;
    }
    if (spill_index == 0) {
      // The dynamic frame alignment state overwrites the first local.
      // The first local is saved at the end of the unoptimized frame.
      spill_index = graph()->osr()->UnoptimizedFrameSlots();
    }
2620
  }
2621
  return DefineAsSpilled(new(zone()) LUnknownOSRValue, spill_index);
2622 2623 2624 2625
}


LInstruction* LChunkBuilder::DoCallStub(HCallStub* instr) {
2626
  LOperand* context = UseFixed(instr->context(), esi);
2627
  LCallStub* result = new(zone()) LCallStub(context);
2628
  return MarkAsCall(DefineFixed(result, eax), instr);
2629 2630 2631 2632
}


LInstruction* LChunkBuilder::DoArgumentsObject(HArgumentsObject* instr) {
2633 2634 2635 2636
  // There are no real uses of the arguments object.
  // arguments.length and element access are supported directly on
  // stack arguments, and any real arguments object use causes a bailout.
  // So this value is never used.
2637 2638 2639 2640
  return NULL;
}


2641
LInstruction* LChunkBuilder::DoCapturedObject(HCapturedObject* instr) {
2642
  instr->ReplayEnvironment(current_block_->last_environment());
2643

2644 2645 2646 2647 2648
  // There are no real uses of a captured object.
  return NULL;
}


2649
LInstruction* LChunkBuilder::DoAccessArgumentsAt(HAccessArgumentsAt* instr) {
2650
  info()->MarkAsRequiresFrame();
2651
  LOperand* args = UseRegister(instr->arguments());
2652 2653 2654 2655 2656 2657 2658 2659 2660
  LOperand* length;
  LOperand* index;
  if (instr->length()->IsConstant() && instr->index()->IsConstant()) {
    length = UseRegisterOrConstant(instr->length());
    index = UseOrConstant(instr->index());
  } else {
    length = UseTempRegister(instr->length());
    index = Use(instr->index());
  }
2661
  return DefineAsRegister(new(zone()) LAccessArgumentsAt(args, length, index));
2662 2663 2664
}


2665 2666
LInstruction* LChunkBuilder::DoToFastProperties(HToFastProperties* instr) {
  LOperand* object = UseFixed(instr->value(), eax);
2667
  LToFastProperties* result = new(zone()) LToFastProperties(object);
2668 2669 2670 2671
  return MarkAsCall(DefineFixed(result, eax), instr);
}


2672
LInstruction* LChunkBuilder::DoTypeof(HTypeof* instr) {
2673 2674
  LOperand* context = UseFixed(instr->context(), esi);
  LOperand* value = UseAtStart(instr->value());
2675
  LTypeof* result = new(zone()) LTypeof(context, value);
2676 2677 2678 2679
  return MarkAsCall(DefineFixed(result, eax), instr);
}


2680
LInstruction* LChunkBuilder::DoTypeofIsAndBranch(HTypeofIsAndBranch* instr) {
2681 2682
  LInstruction* goto_instr = CheckElideControlInstruction(instr);
  if (goto_instr != NULL) return goto_instr;
2683
  return new(zone()) LTypeofIsAndBranch(UseTempRegister(instr->value()));
2684 2685
}

2686

2687 2688
LInstruction* LChunkBuilder::DoIsConstructCallAndBranch(
    HIsConstructCallAndBranch* instr) {
2689
  return new(zone()) LIsConstructCallAndBranch(TempRegister());
2690 2691 2692
}


2693
LInstruction* LChunkBuilder::DoSimulate(HSimulate* instr) {
2694
  instr->ReplayEnvironment(current_block_->last_environment());
2695 2696 2697

  // If there is an instruction pending deoptimization environment create a
  // lazy bailout instruction to capture the environment.
2698
  if (!pending_deoptimization_ast_id_.IsNone()) {
2699
    ASSERT(pending_deoptimization_ast_id_ == instr->ast_id());
2700
    LLazyBailout* lazy_bailout = new(zone()) LLazyBailout;
2701
    LInstruction* result = AssignEnvironment(lazy_bailout);
2702 2703
    // Store the lazy deopt environment with the instruction if needed. Right
    // now it is only used for LInstanceOfKnownGlobal.
2704
    instruction_pending_deoptimization_environment_->
2705 2706
        SetDeferredLazyDeoptimizationEnvironment(result->environment());
    instruction_pending_deoptimization_environment_ = NULL;
2707
    pending_deoptimization_ast_id_ = BailoutId::None();
2708 2709 2710 2711 2712 2713 2714 2715
    return result;
  }

  return NULL;
}


LInstruction* LChunkBuilder::DoStackCheck(HStackCheck* instr) {
2716
  info()->MarkAsDeferredCalling();
2717 2718 2719 2720 2721 2722 2723 2724 2725
  if (instr->is_function_entry()) {
    LOperand* context = UseFixed(instr->context(), esi);
    return MarkAsCall(new(zone()) LStackCheck(context), instr);
  } else {
    ASSERT(instr->is_backwards_branch());
    LOperand* context = UseAny(instr->context());
    return AssignEnvironment(
        AssignPointerMap(new(zone()) LStackCheck(context)));
  }
2726 2727 2728 2729 2730 2731 2732
}


LInstruction* LChunkBuilder::DoEnterInlined(HEnterInlined* instr) {
  HEnvironment* outer = current_block_->last_environment();
  HConstant* undefined = graph()->GetConstantUndefined();
  HEnvironment* inner = outer->CopyForInlining(instr->closure(),
2733
                                               instr->arguments_count(),
2734
                                               instr->function(),
2735
                                               undefined,
2736 2737
                                               instr->inlining_kind(),
                                               instr->undefined_receiver());
2738 2739 2740
  // Only replay binding of arguments object if it wasn't removed from graph.
  if (instr->arguments_var() != NULL && instr->arguments_object()->IsLinked()) {
    inner->Bind(instr->arguments_var(), instr->arguments_object());
2741
  }
2742
  inner->set_entry(instr);
2743 2744 2745 2746 2747 2748 2749
  current_block_->UpdateEnvironment(inner);
  chunk_->AddInlinedClosure(instr->closure());
  return NULL;
}


LInstruction* LChunkBuilder::DoLeaveInlined(HLeaveInlined* instr) {
2750 2751 2752 2753
  LInstruction* pop = NULL;

  HEnvironment* env = current_block_->last_environment();

2754
  if (env->entry()->arguments_pushed()) {
2755 2756
    int argument_count = env->arguments_environment()->parameter_count();
    pop = new(zone()) LDrop(argument_count);
2757
    ASSERT(instr->argument_delta() == -argument_count);
2758 2759
  }

2760 2761
  HEnvironment* outer = current_block_->last_environment()->
      DiscardInlined(false);
2762
  current_block_->UpdateEnvironment(outer);
2763
  return pop;
2764 2765 2766
}


2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795
LInstruction* LChunkBuilder::DoForInPrepareMap(HForInPrepareMap* instr) {
  LOperand* context = UseFixed(instr->context(), esi);
  LOperand* object = UseFixed(instr->enumerable(), eax);
  LForInPrepareMap* result = new(zone()) LForInPrepareMap(context, object);
  return MarkAsCall(DefineFixed(result, eax), instr, CAN_DEOPTIMIZE_EAGERLY);
}


LInstruction* LChunkBuilder::DoForInCacheArray(HForInCacheArray* instr) {
  LOperand* map = UseRegister(instr->map());
  return AssignEnvironment(DefineAsRegister(
      new(zone()) LForInCacheArray(map)));
}


LInstruction* LChunkBuilder::DoCheckMapValue(HCheckMapValue* instr) {
  LOperand* value = UseRegisterAtStart(instr->value());
  LOperand* map = UseRegisterAtStart(instr->map());
  return AssignEnvironment(new(zone()) LCheckMapValue(value, map));
}


LInstruction* LChunkBuilder::DoLoadFieldByIndex(HLoadFieldByIndex* instr) {
  LOperand* object = UseRegister(instr->object());
  LOperand* index = UseTempRegister(instr->index());
  return DefineSameAsFirst(new(zone()) LLoadFieldByIndex(object, index));
}


2796
} }  // namespace v8::internal
2797 2798

#endif  // V8_TARGET_ARCH_IA32