1 // Copyright 2012 the V8 project authors. All rights reserved. 2 // Redistribution and use in source and binary forms, with or without 3 // modification, are permitted provided that the following conditions are 4 // met: 5 // 6 // * Redistributions of source code must retain the above copyright 7 // notice, this list of conditions and the following disclaimer. 8 // * Redistributions in binary form must reproduce the above 9 // copyright notice, this list of conditions and the following 10 // disclaimer in the documentation and/or other materials provided 11 // with the distribution. 12 // * Neither the name of Google Inc. nor the names of its 13 // contributors may be used to endorse or promote products derived 14 // from this software without specific prior written permission. 15 // 16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 28 #include "v8.h" 29 30 #if V8_TARGET_ARCH_X64 31 32 #include "code-stubs.h" 33 #include "codegen.h" 34 #include "compiler.h" 35 #include "debug.h" 36 #include "full-codegen.h" 37 #include "isolate-inl.h" 38 #include "parser.h" 39 #include "scopes.h" 40 #include "stub-cache.h" 41 42 namespace v8 { 43 namespace internal { 44 45 #define __ ACCESS_MASM(masm_) 46 47 48 class JumpPatchSite BASE_EMBEDDED { 49 public: 50 explicit JumpPatchSite(MacroAssembler* masm) : masm_(masm) { 51 #ifdef DEBUG 52 info_emitted_ = false; 53 #endif 54 } 55 56 ~JumpPatchSite() { 57 ASSERT(patch_site_.is_bound() == info_emitted_); 58 } 59 60 void EmitJumpIfNotSmi(Register reg, 61 Label* target, 62 Label::Distance near_jump = Label::kFar) { 63 __ testb(reg, Immediate(kSmiTagMask)); 64 EmitJump(not_carry, target, near_jump); // Always taken before patched. 65 } 66 67 void EmitJumpIfSmi(Register reg, 68 Label* target, 69 Label::Distance near_jump = Label::kFar) { 70 __ testb(reg, Immediate(kSmiTagMask)); 71 EmitJump(carry, target, near_jump); // Never taken before patched. 72 } 73 74 void EmitPatchInfo() { 75 if (patch_site_.is_bound()) { 76 int delta_to_patch_site = masm_->SizeOfCodeGeneratedSince(&patch_site_); 77 ASSERT(is_int8(delta_to_patch_site)); 78 __ testl(rax, Immediate(delta_to_patch_site)); 79 #ifdef DEBUG 80 info_emitted_ = true; 81 #endif 82 } else { 83 __ nop(); // Signals no inlined code. 84 } 85 } 86 87 private: 88 // jc will be patched with jz, jnc will become jnz. 89 void EmitJump(Condition cc, Label* target, Label::Distance near_jump) { 90 ASSERT(!patch_site_.is_bound() && !info_emitted_); 91 ASSERT(cc == carry || cc == not_carry); 92 __ bind(&patch_site_); 93 __ j(cc, target, near_jump); 94 } 95 96 MacroAssembler* masm_; 97 Label patch_site_; 98 #ifdef DEBUG 99 bool info_emitted_; 100 #endif 101 }; 102 103 104 // Generate code for a JS function. On entry to the function the receiver 105 // and arguments have been pushed on the stack left to right, with the 106 // return address on top of them. The actual argument count matches the 107 // formal parameter count expected by the function. 108 // 109 // The live registers are: 110 // o rdi: the JS function object being called (i.e. ourselves) 111 // o rsi: our context 112 // o rbp: our caller's frame pointer 113 // o rsp: stack pointer (pointing to return address) 114 // 115 // The function builds a JS frame. Please see JavaScriptFrameConstants in 116 // frames-x64.h for its layout. 117 void FullCodeGenerator::Generate() { 118 CompilationInfo* info = info_; 119 handler_table_ = 120 isolate()->factory()->NewFixedArray(function()->handler_count(), TENURED); 121 profiling_counter_ = isolate()->factory()->NewCell( 122 Handle<Smi>(Smi::FromInt(FLAG_interrupt_budget), isolate())); 123 SetFunctionPosition(function()); 124 Comment cmnt(masm_, "[ function compiled by full code generator"); 125 126 ProfileEntryHookStub::MaybeCallEntryHook(masm_); 127 128 #ifdef DEBUG 129 if (strlen(FLAG_stop_at) > 0 && 130 info->function()->name()->IsUtf8EqualTo(CStrVector(FLAG_stop_at))) { 131 __ int3(); 132 } 133 #endif 134 135 // Strict mode functions and builtins need to replace the receiver 136 // with undefined when called as functions (without an explicit 137 // receiver object). rcx is zero for method calls and non-zero for 138 // function calls. 139 if (!info->is_classic_mode() || info->is_native()) { 140 Label ok; 141 __ testq(rcx, rcx); 142 __ j(zero, &ok, Label::kNear); 143 StackArgumentsAccessor args(rsp, info->scope()->num_parameters()); 144 __ LoadRoot(kScratchRegister, Heap::kUndefinedValueRootIndex); 145 __ movq(args.GetReceiverOperand(), kScratchRegister); 146 __ bind(&ok); 147 } 148 149 // Open a frame scope to indicate that there is a frame on the stack. The 150 // MANUAL indicates that the scope shouldn't actually generate code to set up 151 // the frame (that is done below). 152 FrameScope frame_scope(masm_, StackFrame::MANUAL); 153 154 info->set_prologue_offset(masm_->pc_offset()); 155 __ Prologue(BUILD_FUNCTION_FRAME); 156 info->AddNoFrameRange(0, masm_->pc_offset()); 157 158 { Comment cmnt(masm_, "[ Allocate locals"); 159 int locals_count = info->scope()->num_stack_slots(); 160 // Generators allocate locals, if any, in context slots. 161 ASSERT(!info->function()->is_generator() || locals_count == 0); 162 if (locals_count == 1) { 163 __ PushRoot(Heap::kUndefinedValueRootIndex); 164 } else if (locals_count > 1) { 165 __ LoadRoot(rdx, Heap::kUndefinedValueRootIndex); 166 for (int i = 0; i < locals_count; i++) { 167 __ push(rdx); 168 } 169 } 170 } 171 172 bool function_in_register = true; 173 174 // Possibly allocate a local context. 175 int heap_slots = info->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS; 176 if (heap_slots > 0) { 177 Comment cmnt(masm_, "[ Allocate context"); 178 // Argument to NewContext is the function, which is still in rdi. 179 __ push(rdi); 180 if (FLAG_harmony_scoping && info->scope()->is_global_scope()) { 181 __ Push(info->scope()->GetScopeInfo()); 182 __ CallRuntime(Runtime::kNewGlobalContext, 2); 183 } else if (heap_slots <= FastNewContextStub::kMaximumSlots) { 184 FastNewContextStub stub(heap_slots); 185 __ CallStub(&stub); 186 } else { 187 __ CallRuntime(Runtime::kNewFunctionContext, 1); 188 } 189 function_in_register = false; 190 // Context is returned in both rax and rsi. It replaces the context 191 // passed to us. It's saved in the stack and kept live in rsi. 192 __ movq(Operand(rbp, StandardFrameConstants::kContextOffset), rsi); 193 194 // Copy any necessary parameters into the context. 195 int num_parameters = info->scope()->num_parameters(); 196 for (int i = 0; i < num_parameters; i++) { 197 Variable* var = scope()->parameter(i); 198 if (var->IsContextSlot()) { 199 int parameter_offset = StandardFrameConstants::kCallerSPOffset + 200 (num_parameters - 1 - i) * kPointerSize; 201 // Load parameter from stack. 202 __ movq(rax, Operand(rbp, parameter_offset)); 203 // Store it in the context. 204 int context_offset = Context::SlotOffset(var->index()); 205 __ movq(Operand(rsi, context_offset), rax); 206 // Update the write barrier. This clobbers rax and rbx. 207 __ RecordWriteContextSlot( 208 rsi, context_offset, rax, rbx, kDontSaveFPRegs); 209 } 210 } 211 } 212 213 // Possibly allocate an arguments object. 214 Variable* arguments = scope()->arguments(); 215 if (arguments != NULL) { 216 // Arguments object must be allocated after the context object, in 217 // case the "arguments" or ".arguments" variables are in the context. 218 Comment cmnt(masm_, "[ Allocate arguments object"); 219 if (function_in_register) { 220 __ push(rdi); 221 } else { 222 __ push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); 223 } 224 // The receiver is just before the parameters on the caller's stack. 225 int num_parameters = info->scope()->num_parameters(); 226 int offset = num_parameters * kPointerSize; 227 __ lea(rdx, 228 Operand(rbp, StandardFrameConstants::kCallerSPOffset + offset)); 229 __ push(rdx); 230 __ Push(Smi::FromInt(num_parameters)); 231 // Arguments to ArgumentsAccessStub: 232 // function, receiver address, parameter count. 233 // The stub will rewrite receiver and parameter count if the previous 234 // stack frame was an arguments adapter frame. 235 ArgumentsAccessStub::Type type; 236 if (!is_classic_mode()) { 237 type = ArgumentsAccessStub::NEW_STRICT; 238 } else if (function()->has_duplicate_parameters()) { 239 type = ArgumentsAccessStub::NEW_NON_STRICT_SLOW; 240 } else { 241 type = ArgumentsAccessStub::NEW_NON_STRICT_FAST; 242 } 243 ArgumentsAccessStub stub(type); 244 __ CallStub(&stub); 245 246 SetVar(arguments, rax, rbx, rdx); 247 } 248 249 if (FLAG_trace) { 250 __ CallRuntime(Runtime::kTraceEnter, 0); 251 } 252 253 // Visit the declarations and body unless there is an illegal 254 // redeclaration. 255 if (scope()->HasIllegalRedeclaration()) { 256 Comment cmnt(masm_, "[ Declarations"); 257 scope()->VisitIllegalRedeclaration(this); 258 259 } else { 260 PrepareForBailoutForId(BailoutId::FunctionEntry(), NO_REGISTERS); 261 { Comment cmnt(masm_, "[ Declarations"); 262 // For named function expressions, declare the function name as a 263 // constant. 264 if (scope()->is_function_scope() && scope()->function() != NULL) { 265 VariableDeclaration* function = scope()->function(); 266 ASSERT(function->proxy()->var()->mode() == CONST || 267 function->proxy()->var()->mode() == CONST_HARMONY); 268 ASSERT(function->proxy()->var()->location() != Variable::UNALLOCATED); 269 VisitVariableDeclaration(function); 270 } 271 VisitDeclarations(scope()->declarations()); 272 } 273 274 { Comment cmnt(masm_, "[ Stack check"); 275 PrepareForBailoutForId(BailoutId::Declarations(), NO_REGISTERS); 276 Label ok; 277 __ CompareRoot(rsp, Heap::kStackLimitRootIndex); 278 __ j(above_equal, &ok, Label::kNear); 279 __ call(isolate()->builtins()->StackCheck(), RelocInfo::CODE_TARGET); 280 __ bind(&ok); 281 } 282 283 { Comment cmnt(masm_, "[ Body"); 284 ASSERT(loop_depth() == 0); 285 VisitStatements(function()->body()); 286 ASSERT(loop_depth() == 0); 287 } 288 } 289 290 // Always emit a 'return undefined' in case control fell off the end of 291 // the body. 292 { Comment cmnt(masm_, "[ return <undefined>;"); 293 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex); 294 EmitReturnSequence(); 295 } 296 } 297 298 299 void FullCodeGenerator::ClearAccumulator() { 300 __ Set(rax, 0); 301 } 302 303 304 void FullCodeGenerator::EmitProfilingCounterDecrement(int delta) { 305 __ movq(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT); 306 __ SmiAddConstant(FieldOperand(rbx, Cell::kValueOffset), 307 Smi::FromInt(-delta)); 308 } 309 310 311 void FullCodeGenerator::EmitProfilingCounterReset() { 312 int reset_value = FLAG_interrupt_budget; 313 if (info_->ShouldSelfOptimize() && !FLAG_retry_self_opt) { 314 // Self-optimization is a one-off thing; if it fails, don't try again. 315 reset_value = Smi::kMaxValue; 316 } 317 __ movq(rbx, profiling_counter_, RelocInfo::EMBEDDED_OBJECT); 318 __ Move(kScratchRegister, Smi::FromInt(reset_value)); 319 __ movq(FieldOperand(rbx, Cell::kValueOffset), kScratchRegister); 320 } 321 322 323 void FullCodeGenerator::EmitBackEdgeBookkeeping(IterationStatement* stmt, 324 Label* back_edge_target) { 325 Comment cmnt(masm_, "[ Back edge bookkeeping"); 326 Label ok; 327 328 int weight = 1; 329 if (FLAG_weighted_back_edges) { 330 ASSERT(back_edge_target->is_bound()); 331 int distance = masm_->SizeOfCodeGeneratedSince(back_edge_target); 332 weight = Min(kMaxBackEdgeWeight, 333 Max(1, distance / kCodeSizeMultiplier)); 334 } 335 EmitProfilingCounterDecrement(weight); 336 __ j(positive, &ok, Label::kNear); 337 __ call(isolate()->builtins()->InterruptCheck(), RelocInfo::CODE_TARGET); 338 339 // Record a mapping of this PC offset to the OSR id. This is used to find 340 // the AST id from the unoptimized code in order to use it as a key into 341 // the deoptimization input data found in the optimized code. 342 RecordBackEdge(stmt->OsrEntryId()); 343 344 EmitProfilingCounterReset(); 345 346 __ bind(&ok); 347 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS); 348 // Record a mapping of the OSR id to this PC. This is used if the OSR 349 // entry becomes the target of a bailout. We don't expect it to be, but 350 // we want it to work if it is. 351 PrepareForBailoutForId(stmt->OsrEntryId(), NO_REGISTERS); 352 } 353 354 355 void FullCodeGenerator::EmitReturnSequence() { 356 Comment cmnt(masm_, "[ Return sequence"); 357 if (return_label_.is_bound()) { 358 __ jmp(&return_label_); 359 } else { 360 __ bind(&return_label_); 361 if (FLAG_trace) { 362 __ push(rax); 363 __ CallRuntime(Runtime::kTraceExit, 1); 364 } 365 if (FLAG_interrupt_at_exit || FLAG_self_optimization) { 366 // Pretend that the exit is a backwards jump to the entry. 367 int weight = 1; 368 if (info_->ShouldSelfOptimize()) { 369 weight = FLAG_interrupt_budget / FLAG_self_opt_count; 370 } else if (FLAG_weighted_back_edges) { 371 int distance = masm_->pc_offset(); 372 weight = Min(kMaxBackEdgeWeight, 373 Max(1, distance / kCodeSizeMultiplier)); 374 } 375 EmitProfilingCounterDecrement(weight); 376 Label ok; 377 __ j(positive, &ok, Label::kNear); 378 __ push(rax); 379 if (info_->ShouldSelfOptimize() && FLAG_direct_self_opt) { 380 __ push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); 381 __ CallRuntime(Runtime::kOptimizeFunctionOnNextCall, 1); 382 } else { 383 __ call(isolate()->builtins()->InterruptCheck(), 384 RelocInfo::CODE_TARGET); 385 } 386 __ pop(rax); 387 EmitProfilingCounterReset(); 388 __ bind(&ok); 389 } 390 #ifdef DEBUG 391 // Add a label for checking the size of the code used for returning. 392 Label check_exit_codesize; 393 masm_->bind(&check_exit_codesize); 394 #endif 395 CodeGenerator::RecordPositions(masm_, function()->end_position() - 1); 396 __ RecordJSReturn(); 397 // Do not use the leave instruction here because it is too short to 398 // patch with the code required by the debugger. 399 __ movq(rsp, rbp); 400 __ pop(rbp); 401 int no_frame_start = masm_->pc_offset(); 402 403 int arguments_bytes = (info_->scope()->num_parameters() + 1) * kPointerSize; 404 __ Ret(arguments_bytes, rcx); 405 406 #ifdef ENABLE_DEBUGGER_SUPPORT 407 // Add padding that will be overwritten by a debugger breakpoint. We 408 // have just generated at least 7 bytes: "movq rsp, rbp; pop rbp; ret k" 409 // (3 + 1 + 3). 410 const int kPadding = Assembler::kJSReturnSequenceLength - 7; 411 for (int i = 0; i < kPadding; ++i) { 412 masm_->int3(); 413 } 414 // Check that the size of the code used for returning is large enough 415 // for the debugger's requirements. 416 ASSERT(Assembler::kJSReturnSequenceLength <= 417 masm_->SizeOfCodeGeneratedSince(&check_exit_codesize)); 418 #endif 419 info_->AddNoFrameRange(no_frame_start, masm_->pc_offset()); 420 } 421 } 422 423 424 void FullCodeGenerator::EffectContext::Plug(Variable* var) const { 425 ASSERT(var->IsStackAllocated() || var->IsContextSlot()); 426 } 427 428 429 void FullCodeGenerator::AccumulatorValueContext::Plug(Variable* var) const { 430 ASSERT(var->IsStackAllocated() || var->IsContextSlot()); 431 codegen()->GetVar(result_register(), var); 432 } 433 434 435 void FullCodeGenerator::StackValueContext::Plug(Variable* var) const { 436 ASSERT(var->IsStackAllocated() || var->IsContextSlot()); 437 MemOperand operand = codegen()->VarOperand(var, result_register()); 438 __ push(operand); 439 } 440 441 442 void FullCodeGenerator::TestContext::Plug(Variable* var) const { 443 codegen()->GetVar(result_register(), var); 444 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL); 445 codegen()->DoTest(this); 446 } 447 448 449 void FullCodeGenerator::EffectContext::Plug(Heap::RootListIndex index) const { 450 } 451 452 453 void FullCodeGenerator::AccumulatorValueContext::Plug( 454 Heap::RootListIndex index) const { 455 __ LoadRoot(result_register(), index); 456 } 457 458 459 void FullCodeGenerator::StackValueContext::Plug( 460 Heap::RootListIndex index) const { 461 __ PushRoot(index); 462 } 463 464 465 void FullCodeGenerator::TestContext::Plug(Heap::RootListIndex index) const { 466 codegen()->PrepareForBailoutBeforeSplit(condition(), 467 true, 468 true_label_, 469 false_label_); 470 if (index == Heap::kUndefinedValueRootIndex || 471 index == Heap::kNullValueRootIndex || 472 index == Heap::kFalseValueRootIndex) { 473 if (false_label_ != fall_through_) __ jmp(false_label_); 474 } else if (index == Heap::kTrueValueRootIndex) { 475 if (true_label_ != fall_through_) __ jmp(true_label_); 476 } else { 477 __ LoadRoot(result_register(), index); 478 codegen()->DoTest(this); 479 } 480 } 481 482 483 void FullCodeGenerator::EffectContext::Plug(Handle<Object> lit) const { 484 } 485 486 487 void FullCodeGenerator::AccumulatorValueContext::Plug( 488 Handle<Object> lit) const { 489 if (lit->IsSmi()) { 490 __ SafeMove(result_register(), Smi::cast(*lit)); 491 } else { 492 __ Move(result_register(), lit); 493 } 494 } 495 496 497 void FullCodeGenerator::StackValueContext::Plug(Handle<Object> lit) const { 498 if (lit->IsSmi()) { 499 __ SafePush(Smi::cast(*lit)); 500 } else { 501 __ Push(lit); 502 } 503 } 504 505 506 void FullCodeGenerator::TestContext::Plug(Handle<Object> lit) const { 507 codegen()->PrepareForBailoutBeforeSplit(condition(), 508 true, 509 true_label_, 510 false_label_); 511 ASSERT(!lit->IsUndetectableObject()); // There are no undetectable literals. 512 if (lit->IsUndefined() || lit->IsNull() || lit->IsFalse()) { 513 if (false_label_ != fall_through_) __ jmp(false_label_); 514 } else if (lit->IsTrue() || lit->IsJSObject()) { 515 if (true_label_ != fall_through_) __ jmp(true_label_); 516 } else if (lit->IsString()) { 517 if (String::cast(*lit)->length() == 0) { 518 if (false_label_ != fall_through_) __ jmp(false_label_); 519 } else { 520 if (true_label_ != fall_through_) __ jmp(true_label_); 521 } 522 } else if (lit->IsSmi()) { 523 if (Smi::cast(*lit)->value() == 0) { 524 if (false_label_ != fall_through_) __ jmp(false_label_); 525 } else { 526 if (true_label_ != fall_through_) __ jmp(true_label_); 527 } 528 } else { 529 // For simplicity we always test the accumulator register. 530 __ Move(result_register(), lit); 531 codegen()->DoTest(this); 532 } 533 } 534 535 536 void FullCodeGenerator::EffectContext::DropAndPlug(int count, 537 Register reg) const { 538 ASSERT(count > 0); 539 __ Drop(count); 540 } 541 542 543 void FullCodeGenerator::AccumulatorValueContext::DropAndPlug( 544 int count, 545 Register reg) const { 546 ASSERT(count > 0); 547 __ Drop(count); 548 __ Move(result_register(), reg); 549 } 550 551 552 void FullCodeGenerator::StackValueContext::DropAndPlug(int count, 553 Register reg) const { 554 ASSERT(count > 0); 555 if (count > 1) __ Drop(count - 1); 556 __ movq(Operand(rsp, 0), reg); 557 } 558 559 560 void FullCodeGenerator::TestContext::DropAndPlug(int count, 561 Register reg) const { 562 ASSERT(count > 0); 563 // For simplicity we always test the accumulator register. 564 __ Drop(count); 565 __ Move(result_register(), reg); 566 codegen()->PrepareForBailoutBeforeSplit(condition(), false, NULL, NULL); 567 codegen()->DoTest(this); 568 } 569 570 571 void FullCodeGenerator::EffectContext::Plug(Label* materialize_true, 572 Label* materialize_false) const { 573 ASSERT(materialize_true == materialize_false); 574 __ bind(materialize_true); 575 } 576 577 578 void FullCodeGenerator::AccumulatorValueContext::Plug( 579 Label* materialize_true, 580 Label* materialize_false) const { 581 Label done; 582 __ bind(materialize_true); 583 __ Move(result_register(), isolate()->factory()->true_value()); 584 __ jmp(&done, Label::kNear); 585 __ bind(materialize_false); 586 __ Move(result_register(), isolate()->factory()->false_value()); 587 __ bind(&done); 588 } 589 590 591 void FullCodeGenerator::StackValueContext::Plug( 592 Label* materialize_true, 593 Label* materialize_false) const { 594 Label done; 595 __ bind(materialize_true); 596 __ Push(isolate()->factory()->true_value()); 597 __ jmp(&done, Label::kNear); 598 __ bind(materialize_false); 599 __ Push(isolate()->factory()->false_value()); 600 __ bind(&done); 601 } 602 603 604 void FullCodeGenerator::TestContext::Plug(Label* materialize_true, 605 Label* materialize_false) const { 606 ASSERT(materialize_true == true_label_); 607 ASSERT(materialize_false == false_label_); 608 } 609 610 611 void FullCodeGenerator::EffectContext::Plug(bool flag) const { 612 } 613 614 615 void FullCodeGenerator::AccumulatorValueContext::Plug(bool flag) const { 616 Heap::RootListIndex value_root_index = 617 flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex; 618 __ LoadRoot(result_register(), value_root_index); 619 } 620 621 622 void FullCodeGenerator::StackValueContext::Plug(bool flag) const { 623 Heap::RootListIndex value_root_index = 624 flag ? Heap::kTrueValueRootIndex : Heap::kFalseValueRootIndex; 625 __ PushRoot(value_root_index); 626 } 627 628 629 void FullCodeGenerator::TestContext::Plug(bool flag) const { 630 codegen()->PrepareForBailoutBeforeSplit(condition(), 631 true, 632 true_label_, 633 false_label_); 634 if (flag) { 635 if (true_label_ != fall_through_) __ jmp(true_label_); 636 } else { 637 if (false_label_ != fall_through_) __ jmp(false_label_); 638 } 639 } 640 641 642 void FullCodeGenerator::DoTest(Expression* condition, 643 Label* if_true, 644 Label* if_false, 645 Label* fall_through) { 646 Handle<Code> ic = ToBooleanStub::GetUninitialized(isolate()); 647 CallIC(ic, RelocInfo::CODE_TARGET, condition->test_id()); 648 __ testq(result_register(), result_register()); 649 // The stub returns nonzero for true. 650 Split(not_zero, if_true, if_false, fall_through); 651 } 652 653 654 void FullCodeGenerator::Split(Condition cc, 655 Label* if_true, 656 Label* if_false, 657 Label* fall_through) { 658 if (if_false == fall_through) { 659 __ j(cc, if_true); 660 } else if (if_true == fall_through) { 661 __ j(NegateCondition(cc), if_false); 662 } else { 663 __ j(cc, if_true); 664 __ jmp(if_false); 665 } 666 } 667 668 669 MemOperand FullCodeGenerator::StackOperand(Variable* var) { 670 ASSERT(var->IsStackAllocated()); 671 // Offset is negative because higher indexes are at lower addresses. 672 int offset = -var->index() * kPointerSize; 673 // Adjust by a (parameter or local) base offset. 674 if (var->IsParameter()) { 675 offset += kFPOnStackSize + kPCOnStackSize + 676 (info_->scope()->num_parameters() - 1) * kPointerSize; 677 } else { 678 offset += JavaScriptFrameConstants::kLocal0Offset; 679 } 680 return Operand(rbp, offset); 681 } 682 683 684 MemOperand FullCodeGenerator::VarOperand(Variable* var, Register scratch) { 685 ASSERT(var->IsContextSlot() || var->IsStackAllocated()); 686 if (var->IsContextSlot()) { 687 int context_chain_length = scope()->ContextChainLength(var->scope()); 688 __ LoadContext(scratch, context_chain_length); 689 return ContextOperand(scratch, var->index()); 690 } else { 691 return StackOperand(var); 692 } 693 } 694 695 696 void FullCodeGenerator::GetVar(Register dest, Variable* var) { 697 ASSERT(var->IsContextSlot() || var->IsStackAllocated()); 698 MemOperand location = VarOperand(var, dest); 699 __ movq(dest, location); 700 } 701 702 703 void FullCodeGenerator::SetVar(Variable* var, 704 Register src, 705 Register scratch0, 706 Register scratch1) { 707 ASSERT(var->IsContextSlot() || var->IsStackAllocated()); 708 ASSERT(!scratch0.is(src)); 709 ASSERT(!scratch0.is(scratch1)); 710 ASSERT(!scratch1.is(src)); 711 MemOperand location = VarOperand(var, scratch0); 712 __ movq(location, src); 713 714 // Emit the write barrier code if the location is in the heap. 715 if (var->IsContextSlot()) { 716 int offset = Context::SlotOffset(var->index()); 717 __ RecordWriteContextSlot(scratch0, offset, src, scratch1, kDontSaveFPRegs); 718 } 719 } 720 721 722 void FullCodeGenerator::PrepareForBailoutBeforeSplit(Expression* expr, 723 bool should_normalize, 724 Label* if_true, 725 Label* if_false) { 726 // Only prepare for bailouts before splits if we're in a test 727 // context. Otherwise, we let the Visit function deal with the 728 // preparation to avoid preparing with the same AST id twice. 729 if (!context()->IsTest() || !info_->IsOptimizable()) return; 730 731 Label skip; 732 if (should_normalize) __ jmp(&skip, Label::kNear); 733 PrepareForBailout(expr, TOS_REG); 734 if (should_normalize) { 735 __ CompareRoot(rax, Heap::kTrueValueRootIndex); 736 Split(equal, if_true, if_false, NULL); 737 __ bind(&skip); 738 } 739 } 740 741 742 void FullCodeGenerator::EmitDebugCheckDeclarationContext(Variable* variable) { 743 // The variable in the declaration always resides in the current context. 744 ASSERT_EQ(0, scope()->ContextChainLength(variable->scope())); 745 if (generate_debug_code_) { 746 // Check that we're not inside a with or catch context. 747 __ movq(rbx, FieldOperand(rsi, HeapObject::kMapOffset)); 748 __ CompareRoot(rbx, Heap::kWithContextMapRootIndex); 749 __ Check(not_equal, kDeclarationInWithContext); 750 __ CompareRoot(rbx, Heap::kCatchContextMapRootIndex); 751 __ Check(not_equal, kDeclarationInCatchContext); 752 } 753 } 754 755 756 void FullCodeGenerator::VisitVariableDeclaration( 757 VariableDeclaration* declaration) { 758 // If it was not possible to allocate the variable at compile time, we 759 // need to "declare" it at runtime to make sure it actually exists in the 760 // local context. 761 VariableProxy* proxy = declaration->proxy(); 762 VariableMode mode = declaration->mode(); 763 Variable* variable = proxy->var(); 764 bool hole_init = mode == CONST || mode == CONST_HARMONY || mode == LET; 765 switch (variable->location()) { 766 case Variable::UNALLOCATED: 767 globals_->Add(variable->name(), zone()); 768 globals_->Add(variable->binding_needs_init() 769 ? isolate()->factory()->the_hole_value() 770 : isolate()->factory()->undefined_value(), 771 zone()); 772 break; 773 774 case Variable::PARAMETER: 775 case Variable::LOCAL: 776 if (hole_init) { 777 Comment cmnt(masm_, "[ VariableDeclaration"); 778 __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex); 779 __ movq(StackOperand(variable), kScratchRegister); 780 } 781 break; 782 783 case Variable::CONTEXT: 784 if (hole_init) { 785 Comment cmnt(masm_, "[ VariableDeclaration"); 786 EmitDebugCheckDeclarationContext(variable); 787 __ LoadRoot(kScratchRegister, Heap::kTheHoleValueRootIndex); 788 __ movq(ContextOperand(rsi, variable->index()), kScratchRegister); 789 // No write barrier since the hole value is in old space. 790 PrepareForBailoutForId(proxy->id(), NO_REGISTERS); 791 } 792 break; 793 794 case Variable::LOOKUP: { 795 Comment cmnt(masm_, "[ VariableDeclaration"); 796 __ push(rsi); 797 __ Push(variable->name()); 798 // Declaration nodes are always introduced in one of four modes. 799 ASSERT(IsDeclaredVariableMode(mode)); 800 PropertyAttributes attr = 801 IsImmutableVariableMode(mode) ? READ_ONLY : NONE; 802 __ Push(Smi::FromInt(attr)); 803 // Push initial value, if any. 804 // Note: For variables we must not push an initial value (such as 805 // 'undefined') because we may have a (legal) redeclaration and we 806 // must not destroy the current value. 807 if (hole_init) { 808 __ PushRoot(Heap::kTheHoleValueRootIndex); 809 } else { 810 __ Push(Smi::FromInt(0)); // Indicates no initial value. 811 } 812 __ CallRuntime(Runtime::kDeclareContextSlot, 4); 813 break; 814 } 815 } 816 } 817 818 819 void FullCodeGenerator::VisitFunctionDeclaration( 820 FunctionDeclaration* declaration) { 821 VariableProxy* proxy = declaration->proxy(); 822 Variable* variable = proxy->var(); 823 switch (variable->location()) { 824 case Variable::UNALLOCATED: { 825 globals_->Add(variable->name(), zone()); 826 Handle<SharedFunctionInfo> function = 827 Compiler::BuildFunctionInfo(declaration->fun(), script()); 828 // Check for stack-overflow exception. 829 if (function.is_null()) return SetStackOverflow(); 830 globals_->Add(function, zone()); 831 break; 832 } 833 834 case Variable::PARAMETER: 835 case Variable::LOCAL: { 836 Comment cmnt(masm_, "[ FunctionDeclaration"); 837 VisitForAccumulatorValue(declaration->fun()); 838 __ movq(StackOperand(variable), result_register()); 839 break; 840 } 841 842 case Variable::CONTEXT: { 843 Comment cmnt(masm_, "[ FunctionDeclaration"); 844 EmitDebugCheckDeclarationContext(variable); 845 VisitForAccumulatorValue(declaration->fun()); 846 __ movq(ContextOperand(rsi, variable->index()), result_register()); 847 int offset = Context::SlotOffset(variable->index()); 848 // We know that we have written a function, which is not a smi. 849 __ RecordWriteContextSlot(rsi, 850 offset, 851 result_register(), 852 rcx, 853 kDontSaveFPRegs, 854 EMIT_REMEMBERED_SET, 855 OMIT_SMI_CHECK); 856 PrepareForBailoutForId(proxy->id(), NO_REGISTERS); 857 break; 858 } 859 860 case Variable::LOOKUP: { 861 Comment cmnt(masm_, "[ FunctionDeclaration"); 862 __ push(rsi); 863 __ Push(variable->name()); 864 __ Push(Smi::FromInt(NONE)); 865 VisitForStackValue(declaration->fun()); 866 __ CallRuntime(Runtime::kDeclareContextSlot, 4); 867 break; 868 } 869 } 870 } 871 872 873 void FullCodeGenerator::VisitModuleDeclaration(ModuleDeclaration* declaration) { 874 Variable* variable = declaration->proxy()->var(); 875 ASSERT(variable->location() == Variable::CONTEXT); 876 ASSERT(variable->interface()->IsFrozen()); 877 878 Comment cmnt(masm_, "[ ModuleDeclaration"); 879 EmitDebugCheckDeclarationContext(variable); 880 881 // Load instance object. 882 __ LoadContext(rax, scope_->ContextChainLength(scope_->GlobalScope())); 883 __ movq(rax, ContextOperand(rax, variable->interface()->Index())); 884 __ movq(rax, ContextOperand(rax, Context::EXTENSION_INDEX)); 885 886 // Assign it. 887 __ movq(ContextOperand(rsi, variable->index()), rax); 888 // We know that we have written a module, which is not a smi. 889 __ RecordWriteContextSlot(rsi, 890 Context::SlotOffset(variable->index()), 891 rax, 892 rcx, 893 kDontSaveFPRegs, 894 EMIT_REMEMBERED_SET, 895 OMIT_SMI_CHECK); 896 PrepareForBailoutForId(declaration->proxy()->id(), NO_REGISTERS); 897 898 // Traverse into body. 899 Visit(declaration->module()); 900 } 901 902 903 void FullCodeGenerator::VisitImportDeclaration(ImportDeclaration* declaration) { 904 VariableProxy* proxy = declaration->proxy(); 905 Variable* variable = proxy->var(); 906 switch (variable->location()) { 907 case Variable::UNALLOCATED: 908 // TODO(rossberg) 909 break; 910 911 case Variable::CONTEXT: { 912 Comment cmnt(masm_, "[ ImportDeclaration"); 913 EmitDebugCheckDeclarationContext(variable); 914 // TODO(rossberg) 915 break; 916 } 917 918 case Variable::PARAMETER: 919 case Variable::LOCAL: 920 case Variable::LOOKUP: 921 UNREACHABLE(); 922 } 923 } 924 925 926 void FullCodeGenerator::VisitExportDeclaration(ExportDeclaration* declaration) { 927 // TODO(rossberg) 928 } 929 930 931 void FullCodeGenerator::DeclareGlobals(Handle<FixedArray> pairs) { 932 // Call the runtime to declare the globals. 933 __ push(rsi); // The context is the first argument. 934 __ Push(pairs); 935 __ Push(Smi::FromInt(DeclareGlobalsFlags())); 936 __ CallRuntime(Runtime::kDeclareGlobals, 3); 937 // Return value is ignored. 938 } 939 940 941 void FullCodeGenerator::DeclareModules(Handle<FixedArray> descriptions) { 942 // Call the runtime to declare the modules. 943 __ Push(descriptions); 944 __ CallRuntime(Runtime::kDeclareModules, 1); 945 // Return value is ignored. 946 } 947 948 949 void FullCodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) { 950 Comment cmnt(masm_, "[ SwitchStatement"); 951 Breakable nested_statement(this, stmt); 952 SetStatementPosition(stmt); 953 954 // Keep the switch value on the stack until a case matches. 955 VisitForStackValue(stmt->tag()); 956 PrepareForBailoutForId(stmt->EntryId(), NO_REGISTERS); 957 958 ZoneList<CaseClause*>* clauses = stmt->cases(); 959 CaseClause* default_clause = NULL; // Can occur anywhere in the list. 960 961 Label next_test; // Recycled for each test. 962 // Compile all the tests with branches to their bodies. 963 for (int i = 0; i < clauses->length(); i++) { 964 CaseClause* clause = clauses->at(i); 965 clause->body_target()->Unuse(); 966 967 // The default is not a test, but remember it as final fall through. 968 if (clause->is_default()) { 969 default_clause = clause; 970 continue; 971 } 972 973 Comment cmnt(masm_, "[ Case comparison"); 974 __ bind(&next_test); 975 next_test.Unuse(); 976 977 // Compile the label expression. 978 VisitForAccumulatorValue(clause->label()); 979 980 // Perform the comparison as if via '==='. 981 __ movq(rdx, Operand(rsp, 0)); // Switch value. 982 bool inline_smi_code = ShouldInlineSmiCase(Token::EQ_STRICT); 983 JumpPatchSite patch_site(masm_); 984 if (inline_smi_code) { 985 Label slow_case; 986 __ movq(rcx, rdx); 987 __ or_(rcx, rax); 988 patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear); 989 990 __ cmpq(rdx, rax); 991 __ j(not_equal, &next_test); 992 __ Drop(1); // Switch value is no longer needed. 993 __ jmp(clause->body_target()); 994 __ bind(&slow_case); 995 } 996 997 // Record position before stub call for type feedback. 998 SetSourcePosition(clause->position()); 999 Handle<Code> ic = CompareIC::GetUninitialized(isolate(), Token::EQ_STRICT); 1000 CallIC(ic, RelocInfo::CODE_TARGET, clause->CompareId()); 1001 patch_site.EmitPatchInfo(); 1002 1003 __ testq(rax, rax); 1004 __ j(not_equal, &next_test); 1005 __ Drop(1); // Switch value is no longer needed. 1006 __ jmp(clause->body_target()); 1007 } 1008 1009 // Discard the test value and jump to the default if present, otherwise to 1010 // the end of the statement. 1011 __ bind(&next_test); 1012 __ Drop(1); // Switch value is no longer needed. 1013 if (default_clause == NULL) { 1014 __ jmp(nested_statement.break_label()); 1015 } else { 1016 __ jmp(default_clause->body_target()); 1017 } 1018 1019 // Compile all the case bodies. 1020 for (int i = 0; i < clauses->length(); i++) { 1021 Comment cmnt(masm_, "[ Case body"); 1022 CaseClause* clause = clauses->at(i); 1023 __ bind(clause->body_target()); 1024 PrepareForBailoutForId(clause->EntryId(), NO_REGISTERS); 1025 VisitStatements(clause->statements()); 1026 } 1027 1028 __ bind(nested_statement.break_label()); 1029 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS); 1030 } 1031 1032 1033 void FullCodeGenerator::VisitForInStatement(ForInStatement* stmt) { 1034 Comment cmnt(masm_, "[ ForInStatement"); 1035 SetStatementPosition(stmt); 1036 1037 Label loop, exit; 1038 ForIn loop_statement(this, stmt); 1039 increment_loop_depth(); 1040 1041 // Get the object to enumerate over. If the object is null or undefined, skip 1042 // over the loop. See ECMA-262 version 5, section 12.6.4. 1043 VisitForAccumulatorValue(stmt->enumerable()); 1044 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex); 1045 __ j(equal, &exit); 1046 Register null_value = rdi; 1047 __ LoadRoot(null_value, Heap::kNullValueRootIndex); 1048 __ cmpq(rax, null_value); 1049 __ j(equal, &exit); 1050 1051 PrepareForBailoutForId(stmt->PrepareId(), TOS_REG); 1052 1053 // Convert the object to a JS object. 1054 Label convert, done_convert; 1055 __ JumpIfSmi(rax, &convert); 1056 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rcx); 1057 __ j(above_equal, &done_convert); 1058 __ bind(&convert); 1059 __ push(rax); 1060 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION); 1061 __ bind(&done_convert); 1062 __ push(rax); 1063 1064 // Check for proxies. 1065 Label call_runtime; 1066 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE); 1067 __ CmpObjectType(rax, LAST_JS_PROXY_TYPE, rcx); 1068 __ j(below_equal, &call_runtime); 1069 1070 // Check cache validity in generated code. This is a fast case for 1071 // the JSObject::IsSimpleEnum cache validity checks. If we cannot 1072 // guarantee cache validity, call the runtime system to check cache 1073 // validity or get the property names in a fixed array. 1074 __ CheckEnumCache(null_value, &call_runtime); 1075 1076 // The enum cache is valid. Load the map of the object being 1077 // iterated over and use the cache for the iteration. 1078 Label use_cache; 1079 __ movq(rax, FieldOperand(rax, HeapObject::kMapOffset)); 1080 __ jmp(&use_cache, Label::kNear); 1081 1082 // Get the set of properties to enumerate. 1083 __ bind(&call_runtime); 1084 __ push(rax); // Duplicate the enumerable object on the stack. 1085 __ CallRuntime(Runtime::kGetPropertyNamesFast, 1); 1086 1087 // If we got a map from the runtime call, we can do a fast 1088 // modification check. Otherwise, we got a fixed array, and we have 1089 // to do a slow check. 1090 Label fixed_array; 1091 __ CompareRoot(FieldOperand(rax, HeapObject::kMapOffset), 1092 Heap::kMetaMapRootIndex); 1093 __ j(not_equal, &fixed_array); 1094 1095 // We got a map in register rax. Get the enumeration cache from it. 1096 __ bind(&use_cache); 1097 1098 Label no_descriptors; 1099 1100 __ EnumLength(rdx, rax); 1101 __ Cmp(rdx, Smi::FromInt(0)); 1102 __ j(equal, &no_descriptors); 1103 1104 __ LoadInstanceDescriptors(rax, rcx); 1105 __ movq(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheOffset)); 1106 __ movq(rcx, FieldOperand(rcx, DescriptorArray::kEnumCacheBridgeCacheOffset)); 1107 1108 // Set up the four remaining stack slots. 1109 __ push(rax); // Map. 1110 __ push(rcx); // Enumeration cache. 1111 __ push(rdx); // Number of valid entries for the map in the enum cache. 1112 __ Push(Smi::FromInt(0)); // Initial index. 1113 __ jmp(&loop); 1114 1115 __ bind(&no_descriptors); 1116 __ addq(rsp, Immediate(kPointerSize)); 1117 __ jmp(&exit); 1118 1119 // We got a fixed array in register rax. Iterate through that. 1120 Label non_proxy; 1121 __ bind(&fixed_array); 1122 1123 Handle<Cell> cell = isolate()->factory()->NewCell( 1124 Handle<Object>(Smi::FromInt(TypeFeedbackCells::kForInFastCaseMarker), 1125 isolate())); 1126 RecordTypeFeedbackCell(stmt->ForInFeedbackId(), cell); 1127 __ Move(rbx, cell); 1128 __ Move(FieldOperand(rbx, Cell::kValueOffset), 1129 Smi::FromInt(TypeFeedbackCells::kForInSlowCaseMarker)); 1130 1131 __ Move(rbx, Smi::FromInt(1)); // Smi indicates slow check 1132 __ movq(rcx, Operand(rsp, 0 * kPointerSize)); // Get enumerated object 1133 STATIC_ASSERT(FIRST_JS_PROXY_TYPE == FIRST_SPEC_OBJECT_TYPE); 1134 __ CmpObjectType(rcx, LAST_JS_PROXY_TYPE, rcx); 1135 __ j(above, &non_proxy); 1136 __ Move(rbx, Smi::FromInt(0)); // Zero indicates proxy 1137 __ bind(&non_proxy); 1138 __ push(rbx); // Smi 1139 __ push(rax); // Array 1140 __ movq(rax, FieldOperand(rax, FixedArray::kLengthOffset)); 1141 __ push(rax); // Fixed array length (as smi). 1142 __ Push(Smi::FromInt(0)); // Initial index. 1143 1144 // Generate code for doing the condition check. 1145 PrepareForBailoutForId(stmt->BodyId(), NO_REGISTERS); 1146 __ bind(&loop); 1147 __ movq(rax, Operand(rsp, 0 * kPointerSize)); // Get the current index. 1148 __ cmpq(rax, Operand(rsp, 1 * kPointerSize)); // Compare to the array length. 1149 __ j(above_equal, loop_statement.break_label()); 1150 1151 // Get the current entry of the array into register rbx. 1152 __ movq(rbx, Operand(rsp, 2 * kPointerSize)); 1153 SmiIndex index = masm()->SmiToIndex(rax, rax, kPointerSizeLog2); 1154 __ movq(rbx, FieldOperand(rbx, 1155 index.reg, 1156 index.scale, 1157 FixedArray::kHeaderSize)); 1158 1159 // Get the expected map from the stack or a smi in the 1160 // permanent slow case into register rdx. 1161 __ movq(rdx, Operand(rsp, 3 * kPointerSize)); 1162 1163 // Check if the expected map still matches that of the enumerable. 1164 // If not, we may have to filter the key. 1165 Label update_each; 1166 __ movq(rcx, Operand(rsp, 4 * kPointerSize)); 1167 __ cmpq(rdx, FieldOperand(rcx, HeapObject::kMapOffset)); 1168 __ j(equal, &update_each, Label::kNear); 1169 1170 // For proxies, no filtering is done. 1171 // TODO(rossberg): What if only a prototype is a proxy? Not specified yet. 1172 __ Cmp(rdx, Smi::FromInt(0)); 1173 __ j(equal, &update_each, Label::kNear); 1174 1175 // Convert the entry to a string or null if it isn't a property 1176 // anymore. If the property has been removed while iterating, we 1177 // just skip it. 1178 __ push(rcx); // Enumerable. 1179 __ push(rbx); // Current entry. 1180 __ InvokeBuiltin(Builtins::FILTER_KEY, CALL_FUNCTION); 1181 __ Cmp(rax, Smi::FromInt(0)); 1182 __ j(equal, loop_statement.continue_label()); 1183 __ movq(rbx, rax); 1184 1185 // Update the 'each' property or variable from the possibly filtered 1186 // entry in register rbx. 1187 __ bind(&update_each); 1188 __ movq(result_register(), rbx); 1189 // Perform the assignment as if via '='. 1190 { EffectContext context(this); 1191 EmitAssignment(stmt->each()); 1192 } 1193 1194 // Generate code for the body of the loop. 1195 Visit(stmt->body()); 1196 1197 // Generate code for going to the next element by incrementing the 1198 // index (smi) stored on top of the stack. 1199 __ bind(loop_statement.continue_label()); 1200 __ SmiAddConstant(Operand(rsp, 0 * kPointerSize), Smi::FromInt(1)); 1201 1202 EmitBackEdgeBookkeeping(stmt, &loop); 1203 __ jmp(&loop); 1204 1205 // Remove the pointers stored on the stack. 1206 __ bind(loop_statement.break_label()); 1207 __ addq(rsp, Immediate(5 * kPointerSize)); 1208 1209 // Exit and decrement the loop depth. 1210 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS); 1211 __ bind(&exit); 1212 decrement_loop_depth(); 1213 } 1214 1215 1216 void FullCodeGenerator::VisitForOfStatement(ForOfStatement* stmt) { 1217 Comment cmnt(masm_, "[ ForOfStatement"); 1218 SetStatementPosition(stmt); 1219 1220 Iteration loop_statement(this, stmt); 1221 increment_loop_depth(); 1222 1223 // var iterator = iterable[@@iterator]() 1224 VisitForAccumulatorValue(stmt->assign_iterator()); 1225 1226 // As with for-in, skip the loop if the iterator is null or undefined. 1227 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex); 1228 __ j(equal, loop_statement.break_label()); 1229 __ CompareRoot(rax, Heap::kNullValueRootIndex); 1230 __ j(equal, loop_statement.break_label()); 1231 1232 // Convert the iterator to a JS object. 1233 Label convert, done_convert; 1234 __ JumpIfSmi(rax, &convert); 1235 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rcx); 1236 __ j(above_equal, &done_convert); 1237 __ bind(&convert); 1238 __ push(rax); 1239 __ InvokeBuiltin(Builtins::TO_OBJECT, CALL_FUNCTION); 1240 __ bind(&done_convert); 1241 1242 // Loop entry. 1243 __ bind(loop_statement.continue_label()); 1244 1245 // result = iterator.next() 1246 VisitForEffect(stmt->next_result()); 1247 1248 // if (result.done) break; 1249 Label result_not_done; 1250 VisitForControl(stmt->result_done(), 1251 loop_statement.break_label(), 1252 &result_not_done, 1253 &result_not_done); 1254 __ bind(&result_not_done); 1255 1256 // each = result.value 1257 VisitForEffect(stmt->assign_each()); 1258 1259 // Generate code for the body of the loop. 1260 Visit(stmt->body()); 1261 1262 // Check stack before looping. 1263 PrepareForBailoutForId(stmt->BackEdgeId(), NO_REGISTERS); 1264 EmitBackEdgeBookkeeping(stmt, loop_statement.continue_label()); 1265 __ jmp(loop_statement.continue_label()); 1266 1267 // Exit and decrement the loop depth. 1268 PrepareForBailoutForId(stmt->ExitId(), NO_REGISTERS); 1269 __ bind(loop_statement.break_label()); 1270 decrement_loop_depth(); 1271 } 1272 1273 1274 void FullCodeGenerator::EmitNewClosure(Handle<SharedFunctionInfo> info, 1275 bool pretenure) { 1276 // Use the fast case closure allocation code that allocates in new 1277 // space for nested functions that don't need literals cloning. If 1278 // we're running with the --always-opt or the --prepare-always-opt 1279 // flag, we need to use the runtime function so that the new function 1280 // we are creating here gets a chance to have its code optimized and 1281 // doesn't just get a copy of the existing unoptimized code. 1282 if (!FLAG_always_opt && 1283 !FLAG_prepare_always_opt && 1284 !pretenure && 1285 scope()->is_function_scope() && 1286 info->num_literals() == 0) { 1287 FastNewClosureStub stub(info->language_mode(), info->is_generator()); 1288 __ Move(rbx, info); 1289 __ CallStub(&stub); 1290 } else { 1291 __ push(rsi); 1292 __ Push(info); 1293 __ Push(pretenure 1294 ? isolate()->factory()->true_value() 1295 : isolate()->factory()->false_value()); 1296 __ CallRuntime(Runtime::kNewClosure, 3); 1297 } 1298 context()->Plug(rax); 1299 } 1300 1301 1302 void FullCodeGenerator::VisitVariableProxy(VariableProxy* expr) { 1303 Comment cmnt(masm_, "[ VariableProxy"); 1304 EmitVariableLoad(expr); 1305 } 1306 1307 1308 void FullCodeGenerator::EmitLoadGlobalCheckExtensions(Variable* var, 1309 TypeofState typeof_state, 1310 Label* slow) { 1311 Register context = rsi; 1312 Register temp = rdx; 1313 1314 Scope* s = scope(); 1315 while (s != NULL) { 1316 if (s->num_heap_slots() > 0) { 1317 if (s->calls_non_strict_eval()) { 1318 // Check that extension is NULL. 1319 __ cmpq(ContextOperand(context, Context::EXTENSION_INDEX), 1320 Immediate(0)); 1321 __ j(not_equal, slow); 1322 } 1323 // Load next context in chain. 1324 __ movq(temp, ContextOperand(context, Context::PREVIOUS_INDEX)); 1325 // Walk the rest of the chain without clobbering rsi. 1326 context = temp; 1327 } 1328 // If no outer scope calls eval, we do not need to check more 1329 // context extensions. If we have reached an eval scope, we check 1330 // all extensions from this point. 1331 if (!s->outer_scope_calls_non_strict_eval() || s->is_eval_scope()) break; 1332 s = s->outer_scope(); 1333 } 1334 1335 if (s != NULL && s->is_eval_scope()) { 1336 // Loop up the context chain. There is no frame effect so it is 1337 // safe to use raw labels here. 1338 Label next, fast; 1339 if (!context.is(temp)) { 1340 __ movq(temp, context); 1341 } 1342 // Load map for comparison into register, outside loop. 1343 __ LoadRoot(kScratchRegister, Heap::kNativeContextMapRootIndex); 1344 __ bind(&next); 1345 // Terminate at native context. 1346 __ cmpq(kScratchRegister, FieldOperand(temp, HeapObject::kMapOffset)); 1347 __ j(equal, &fast, Label::kNear); 1348 // Check that extension is NULL. 1349 __ cmpq(ContextOperand(temp, Context::EXTENSION_INDEX), Immediate(0)); 1350 __ j(not_equal, slow); 1351 // Load next context in chain. 1352 __ movq(temp, ContextOperand(temp, Context::PREVIOUS_INDEX)); 1353 __ jmp(&next); 1354 __ bind(&fast); 1355 } 1356 1357 // All extension objects were empty and it is safe to use a global 1358 // load IC call. 1359 __ movq(rax, GlobalObjectOperand()); 1360 __ Move(rcx, var->name()); 1361 Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); 1362 RelocInfo::Mode mode = (typeof_state == INSIDE_TYPEOF) 1363 ? RelocInfo::CODE_TARGET 1364 : RelocInfo::CODE_TARGET_CONTEXT; 1365 CallIC(ic, mode); 1366 } 1367 1368 1369 MemOperand FullCodeGenerator::ContextSlotOperandCheckExtensions(Variable* var, 1370 Label* slow) { 1371 ASSERT(var->IsContextSlot()); 1372 Register context = rsi; 1373 Register temp = rbx; 1374 1375 for (Scope* s = scope(); s != var->scope(); s = s->outer_scope()) { 1376 if (s->num_heap_slots() > 0) { 1377 if (s->calls_non_strict_eval()) { 1378 // Check that extension is NULL. 1379 __ cmpq(ContextOperand(context, Context::EXTENSION_INDEX), 1380 Immediate(0)); 1381 __ j(not_equal, slow); 1382 } 1383 __ movq(temp, ContextOperand(context, Context::PREVIOUS_INDEX)); 1384 // Walk the rest of the chain without clobbering rsi. 1385 context = temp; 1386 } 1387 } 1388 // Check that last extension is NULL. 1389 __ cmpq(ContextOperand(context, Context::EXTENSION_INDEX), Immediate(0)); 1390 __ j(not_equal, slow); 1391 1392 // This function is used only for loads, not stores, so it's safe to 1393 // return an rsi-based operand (the write barrier cannot be allowed to 1394 // destroy the rsi register). 1395 return ContextOperand(context, var->index()); 1396 } 1397 1398 1399 void FullCodeGenerator::EmitDynamicLookupFastCase(Variable* var, 1400 TypeofState typeof_state, 1401 Label* slow, 1402 Label* done) { 1403 // Generate fast-case code for variables that might be shadowed by 1404 // eval-introduced variables. Eval is used a lot without 1405 // introducing variables. In those cases, we do not want to 1406 // perform a runtime call for all variables in the scope 1407 // containing the eval. 1408 if (var->mode() == DYNAMIC_GLOBAL) { 1409 EmitLoadGlobalCheckExtensions(var, typeof_state, slow); 1410 __ jmp(done); 1411 } else if (var->mode() == DYNAMIC_LOCAL) { 1412 Variable* local = var->local_if_not_shadowed(); 1413 __ movq(rax, ContextSlotOperandCheckExtensions(local, slow)); 1414 if (local->mode() == LET || 1415 local->mode() == CONST || 1416 local->mode() == CONST_HARMONY) { 1417 __ CompareRoot(rax, Heap::kTheHoleValueRootIndex); 1418 __ j(not_equal, done); 1419 if (local->mode() == CONST) { 1420 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex); 1421 } else { // LET || CONST_HARMONY 1422 __ Push(var->name()); 1423 __ CallRuntime(Runtime::kThrowReferenceError, 1); 1424 } 1425 } 1426 __ jmp(done); 1427 } 1428 } 1429 1430 1431 void FullCodeGenerator::EmitVariableLoad(VariableProxy* proxy) { 1432 // Record position before possible IC call. 1433 SetSourcePosition(proxy->position()); 1434 Variable* var = proxy->var(); 1435 1436 // Three cases: global variables, lookup variables, and all other types of 1437 // variables. 1438 switch (var->location()) { 1439 case Variable::UNALLOCATED: { 1440 Comment cmnt(masm_, "Global variable"); 1441 // Use inline caching. Variable name is passed in rcx and the global 1442 // object on the stack. 1443 __ Move(rcx, var->name()); 1444 __ movq(rax, GlobalObjectOperand()); 1445 Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); 1446 CallIC(ic, RelocInfo::CODE_TARGET_CONTEXT); 1447 context()->Plug(rax); 1448 break; 1449 } 1450 1451 case Variable::PARAMETER: 1452 case Variable::LOCAL: 1453 case Variable::CONTEXT: { 1454 Comment cmnt(masm_, var->IsContextSlot() ? "Context slot" : "Stack slot"); 1455 if (var->binding_needs_init()) { 1456 // var->scope() may be NULL when the proxy is located in eval code and 1457 // refers to a potential outside binding. Currently those bindings are 1458 // always looked up dynamically, i.e. in that case 1459 // var->location() == LOOKUP. 1460 // always holds. 1461 ASSERT(var->scope() != NULL); 1462 1463 // Check if the binding really needs an initialization check. The check 1464 // can be skipped in the following situation: we have a LET or CONST 1465 // binding in harmony mode, both the Variable and the VariableProxy have 1466 // the same declaration scope (i.e. they are both in global code, in the 1467 // same function or in the same eval code) and the VariableProxy is in 1468 // the source physically located after the initializer of the variable. 1469 // 1470 // We cannot skip any initialization checks for CONST in non-harmony 1471 // mode because const variables may be declared but never initialized: 1472 // if (false) { const x; }; var y = x; 1473 // 1474 // The condition on the declaration scopes is a conservative check for 1475 // nested functions that access a binding and are called before the 1476 // binding is initialized: 1477 // function() { f(); let x = 1; function f() { x = 2; } } 1478 // 1479 bool skip_init_check; 1480 if (var->scope()->DeclarationScope() != scope()->DeclarationScope()) { 1481 skip_init_check = false; 1482 } else { 1483 // Check that we always have valid source position. 1484 ASSERT(var->initializer_position() != RelocInfo::kNoPosition); 1485 ASSERT(proxy->position() != RelocInfo::kNoPosition); 1486 skip_init_check = var->mode() != CONST && 1487 var->initializer_position() < proxy->position(); 1488 } 1489 1490 if (!skip_init_check) { 1491 // Let and const need a read barrier. 1492 Label done; 1493 GetVar(rax, var); 1494 __ CompareRoot(rax, Heap::kTheHoleValueRootIndex); 1495 __ j(not_equal, &done, Label::kNear); 1496 if (var->mode() == LET || var->mode() == CONST_HARMONY) { 1497 // Throw a reference error when using an uninitialized let/const 1498 // binding in harmony mode. 1499 __ Push(var->name()); 1500 __ CallRuntime(Runtime::kThrowReferenceError, 1); 1501 } else { 1502 // Uninitalized const bindings outside of harmony mode are unholed. 1503 ASSERT(var->mode() == CONST); 1504 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex); 1505 } 1506 __ bind(&done); 1507 context()->Plug(rax); 1508 break; 1509 } 1510 } 1511 context()->Plug(var); 1512 break; 1513 } 1514 1515 case Variable::LOOKUP: { 1516 Label done, slow; 1517 // Generate code for loading from variables potentially shadowed 1518 // by eval-introduced variables. 1519 EmitDynamicLookupFastCase(var, NOT_INSIDE_TYPEOF, &slow, &done); 1520 __ bind(&slow); 1521 Comment cmnt(masm_, "Lookup slot"); 1522 __ push(rsi); // Context. 1523 __ Push(var->name()); 1524 __ CallRuntime(Runtime::kLoadContextSlot, 2); 1525 __ bind(&done); 1526 context()->Plug(rax); 1527 break; 1528 } 1529 } 1530 } 1531 1532 1533 void FullCodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) { 1534 Comment cmnt(masm_, "[ RegExpLiteral"); 1535 Label materialized; 1536 // Registers will be used as follows: 1537 // rdi = JS function. 1538 // rcx = literals array. 1539 // rbx = regexp literal. 1540 // rax = regexp literal clone. 1541 __ movq(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); 1542 __ movq(rcx, FieldOperand(rdi, JSFunction::kLiteralsOffset)); 1543 int literal_offset = 1544 FixedArray::kHeaderSize + expr->literal_index() * kPointerSize; 1545 __ movq(rbx, FieldOperand(rcx, literal_offset)); 1546 __ CompareRoot(rbx, Heap::kUndefinedValueRootIndex); 1547 __ j(not_equal, &materialized, Label::kNear); 1548 1549 // Create regexp literal using runtime function 1550 // Result will be in rax. 1551 __ push(rcx); 1552 __ Push(Smi::FromInt(expr->literal_index())); 1553 __ Push(expr->pattern()); 1554 __ Push(expr->flags()); 1555 __ CallRuntime(Runtime::kMaterializeRegExpLiteral, 4); 1556 __ movq(rbx, rax); 1557 1558 __ bind(&materialized); 1559 int size = JSRegExp::kSize + JSRegExp::kInObjectFieldCount * kPointerSize; 1560 Label allocated, runtime_allocate; 1561 __ Allocate(size, rax, rcx, rdx, &runtime_allocate, TAG_OBJECT); 1562 __ jmp(&allocated); 1563 1564 __ bind(&runtime_allocate); 1565 __ push(rbx); 1566 __ Push(Smi::FromInt(size)); 1567 __ CallRuntime(Runtime::kAllocateInNewSpace, 1); 1568 __ pop(rbx); 1569 1570 __ bind(&allocated); 1571 // Copy the content into the newly allocated memory. 1572 // (Unroll copy loop once for better throughput). 1573 for (int i = 0; i < size - kPointerSize; i += 2 * kPointerSize) { 1574 __ movq(rdx, FieldOperand(rbx, i)); 1575 __ movq(rcx, FieldOperand(rbx, i + kPointerSize)); 1576 __ movq(FieldOperand(rax, i), rdx); 1577 __ movq(FieldOperand(rax, i + kPointerSize), rcx); 1578 } 1579 if ((size % (2 * kPointerSize)) != 0) { 1580 __ movq(rdx, FieldOperand(rbx, size - kPointerSize)); 1581 __ movq(FieldOperand(rax, size - kPointerSize), rdx); 1582 } 1583 context()->Plug(rax); 1584 } 1585 1586 1587 void FullCodeGenerator::EmitAccessor(Expression* expression) { 1588 if (expression == NULL) { 1589 __ PushRoot(Heap::kNullValueRootIndex); 1590 } else { 1591 VisitForStackValue(expression); 1592 } 1593 } 1594 1595 1596 void FullCodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) { 1597 Comment cmnt(masm_, "[ ObjectLiteral"); 1598 1599 expr->BuildConstantProperties(isolate()); 1600 Handle<FixedArray> constant_properties = expr->constant_properties(); 1601 int flags = expr->fast_elements() 1602 ? ObjectLiteral::kFastElements 1603 : ObjectLiteral::kNoFlags; 1604 flags |= expr->has_function() 1605 ? ObjectLiteral::kHasFunction 1606 : ObjectLiteral::kNoFlags; 1607 int properties_count = constant_properties->length() / 2; 1608 if ((FLAG_track_double_fields && expr->may_store_doubles()) || 1609 expr->depth() > 1 || Serializer::enabled() || 1610 flags != ObjectLiteral::kFastElements || 1611 properties_count > FastCloneShallowObjectStub::kMaximumClonedProperties) { 1612 __ movq(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); 1613 __ push(FieldOperand(rdi, JSFunction::kLiteralsOffset)); 1614 __ Push(Smi::FromInt(expr->literal_index())); 1615 __ Push(constant_properties); 1616 __ Push(Smi::FromInt(flags)); 1617 __ CallRuntime(Runtime::kCreateObjectLiteral, 4); 1618 } else { 1619 __ movq(rdi, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); 1620 __ movq(rax, FieldOperand(rdi, JSFunction::kLiteralsOffset)); 1621 __ Move(rbx, Smi::FromInt(expr->literal_index())); 1622 __ Move(rcx, constant_properties); 1623 __ Move(rdx, Smi::FromInt(flags)); 1624 FastCloneShallowObjectStub stub(properties_count); 1625 __ CallStub(&stub); 1626 } 1627 1628 // If result_saved is true the result is on top of the stack. If 1629 // result_saved is false the result is in rax. 1630 bool result_saved = false; 1631 1632 // Mark all computed expressions that are bound to a key that 1633 // is shadowed by a later occurrence of the same key. For the 1634 // marked expressions, no store code is emitted. 1635 expr->CalculateEmitStore(zone()); 1636 1637 AccessorTable accessor_table(zone()); 1638 for (int i = 0; i < expr->properties()->length(); i++) { 1639 ObjectLiteral::Property* property = expr->properties()->at(i); 1640 if (property->IsCompileTimeValue()) continue; 1641 1642 Literal* key = property->key(); 1643 Expression* value = property->value(); 1644 if (!result_saved) { 1645 __ push(rax); // Save result on the stack 1646 result_saved = true; 1647 } 1648 switch (property->kind()) { 1649 case ObjectLiteral::Property::CONSTANT: 1650 UNREACHABLE(); 1651 case ObjectLiteral::Property::MATERIALIZED_LITERAL: 1652 ASSERT(!CompileTimeValue::IsCompileTimeValue(value)); 1653 // Fall through. 1654 case ObjectLiteral::Property::COMPUTED: 1655 if (key->value()->IsInternalizedString()) { 1656 if (property->emit_store()) { 1657 VisitForAccumulatorValue(value); 1658 __ Move(rcx, key->value()); 1659 __ movq(rdx, Operand(rsp, 0)); 1660 Handle<Code> ic = is_classic_mode() 1661 ? isolate()->builtins()->StoreIC_Initialize() 1662 : isolate()->builtins()->StoreIC_Initialize_Strict(); 1663 CallIC(ic, RelocInfo::CODE_TARGET, key->LiteralFeedbackId()); 1664 PrepareForBailoutForId(key->id(), NO_REGISTERS); 1665 } else { 1666 VisitForEffect(value); 1667 } 1668 break; 1669 } 1670 __ push(Operand(rsp, 0)); // Duplicate receiver. 1671 VisitForStackValue(key); 1672 VisitForStackValue(value); 1673 if (property->emit_store()) { 1674 __ Push(Smi::FromInt(NONE)); // PropertyAttributes 1675 __ CallRuntime(Runtime::kSetProperty, 4); 1676 } else { 1677 __ Drop(3); 1678 } 1679 break; 1680 case ObjectLiteral::Property::PROTOTYPE: 1681 __ push(Operand(rsp, 0)); // Duplicate receiver. 1682 VisitForStackValue(value); 1683 if (property->emit_store()) { 1684 __ CallRuntime(Runtime::kSetPrototype, 2); 1685 } else { 1686 __ Drop(2); 1687 } 1688 break; 1689 case ObjectLiteral::Property::GETTER: 1690 accessor_table.lookup(key)->second->getter = value; 1691 break; 1692 case ObjectLiteral::Property::SETTER: 1693 accessor_table.lookup(key)->second->setter = value; 1694 break; 1695 } 1696 } 1697 1698 // Emit code to define accessors, using only a single call to the runtime for 1699 // each pair of corresponding getters and setters. 1700 for (AccessorTable::Iterator it = accessor_table.begin(); 1701 it != accessor_table.end(); 1702 ++it) { 1703 __ push(Operand(rsp, 0)); // Duplicate receiver. 1704 VisitForStackValue(it->first); 1705 EmitAccessor(it->second->getter); 1706 EmitAccessor(it->second->setter); 1707 __ Push(Smi::FromInt(NONE)); 1708 __ CallRuntime(Runtime::kDefineOrRedefineAccessorProperty, 5); 1709 } 1710 1711 if (expr->has_function()) { 1712 ASSERT(result_saved); 1713 __ push(Operand(rsp, 0)); 1714 __ CallRuntime(Runtime::kToFastProperties, 1); 1715 } 1716 1717 if (result_saved) { 1718 context()->PlugTOS(); 1719 } else { 1720 context()->Plug(rax); 1721 } 1722 } 1723 1724 1725 void FullCodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) { 1726 Comment cmnt(masm_, "[ ArrayLiteral"); 1727 1728 expr->BuildConstantElements(isolate()); 1729 int flags = expr->depth() == 1 1730 ? ArrayLiteral::kShallowElements 1731 : ArrayLiteral::kNoFlags; 1732 1733 ZoneList<Expression*>* subexprs = expr->values(); 1734 int length = subexprs->length(); 1735 Handle<FixedArray> constant_elements = expr->constant_elements(); 1736 ASSERT_EQ(2, constant_elements->length()); 1737 ElementsKind constant_elements_kind = 1738 static_cast<ElementsKind>(Smi::cast(constant_elements->get(0))->value()); 1739 bool has_constant_fast_elements = 1740 IsFastObjectElementsKind(constant_elements_kind); 1741 Handle<FixedArrayBase> constant_elements_values( 1742 FixedArrayBase::cast(constant_elements->get(1))); 1743 1744 AllocationSiteMode allocation_site_mode = FLAG_track_allocation_sites 1745 ? TRACK_ALLOCATION_SITE : DONT_TRACK_ALLOCATION_SITE; 1746 if (has_constant_fast_elements && !FLAG_allocation_site_pretenuring) { 1747 // If the only customer of allocation sites is transitioning, then 1748 // we can turn it off if we don't have anywhere else to transition to. 1749 allocation_site_mode = DONT_TRACK_ALLOCATION_SITE; 1750 } 1751 1752 Heap* heap = isolate()->heap(); 1753 if (has_constant_fast_elements && 1754 constant_elements_values->map() == heap->fixed_cow_array_map()) { 1755 // If the elements are already FAST_*_ELEMENTS, the boilerplate cannot 1756 // change, so it's possible to specialize the stub in advance. 1757 __ IncrementCounter(isolate()->counters()->cow_arrays_created_stub(), 1); 1758 __ movq(rbx, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); 1759 __ movq(rax, FieldOperand(rbx, JSFunction::kLiteralsOffset)); 1760 __ Move(rbx, Smi::FromInt(expr->literal_index())); 1761 __ Move(rcx, constant_elements); 1762 FastCloneShallowArrayStub stub( 1763 FastCloneShallowArrayStub::COPY_ON_WRITE_ELEMENTS, 1764 allocation_site_mode, 1765 length); 1766 __ CallStub(&stub); 1767 } else if (expr->depth() > 1 || Serializer::enabled() || 1768 length > FastCloneShallowArrayStub::kMaximumClonedLength) { 1769 __ movq(rbx, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); 1770 __ push(FieldOperand(rbx, JSFunction::kLiteralsOffset)); 1771 __ Push(Smi::FromInt(expr->literal_index())); 1772 __ Push(constant_elements); 1773 __ Push(Smi::FromInt(flags)); 1774 __ CallRuntime(Runtime::kCreateArrayLiteral, 4); 1775 } else { 1776 ASSERT(IsFastSmiOrObjectElementsKind(constant_elements_kind) || 1777 FLAG_smi_only_arrays); 1778 FastCloneShallowArrayStub::Mode mode = 1779 FastCloneShallowArrayStub::CLONE_ANY_ELEMENTS; 1780 1781 // If the elements are already FAST_*_ELEMENTS, the boilerplate cannot 1782 // change, so it's possible to specialize the stub in advance. 1783 if (has_constant_fast_elements) { 1784 mode = FastCloneShallowArrayStub::CLONE_ELEMENTS; 1785 } 1786 1787 __ movq(rbx, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); 1788 __ movq(rax, FieldOperand(rbx, JSFunction::kLiteralsOffset)); 1789 __ Move(rbx, Smi::FromInt(expr->literal_index())); 1790 __ Move(rcx, constant_elements); 1791 FastCloneShallowArrayStub stub(mode, allocation_site_mode, length); 1792 __ CallStub(&stub); 1793 } 1794 1795 bool result_saved = false; // Is the result saved to the stack? 1796 1797 // Emit code to evaluate all the non-constant subexpressions and to store 1798 // them into the newly cloned array. 1799 for (int i = 0; i < length; i++) { 1800 Expression* subexpr = subexprs->at(i); 1801 // If the subexpression is a literal or a simple materialized literal it 1802 // is already set in the cloned array. 1803 if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue; 1804 1805 if (!result_saved) { 1806 __ push(rax); // array literal 1807 __ Push(Smi::FromInt(expr->literal_index())); 1808 result_saved = true; 1809 } 1810 VisitForAccumulatorValue(subexpr); 1811 1812 if (IsFastObjectElementsKind(constant_elements_kind)) { 1813 // Fast-case array literal with ElementsKind of FAST_*_ELEMENTS, they 1814 // cannot transition and don't need to call the runtime stub. 1815 int offset = FixedArray::kHeaderSize + (i * kPointerSize); 1816 __ movq(rbx, Operand(rsp, kPointerSize)); // Copy of array literal. 1817 __ movq(rbx, FieldOperand(rbx, JSObject::kElementsOffset)); 1818 // Store the subexpression value in the array's elements. 1819 __ movq(FieldOperand(rbx, offset), result_register()); 1820 // Update the write barrier for the array store. 1821 __ RecordWriteField(rbx, offset, result_register(), rcx, 1822 kDontSaveFPRegs, 1823 EMIT_REMEMBERED_SET, 1824 INLINE_SMI_CHECK); 1825 } else { 1826 // Store the subexpression value in the array's elements. 1827 __ Move(rcx, Smi::FromInt(i)); 1828 StoreArrayLiteralElementStub stub; 1829 __ CallStub(&stub); 1830 } 1831 1832 PrepareForBailoutForId(expr->GetIdForElement(i), NO_REGISTERS); 1833 } 1834 1835 if (result_saved) { 1836 __ addq(rsp, Immediate(kPointerSize)); // literal index 1837 context()->PlugTOS(); 1838 } else { 1839 context()->Plug(rax); 1840 } 1841 } 1842 1843 1844 void FullCodeGenerator::VisitAssignment(Assignment* expr) { 1845 Comment cmnt(masm_, "[ Assignment"); 1846 // Invalid left-hand sides are rewritten to have a 'throw ReferenceError' 1847 // on the left-hand side. 1848 if (!expr->target()->IsValidLeftHandSide()) { 1849 VisitForEffect(expr->target()); 1850 return; 1851 } 1852 1853 // Left-hand side can only be a property, a global or a (parameter or local) 1854 // slot. 1855 enum LhsKind { VARIABLE, NAMED_PROPERTY, KEYED_PROPERTY }; 1856 LhsKind assign_type = VARIABLE; 1857 Property* property = expr->target()->AsProperty(); 1858 if (property != NULL) { 1859 assign_type = (property->key()->IsPropertyName()) 1860 ? NAMED_PROPERTY 1861 : KEYED_PROPERTY; 1862 } 1863 1864 // Evaluate LHS expression. 1865 switch (assign_type) { 1866 case VARIABLE: 1867 // Nothing to do here. 1868 break; 1869 case NAMED_PROPERTY: 1870 if (expr->is_compound()) { 1871 // We need the receiver both on the stack and in the accumulator. 1872 VisitForAccumulatorValue(property->obj()); 1873 __ push(result_register()); 1874 } else { 1875 VisitForStackValue(property->obj()); 1876 } 1877 break; 1878 case KEYED_PROPERTY: { 1879 if (expr->is_compound()) { 1880 VisitForStackValue(property->obj()); 1881 VisitForAccumulatorValue(property->key()); 1882 __ movq(rdx, Operand(rsp, 0)); 1883 __ push(rax); 1884 } else { 1885 VisitForStackValue(property->obj()); 1886 VisitForStackValue(property->key()); 1887 } 1888 break; 1889 } 1890 } 1891 1892 // For compound assignments we need another deoptimization point after the 1893 // variable/property load. 1894 if (expr->is_compound()) { 1895 { AccumulatorValueContext context(this); 1896 switch (assign_type) { 1897 case VARIABLE: 1898 EmitVariableLoad(expr->target()->AsVariableProxy()); 1899 PrepareForBailout(expr->target(), TOS_REG); 1900 break; 1901 case NAMED_PROPERTY: 1902 EmitNamedPropertyLoad(property); 1903 PrepareForBailoutForId(property->LoadId(), TOS_REG); 1904 break; 1905 case KEYED_PROPERTY: 1906 EmitKeyedPropertyLoad(property); 1907 PrepareForBailoutForId(property->LoadId(), TOS_REG); 1908 break; 1909 } 1910 } 1911 1912 Token::Value op = expr->binary_op(); 1913 __ push(rax); // Left operand goes on the stack. 1914 VisitForAccumulatorValue(expr->value()); 1915 1916 OverwriteMode mode = expr->value()->ResultOverwriteAllowed() 1917 ? OVERWRITE_RIGHT 1918 : NO_OVERWRITE; 1919 SetSourcePosition(expr->position() + 1); 1920 AccumulatorValueContext context(this); 1921 if (ShouldInlineSmiCase(op)) { 1922 EmitInlineSmiBinaryOp(expr->binary_operation(), 1923 op, 1924 mode, 1925 expr->target(), 1926 expr->value()); 1927 } else { 1928 EmitBinaryOp(expr->binary_operation(), op, mode); 1929 } 1930 // Deoptimization point in case the binary operation may have side effects. 1931 PrepareForBailout(expr->binary_operation(), TOS_REG); 1932 } else { 1933 VisitForAccumulatorValue(expr->value()); 1934 } 1935 1936 // Record source position before possible IC call. 1937 SetSourcePosition(expr->position()); 1938 1939 // Store the value. 1940 switch (assign_type) { 1941 case VARIABLE: 1942 EmitVariableAssignment(expr->target()->AsVariableProxy()->var(), 1943 expr->op()); 1944 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG); 1945 context()->Plug(rax); 1946 break; 1947 case NAMED_PROPERTY: 1948 EmitNamedPropertyAssignment(expr); 1949 break; 1950 case KEYED_PROPERTY: 1951 EmitKeyedPropertyAssignment(expr); 1952 break; 1953 } 1954 } 1955 1956 1957 void FullCodeGenerator::VisitYield(Yield* expr) { 1958 Comment cmnt(masm_, "[ Yield"); 1959 // Evaluate yielded value first; the initial iterator definition depends on 1960 // this. It stays on the stack while we update the iterator. 1961 VisitForStackValue(expr->expression()); 1962 1963 switch (expr->yield_kind()) { 1964 case Yield::SUSPEND: 1965 // Pop value from top-of-stack slot; box result into result register. 1966 EmitCreateIteratorResult(false); 1967 __ push(result_register()); 1968 // Fall through. 1969 case Yield::INITIAL: { 1970 Label suspend, continuation, post_runtime, resume; 1971 1972 __ jmp(&suspend); 1973 1974 __ bind(&continuation); 1975 __ jmp(&resume); 1976 1977 __ bind(&suspend); 1978 VisitForAccumulatorValue(expr->generator_object()); 1979 ASSERT(continuation.pos() > 0 && Smi::IsValid(continuation.pos())); 1980 __ Move(FieldOperand(rax, JSGeneratorObject::kContinuationOffset), 1981 Smi::FromInt(continuation.pos())); 1982 __ movq(FieldOperand(rax, JSGeneratorObject::kContextOffset), rsi); 1983 __ movq(rcx, rsi); 1984 __ RecordWriteField(rax, JSGeneratorObject::kContextOffset, rcx, rdx, 1985 kDontSaveFPRegs); 1986 __ lea(rbx, Operand(rbp, StandardFrameConstants::kExpressionsOffset)); 1987 __ cmpq(rsp, rbx); 1988 __ j(equal, &post_runtime); 1989 __ push(rax); // generator object 1990 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1); 1991 __ movq(context_register(), 1992 Operand(rbp, StandardFrameConstants::kContextOffset)); 1993 __ bind(&post_runtime); 1994 1995 __ pop(result_register()); 1996 EmitReturnSequence(); 1997 1998 __ bind(&resume); 1999 context()->Plug(result_register()); 2000 break; 2001 } 2002 2003 case Yield::FINAL: { 2004 VisitForAccumulatorValue(expr->generator_object()); 2005 __ Move(FieldOperand(result_register(), 2006 JSGeneratorObject::kContinuationOffset), 2007 Smi::FromInt(JSGeneratorObject::kGeneratorClosed)); 2008 // Pop value from top-of-stack slot, box result into result register. 2009 EmitCreateIteratorResult(true); 2010 EmitUnwindBeforeReturn(); 2011 EmitReturnSequence(); 2012 break; 2013 } 2014 2015 case Yield::DELEGATING: { 2016 VisitForStackValue(expr->generator_object()); 2017 2018 // Initial stack layout is as follows: 2019 // [sp + 1 * kPointerSize] iter 2020 // [sp + 0 * kPointerSize] g 2021 2022 Label l_catch, l_try, l_suspend, l_continuation, l_resume; 2023 Label l_next, l_call, l_loop; 2024 // Initial send value is undefined. 2025 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex); 2026 __ jmp(&l_next); 2027 2028 // catch (e) { receiver = iter; f = 'throw'; arg = e; goto l_call; } 2029 __ bind(&l_catch); 2030 handler_table()->set(expr->index(), Smi::FromInt(l_catch.pos())); 2031 __ LoadRoot(rcx, Heap::kthrow_stringRootIndex); // "throw" 2032 __ push(rcx); 2033 __ push(Operand(rsp, 2 * kPointerSize)); // iter 2034 __ push(rax); // exception 2035 __ jmp(&l_call); 2036 2037 // try { received = %yield result } 2038 // Shuffle the received result above a try handler and yield it without 2039 // re-boxing. 2040 __ bind(&l_try); 2041 __ pop(rax); // result 2042 __ PushTryHandler(StackHandler::CATCH, expr->index()); 2043 const int handler_size = StackHandlerConstants::kSize; 2044 __ push(rax); // result 2045 __ jmp(&l_suspend); 2046 __ bind(&l_continuation); 2047 __ jmp(&l_resume); 2048 __ bind(&l_suspend); 2049 const int generator_object_depth = kPointerSize + handler_size; 2050 __ movq(rax, Operand(rsp, generator_object_depth)); 2051 __ push(rax); // g 2052 ASSERT(l_continuation.pos() > 0 && Smi::IsValid(l_continuation.pos())); 2053 __ Move(FieldOperand(rax, JSGeneratorObject::kContinuationOffset), 2054 Smi::FromInt(l_continuation.pos())); 2055 __ movq(FieldOperand(rax, JSGeneratorObject::kContextOffset), rsi); 2056 __ movq(rcx, rsi); 2057 __ RecordWriteField(rax, JSGeneratorObject::kContextOffset, rcx, rdx, 2058 kDontSaveFPRegs); 2059 __ CallRuntime(Runtime::kSuspendJSGeneratorObject, 1); 2060 __ movq(context_register(), 2061 Operand(rbp, StandardFrameConstants::kContextOffset)); 2062 __ pop(rax); // result 2063 EmitReturnSequence(); 2064 __ bind(&l_resume); // received in rax 2065 __ PopTryHandler(); 2066 2067 // receiver = iter; f = 'next'; arg = received; 2068 __ bind(&l_next); 2069 __ LoadRoot(rcx, Heap::knext_stringRootIndex); // "next" 2070 __ push(rcx); 2071 __ push(Operand(rsp, 2 * kPointerSize)); // iter 2072 __ push(rax); // received 2073 2074 // result = receiver[f](arg); 2075 __ bind(&l_call); 2076 Handle<Code> ic = isolate()->stub_cache()->ComputeKeyedCallInitialize(1); 2077 CallIC(ic); 2078 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); 2079 __ Drop(1); // The key is still on the stack; drop it. 2080 2081 // if (!result.done) goto l_try; 2082 __ bind(&l_loop); 2083 __ push(rax); // save result 2084 __ LoadRoot(rcx, Heap::kdone_stringRootIndex); // "done" 2085 Handle<Code> done_ic = isolate()->builtins()->LoadIC_Initialize(); 2086 CallIC(done_ic); // result.done in rax 2087 Handle<Code> bool_ic = ToBooleanStub::GetUninitialized(isolate()); 2088 CallIC(bool_ic); 2089 __ testq(result_register(), result_register()); 2090 __ j(zero, &l_try); 2091 2092 // result.value 2093 __ pop(rax); // result 2094 __ LoadRoot(rcx, Heap::kvalue_stringRootIndex); // "value" 2095 Handle<Code> value_ic = isolate()->builtins()->LoadIC_Initialize(); 2096 CallIC(value_ic); // result.value in rax 2097 context()->DropAndPlug(2, rax); // drop iter and g 2098 break; 2099 } 2100 } 2101 } 2102 2103 2104 void FullCodeGenerator::EmitGeneratorResume(Expression *generator, 2105 Expression *value, 2106 JSGeneratorObject::ResumeMode resume_mode) { 2107 // The value stays in rax, and is ultimately read by the resumed generator, as 2108 // if the CallRuntime(Runtime::kSuspendJSGeneratorObject) returned it. rbx 2109 // will hold the generator object until the activation has been resumed. 2110 VisitForStackValue(generator); 2111 VisitForAccumulatorValue(value); 2112 __ pop(rbx); 2113 2114 // Check generator state. 2115 Label wrong_state, done; 2116 STATIC_ASSERT(JSGeneratorObject::kGeneratorExecuting <= 0); 2117 STATIC_ASSERT(JSGeneratorObject::kGeneratorClosed <= 0); 2118 __ SmiCompare(FieldOperand(rbx, JSGeneratorObject::kContinuationOffset), 2119 Smi::FromInt(0)); 2120 __ j(less_equal, &wrong_state); 2121 2122 // Load suspended function and context. 2123 __ movq(rsi, FieldOperand(rbx, JSGeneratorObject::kContextOffset)); 2124 __ movq(rdi, FieldOperand(rbx, JSGeneratorObject::kFunctionOffset)); 2125 2126 // Push receiver. 2127 __ push(FieldOperand(rbx, JSGeneratorObject::kReceiverOffset)); 2128 2129 // Push holes for arguments to generator function. 2130 __ movq(rdx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset)); 2131 __ movsxlq(rdx, 2132 FieldOperand(rdx, 2133 SharedFunctionInfo::kFormalParameterCountOffset)); 2134 __ LoadRoot(rcx, Heap::kTheHoleValueRootIndex); 2135 Label push_argument_holes, push_frame; 2136 __ bind(&push_argument_holes); 2137 __ subq(rdx, Immediate(1)); 2138 __ j(carry, &push_frame); 2139 __ push(rcx); 2140 __ jmp(&push_argument_holes); 2141 2142 // Enter a new JavaScript frame, and initialize its slots as they were when 2143 // the generator was suspended. 2144 Label resume_frame; 2145 __ bind(&push_frame); 2146 __ call(&resume_frame); 2147 __ jmp(&done); 2148 __ bind(&resume_frame); 2149 __ push(rbp); // Caller's frame pointer. 2150 __ movq(rbp, rsp); 2151 __ push(rsi); // Callee's context. 2152 __ push(rdi); // Callee's JS Function. 2153 2154 // Load the operand stack size. 2155 __ movq(rdx, FieldOperand(rbx, JSGeneratorObject::kOperandStackOffset)); 2156 __ movq(rdx, FieldOperand(rdx, FixedArray::kLengthOffset)); 2157 __ SmiToInteger32(rdx, rdx); 2158 2159 // If we are sending a value and there is no operand stack, we can jump back 2160 // in directly. 2161 if (resume_mode == JSGeneratorObject::NEXT) { 2162 Label slow_resume; 2163 __ cmpq(rdx, Immediate(0)); 2164 __ j(not_zero, &slow_resume); 2165 __ movq(rdx, FieldOperand(rdi, JSFunction::kCodeEntryOffset)); 2166 __ SmiToInteger64(rcx, 2167 FieldOperand(rbx, JSGeneratorObject::kContinuationOffset)); 2168 __ addq(rdx, rcx); 2169 __ Move(FieldOperand(rbx, JSGeneratorObject::kContinuationOffset), 2170 Smi::FromInt(JSGeneratorObject::kGeneratorExecuting)); 2171 __ jmp(rdx); 2172 __ bind(&slow_resume); 2173 } 2174 2175 // Otherwise, we push holes for the operand stack and call the runtime to fix 2176 // up the stack and the handlers. 2177 Label push_operand_holes, call_resume; 2178 __ bind(&push_operand_holes); 2179 __ subq(rdx, Immediate(1)); 2180 __ j(carry, &call_resume); 2181 __ push(rcx); 2182 __ jmp(&push_operand_holes); 2183 __ bind(&call_resume); 2184 __ push(rbx); 2185 __ push(result_register()); 2186 __ Push(Smi::FromInt(resume_mode)); 2187 __ CallRuntime(Runtime::kResumeJSGeneratorObject, 3); 2188 // Not reached: the runtime call returns elsewhere. 2189 __ Abort(kGeneratorFailedToResume); 2190 2191 // Throw error if we attempt to operate on a running generator. 2192 __ bind(&wrong_state); 2193 __ push(rbx); 2194 __ CallRuntime(Runtime::kThrowGeneratorStateError, 1); 2195 2196 __ bind(&done); 2197 context()->Plug(result_register()); 2198 } 2199 2200 2201 void FullCodeGenerator::EmitCreateIteratorResult(bool done) { 2202 Label gc_required; 2203 Label allocated; 2204 2205 Handle<Map> map(isolate()->native_context()->generator_result_map()); 2206 2207 __ Allocate(map->instance_size(), rax, rcx, rdx, &gc_required, TAG_OBJECT); 2208 __ jmp(&allocated); 2209 2210 __ bind(&gc_required); 2211 __ Push(Smi::FromInt(map->instance_size())); 2212 __ CallRuntime(Runtime::kAllocateInNewSpace, 1); 2213 __ movq(context_register(), 2214 Operand(rbp, StandardFrameConstants::kContextOffset)); 2215 2216 __ bind(&allocated); 2217 __ Move(rbx, map); 2218 __ pop(rcx); 2219 __ Move(rdx, isolate()->factory()->ToBoolean(done)); 2220 ASSERT_EQ(map->instance_size(), 5 * kPointerSize); 2221 __ movq(FieldOperand(rax, HeapObject::kMapOffset), rbx); 2222 __ Move(FieldOperand(rax, JSObject::kPropertiesOffset), 2223 isolate()->factory()->empty_fixed_array()); 2224 __ Move(FieldOperand(rax, JSObject::kElementsOffset), 2225 isolate()->factory()->empty_fixed_array()); 2226 __ movq(FieldOperand(rax, JSGeneratorObject::kResultValuePropertyOffset), 2227 rcx); 2228 __ movq(FieldOperand(rax, JSGeneratorObject::kResultDonePropertyOffset), 2229 rdx); 2230 2231 // Only the value field needs a write barrier, as the other values are in the 2232 // root set. 2233 __ RecordWriteField(rax, JSGeneratorObject::kResultValuePropertyOffset, 2234 rcx, rdx, kDontSaveFPRegs); 2235 } 2236 2237 2238 void FullCodeGenerator::EmitNamedPropertyLoad(Property* prop) { 2239 SetSourcePosition(prop->position()); 2240 Literal* key = prop->key()->AsLiteral(); 2241 __ Move(rcx, key->value()); 2242 Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); 2243 CallIC(ic, RelocInfo::CODE_TARGET, prop->PropertyFeedbackId()); 2244 } 2245 2246 2247 void FullCodeGenerator::EmitKeyedPropertyLoad(Property* prop) { 2248 SetSourcePosition(prop->position()); 2249 Handle<Code> ic = isolate()->builtins()->KeyedLoadIC_Initialize(); 2250 CallIC(ic, RelocInfo::CODE_TARGET, prop->PropertyFeedbackId()); 2251 } 2252 2253 2254 void FullCodeGenerator::EmitInlineSmiBinaryOp(BinaryOperation* expr, 2255 Token::Value op, 2256 OverwriteMode mode, 2257 Expression* left, 2258 Expression* right) { 2259 // Do combined smi check of the operands. Left operand is on the 2260 // stack (popped into rdx). Right operand is in rax but moved into 2261 // rcx to make the shifts easier. 2262 Label done, stub_call, smi_case; 2263 __ pop(rdx); 2264 __ movq(rcx, rax); 2265 __ or_(rax, rdx); 2266 JumpPatchSite patch_site(masm_); 2267 patch_site.EmitJumpIfSmi(rax, &smi_case, Label::kNear); 2268 2269 __ bind(&stub_call); 2270 __ movq(rax, rcx); 2271 BinaryOpICStub stub(op, mode); 2272 CallIC(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, 2273 expr->BinaryOperationFeedbackId()); 2274 patch_site.EmitPatchInfo(); 2275 __ jmp(&done, Label::kNear); 2276 2277 __ bind(&smi_case); 2278 switch (op) { 2279 case Token::SAR: 2280 __ SmiShiftArithmeticRight(rax, rdx, rcx); 2281 break; 2282 case Token::SHL: 2283 __ SmiShiftLeft(rax, rdx, rcx); 2284 break; 2285 case Token::SHR: 2286 __ SmiShiftLogicalRight(rax, rdx, rcx, &stub_call); 2287 break; 2288 case Token::ADD: 2289 __ SmiAdd(rax, rdx, rcx, &stub_call); 2290 break; 2291 case Token::SUB: 2292 __ SmiSub(rax, rdx, rcx, &stub_call); 2293 break; 2294 case Token::MUL: 2295 __ SmiMul(rax, rdx, rcx, &stub_call); 2296 break; 2297 case Token::BIT_OR: 2298 __ SmiOr(rax, rdx, rcx); 2299 break; 2300 case Token::BIT_AND: 2301 __ SmiAnd(rax, rdx, rcx); 2302 break; 2303 case Token::BIT_XOR: 2304 __ SmiXor(rax, rdx, rcx); 2305 break; 2306 default: 2307 UNREACHABLE(); 2308 break; 2309 } 2310 2311 __ bind(&done); 2312 context()->Plug(rax); 2313 } 2314 2315 2316 void FullCodeGenerator::EmitBinaryOp(BinaryOperation* expr, 2317 Token::Value op, 2318 OverwriteMode mode) { 2319 __ pop(rdx); 2320 BinaryOpICStub stub(op, mode); 2321 JumpPatchSite patch_site(masm_); // unbound, signals no inlined smi code. 2322 CallIC(stub.GetCode(isolate()), RelocInfo::CODE_TARGET, 2323 expr->BinaryOperationFeedbackId()); 2324 patch_site.EmitPatchInfo(); 2325 context()->Plug(rax); 2326 } 2327 2328 2329 void FullCodeGenerator::EmitAssignment(Expression* expr) { 2330 // Invalid left-hand sides are rewritten by the parser to have a 'throw 2331 // ReferenceError' on the left-hand side. 2332 if (!expr->IsValidLeftHandSide()) { 2333 VisitForEffect(expr); 2334 return; 2335 } 2336 2337 // Left-hand side can only be a property, a global or a (parameter or local) 2338 // slot. 2339 enum LhsKind { VARIABLE, NAMED_PROPERTY, KEYED_PROPERTY }; 2340 LhsKind assign_type = VARIABLE; 2341 Property* prop = expr->AsProperty(); 2342 if (prop != NULL) { 2343 assign_type = (prop->key()->IsPropertyName()) 2344 ? NAMED_PROPERTY 2345 : KEYED_PROPERTY; 2346 } 2347 2348 switch (assign_type) { 2349 case VARIABLE: { 2350 Variable* var = expr->AsVariableProxy()->var(); 2351 EffectContext context(this); 2352 EmitVariableAssignment(var, Token::ASSIGN); 2353 break; 2354 } 2355 case NAMED_PROPERTY: { 2356 __ push(rax); // Preserve value. 2357 VisitForAccumulatorValue(prop->obj()); 2358 __ movq(rdx, rax); 2359 __ pop(rax); // Restore value. 2360 __ Move(rcx, prop->key()->AsLiteral()->value()); 2361 Handle<Code> ic = is_classic_mode() 2362 ? isolate()->builtins()->StoreIC_Initialize() 2363 : isolate()->builtins()->StoreIC_Initialize_Strict(); 2364 CallIC(ic); 2365 break; 2366 } 2367 case KEYED_PROPERTY: { 2368 __ push(rax); // Preserve value. 2369 VisitForStackValue(prop->obj()); 2370 VisitForAccumulatorValue(prop->key()); 2371 __ movq(rcx, rax); 2372 __ pop(rdx); 2373 __ pop(rax); // Restore value. 2374 Handle<Code> ic = is_classic_mode() 2375 ? isolate()->builtins()->KeyedStoreIC_Initialize() 2376 : isolate()->builtins()->KeyedStoreIC_Initialize_Strict(); 2377 CallIC(ic); 2378 break; 2379 } 2380 } 2381 context()->Plug(rax); 2382 } 2383 2384 2385 void FullCodeGenerator::EmitVariableAssignment(Variable* var, 2386 Token::Value op) { 2387 if (var->IsUnallocated()) { 2388 // Global var, const, or let. 2389 __ Move(rcx, var->name()); 2390 __ movq(rdx, GlobalObjectOperand()); 2391 Handle<Code> ic = is_classic_mode() 2392 ? isolate()->builtins()->StoreIC_Initialize() 2393 : isolate()->builtins()->StoreIC_Initialize_Strict(); 2394 CallIC(ic, RelocInfo::CODE_TARGET_CONTEXT); 2395 } else if (op == Token::INIT_CONST) { 2396 // Const initializers need a write barrier. 2397 ASSERT(!var->IsParameter()); // No const parameters. 2398 if (var->IsStackLocal()) { 2399 Label skip; 2400 __ movq(rdx, StackOperand(var)); 2401 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex); 2402 __ j(not_equal, &skip); 2403 __ movq(StackOperand(var), rax); 2404 __ bind(&skip); 2405 } else { 2406 ASSERT(var->IsContextSlot() || var->IsLookupSlot()); 2407 // Like var declarations, const declarations are hoisted to function 2408 // scope. However, unlike var initializers, const initializers are 2409 // able to drill a hole to that function context, even from inside a 2410 // 'with' context. We thus bypass the normal static scope lookup for 2411 // var->IsContextSlot(). 2412 __ push(rax); 2413 __ push(rsi); 2414 __ Push(var->name()); 2415 __ CallRuntime(Runtime::kInitializeConstContextSlot, 3); 2416 } 2417 2418 } else if (var->mode() == LET && op != Token::INIT_LET) { 2419 // Non-initializing assignment to let variable needs a write barrier. 2420 if (var->IsLookupSlot()) { 2421 __ push(rax); // Value. 2422 __ push(rsi); // Context. 2423 __ Push(var->name()); 2424 __ Push(Smi::FromInt(language_mode())); 2425 __ CallRuntime(Runtime::kStoreContextSlot, 4); 2426 } else { 2427 ASSERT(var->IsStackAllocated() || var->IsContextSlot()); 2428 Label assign; 2429 MemOperand location = VarOperand(var, rcx); 2430 __ movq(rdx, location); 2431 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex); 2432 __ j(not_equal, &assign, Label::kNear); 2433 __ Push(var->name()); 2434 __ CallRuntime(Runtime::kThrowReferenceError, 1); 2435 __ bind(&assign); 2436 __ movq(location, rax); 2437 if (var->IsContextSlot()) { 2438 __ movq(rdx, rax); 2439 __ RecordWriteContextSlot( 2440 rcx, Context::SlotOffset(var->index()), rdx, rbx, kDontSaveFPRegs); 2441 } 2442 } 2443 2444 } else if (!var->is_const_mode() || op == Token::INIT_CONST_HARMONY) { 2445 // Assignment to var or initializing assignment to let/const 2446 // in harmony mode. 2447 if (var->IsStackAllocated() || var->IsContextSlot()) { 2448 MemOperand location = VarOperand(var, rcx); 2449 if (generate_debug_code_ && op == Token::INIT_LET) { 2450 // Check for an uninitialized let binding. 2451 __ movq(rdx, location); 2452 __ CompareRoot(rdx, Heap::kTheHoleValueRootIndex); 2453 __ Check(equal, kLetBindingReInitialization); 2454 } 2455 // Perform the assignment. 2456 __ movq(location, rax); 2457 if (var->IsContextSlot()) { 2458 __ movq(rdx, rax); 2459 __ RecordWriteContextSlot( 2460 rcx, Context::SlotOffset(var->index()), rdx, rbx, kDontSaveFPRegs); 2461 } 2462 } else { 2463 ASSERT(var->IsLookupSlot()); 2464 __ push(rax); // Value. 2465 __ push(rsi); // Context. 2466 __ Push(var->name()); 2467 __ Push(Smi::FromInt(language_mode())); 2468 __ CallRuntime(Runtime::kStoreContextSlot, 4); 2469 } 2470 } 2471 // Non-initializing assignments to consts are ignored. 2472 } 2473 2474 2475 void FullCodeGenerator::EmitNamedPropertyAssignment(Assignment* expr) { 2476 // Assignment to a property, using a named store IC. 2477 Property* prop = expr->target()->AsProperty(); 2478 ASSERT(prop != NULL); 2479 ASSERT(prop->key()->AsLiteral() != NULL); 2480 2481 // Record source code position before IC call. 2482 SetSourcePosition(expr->position()); 2483 __ Move(rcx, prop->key()->AsLiteral()->value()); 2484 __ pop(rdx); 2485 Handle<Code> ic = is_classic_mode() 2486 ? isolate()->builtins()->StoreIC_Initialize() 2487 : isolate()->builtins()->StoreIC_Initialize_Strict(); 2488 CallIC(ic, RelocInfo::CODE_TARGET, expr->AssignmentFeedbackId()); 2489 2490 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG); 2491 context()->Plug(rax); 2492 } 2493 2494 2495 void FullCodeGenerator::EmitKeyedPropertyAssignment(Assignment* expr) { 2496 // Assignment to a property, using a keyed store IC. 2497 2498 __ pop(rcx); 2499 __ pop(rdx); 2500 // Record source code position before IC call. 2501 SetSourcePosition(expr->position()); 2502 Handle<Code> ic = is_classic_mode() 2503 ? isolate()->builtins()->KeyedStoreIC_Initialize() 2504 : isolate()->builtins()->KeyedStoreIC_Initialize_Strict(); 2505 CallIC(ic, RelocInfo::CODE_TARGET, expr->AssignmentFeedbackId()); 2506 2507 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG); 2508 context()->Plug(rax); 2509 } 2510 2511 2512 void FullCodeGenerator::VisitProperty(Property* expr) { 2513 Comment cmnt(masm_, "[ Property"); 2514 Expression* key = expr->key(); 2515 2516 if (key->IsPropertyName()) { 2517 VisitForAccumulatorValue(expr->obj()); 2518 EmitNamedPropertyLoad(expr); 2519 PrepareForBailoutForId(expr->LoadId(), TOS_REG); 2520 context()->Plug(rax); 2521 } else { 2522 VisitForStackValue(expr->obj()); 2523 VisitForAccumulatorValue(expr->key()); 2524 __ pop(rdx); 2525 EmitKeyedPropertyLoad(expr); 2526 context()->Plug(rax); 2527 } 2528 } 2529 2530 2531 void FullCodeGenerator::CallIC(Handle<Code> code, 2532 RelocInfo::Mode rmode, 2533 TypeFeedbackId ast_id) { 2534 ic_total_count_++; 2535 __ call(code, rmode, ast_id); 2536 } 2537 2538 2539 void FullCodeGenerator::EmitCallWithIC(Call* expr, 2540 Handle<Object> name, 2541 RelocInfo::Mode mode) { 2542 // Code common for calls using the IC. 2543 ZoneList<Expression*>* args = expr->arguments(); 2544 int arg_count = args->length(); 2545 { PreservePositionScope scope(masm()->positions_recorder()); 2546 for (int i = 0; i < arg_count; i++) { 2547 VisitForStackValue(args->at(i)); 2548 } 2549 __ Move(rcx, name); 2550 } 2551 // Record source position for debugger. 2552 SetSourcePosition(expr->position()); 2553 // Call the IC initialization code. 2554 Handle<Code> ic = 2555 isolate()->stub_cache()->ComputeCallInitialize(arg_count, mode); 2556 CallIC(ic, mode, expr->CallFeedbackId()); 2557 RecordJSReturnSite(expr); 2558 // Restore context register. 2559 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); 2560 context()->Plug(rax); 2561 } 2562 2563 2564 void FullCodeGenerator::EmitKeyedCallWithIC(Call* expr, 2565 Expression* key) { 2566 // Load the key. 2567 VisitForAccumulatorValue(key); 2568 2569 // Swap the name of the function and the receiver on the stack to follow 2570 // the calling convention for call ICs. 2571 __ pop(rcx); 2572 __ push(rax); 2573 __ push(rcx); 2574 2575 // Load the arguments. 2576 ZoneList<Expression*>* args = expr->arguments(); 2577 int arg_count = args->length(); 2578 { PreservePositionScope scope(masm()->positions_recorder()); 2579 for (int i = 0; i < arg_count; i++) { 2580 VisitForStackValue(args->at(i)); 2581 } 2582 } 2583 // Record source position for debugger. 2584 SetSourcePosition(expr->position()); 2585 // Call the IC initialization code. 2586 Handle<Code> ic = 2587 isolate()->stub_cache()->ComputeKeyedCallInitialize(arg_count); 2588 __ movq(rcx, Operand(rsp, (arg_count + 1) * kPointerSize)); // Key. 2589 CallIC(ic, RelocInfo::CODE_TARGET, expr->CallFeedbackId()); 2590 RecordJSReturnSite(expr); 2591 // Restore context register. 2592 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); 2593 context()->DropAndPlug(1, rax); // Drop the key still on the stack. 2594 } 2595 2596 2597 void FullCodeGenerator::EmitCallWithStub(Call* expr, CallFunctionFlags flags) { 2598 // Code common for calls using the call stub. 2599 ZoneList<Expression*>* args = expr->arguments(); 2600 int arg_count = args->length(); 2601 { PreservePositionScope scope(masm()->positions_recorder()); 2602 for (int i = 0; i < arg_count; i++) { 2603 VisitForStackValue(args->at(i)); 2604 } 2605 } 2606 // Record source position for debugger. 2607 SetSourcePosition(expr->position()); 2608 2609 // Record call targets in unoptimized code. 2610 flags = static_cast<CallFunctionFlags>(flags | RECORD_CALL_TARGET); 2611 Handle<Object> uninitialized = 2612 TypeFeedbackCells::UninitializedSentinel(isolate()); 2613 Handle<Cell> cell = isolate()->factory()->NewCell(uninitialized); 2614 RecordTypeFeedbackCell(expr->CallFeedbackId(), cell); 2615 __ Move(rbx, cell); 2616 2617 CallFunctionStub stub(arg_count, flags); 2618 __ movq(rdi, Operand(rsp, (arg_count + 1) * kPointerSize)); 2619 __ CallStub(&stub, expr->CallFeedbackId()); 2620 RecordJSReturnSite(expr); 2621 // Restore context register. 2622 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); 2623 // Discard the function left on TOS. 2624 context()->DropAndPlug(1, rax); 2625 } 2626 2627 2628 void FullCodeGenerator::EmitResolvePossiblyDirectEval(int arg_count) { 2629 // Push copy of the first argument or undefined if it doesn't exist. 2630 if (arg_count > 0) { 2631 __ push(Operand(rsp, arg_count * kPointerSize)); 2632 } else { 2633 __ PushRoot(Heap::kUndefinedValueRootIndex); 2634 } 2635 2636 // Push the receiver of the enclosing function and do runtime call. 2637 StackArgumentsAccessor args(rbp, info_->scope()->num_parameters()); 2638 __ push(args.GetReceiverOperand()); 2639 2640 // Push the language mode. 2641 __ Push(Smi::FromInt(language_mode())); 2642 2643 // Push the start position of the scope the calls resides in. 2644 __ Push(Smi::FromInt(scope()->start_position())); 2645 2646 // Do the runtime call. 2647 __ CallRuntime(Runtime::kResolvePossiblyDirectEval, 5); 2648 } 2649 2650 2651 void FullCodeGenerator::VisitCall(Call* expr) { 2652 #ifdef DEBUG 2653 // We want to verify that RecordJSReturnSite gets called on all paths 2654 // through this function. Avoid early returns. 2655 expr->return_is_recorded_ = false; 2656 #endif 2657 2658 Comment cmnt(masm_, "[ Call"); 2659 Expression* callee = expr->expression(); 2660 VariableProxy* proxy = callee->AsVariableProxy(); 2661 Property* property = callee->AsProperty(); 2662 2663 if (proxy != NULL && proxy->var()->is_possibly_eval(isolate())) { 2664 // In a call to eval, we first call %ResolvePossiblyDirectEval to 2665 // resolve the function we need to call and the receiver of the call. 2666 // Then we call the resolved function using the given arguments. 2667 ZoneList<Expression*>* args = expr->arguments(); 2668 int arg_count = args->length(); 2669 { PreservePositionScope pos_scope(masm()->positions_recorder()); 2670 VisitForStackValue(callee); 2671 __ PushRoot(Heap::kUndefinedValueRootIndex); // Reserved receiver slot. 2672 2673 // Push the arguments. 2674 for (int i = 0; i < arg_count; i++) { 2675 VisitForStackValue(args->at(i)); 2676 } 2677 2678 // Push a copy of the function (found below the arguments) and resolve 2679 // eval. 2680 __ push(Operand(rsp, (arg_count + 1) * kPointerSize)); 2681 EmitResolvePossiblyDirectEval(arg_count); 2682 2683 // The runtime call returns a pair of values in rax (function) and 2684 // rdx (receiver). Touch up the stack with the right values. 2685 __ movq(Operand(rsp, (arg_count + 0) * kPointerSize), rdx); 2686 __ movq(Operand(rsp, (arg_count + 1) * kPointerSize), rax); 2687 } 2688 // Record source position for debugger. 2689 SetSourcePosition(expr->position()); 2690 CallFunctionStub stub(arg_count, RECEIVER_MIGHT_BE_IMPLICIT); 2691 __ movq(rdi, Operand(rsp, (arg_count + 1) * kPointerSize)); 2692 __ CallStub(&stub); 2693 RecordJSReturnSite(expr); 2694 // Restore context register. 2695 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); 2696 context()->DropAndPlug(1, rax); 2697 } else if (proxy != NULL && proxy->var()->IsUnallocated()) { 2698 // Call to a global variable. Push global object as receiver for the 2699 // call IC lookup. 2700 __ push(GlobalObjectOperand()); 2701 EmitCallWithIC(expr, proxy->name(), RelocInfo::CODE_TARGET_CONTEXT); 2702 } else if (proxy != NULL && proxy->var()->IsLookupSlot()) { 2703 // Call to a lookup slot (dynamically introduced variable). 2704 Label slow, done; 2705 2706 { PreservePositionScope scope(masm()->positions_recorder()); 2707 // Generate code for loading from variables potentially shadowed by 2708 // eval-introduced variables. 2709 EmitDynamicLookupFastCase(proxy->var(), NOT_INSIDE_TYPEOF, &slow, &done); 2710 } 2711 __ bind(&slow); 2712 // Call the runtime to find the function to call (returned in rax) and 2713 // the object holding it (returned in rdx). 2714 __ push(context_register()); 2715 __ Push(proxy->name()); 2716 __ CallRuntime(Runtime::kLoadContextSlot, 2); 2717 __ push(rax); // Function. 2718 __ push(rdx); // Receiver. 2719 2720 // If fast case code has been generated, emit code to push the function 2721 // and receiver and have the slow path jump around this code. 2722 if (done.is_linked()) { 2723 Label call; 2724 __ jmp(&call, Label::kNear); 2725 __ bind(&done); 2726 // Push function. 2727 __ push(rax); 2728 // The receiver is implicitly the global receiver. Indicate this by 2729 // passing the hole to the call function stub. 2730 __ PushRoot(Heap::kTheHoleValueRootIndex); 2731 __ bind(&call); 2732 } 2733 2734 // The receiver is either the global receiver or an object found by 2735 // LoadContextSlot. That object could be the hole if the receiver is 2736 // implicitly the global object. 2737 EmitCallWithStub(expr, RECEIVER_MIGHT_BE_IMPLICIT); 2738 } else if (property != NULL) { 2739 { PreservePositionScope scope(masm()->positions_recorder()); 2740 VisitForStackValue(property->obj()); 2741 } 2742 if (property->key()->IsPropertyName()) { 2743 EmitCallWithIC(expr, 2744 property->key()->AsLiteral()->value(), 2745 RelocInfo::CODE_TARGET); 2746 } else { 2747 EmitKeyedCallWithIC(expr, property->key()); 2748 } 2749 } else { 2750 // Call to an arbitrary expression not handled specially above. 2751 { PreservePositionScope scope(masm()->positions_recorder()); 2752 VisitForStackValue(callee); 2753 } 2754 // Load global receiver object. 2755 __ movq(rbx, GlobalObjectOperand()); 2756 __ push(FieldOperand(rbx, GlobalObject::kGlobalReceiverOffset)); 2757 // Emit function call. 2758 EmitCallWithStub(expr, NO_CALL_FUNCTION_FLAGS); 2759 } 2760 2761 #ifdef DEBUG 2762 // RecordJSReturnSite should have been called. 2763 ASSERT(expr->return_is_recorded_); 2764 #endif 2765 } 2766 2767 2768 void FullCodeGenerator::VisitCallNew(CallNew* expr) { 2769 Comment cmnt(masm_, "[ CallNew"); 2770 // According to ECMA-262, section 11.2.2, page 44, the function 2771 // expression in new calls must be evaluated before the 2772 // arguments. 2773 2774 // Push constructor on the stack. If it's not a function it's used as 2775 // receiver for CALL_NON_FUNCTION, otherwise the value on the stack is 2776 // ignored. 2777 VisitForStackValue(expr->expression()); 2778 2779 // Push the arguments ("left-to-right") on the stack. 2780 ZoneList<Expression*>* args = expr->arguments(); 2781 int arg_count = args->length(); 2782 for (int i = 0; i < arg_count; i++) { 2783 VisitForStackValue(args->at(i)); 2784 } 2785 2786 // Call the construct call builtin that handles allocation and 2787 // constructor invocation. 2788 SetSourcePosition(expr->position()); 2789 2790 // Load function and argument count into rdi and rax. 2791 __ Set(rax, arg_count); 2792 __ movq(rdi, Operand(rsp, arg_count * kPointerSize)); 2793 2794 // Record call targets in unoptimized code, but not in the snapshot. 2795 Handle<Object> uninitialized = 2796 TypeFeedbackCells::UninitializedSentinel(isolate()); 2797 Handle<Cell> cell = isolate()->factory()->NewCell(uninitialized); 2798 RecordTypeFeedbackCell(expr->CallNewFeedbackId(), cell); 2799 __ Move(rbx, cell); 2800 2801 CallConstructStub stub(RECORD_CALL_TARGET); 2802 __ Call(stub.GetCode(isolate()), RelocInfo::CONSTRUCT_CALL); 2803 PrepareForBailoutForId(expr->ReturnId(), TOS_REG); 2804 context()->Plug(rax); 2805 } 2806 2807 2808 void FullCodeGenerator::EmitIsSmi(CallRuntime* expr) { 2809 ZoneList<Expression*>* args = expr->arguments(); 2810 ASSERT(args->length() == 1); 2811 2812 VisitForAccumulatorValue(args->at(0)); 2813 2814 Label materialize_true, materialize_false; 2815 Label* if_true = NULL; 2816 Label* if_false = NULL; 2817 Label* fall_through = NULL; 2818 context()->PrepareTest(&materialize_true, &materialize_false, 2819 &if_true, &if_false, &fall_through); 2820 2821 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 2822 __ JumpIfSmi(rax, if_true); 2823 __ jmp(if_false); 2824 2825 context()->Plug(if_true, if_false); 2826 } 2827 2828 2829 void FullCodeGenerator::EmitIsNonNegativeSmi(CallRuntime* expr) { 2830 ZoneList<Expression*>* args = expr->arguments(); 2831 ASSERT(args->length() == 1); 2832 2833 VisitForAccumulatorValue(args->at(0)); 2834 2835 Label materialize_true, materialize_false; 2836 Label* if_true = NULL; 2837 Label* if_false = NULL; 2838 Label* fall_through = NULL; 2839 context()->PrepareTest(&materialize_true, &materialize_false, 2840 &if_true, &if_false, &fall_through); 2841 2842 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 2843 Condition non_negative_smi = masm()->CheckNonNegativeSmi(rax); 2844 Split(non_negative_smi, if_true, if_false, fall_through); 2845 2846 context()->Plug(if_true, if_false); 2847 } 2848 2849 2850 void FullCodeGenerator::EmitIsObject(CallRuntime* expr) { 2851 ZoneList<Expression*>* args = expr->arguments(); 2852 ASSERT(args->length() == 1); 2853 2854 VisitForAccumulatorValue(args->at(0)); 2855 2856 Label materialize_true, materialize_false; 2857 Label* if_true = NULL; 2858 Label* if_false = NULL; 2859 Label* fall_through = NULL; 2860 context()->PrepareTest(&materialize_true, &materialize_false, 2861 &if_true, &if_false, &fall_through); 2862 2863 __ JumpIfSmi(rax, if_false); 2864 __ CompareRoot(rax, Heap::kNullValueRootIndex); 2865 __ j(equal, if_true); 2866 __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset)); 2867 // Undetectable objects behave like undefined when tested with typeof. 2868 __ testb(FieldOperand(rbx, Map::kBitFieldOffset), 2869 Immediate(1 << Map::kIsUndetectable)); 2870 __ j(not_zero, if_false); 2871 __ movzxbq(rbx, FieldOperand(rbx, Map::kInstanceTypeOffset)); 2872 __ cmpq(rbx, Immediate(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE)); 2873 __ j(below, if_false); 2874 __ cmpq(rbx, Immediate(LAST_NONCALLABLE_SPEC_OBJECT_TYPE)); 2875 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 2876 Split(below_equal, if_true, if_false, fall_through); 2877 2878 context()->Plug(if_true, if_false); 2879 } 2880 2881 2882 void FullCodeGenerator::EmitIsSpecObject(CallRuntime* expr) { 2883 ZoneList<Expression*>* args = expr->arguments(); 2884 ASSERT(args->length() == 1); 2885 2886 VisitForAccumulatorValue(args->at(0)); 2887 2888 Label materialize_true, materialize_false; 2889 Label* if_true = NULL; 2890 Label* if_false = NULL; 2891 Label* fall_through = NULL; 2892 context()->PrepareTest(&materialize_true, &materialize_false, 2893 &if_true, &if_false, &fall_through); 2894 2895 __ JumpIfSmi(rax, if_false); 2896 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rbx); 2897 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 2898 Split(above_equal, if_true, if_false, fall_through); 2899 2900 context()->Plug(if_true, if_false); 2901 } 2902 2903 2904 void FullCodeGenerator::EmitIsUndetectableObject(CallRuntime* expr) { 2905 ZoneList<Expression*>* args = expr->arguments(); 2906 ASSERT(args->length() == 1); 2907 2908 VisitForAccumulatorValue(args->at(0)); 2909 2910 Label materialize_true, materialize_false; 2911 Label* if_true = NULL; 2912 Label* if_false = NULL; 2913 Label* fall_through = NULL; 2914 context()->PrepareTest(&materialize_true, &materialize_false, 2915 &if_true, &if_false, &fall_through); 2916 2917 __ JumpIfSmi(rax, if_false); 2918 __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset)); 2919 __ testb(FieldOperand(rbx, Map::kBitFieldOffset), 2920 Immediate(1 << Map::kIsUndetectable)); 2921 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 2922 Split(not_zero, if_true, if_false, fall_through); 2923 2924 context()->Plug(if_true, if_false); 2925 } 2926 2927 2928 void FullCodeGenerator::EmitIsStringWrapperSafeForDefaultValueOf( 2929 CallRuntime* expr) { 2930 ZoneList<Expression*>* args = expr->arguments(); 2931 ASSERT(args->length() == 1); 2932 2933 VisitForAccumulatorValue(args->at(0)); 2934 2935 Label materialize_true, materialize_false, skip_lookup; 2936 Label* if_true = NULL; 2937 Label* if_false = NULL; 2938 Label* fall_through = NULL; 2939 context()->PrepareTest(&materialize_true, &materialize_false, 2940 &if_true, &if_false, &fall_through); 2941 2942 __ AssertNotSmi(rax); 2943 2944 // Check whether this map has already been checked to be safe for default 2945 // valueOf. 2946 __ movq(rbx, FieldOperand(rax, HeapObject::kMapOffset)); 2947 __ testb(FieldOperand(rbx, Map::kBitField2Offset), 2948 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf)); 2949 __ j(not_zero, &skip_lookup); 2950 2951 // Check for fast case object. Generate false result for slow case object. 2952 __ movq(rcx, FieldOperand(rax, JSObject::kPropertiesOffset)); 2953 __ movq(rcx, FieldOperand(rcx, HeapObject::kMapOffset)); 2954 __ CompareRoot(rcx, Heap::kHashTableMapRootIndex); 2955 __ j(equal, if_false); 2956 2957 // Look for valueOf string in the descriptor array, and indicate false if 2958 // found. Since we omit an enumeration index check, if it is added via a 2959 // transition that shares its descriptor array, this is a false positive. 2960 Label entry, loop, done; 2961 2962 // Skip loop if no descriptors are valid. 2963 __ NumberOfOwnDescriptors(rcx, rbx); 2964 __ cmpq(rcx, Immediate(0)); 2965 __ j(equal, &done); 2966 2967 __ LoadInstanceDescriptors(rbx, r8); 2968 // rbx: descriptor array. 2969 // rcx: valid entries in the descriptor array. 2970 // Calculate the end of the descriptor array. 2971 __ imul(rcx, rcx, Immediate(DescriptorArray::kDescriptorSize)); 2972 SmiIndex index = masm_->SmiToIndex(rdx, rcx, kPointerSizeLog2); 2973 __ lea(rcx, 2974 Operand( 2975 r8, index.reg, index.scale, DescriptorArray::kFirstOffset)); 2976 // Calculate location of the first key name. 2977 __ addq(r8, Immediate(DescriptorArray::kFirstOffset)); 2978 // Loop through all the keys in the descriptor array. If one of these is the 2979 // internalized string "valueOf" the result is false. 2980 __ jmp(&entry); 2981 __ bind(&loop); 2982 __ movq(rdx, FieldOperand(r8, 0)); 2983 __ Cmp(rdx, isolate()->factory()->value_of_string()); 2984 __ j(equal, if_false); 2985 __ addq(r8, Immediate(DescriptorArray::kDescriptorSize * kPointerSize)); 2986 __ bind(&entry); 2987 __ cmpq(r8, rcx); 2988 __ j(not_equal, &loop); 2989 2990 __ bind(&done); 2991 2992 // Set the bit in the map to indicate that there is no local valueOf field. 2993 __ or_(FieldOperand(rbx, Map::kBitField2Offset), 2994 Immediate(1 << Map::kStringWrapperSafeForDefaultValueOf)); 2995 2996 __ bind(&skip_lookup); 2997 2998 // If a valueOf property is not found on the object check that its 2999 // prototype is the un-modified String prototype. If not result is false. 3000 __ movq(rcx, FieldOperand(rbx, Map::kPrototypeOffset)); 3001 __ testq(rcx, Immediate(kSmiTagMask)); 3002 __ j(zero, if_false); 3003 __ movq(rcx, FieldOperand(rcx, HeapObject::kMapOffset)); 3004 __ movq(rdx, Operand(rsi, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX))); 3005 __ movq(rdx, FieldOperand(rdx, GlobalObject::kNativeContextOffset)); 3006 __ cmpq(rcx, 3007 ContextOperand(rdx, Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX)); 3008 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 3009 Split(equal, if_true, if_false, fall_through); 3010 3011 context()->Plug(if_true, if_false); 3012 } 3013 3014 3015 void FullCodeGenerator::EmitIsFunction(CallRuntime* expr) { 3016 ZoneList<Expression*>* args = expr->arguments(); 3017 ASSERT(args->length() == 1); 3018 3019 VisitForAccumulatorValue(args->at(0)); 3020 3021 Label materialize_true, materialize_false; 3022 Label* if_true = NULL; 3023 Label* if_false = NULL; 3024 Label* fall_through = NULL; 3025 context()->PrepareTest(&materialize_true, &materialize_false, 3026 &if_true, &if_false, &fall_through); 3027 3028 __ JumpIfSmi(rax, if_false); 3029 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx); 3030 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 3031 Split(equal, if_true, if_false, fall_through); 3032 3033 context()->Plug(if_true, if_false); 3034 } 3035 3036 3037 void FullCodeGenerator::EmitIsMinusZero(CallRuntime* expr) { 3038 ZoneList<Expression*>* args = expr->arguments(); 3039 ASSERT(args->length() == 1); 3040 3041 VisitForAccumulatorValue(args->at(0)); 3042 3043 Label materialize_true, materialize_false; 3044 Label* if_true = NULL; 3045 Label* if_false = NULL; 3046 Label* fall_through = NULL; 3047 context()->PrepareTest(&materialize_true, &materialize_false, 3048 &if_true, &if_false, &fall_through); 3049 3050 Handle<Map> map = masm()->isolate()->factory()->heap_number_map(); 3051 __ CheckMap(rax, map, if_false, DO_SMI_CHECK); 3052 __ cmpl(FieldOperand(rax, HeapNumber::kExponentOffset), 3053 Immediate(0x80000000)); 3054 __ j(not_equal, if_false); 3055 __ cmpl(FieldOperand(rax, HeapNumber::kMantissaOffset), 3056 Immediate(0x00000000)); 3057 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 3058 Split(equal, if_true, if_false, fall_through); 3059 3060 context()->Plug(if_true, if_false); 3061 } 3062 3063 3064 void FullCodeGenerator::EmitIsArray(CallRuntime* expr) { 3065 ZoneList<Expression*>* args = expr->arguments(); 3066 ASSERT(args->length() == 1); 3067 3068 VisitForAccumulatorValue(args->at(0)); 3069 3070 Label materialize_true, materialize_false; 3071 Label* if_true = NULL; 3072 Label* if_false = NULL; 3073 Label* fall_through = NULL; 3074 context()->PrepareTest(&materialize_true, &materialize_false, 3075 &if_true, &if_false, &fall_through); 3076 3077 __ JumpIfSmi(rax, if_false); 3078 __ CmpObjectType(rax, JS_ARRAY_TYPE, rbx); 3079 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 3080 Split(equal, if_true, if_false, fall_through); 3081 3082 context()->Plug(if_true, if_false); 3083 } 3084 3085 3086 void FullCodeGenerator::EmitIsRegExp(CallRuntime* expr) { 3087 ZoneList<Expression*>* args = expr->arguments(); 3088 ASSERT(args->length() == 1); 3089 3090 VisitForAccumulatorValue(args->at(0)); 3091 3092 Label materialize_true, materialize_false; 3093 Label* if_true = NULL; 3094 Label* if_false = NULL; 3095 Label* fall_through = NULL; 3096 context()->PrepareTest(&materialize_true, &materialize_false, 3097 &if_true, &if_false, &fall_through); 3098 3099 __ JumpIfSmi(rax, if_false); 3100 __ CmpObjectType(rax, JS_REGEXP_TYPE, rbx); 3101 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 3102 Split(equal, if_true, if_false, fall_through); 3103 3104 context()->Plug(if_true, if_false); 3105 } 3106 3107 3108 3109 void FullCodeGenerator::EmitIsConstructCall(CallRuntime* expr) { 3110 ASSERT(expr->arguments()->length() == 0); 3111 3112 Label materialize_true, materialize_false; 3113 Label* if_true = NULL; 3114 Label* if_false = NULL; 3115 Label* fall_through = NULL; 3116 context()->PrepareTest(&materialize_true, &materialize_false, 3117 &if_true, &if_false, &fall_through); 3118 3119 // Get the frame pointer for the calling frame. 3120 __ movq(rax, Operand(rbp, StandardFrameConstants::kCallerFPOffset)); 3121 3122 // Skip the arguments adaptor frame if it exists. 3123 Label check_frame_marker; 3124 __ Cmp(Operand(rax, StandardFrameConstants::kContextOffset), 3125 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)); 3126 __ j(not_equal, &check_frame_marker); 3127 __ movq(rax, Operand(rax, StandardFrameConstants::kCallerFPOffset)); 3128 3129 // Check the marker in the calling frame. 3130 __ bind(&check_frame_marker); 3131 __ Cmp(Operand(rax, StandardFrameConstants::kMarkerOffset), 3132 Smi::FromInt(StackFrame::CONSTRUCT)); 3133 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 3134 Split(equal, if_true, if_false, fall_through); 3135 3136 context()->Plug(if_true, if_false); 3137 } 3138 3139 3140 void FullCodeGenerator::EmitObjectEquals(CallRuntime* expr) { 3141 ZoneList<Expression*>* args = expr->arguments(); 3142 ASSERT(args->length() == 2); 3143 3144 // Load the two objects into registers and perform the comparison. 3145 VisitForStackValue(args->at(0)); 3146 VisitForAccumulatorValue(args->at(1)); 3147 3148 Label materialize_true, materialize_false; 3149 Label* if_true = NULL; 3150 Label* if_false = NULL; 3151 Label* fall_through = NULL; 3152 context()->PrepareTest(&materialize_true, &materialize_false, 3153 &if_true, &if_false, &fall_through); 3154 3155 __ pop(rbx); 3156 __ cmpq(rax, rbx); 3157 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 3158 Split(equal, if_true, if_false, fall_through); 3159 3160 context()->Plug(if_true, if_false); 3161 } 3162 3163 3164 void FullCodeGenerator::EmitArguments(CallRuntime* expr) { 3165 ZoneList<Expression*>* args = expr->arguments(); 3166 ASSERT(args->length() == 1); 3167 3168 // ArgumentsAccessStub expects the key in rdx and the formal 3169 // parameter count in rax. 3170 VisitForAccumulatorValue(args->at(0)); 3171 __ movq(rdx, rax); 3172 __ Move(rax, Smi::FromInt(info_->scope()->num_parameters())); 3173 ArgumentsAccessStub stub(ArgumentsAccessStub::READ_ELEMENT); 3174 __ CallStub(&stub); 3175 context()->Plug(rax); 3176 } 3177 3178 3179 void FullCodeGenerator::EmitArgumentsLength(CallRuntime* expr) { 3180 ASSERT(expr->arguments()->length() == 0); 3181 3182 Label exit; 3183 // Get the number of formal parameters. 3184 __ Move(rax, Smi::FromInt(info_->scope()->num_parameters())); 3185 3186 // Check if the calling frame is an arguments adaptor frame. 3187 __ movq(rbx, Operand(rbp, StandardFrameConstants::kCallerFPOffset)); 3188 __ Cmp(Operand(rbx, StandardFrameConstants::kContextOffset), 3189 Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)); 3190 __ j(not_equal, &exit, Label::kNear); 3191 3192 // Arguments adaptor case: Read the arguments length from the 3193 // adaptor frame. 3194 __ movq(rax, Operand(rbx, ArgumentsAdaptorFrameConstants::kLengthOffset)); 3195 3196 __ bind(&exit); 3197 __ AssertSmi(rax); 3198 context()->Plug(rax); 3199 } 3200 3201 3202 void FullCodeGenerator::EmitClassOf(CallRuntime* expr) { 3203 ZoneList<Expression*>* args = expr->arguments(); 3204 ASSERT(args->length() == 1); 3205 Label done, null, function, non_function_constructor; 3206 3207 VisitForAccumulatorValue(args->at(0)); 3208 3209 // If the object is a smi, we return null. 3210 __ JumpIfSmi(rax, &null); 3211 3212 // Check that the object is a JS object but take special care of JS 3213 // functions to make sure they have 'Function' as their class. 3214 // Assume that there are only two callable types, and one of them is at 3215 // either end of the type range for JS object types. Saves extra comparisons. 3216 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2); 3217 __ CmpObjectType(rax, FIRST_SPEC_OBJECT_TYPE, rax); 3218 // Map is now in rax. 3219 __ j(below, &null); 3220 STATIC_ASSERT(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE == 3221 FIRST_SPEC_OBJECT_TYPE + 1); 3222 __ j(equal, &function); 3223 3224 __ CmpInstanceType(rax, LAST_SPEC_OBJECT_TYPE); 3225 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == 3226 LAST_SPEC_OBJECT_TYPE - 1); 3227 __ j(equal, &function); 3228 // Assume that there is no larger type. 3229 STATIC_ASSERT(LAST_NONCALLABLE_SPEC_OBJECT_TYPE == LAST_TYPE - 1); 3230 3231 // Check if the constructor in the map is a JS function. 3232 __ movq(rax, FieldOperand(rax, Map::kConstructorOffset)); 3233 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx); 3234 __ j(not_equal, &non_function_constructor); 3235 3236 // rax now contains the constructor function. Grab the 3237 // instance class name from there. 3238 __ movq(rax, FieldOperand(rax, JSFunction::kSharedFunctionInfoOffset)); 3239 __ movq(rax, FieldOperand(rax, SharedFunctionInfo::kInstanceClassNameOffset)); 3240 __ jmp(&done); 3241 3242 // Functions have class 'Function'. 3243 __ bind(&function); 3244 __ Move(rax, isolate()->factory()->function_class_string()); 3245 __ jmp(&done); 3246 3247 // Objects with a non-function constructor have class 'Object'. 3248 __ bind(&non_function_constructor); 3249 __ Move(rax, isolate()->factory()->Object_string()); 3250 __ jmp(&done); 3251 3252 // Non-JS objects have class null. 3253 __ bind(&null); 3254 __ LoadRoot(rax, Heap::kNullValueRootIndex); 3255 3256 // All done. 3257 __ bind(&done); 3258 3259 context()->Plug(rax); 3260 } 3261 3262 3263 void FullCodeGenerator::EmitLog(CallRuntime* expr) { 3264 // Conditionally generate a log call. 3265 // Args: 3266 // 0 (literal string): The type of logging (corresponds to the flags). 3267 // This is used to determine whether or not to generate the log call. 3268 // 1 (string): Format string. Access the string at argument index 2 3269 // with '%2s' (see Logger::LogRuntime for all the formats). 3270 // 2 (array): Arguments to the format string. 3271 ZoneList<Expression*>* args = expr->arguments(); 3272 ASSERT_EQ(args->length(), 3); 3273 if (CodeGenerator::ShouldGenerateLog(isolate(), args->at(0))) { 3274 VisitForStackValue(args->at(1)); 3275 VisitForStackValue(args->at(2)); 3276 __ CallRuntime(Runtime::kLog, 2); 3277 } 3278 // Finally, we're expected to leave a value on the top of the stack. 3279 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex); 3280 context()->Plug(rax); 3281 } 3282 3283 3284 void FullCodeGenerator::EmitSubString(CallRuntime* expr) { 3285 // Load the arguments on the stack and call the stub. 3286 SubStringStub stub; 3287 ZoneList<Expression*>* args = expr->arguments(); 3288 ASSERT(args->length() == 3); 3289 VisitForStackValue(args->at(0)); 3290 VisitForStackValue(args->at(1)); 3291 VisitForStackValue(args->at(2)); 3292 __ CallStub(&stub); 3293 context()->Plug(rax); 3294 } 3295 3296 3297 void FullCodeGenerator::EmitRegExpExec(CallRuntime* expr) { 3298 // Load the arguments on the stack and call the stub. 3299 RegExpExecStub stub; 3300 ZoneList<Expression*>* args = expr->arguments(); 3301 ASSERT(args->length() == 4); 3302 VisitForStackValue(args->at(0)); 3303 VisitForStackValue(args->at(1)); 3304 VisitForStackValue(args->at(2)); 3305 VisitForStackValue(args->at(3)); 3306 __ CallStub(&stub); 3307 context()->Plug(rax); 3308 } 3309 3310 3311 void FullCodeGenerator::EmitValueOf(CallRuntime* expr) { 3312 ZoneList<Expression*>* args = expr->arguments(); 3313 ASSERT(args->length() == 1); 3314 3315 VisitForAccumulatorValue(args->at(0)); // Load the object. 3316 3317 Label done; 3318 // If the object is a smi return the object. 3319 __ JumpIfSmi(rax, &done); 3320 // If the object is not a value type, return the object. 3321 __ CmpObjectType(rax, JS_VALUE_TYPE, rbx); 3322 __ j(not_equal, &done); 3323 __ movq(rax, FieldOperand(rax, JSValue::kValueOffset)); 3324 3325 __ bind(&done); 3326 context()->Plug(rax); 3327 } 3328 3329 3330 void FullCodeGenerator::EmitDateField(CallRuntime* expr) { 3331 ZoneList<Expression*>* args = expr->arguments(); 3332 ASSERT(args->length() == 2); 3333 ASSERT_NE(NULL, args->at(1)->AsLiteral()); 3334 Smi* index = Smi::cast(*(args->at(1)->AsLiteral()->value())); 3335 3336 VisitForAccumulatorValue(args->at(0)); // Load the object. 3337 3338 Label runtime, done, not_date_object; 3339 Register object = rax; 3340 Register result = rax; 3341 Register scratch = rcx; 3342 3343 __ JumpIfSmi(object, ¬_date_object); 3344 __ CmpObjectType(object, JS_DATE_TYPE, scratch); 3345 __ j(not_equal, ¬_date_object); 3346 3347 if (index->value() == 0) { 3348 __ movq(result, FieldOperand(object, JSDate::kValueOffset)); 3349 __ jmp(&done); 3350 } else { 3351 if (index->value() < JSDate::kFirstUncachedField) { 3352 ExternalReference stamp = ExternalReference::date_cache_stamp(isolate()); 3353 Operand stamp_operand = __ ExternalOperand(stamp); 3354 __ movq(scratch, stamp_operand); 3355 __ cmpq(scratch, FieldOperand(object, JSDate::kCacheStampOffset)); 3356 __ j(not_equal, &runtime, Label::kNear); 3357 __ movq(result, FieldOperand(object, JSDate::kValueOffset + 3358 kPointerSize * index->value())); 3359 __ jmp(&done); 3360 } 3361 __ bind(&runtime); 3362 __ PrepareCallCFunction(2); 3363 __ movq(arg_reg_1, object); 3364 __ movq(arg_reg_2, index, RelocInfo::NONE64); 3365 __ CallCFunction(ExternalReference::get_date_field_function(isolate()), 2); 3366 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); 3367 __ jmp(&done); 3368 } 3369 3370 __ bind(¬_date_object); 3371 __ CallRuntime(Runtime::kThrowNotDateError, 0); 3372 __ bind(&done); 3373 context()->Plug(rax); 3374 } 3375 3376 3377 void FullCodeGenerator::EmitOneByteSeqStringSetChar(CallRuntime* expr) { 3378 ZoneList<Expression*>* args = expr->arguments(); 3379 ASSERT_EQ(3, args->length()); 3380 3381 Register string = rax; 3382 Register index = rbx; 3383 Register value = rcx; 3384 3385 VisitForStackValue(args->at(1)); // index 3386 VisitForStackValue(args->at(2)); // value 3387 VisitForAccumulatorValue(args->at(0)); // string 3388 __ pop(value); 3389 __ pop(index); 3390 3391 if (FLAG_debug_code) { 3392 __ ThrowIf(NegateCondition(__ CheckSmi(value)), kNonSmiValue); 3393 __ ThrowIf(NegateCondition(__ CheckSmi(index)), kNonSmiValue); 3394 } 3395 3396 __ SmiToInteger32(value, value); 3397 __ SmiToInteger32(index, index); 3398 3399 if (FLAG_debug_code) { 3400 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag; 3401 __ EmitSeqStringSetCharCheck(string, index, value, one_byte_seq_type); 3402 } 3403 3404 __ movb(FieldOperand(string, index, times_1, SeqOneByteString::kHeaderSize), 3405 value); 3406 context()->Plug(string); 3407 } 3408 3409 3410 void FullCodeGenerator::EmitTwoByteSeqStringSetChar(CallRuntime* expr) { 3411 ZoneList<Expression*>* args = expr->arguments(); 3412 ASSERT_EQ(3, args->length()); 3413 3414 Register string = rax; 3415 Register index = rbx; 3416 Register value = rcx; 3417 3418 VisitForStackValue(args->at(1)); // index 3419 VisitForStackValue(args->at(2)); // value 3420 VisitForAccumulatorValue(args->at(0)); // string 3421 __ pop(value); 3422 __ pop(index); 3423 3424 if (FLAG_debug_code) { 3425 __ ThrowIf(NegateCondition(__ CheckSmi(value)), kNonSmiValue); 3426 __ ThrowIf(NegateCondition(__ CheckSmi(index)), kNonSmiValue); 3427 } 3428 3429 __ SmiToInteger32(value, value); 3430 __ SmiToInteger32(index, index); 3431 3432 if (FLAG_debug_code) { 3433 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag; 3434 __ EmitSeqStringSetCharCheck(string, index, value, two_byte_seq_type); 3435 } 3436 3437 __ movw(FieldOperand(string, index, times_2, SeqTwoByteString::kHeaderSize), 3438 value); 3439 context()->Plug(rax); 3440 } 3441 3442 3443 void FullCodeGenerator::EmitMathPow(CallRuntime* expr) { 3444 // Load the arguments on the stack and call the runtime function. 3445 ZoneList<Expression*>* args = expr->arguments(); 3446 ASSERT(args->length() == 2); 3447 VisitForStackValue(args->at(0)); 3448 VisitForStackValue(args->at(1)); 3449 MathPowStub stub(MathPowStub::ON_STACK); 3450 __ CallStub(&stub); 3451 context()->Plug(rax); 3452 } 3453 3454 3455 void FullCodeGenerator::EmitSetValueOf(CallRuntime* expr) { 3456 ZoneList<Expression*>* args = expr->arguments(); 3457 ASSERT(args->length() == 2); 3458 3459 VisitForStackValue(args->at(0)); // Load the object. 3460 VisitForAccumulatorValue(args->at(1)); // Load the value. 3461 __ pop(rbx); // rax = value. rbx = object. 3462 3463 Label done; 3464 // If the object is a smi, return the value. 3465 __ JumpIfSmi(rbx, &done); 3466 3467 // If the object is not a value type, return the value. 3468 __ CmpObjectType(rbx, JS_VALUE_TYPE, rcx); 3469 __ j(not_equal, &done); 3470 3471 // Store the value. 3472 __ movq(FieldOperand(rbx, JSValue::kValueOffset), rax); 3473 // Update the write barrier. Save the value as it will be 3474 // overwritten by the write barrier code and is needed afterward. 3475 __ movq(rdx, rax); 3476 __ RecordWriteField(rbx, JSValue::kValueOffset, rdx, rcx, kDontSaveFPRegs); 3477 3478 __ bind(&done); 3479 context()->Plug(rax); 3480 } 3481 3482 3483 void FullCodeGenerator::EmitNumberToString(CallRuntime* expr) { 3484 ZoneList<Expression*>* args = expr->arguments(); 3485 ASSERT_EQ(args->length(), 1); 3486 3487 // Load the argument into rax and call the stub. 3488 VisitForAccumulatorValue(args->at(0)); 3489 3490 NumberToStringStub stub; 3491 __ CallStub(&stub); 3492 context()->Plug(rax); 3493 } 3494 3495 3496 void FullCodeGenerator::EmitStringCharFromCode(CallRuntime* expr) { 3497 ZoneList<Expression*>* args = expr->arguments(); 3498 ASSERT(args->length() == 1); 3499 3500 VisitForAccumulatorValue(args->at(0)); 3501 3502 Label done; 3503 StringCharFromCodeGenerator generator(rax, rbx); 3504 generator.GenerateFast(masm_); 3505 __ jmp(&done); 3506 3507 NopRuntimeCallHelper call_helper; 3508 generator.GenerateSlow(masm_, call_helper); 3509 3510 __ bind(&done); 3511 context()->Plug(rbx); 3512 } 3513 3514 3515 void FullCodeGenerator::EmitStringCharCodeAt(CallRuntime* expr) { 3516 ZoneList<Expression*>* args = expr->arguments(); 3517 ASSERT(args->length() == 2); 3518 3519 VisitForStackValue(args->at(0)); 3520 VisitForAccumulatorValue(args->at(1)); 3521 3522 Register object = rbx; 3523 Register index = rax; 3524 Register result = rdx; 3525 3526 __ pop(object); 3527 3528 Label need_conversion; 3529 Label index_out_of_range; 3530 Label done; 3531 StringCharCodeAtGenerator generator(object, 3532 index, 3533 result, 3534 &need_conversion, 3535 &need_conversion, 3536 &index_out_of_range, 3537 STRING_INDEX_IS_NUMBER); 3538 generator.GenerateFast(masm_); 3539 __ jmp(&done); 3540 3541 __ bind(&index_out_of_range); 3542 // When the index is out of range, the spec requires us to return 3543 // NaN. 3544 __ LoadRoot(result, Heap::kNanValueRootIndex); 3545 __ jmp(&done); 3546 3547 __ bind(&need_conversion); 3548 // Move the undefined value into the result register, which will 3549 // trigger conversion. 3550 __ LoadRoot(result, Heap::kUndefinedValueRootIndex); 3551 __ jmp(&done); 3552 3553 NopRuntimeCallHelper call_helper; 3554 generator.GenerateSlow(masm_, call_helper); 3555 3556 __ bind(&done); 3557 context()->Plug(result); 3558 } 3559 3560 3561 void FullCodeGenerator::EmitStringCharAt(CallRuntime* expr) { 3562 ZoneList<Expression*>* args = expr->arguments(); 3563 ASSERT(args->length() == 2); 3564 3565 VisitForStackValue(args->at(0)); 3566 VisitForAccumulatorValue(args->at(1)); 3567 3568 Register object = rbx; 3569 Register index = rax; 3570 Register scratch = rdx; 3571 Register result = rax; 3572 3573 __ pop(object); 3574 3575 Label need_conversion; 3576 Label index_out_of_range; 3577 Label done; 3578 StringCharAtGenerator generator(object, 3579 index, 3580 scratch, 3581 result, 3582 &need_conversion, 3583 &need_conversion, 3584 &index_out_of_range, 3585 STRING_INDEX_IS_NUMBER); 3586 generator.GenerateFast(masm_); 3587 __ jmp(&done); 3588 3589 __ bind(&index_out_of_range); 3590 // When the index is out of range, the spec requires us to return 3591 // the empty string. 3592 __ LoadRoot(result, Heap::kempty_stringRootIndex); 3593 __ jmp(&done); 3594 3595 __ bind(&need_conversion); 3596 // Move smi zero into the result register, which will trigger 3597 // conversion. 3598 __ Move(result, Smi::FromInt(0)); 3599 __ jmp(&done); 3600 3601 NopRuntimeCallHelper call_helper; 3602 generator.GenerateSlow(masm_, call_helper); 3603 3604 __ bind(&done); 3605 context()->Plug(result); 3606 } 3607 3608 3609 void FullCodeGenerator::EmitStringAdd(CallRuntime* expr) { 3610 ZoneList<Expression*>* args = expr->arguments(); 3611 ASSERT_EQ(2, args->length()); 3612 3613 if (FLAG_new_string_add) { 3614 VisitForStackValue(args->at(0)); 3615 VisitForAccumulatorValue(args->at(1)); 3616 3617 __ pop(rdx); 3618 NewStringAddStub stub(STRING_ADD_CHECK_BOTH, NOT_TENURED); 3619 __ CallStub(&stub); 3620 } else { 3621 VisitForStackValue(args->at(0)); 3622 VisitForStackValue(args->at(1)); 3623 3624 StringAddStub stub(STRING_ADD_CHECK_BOTH); 3625 __ CallStub(&stub); 3626 } 3627 context()->Plug(rax); 3628 } 3629 3630 3631 void FullCodeGenerator::EmitStringCompare(CallRuntime* expr) { 3632 ZoneList<Expression*>* args = expr->arguments(); 3633 ASSERT_EQ(2, args->length()); 3634 3635 VisitForStackValue(args->at(0)); 3636 VisitForStackValue(args->at(1)); 3637 3638 StringCompareStub stub; 3639 __ CallStub(&stub); 3640 context()->Plug(rax); 3641 } 3642 3643 3644 void FullCodeGenerator::EmitMathLog(CallRuntime* expr) { 3645 // Load the argument on the stack and call the stub. 3646 TranscendentalCacheStub stub(TranscendentalCache::LOG, 3647 TranscendentalCacheStub::TAGGED); 3648 ZoneList<Expression*>* args = expr->arguments(); 3649 ASSERT(args->length() == 1); 3650 VisitForStackValue(args->at(0)); 3651 __ CallStub(&stub); 3652 context()->Plug(rax); 3653 } 3654 3655 3656 void FullCodeGenerator::EmitMathSqrt(CallRuntime* expr) { 3657 // Load the argument on the stack and call the runtime function. 3658 ZoneList<Expression*>* args = expr->arguments(); 3659 ASSERT(args->length() == 1); 3660 VisitForStackValue(args->at(0)); 3661 __ CallRuntime(Runtime::kMath_sqrt, 1); 3662 context()->Plug(rax); 3663 } 3664 3665 3666 void FullCodeGenerator::EmitCallFunction(CallRuntime* expr) { 3667 ZoneList<Expression*>* args = expr->arguments(); 3668 ASSERT(args->length() >= 2); 3669 3670 int arg_count = args->length() - 2; // 2 ~ receiver and function. 3671 for (int i = 0; i < arg_count + 1; i++) { 3672 VisitForStackValue(args->at(i)); 3673 } 3674 VisitForAccumulatorValue(args->last()); // Function. 3675 3676 Label runtime, done; 3677 // Check for non-function argument (including proxy). 3678 __ JumpIfSmi(rax, &runtime); 3679 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rbx); 3680 __ j(not_equal, &runtime); 3681 3682 // InvokeFunction requires the function in rdi. Move it in there. 3683 __ movq(rdi, result_register()); 3684 ParameterCount count(arg_count); 3685 __ InvokeFunction(rdi, count, CALL_FUNCTION, 3686 NullCallWrapper(), CALL_AS_METHOD); 3687 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); 3688 __ jmp(&done); 3689 3690 __ bind(&runtime); 3691 __ push(rax); 3692 __ CallRuntime(Runtime::kCall, args->length()); 3693 __ bind(&done); 3694 3695 context()->Plug(rax); 3696 } 3697 3698 3699 void FullCodeGenerator::EmitRegExpConstructResult(CallRuntime* expr) { 3700 RegExpConstructResultStub stub; 3701 ZoneList<Expression*>* args = expr->arguments(); 3702 ASSERT(args->length() == 3); 3703 VisitForStackValue(args->at(0)); 3704 VisitForStackValue(args->at(1)); 3705 VisitForStackValue(args->at(2)); 3706 __ CallStub(&stub); 3707 context()->Plug(rax); 3708 } 3709 3710 3711 void FullCodeGenerator::EmitGetFromCache(CallRuntime* expr) { 3712 ZoneList<Expression*>* args = expr->arguments(); 3713 ASSERT_EQ(2, args->length()); 3714 3715 ASSERT_NE(NULL, args->at(0)->AsLiteral()); 3716 int cache_id = Smi::cast(*(args->at(0)->AsLiteral()->value()))->value(); 3717 3718 Handle<FixedArray> jsfunction_result_caches( 3719 isolate()->native_context()->jsfunction_result_caches()); 3720 if (jsfunction_result_caches->length() <= cache_id) { 3721 __ Abort(kAttemptToUseUndefinedCache); 3722 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex); 3723 context()->Plug(rax); 3724 return; 3725 } 3726 3727 VisitForAccumulatorValue(args->at(1)); 3728 3729 Register key = rax; 3730 Register cache = rbx; 3731 Register tmp = rcx; 3732 __ movq(cache, ContextOperand(rsi, Context::GLOBAL_OBJECT_INDEX)); 3733 __ movq(cache, 3734 FieldOperand(cache, GlobalObject::kNativeContextOffset)); 3735 __ movq(cache, 3736 ContextOperand(cache, Context::JSFUNCTION_RESULT_CACHES_INDEX)); 3737 __ movq(cache, 3738 FieldOperand(cache, FixedArray::OffsetOfElementAt(cache_id))); 3739 3740 Label done, not_found; 3741 // tmp now holds finger offset as a smi. 3742 STATIC_ASSERT(kSmiTag == 0 && kSmiTagSize == 1); 3743 __ movq(tmp, FieldOperand(cache, JSFunctionResultCache::kFingerOffset)); 3744 SmiIndex index = 3745 __ SmiToIndex(kScratchRegister, tmp, kPointerSizeLog2); 3746 __ cmpq(key, FieldOperand(cache, 3747 index.reg, 3748 index.scale, 3749 FixedArray::kHeaderSize)); 3750 __ j(not_equal, ¬_found, Label::kNear); 3751 __ movq(rax, FieldOperand(cache, 3752 index.reg, 3753 index.scale, 3754 FixedArray::kHeaderSize + kPointerSize)); 3755 __ jmp(&done, Label::kNear); 3756 3757 __ bind(¬_found); 3758 // Call runtime to perform the lookup. 3759 __ push(cache); 3760 __ push(key); 3761 __ CallRuntime(Runtime::kGetFromCache, 2); 3762 3763 __ bind(&done); 3764 context()->Plug(rax); 3765 } 3766 3767 3768 void FullCodeGenerator::EmitIsRegExpEquivalent(CallRuntime* expr) { 3769 ZoneList<Expression*>* args = expr->arguments(); 3770 ASSERT_EQ(2, args->length()); 3771 3772 Register right = rax; 3773 Register left = rbx; 3774 Register tmp = rcx; 3775 3776 VisitForStackValue(args->at(0)); 3777 VisitForAccumulatorValue(args->at(1)); 3778 __ pop(left); 3779 3780 Label done, fail, ok; 3781 __ cmpq(left, right); 3782 __ j(equal, &ok, Label::kNear); 3783 // Fail if either is a non-HeapObject. 3784 Condition either_smi = masm()->CheckEitherSmi(left, right, tmp); 3785 __ j(either_smi, &fail, Label::kNear); 3786 __ j(zero, &fail, Label::kNear); 3787 __ movq(tmp, FieldOperand(left, HeapObject::kMapOffset)); 3788 __ cmpb(FieldOperand(tmp, Map::kInstanceTypeOffset), 3789 Immediate(JS_REGEXP_TYPE)); 3790 __ j(not_equal, &fail, Label::kNear); 3791 __ cmpq(tmp, FieldOperand(right, HeapObject::kMapOffset)); 3792 __ j(not_equal, &fail, Label::kNear); 3793 __ movq(tmp, FieldOperand(left, JSRegExp::kDataOffset)); 3794 __ cmpq(tmp, FieldOperand(right, JSRegExp::kDataOffset)); 3795 __ j(equal, &ok, Label::kNear); 3796 __ bind(&fail); 3797 __ Move(rax, isolate()->factory()->false_value()); 3798 __ jmp(&done, Label::kNear); 3799 __ bind(&ok); 3800 __ Move(rax, isolate()->factory()->true_value()); 3801 __ bind(&done); 3802 3803 context()->Plug(rax); 3804 } 3805 3806 3807 void FullCodeGenerator::EmitHasCachedArrayIndex(CallRuntime* expr) { 3808 ZoneList<Expression*>* args = expr->arguments(); 3809 ASSERT(args->length() == 1); 3810 3811 VisitForAccumulatorValue(args->at(0)); 3812 3813 Label materialize_true, materialize_false; 3814 Label* if_true = NULL; 3815 Label* if_false = NULL; 3816 Label* fall_through = NULL; 3817 context()->PrepareTest(&materialize_true, &materialize_false, 3818 &if_true, &if_false, &fall_through); 3819 3820 __ testl(FieldOperand(rax, String::kHashFieldOffset), 3821 Immediate(String::kContainsCachedArrayIndexMask)); 3822 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 3823 __ j(zero, if_true); 3824 __ jmp(if_false); 3825 3826 context()->Plug(if_true, if_false); 3827 } 3828 3829 3830 void FullCodeGenerator::EmitGetCachedArrayIndex(CallRuntime* expr) { 3831 ZoneList<Expression*>* args = expr->arguments(); 3832 ASSERT(args->length() == 1); 3833 VisitForAccumulatorValue(args->at(0)); 3834 3835 __ AssertString(rax); 3836 3837 __ movl(rax, FieldOperand(rax, String::kHashFieldOffset)); 3838 ASSERT(String::kHashShift >= kSmiTagSize); 3839 __ IndexFromHash(rax, rax); 3840 3841 context()->Plug(rax); 3842 } 3843 3844 3845 void FullCodeGenerator::EmitFastAsciiArrayJoin(CallRuntime* expr) { 3846 Label bailout, return_result, done, one_char_separator, long_separator, 3847 non_trivial_array, not_size_one_array, loop, 3848 loop_1, loop_1_condition, loop_2, loop_2_entry, loop_3, loop_3_entry; 3849 ZoneList<Expression*>* args = expr->arguments(); 3850 ASSERT(args->length() == 2); 3851 // We will leave the separator on the stack until the end of the function. 3852 VisitForStackValue(args->at(1)); 3853 // Load this to rax (= array) 3854 VisitForAccumulatorValue(args->at(0)); 3855 // All aliases of the same register have disjoint lifetimes. 3856 Register array = rax; 3857 Register elements = no_reg; // Will be rax. 3858 3859 Register index = rdx; 3860 3861 Register string_length = rcx; 3862 3863 Register string = rsi; 3864 3865 Register scratch = rbx; 3866 3867 Register array_length = rdi; 3868 Register result_pos = no_reg; // Will be rdi. 3869 3870 Operand separator_operand = Operand(rsp, 2 * kPointerSize); 3871 Operand result_operand = Operand(rsp, 1 * kPointerSize); 3872 Operand array_length_operand = Operand(rsp, 0 * kPointerSize); 3873 // Separator operand is already pushed. Make room for the two 3874 // other stack fields, and clear the direction flag in anticipation 3875 // of calling CopyBytes. 3876 __ subq(rsp, Immediate(2 * kPointerSize)); 3877 __ cld(); 3878 // Check that the array is a JSArray 3879 __ JumpIfSmi(array, &bailout); 3880 __ CmpObjectType(array, JS_ARRAY_TYPE, scratch); 3881 __ j(not_equal, &bailout); 3882 3883 // Check that the array has fast elements. 3884 __ CheckFastElements(scratch, &bailout); 3885 3886 // Array has fast elements, so its length must be a smi. 3887 // If the array has length zero, return the empty string. 3888 __ movq(array_length, FieldOperand(array, JSArray::kLengthOffset)); 3889 __ SmiCompare(array_length, Smi::FromInt(0)); 3890 __ j(not_zero, &non_trivial_array); 3891 __ LoadRoot(rax, Heap::kempty_stringRootIndex); 3892 __ jmp(&return_result); 3893 3894 // Save the array length on the stack. 3895 __ bind(&non_trivial_array); 3896 __ SmiToInteger32(array_length, array_length); 3897 __ movl(array_length_operand, array_length); 3898 3899 // Save the FixedArray containing array's elements. 3900 // End of array's live range. 3901 elements = array; 3902 __ movq(elements, FieldOperand(array, JSArray::kElementsOffset)); 3903 array = no_reg; 3904 3905 3906 // Check that all array elements are sequential ASCII strings, and 3907 // accumulate the sum of their lengths, as a smi-encoded value. 3908 __ Set(index, 0); 3909 __ Set(string_length, 0); 3910 // Loop condition: while (index < array_length). 3911 // Live loop registers: index(int32), array_length(int32), string(String*), 3912 // scratch, string_length(int32), elements(FixedArray*). 3913 if (generate_debug_code_) { 3914 __ cmpq(index, array_length); 3915 __ Assert(below, kNoEmptyArraysHereInEmitFastAsciiArrayJoin); 3916 } 3917 __ bind(&loop); 3918 __ movq(string, FieldOperand(elements, 3919 index, 3920 times_pointer_size, 3921 FixedArray::kHeaderSize)); 3922 __ JumpIfSmi(string, &bailout); 3923 __ movq(scratch, FieldOperand(string, HeapObject::kMapOffset)); 3924 __ movzxbl(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset)); 3925 __ andb(scratch, Immediate( 3926 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask)); 3927 __ cmpb(scratch, Immediate(kStringTag | kOneByteStringTag | kSeqStringTag)); 3928 __ j(not_equal, &bailout); 3929 __ AddSmiField(string_length, 3930 FieldOperand(string, SeqOneByteString::kLengthOffset)); 3931 __ j(overflow, &bailout); 3932 __ incl(index); 3933 __ cmpl(index, array_length); 3934 __ j(less, &loop); 3935 3936 // Live registers: 3937 // string_length: Sum of string lengths. 3938 // elements: FixedArray of strings. 3939 // index: Array length. 3940 // array_length: Array length. 3941 3942 // If array_length is 1, return elements[0], a string. 3943 __ cmpl(array_length, Immediate(1)); 3944 __ j(not_equal, ¬_size_one_array); 3945 __ movq(rax, FieldOperand(elements, FixedArray::kHeaderSize)); 3946 __ jmp(&return_result); 3947 3948 __ bind(¬_size_one_array); 3949 3950 // End of array_length live range. 3951 result_pos = array_length; 3952 array_length = no_reg; 3953 3954 // Live registers: 3955 // string_length: Sum of string lengths. 3956 // elements: FixedArray of strings. 3957 // index: Array length. 3958 3959 // Check that the separator is a sequential ASCII string. 3960 __ movq(string, separator_operand); 3961 __ JumpIfSmi(string, &bailout); 3962 __ movq(scratch, FieldOperand(string, HeapObject::kMapOffset)); 3963 __ movzxbl(scratch, FieldOperand(scratch, Map::kInstanceTypeOffset)); 3964 __ andb(scratch, Immediate( 3965 kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask)); 3966 __ cmpb(scratch, Immediate(kStringTag | kOneByteStringTag | kSeqStringTag)); 3967 __ j(not_equal, &bailout); 3968 3969 // Live registers: 3970 // string_length: Sum of string lengths. 3971 // elements: FixedArray of strings. 3972 // index: Array length. 3973 // string: Separator string. 3974 3975 // Add (separator length times (array_length - 1)) to string_length. 3976 __ SmiToInteger32(scratch, 3977 FieldOperand(string, SeqOneByteString::kLengthOffset)); 3978 __ decl(index); 3979 __ imull(scratch, index); 3980 __ j(overflow, &bailout); 3981 __ addl(string_length, scratch); 3982 __ j(overflow, &bailout); 3983 3984 // Live registers and stack values: 3985 // string_length: Total length of result string. 3986 // elements: FixedArray of strings. 3987 __ AllocateAsciiString(result_pos, string_length, scratch, 3988 index, string, &bailout); 3989 __ movq(result_operand, result_pos); 3990 __ lea(result_pos, FieldOperand(result_pos, SeqOneByteString::kHeaderSize)); 3991 3992 __ movq(string, separator_operand); 3993 __ SmiCompare(FieldOperand(string, SeqOneByteString::kLengthOffset), 3994 Smi::FromInt(1)); 3995 __ j(equal, &one_char_separator); 3996 __ j(greater, &long_separator); 3997 3998 3999 // Empty separator case: 4000 __ Set(index, 0); 4001 __ movl(scratch, array_length_operand); 4002 __ jmp(&loop_1_condition); 4003 // Loop condition: while (index < array_length). 4004 __ bind(&loop_1); 4005 // Each iteration of the loop concatenates one string to the result. 4006 // Live values in registers: 4007 // index: which element of the elements array we are adding to the result. 4008 // result_pos: the position to which we are currently copying characters. 4009 // elements: the FixedArray of strings we are joining. 4010 // scratch: array length. 4011 4012 // Get string = array[index]. 4013 __ movq(string, FieldOperand(elements, index, 4014 times_pointer_size, 4015 FixedArray::kHeaderSize)); 4016 __ SmiToInteger32(string_length, 4017 FieldOperand(string, String::kLengthOffset)); 4018 __ lea(string, 4019 FieldOperand(string, SeqOneByteString::kHeaderSize)); 4020 __ CopyBytes(result_pos, string, string_length); 4021 __ incl(index); 4022 __ bind(&loop_1_condition); 4023 __ cmpl(index, scratch); 4024 __ j(less, &loop_1); // Loop while (index < array_length). 4025 __ jmp(&done); 4026 4027 // Generic bailout code used from several places. 4028 __ bind(&bailout); 4029 __ LoadRoot(rax, Heap::kUndefinedValueRootIndex); 4030 __ jmp(&return_result); 4031 4032 4033 // One-character separator case 4034 __ bind(&one_char_separator); 4035 // Get the separator ASCII character value. 4036 // Register "string" holds the separator. 4037 __ movzxbl(scratch, FieldOperand(string, SeqOneByteString::kHeaderSize)); 4038 __ Set(index, 0); 4039 // Jump into the loop after the code that copies the separator, so the first 4040 // element is not preceded by a separator 4041 __ jmp(&loop_2_entry); 4042 // Loop condition: while (index < length). 4043 __ bind(&loop_2); 4044 // Each iteration of the loop concatenates one string to the result. 4045 // Live values in registers: 4046 // elements: The FixedArray of strings we are joining. 4047 // index: which element of the elements array we are adding to the result. 4048 // result_pos: the position to which we are currently copying characters. 4049 // scratch: Separator character. 4050 4051 // Copy the separator character to the result. 4052 __ movb(Operand(result_pos, 0), scratch); 4053 __ incq(result_pos); 4054 4055 __ bind(&loop_2_entry); 4056 // Get string = array[index]. 4057 __ movq(string, FieldOperand(elements, index, 4058 times_pointer_size, 4059 FixedArray::kHeaderSize)); 4060 __ SmiToInteger32(string_length, 4061 FieldOperand(string, String::kLengthOffset)); 4062 __ lea(string, 4063 FieldOperand(string, SeqOneByteString::kHeaderSize)); 4064 __ CopyBytes(result_pos, string, string_length); 4065 __ incl(index); 4066 __ cmpl(index, array_length_operand); 4067 __ j(less, &loop_2); // End while (index < length). 4068 __ jmp(&done); 4069 4070 4071 // Long separator case (separator is more than one character). 4072 __ bind(&long_separator); 4073 4074 // Make elements point to end of elements array, and index 4075 // count from -array_length to zero, so we don't need to maintain 4076 // a loop limit. 4077 __ movl(index, array_length_operand); 4078 __ lea(elements, FieldOperand(elements, index, times_pointer_size, 4079 FixedArray::kHeaderSize)); 4080 __ neg(index); 4081 4082 // Replace separator string with pointer to its first character, and 4083 // make scratch be its length. 4084 __ movq(string, separator_operand); 4085 __ SmiToInteger32(scratch, 4086 FieldOperand(string, String::kLengthOffset)); 4087 __ lea(string, 4088 FieldOperand(string, SeqOneByteString::kHeaderSize)); 4089 __ movq(separator_operand, string); 4090 4091 // Jump into the loop after the code that copies the separator, so the first 4092 // element is not preceded by a separator 4093 __ jmp(&loop_3_entry); 4094 // Loop condition: while (index < length). 4095 __ bind(&loop_3); 4096 // Each iteration of the loop concatenates one string to the result. 4097 // Live values in registers: 4098 // index: which element of the elements array we are adding to the result. 4099 // result_pos: the position to which we are currently copying characters. 4100 // scratch: Separator length. 4101 // separator_operand (rsp[0x10]): Address of first char of separator. 4102 4103 // Copy the separator to the result. 4104 __ movq(string, separator_operand); 4105 __ movl(string_length, scratch); 4106 __ CopyBytes(result_pos, string, string_length, 2); 4107 4108 __ bind(&loop_3_entry); 4109 // Get string = array[index]. 4110 __ movq(string, Operand(elements, index, times_pointer_size, 0)); 4111 __ SmiToInteger32(string_length, 4112 FieldOperand(string, String::kLengthOffset)); 4113 __ lea(string, 4114 FieldOperand(string, SeqOneByteString::kHeaderSize)); 4115 __ CopyBytes(result_pos, string, string_length); 4116 __ incq(index); 4117 __ j(not_equal, &loop_3); // Loop while (index < 0). 4118 4119 __ bind(&done); 4120 __ movq(rax, result_operand); 4121 4122 __ bind(&return_result); 4123 // Drop temp values from the stack, and restore context register. 4124 __ addq(rsp, Immediate(3 * kPointerSize)); 4125 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); 4126 context()->Plug(rax); 4127 } 4128 4129 4130 void FullCodeGenerator::VisitCallRuntime(CallRuntime* expr) { 4131 Handle<String> name = expr->name(); 4132 if (name->length() > 0 && name->Get(0) == '_') { 4133 Comment cmnt(masm_, "[ InlineRuntimeCall"); 4134 EmitInlineRuntimeCall(expr); 4135 return; 4136 } 4137 4138 Comment cmnt(masm_, "[ CallRuntime"); 4139 ZoneList<Expression*>* args = expr->arguments(); 4140 4141 if (expr->is_jsruntime()) { 4142 // Prepare for calling JS runtime function. 4143 __ movq(rax, GlobalObjectOperand()); 4144 __ push(FieldOperand(rax, GlobalObject::kBuiltinsOffset)); 4145 } 4146 4147 // Push the arguments ("left-to-right"). 4148 int arg_count = args->length(); 4149 for (int i = 0; i < arg_count; i++) { 4150 VisitForStackValue(args->at(i)); 4151 } 4152 4153 if (expr->is_jsruntime()) { 4154 // Call the JS runtime function using a call IC. 4155 __ Move(rcx, expr->name()); 4156 RelocInfo::Mode mode = RelocInfo::CODE_TARGET; 4157 Handle<Code> ic = 4158 isolate()->stub_cache()->ComputeCallInitialize(arg_count, mode); 4159 CallIC(ic, mode, expr->CallRuntimeFeedbackId()); 4160 // Restore context register. 4161 __ movq(rsi, Operand(rbp, StandardFrameConstants::kContextOffset)); 4162 } else { 4163 __ CallRuntime(expr->function(), arg_count); 4164 } 4165 context()->Plug(rax); 4166 } 4167 4168 4169 void FullCodeGenerator::VisitUnaryOperation(UnaryOperation* expr) { 4170 switch (expr->op()) { 4171 case Token::DELETE: { 4172 Comment cmnt(masm_, "[ UnaryOperation (DELETE)"); 4173 Property* property = expr->expression()->AsProperty(); 4174 VariableProxy* proxy = expr->expression()->AsVariableProxy(); 4175 4176 if (property != NULL) { 4177 VisitForStackValue(property->obj()); 4178 VisitForStackValue(property->key()); 4179 StrictModeFlag strict_mode_flag = (language_mode() == CLASSIC_MODE) 4180 ? kNonStrictMode : kStrictMode; 4181 __ Push(Smi::FromInt(strict_mode_flag)); 4182 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION); 4183 context()->Plug(rax); 4184 } else if (proxy != NULL) { 4185 Variable* var = proxy->var(); 4186 // Delete of an unqualified identifier is disallowed in strict mode 4187 // but "delete this" is allowed. 4188 ASSERT(language_mode() == CLASSIC_MODE || var->is_this()); 4189 if (var->IsUnallocated()) { 4190 __ push(GlobalObjectOperand()); 4191 __ Push(var->name()); 4192 __ Push(Smi::FromInt(kNonStrictMode)); 4193 __ InvokeBuiltin(Builtins::DELETE, CALL_FUNCTION); 4194 context()->Plug(rax); 4195 } else if (var->IsStackAllocated() || var->IsContextSlot()) { 4196 // Result of deleting non-global variables is false. 'this' is 4197 // not really a variable, though we implement it as one. The 4198 // subexpression does not have side effects. 4199 context()->Plug(var->is_this()); 4200 } else { 4201 // Non-global variable. Call the runtime to try to delete from the 4202 // context where the variable was introduced. 4203 __ push(context_register()); 4204 __ Push(var->name()); 4205 __ CallRuntime(Runtime::kDeleteContextSlot, 2); 4206 context()->Plug(rax); 4207 } 4208 } else { 4209 // Result of deleting non-property, non-variable reference is true. 4210 // The subexpression may have side effects. 4211 VisitForEffect(expr->expression()); 4212 context()->Plug(true); 4213 } 4214 break; 4215 } 4216 4217 case Token::VOID: { 4218 Comment cmnt(masm_, "[ UnaryOperation (VOID)"); 4219 VisitForEffect(expr->expression()); 4220 context()->Plug(Heap::kUndefinedValueRootIndex); 4221 break; 4222 } 4223 4224 case Token::NOT: { 4225 Comment cmnt(masm_, "[ UnaryOperation (NOT)"); 4226 if (context()->IsEffect()) { 4227 // Unary NOT has no side effects so it's only necessary to visit the 4228 // subexpression. Match the optimizing compiler by not branching. 4229 VisitForEffect(expr->expression()); 4230 } else if (context()->IsTest()) { 4231 const TestContext* test = TestContext::cast(context()); 4232 // The labels are swapped for the recursive call. 4233 VisitForControl(expr->expression(), 4234 test->false_label(), 4235 test->true_label(), 4236 test->fall_through()); 4237 context()->Plug(test->true_label(), test->false_label()); 4238 } else { 4239 // We handle value contexts explicitly rather than simply visiting 4240 // for control and plugging the control flow into the context, 4241 // because we need to prepare a pair of extra administrative AST ids 4242 // for the optimizing compiler. 4243 ASSERT(context()->IsAccumulatorValue() || context()->IsStackValue()); 4244 Label materialize_true, materialize_false, done; 4245 VisitForControl(expr->expression(), 4246 &materialize_false, 4247 &materialize_true, 4248 &materialize_true); 4249 __ bind(&materialize_true); 4250 PrepareForBailoutForId(expr->MaterializeTrueId(), NO_REGISTERS); 4251 if (context()->IsAccumulatorValue()) { 4252 __ LoadRoot(rax, Heap::kTrueValueRootIndex); 4253 } else { 4254 __ PushRoot(Heap::kTrueValueRootIndex); 4255 } 4256 __ jmp(&done, Label::kNear); 4257 __ bind(&materialize_false); 4258 PrepareForBailoutForId(expr->MaterializeFalseId(), NO_REGISTERS); 4259 if (context()->IsAccumulatorValue()) { 4260 __ LoadRoot(rax, Heap::kFalseValueRootIndex); 4261 } else { 4262 __ PushRoot(Heap::kFalseValueRootIndex); 4263 } 4264 __ bind(&done); 4265 } 4266 break; 4267 } 4268 4269 case Token::TYPEOF: { 4270 Comment cmnt(masm_, "[ UnaryOperation (TYPEOF)"); 4271 { StackValueContext context(this); 4272 VisitForTypeofValue(expr->expression()); 4273 } 4274 __ CallRuntime(Runtime::kTypeof, 1); 4275 context()->Plug(rax); 4276 break; 4277 } 4278 4279 default: 4280 UNREACHABLE(); 4281 } 4282 } 4283 4284 4285 void FullCodeGenerator::VisitCountOperation(CountOperation* expr) { 4286 Comment cmnt(masm_, "[ CountOperation"); 4287 SetSourcePosition(expr->position()); 4288 4289 // Invalid left-hand-sides are rewritten to have a 'throw 4290 // ReferenceError' as the left-hand side. 4291 if (!expr->expression()->IsValidLeftHandSide()) { 4292 VisitForEffect(expr->expression()); 4293 return; 4294 } 4295 4296 // Expression can only be a property, a global or a (parameter or local) 4297 // slot. 4298 enum LhsKind { VARIABLE, NAMED_PROPERTY, KEYED_PROPERTY }; 4299 LhsKind assign_type = VARIABLE; 4300 Property* prop = expr->expression()->AsProperty(); 4301 // In case of a property we use the uninitialized expression context 4302 // of the key to detect a named property. 4303 if (prop != NULL) { 4304 assign_type = 4305 (prop->key()->IsPropertyName()) ? NAMED_PROPERTY : KEYED_PROPERTY; 4306 } 4307 4308 // Evaluate expression and get value. 4309 if (assign_type == VARIABLE) { 4310 ASSERT(expr->expression()->AsVariableProxy()->var() != NULL); 4311 AccumulatorValueContext context(this); 4312 EmitVariableLoad(expr->expression()->AsVariableProxy()); 4313 } else { 4314 // Reserve space for result of postfix operation. 4315 if (expr->is_postfix() && !context()->IsEffect()) { 4316 __ Push(Smi::FromInt(0)); 4317 } 4318 if (assign_type == NAMED_PROPERTY) { 4319 VisitForAccumulatorValue(prop->obj()); 4320 __ push(rax); // Copy of receiver, needed for later store. 4321 EmitNamedPropertyLoad(prop); 4322 } else { 4323 VisitForStackValue(prop->obj()); 4324 VisitForAccumulatorValue(prop->key()); 4325 __ movq(rdx, Operand(rsp, 0)); // Leave receiver on stack 4326 __ push(rax); // Copy of key, needed for later store. 4327 EmitKeyedPropertyLoad(prop); 4328 } 4329 } 4330 4331 // We need a second deoptimization point after loading the value 4332 // in case evaluating the property load my have a side effect. 4333 if (assign_type == VARIABLE) { 4334 PrepareForBailout(expr->expression(), TOS_REG); 4335 } else { 4336 PrepareForBailoutForId(prop->LoadId(), TOS_REG); 4337 } 4338 4339 // Inline smi case if we are in a loop. 4340 Label done, stub_call; 4341 JumpPatchSite patch_site(masm_); 4342 if (ShouldInlineSmiCase(expr->op())) { 4343 Label slow; 4344 patch_site.EmitJumpIfNotSmi(rax, &slow, Label::kNear); 4345 4346 // Save result for postfix expressions. 4347 if (expr->is_postfix()) { 4348 if (!context()->IsEffect()) { 4349 // Save the result on the stack. If we have a named or keyed property 4350 // we store the result under the receiver that is currently on top 4351 // of the stack. 4352 switch (assign_type) { 4353 case VARIABLE: 4354 __ push(rax); 4355 break; 4356 case NAMED_PROPERTY: 4357 __ movq(Operand(rsp, kPointerSize), rax); 4358 break; 4359 case KEYED_PROPERTY: 4360 __ movq(Operand(rsp, 2 * kPointerSize), rax); 4361 break; 4362 } 4363 } 4364 } 4365 4366 SmiOperationExecutionMode mode; 4367 mode.Add(PRESERVE_SOURCE_REGISTER); 4368 mode.Add(BAILOUT_ON_NO_OVERFLOW); 4369 if (expr->op() == Token::INC) { 4370 __ SmiAddConstant(rax, rax, Smi::FromInt(1), mode, &done, Label::kNear); 4371 } else { 4372 __ SmiSubConstant(rax, rax, Smi::FromInt(1), mode, &done, Label::kNear); 4373 } 4374 __ jmp(&stub_call, Label::kNear); 4375 __ bind(&slow); 4376 } 4377 4378 ToNumberStub convert_stub; 4379 __ CallStub(&convert_stub); 4380 4381 // Save result for postfix expressions. 4382 if (expr->is_postfix()) { 4383 if (!context()->IsEffect()) { 4384 // Save the result on the stack. If we have a named or keyed property 4385 // we store the result under the receiver that is currently on top 4386 // of the stack. 4387 switch (assign_type) { 4388 case VARIABLE: 4389 __ push(rax); 4390 break; 4391 case NAMED_PROPERTY: 4392 __ movq(Operand(rsp, kPointerSize), rax); 4393 break; 4394 case KEYED_PROPERTY: 4395 __ movq(Operand(rsp, 2 * kPointerSize), rax); 4396 break; 4397 } 4398 } 4399 } 4400 4401 // Record position before stub call. 4402 SetSourcePosition(expr->position()); 4403 4404 // Call stub for +1/-1. 4405 __ bind(&stub_call); 4406 __ movq(rdx, rax); 4407 __ Move(rax, Smi::FromInt(1)); 4408 BinaryOpICStub stub(expr->binary_op(), NO_OVERWRITE); 4409 CallIC(stub.GetCode(isolate()), 4410 RelocInfo::CODE_TARGET, 4411 expr->CountBinOpFeedbackId()); 4412 patch_site.EmitPatchInfo(); 4413 __ bind(&done); 4414 4415 // Store the value returned in rax. 4416 switch (assign_type) { 4417 case VARIABLE: 4418 if (expr->is_postfix()) { 4419 // Perform the assignment as if via '='. 4420 { EffectContext context(this); 4421 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(), 4422 Token::ASSIGN); 4423 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG); 4424 context.Plug(rax); 4425 } 4426 // For all contexts except kEffect: We have the result on 4427 // top of the stack. 4428 if (!context()->IsEffect()) { 4429 context()->PlugTOS(); 4430 } 4431 } else { 4432 // Perform the assignment as if via '='. 4433 EmitVariableAssignment(expr->expression()->AsVariableProxy()->var(), 4434 Token::ASSIGN); 4435 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG); 4436 context()->Plug(rax); 4437 } 4438 break; 4439 case NAMED_PROPERTY: { 4440 __ Move(rcx, prop->key()->AsLiteral()->value()); 4441 __ pop(rdx); 4442 Handle<Code> ic = is_classic_mode() 4443 ? isolate()->builtins()->StoreIC_Initialize() 4444 : isolate()->builtins()->StoreIC_Initialize_Strict(); 4445 CallIC(ic, RelocInfo::CODE_TARGET, expr->CountStoreFeedbackId()); 4446 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG); 4447 if (expr->is_postfix()) { 4448 if (!context()->IsEffect()) { 4449 context()->PlugTOS(); 4450 } 4451 } else { 4452 context()->Plug(rax); 4453 } 4454 break; 4455 } 4456 case KEYED_PROPERTY: { 4457 __ pop(rcx); 4458 __ pop(rdx); 4459 Handle<Code> ic = is_classic_mode() 4460 ? isolate()->builtins()->KeyedStoreIC_Initialize() 4461 : isolate()->builtins()->KeyedStoreIC_Initialize_Strict(); 4462 CallIC(ic, RelocInfo::CODE_TARGET, expr->CountStoreFeedbackId()); 4463 PrepareForBailoutForId(expr->AssignmentId(), TOS_REG); 4464 if (expr->is_postfix()) { 4465 if (!context()->IsEffect()) { 4466 context()->PlugTOS(); 4467 } 4468 } else { 4469 context()->Plug(rax); 4470 } 4471 break; 4472 } 4473 } 4474 } 4475 4476 4477 void FullCodeGenerator::VisitForTypeofValue(Expression* expr) { 4478 VariableProxy* proxy = expr->AsVariableProxy(); 4479 ASSERT(!context()->IsEffect()); 4480 ASSERT(!context()->IsTest()); 4481 4482 if (proxy != NULL && proxy->var()->IsUnallocated()) { 4483 Comment cmnt(masm_, "Global variable"); 4484 __ Move(rcx, proxy->name()); 4485 __ movq(rax, GlobalObjectOperand()); 4486 Handle<Code> ic = isolate()->builtins()->LoadIC_Initialize(); 4487 // Use a regular load, not a contextual load, to avoid a reference 4488 // error. 4489 CallIC(ic); 4490 PrepareForBailout(expr, TOS_REG); 4491 context()->Plug(rax); 4492 } else if (proxy != NULL && proxy->var()->IsLookupSlot()) { 4493 Label done, slow; 4494 4495 // Generate code for loading from variables potentially shadowed 4496 // by eval-introduced variables. 4497 EmitDynamicLookupFastCase(proxy->var(), INSIDE_TYPEOF, &slow, &done); 4498 4499 __ bind(&slow); 4500 __ push(rsi); 4501 __ Push(proxy->name()); 4502 __ CallRuntime(Runtime::kLoadContextSlotNoReferenceError, 2); 4503 PrepareForBailout(expr, TOS_REG); 4504 __ bind(&done); 4505 4506 context()->Plug(rax); 4507 } else { 4508 // This expression cannot throw a reference error at the top level. 4509 VisitInDuplicateContext(expr); 4510 } 4511 } 4512 4513 4514 void FullCodeGenerator::EmitLiteralCompareTypeof(Expression* expr, 4515 Expression* sub_expr, 4516 Handle<String> check) { 4517 Label materialize_true, materialize_false; 4518 Label* if_true = NULL; 4519 Label* if_false = NULL; 4520 Label* fall_through = NULL; 4521 context()->PrepareTest(&materialize_true, &materialize_false, 4522 &if_true, &if_false, &fall_through); 4523 4524 { AccumulatorValueContext context(this); 4525 VisitForTypeofValue(sub_expr); 4526 } 4527 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 4528 4529 if (check->Equals(isolate()->heap()->number_string())) { 4530 __ JumpIfSmi(rax, if_true); 4531 __ movq(rax, FieldOperand(rax, HeapObject::kMapOffset)); 4532 __ CompareRoot(rax, Heap::kHeapNumberMapRootIndex); 4533 Split(equal, if_true, if_false, fall_through); 4534 } else if (check->Equals(isolate()->heap()->string_string())) { 4535 __ JumpIfSmi(rax, if_false); 4536 // Check for undetectable objects => false. 4537 __ CmpObjectType(rax, FIRST_NONSTRING_TYPE, rdx); 4538 __ j(above_equal, if_false); 4539 __ testb(FieldOperand(rdx, Map::kBitFieldOffset), 4540 Immediate(1 << Map::kIsUndetectable)); 4541 Split(zero, if_true, if_false, fall_through); 4542 } else if (check->Equals(isolate()->heap()->symbol_string())) { 4543 __ JumpIfSmi(rax, if_false); 4544 __ CmpObjectType(rax, SYMBOL_TYPE, rdx); 4545 Split(equal, if_true, if_false, fall_through); 4546 } else if (check->Equals(isolate()->heap()->boolean_string())) { 4547 __ CompareRoot(rax, Heap::kTrueValueRootIndex); 4548 __ j(equal, if_true); 4549 __ CompareRoot(rax, Heap::kFalseValueRootIndex); 4550 Split(equal, if_true, if_false, fall_through); 4551 } else if (FLAG_harmony_typeof && 4552 check->Equals(isolate()->heap()->null_string())) { 4553 __ CompareRoot(rax, Heap::kNullValueRootIndex); 4554 Split(equal, if_true, if_false, fall_through); 4555 } else if (check->Equals(isolate()->heap()->undefined_string())) { 4556 __ CompareRoot(rax, Heap::kUndefinedValueRootIndex); 4557 __ j(equal, if_true); 4558 __ JumpIfSmi(rax, if_false); 4559 // Check for undetectable objects => true. 4560 __ movq(rdx, FieldOperand(rax, HeapObject::kMapOffset)); 4561 __ testb(FieldOperand(rdx, Map::kBitFieldOffset), 4562 Immediate(1 << Map::kIsUndetectable)); 4563 Split(not_zero, if_true, if_false, fall_through); 4564 } else if (check->Equals(isolate()->heap()->function_string())) { 4565 __ JumpIfSmi(rax, if_false); 4566 STATIC_ASSERT(NUM_OF_CALLABLE_SPEC_OBJECT_TYPES == 2); 4567 __ CmpObjectType(rax, JS_FUNCTION_TYPE, rdx); 4568 __ j(equal, if_true); 4569 __ CmpInstanceType(rdx, JS_FUNCTION_PROXY_TYPE); 4570 Split(equal, if_true, if_false, fall_through); 4571 } else if (check->Equals(isolate()->heap()->object_string())) { 4572 __ JumpIfSmi(rax, if_false); 4573 if (!FLAG_harmony_typeof) { 4574 __ CompareRoot(rax, Heap::kNullValueRootIndex); 4575 __ j(equal, if_true); 4576 } 4577 __ CmpObjectType(rax, FIRST_NONCALLABLE_SPEC_OBJECT_TYPE, rdx); 4578 __ j(below, if_false); 4579 __ CmpInstanceType(rdx, LAST_NONCALLABLE_SPEC_OBJECT_TYPE); 4580 __ j(above, if_false); 4581 // Check for undetectable objects => false. 4582 __ testb(FieldOperand(rdx, Map::kBitFieldOffset), 4583 Immediate(1 << Map::kIsUndetectable)); 4584 Split(zero, if_true, if_false, fall_through); 4585 } else { 4586 if (if_false != fall_through) __ jmp(if_false); 4587 } 4588 context()->Plug(if_true, if_false); 4589 } 4590 4591 4592 void FullCodeGenerator::VisitCompareOperation(CompareOperation* expr) { 4593 Comment cmnt(masm_, "[ CompareOperation"); 4594 SetSourcePosition(expr->position()); 4595 4596 // First we try a fast inlined version of the compare when one of 4597 // the operands is a literal. 4598 if (TryLiteralCompare(expr)) return; 4599 4600 // Always perform the comparison for its control flow. Pack the result 4601 // into the expression's context after the comparison is performed. 4602 Label materialize_true, materialize_false; 4603 Label* if_true = NULL; 4604 Label* if_false = NULL; 4605 Label* fall_through = NULL; 4606 context()->PrepareTest(&materialize_true, &materialize_false, 4607 &if_true, &if_false, &fall_through); 4608 4609 Token::Value op = expr->op(); 4610 VisitForStackValue(expr->left()); 4611 switch (op) { 4612 case Token::IN: 4613 VisitForStackValue(expr->right()); 4614 __ InvokeBuiltin(Builtins::IN, CALL_FUNCTION); 4615 PrepareForBailoutBeforeSplit(expr, false, NULL, NULL); 4616 __ CompareRoot(rax, Heap::kTrueValueRootIndex); 4617 Split(equal, if_true, if_false, fall_through); 4618 break; 4619 4620 case Token::INSTANCEOF: { 4621 VisitForStackValue(expr->right()); 4622 InstanceofStub stub(InstanceofStub::kNoFlags); 4623 __ CallStub(&stub); 4624 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 4625 __ testq(rax, rax); 4626 // The stub returns 0 for true. 4627 Split(zero, if_true, if_false, fall_through); 4628 break; 4629 } 4630 4631 default: { 4632 VisitForAccumulatorValue(expr->right()); 4633 Condition cc = CompareIC::ComputeCondition(op); 4634 __ pop(rdx); 4635 4636 bool inline_smi_code = ShouldInlineSmiCase(op); 4637 JumpPatchSite patch_site(masm_); 4638 if (inline_smi_code) { 4639 Label slow_case; 4640 __ movq(rcx, rdx); 4641 __ or_(rcx, rax); 4642 patch_site.EmitJumpIfNotSmi(rcx, &slow_case, Label::kNear); 4643 __ cmpq(rdx, rax); 4644 Split(cc, if_true, if_false, NULL); 4645 __ bind(&slow_case); 4646 } 4647 4648 // Record position and call the compare IC. 4649 SetSourcePosition(expr->position()); 4650 Handle<Code> ic = CompareIC::GetUninitialized(isolate(), op); 4651 CallIC(ic, RelocInfo::CODE_TARGET, expr->CompareOperationFeedbackId()); 4652 patch_site.EmitPatchInfo(); 4653 4654 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 4655 __ testq(rax, rax); 4656 Split(cc, if_true, if_false, fall_through); 4657 } 4658 } 4659 4660 // Convert the result of the comparison into one expected for this 4661 // expression's context. 4662 context()->Plug(if_true, if_false); 4663 } 4664 4665 4666 void FullCodeGenerator::EmitLiteralCompareNil(CompareOperation* expr, 4667 Expression* sub_expr, 4668 NilValue nil) { 4669 Label materialize_true, materialize_false; 4670 Label* if_true = NULL; 4671 Label* if_false = NULL; 4672 Label* fall_through = NULL; 4673 context()->PrepareTest(&materialize_true, &materialize_false, 4674 &if_true, &if_false, &fall_through); 4675 4676 VisitForAccumulatorValue(sub_expr); 4677 PrepareForBailoutBeforeSplit(expr, true, if_true, if_false); 4678 if (expr->op() == Token::EQ_STRICT) { 4679 Heap::RootListIndex nil_value = nil == kNullValue ? 4680 Heap::kNullValueRootIndex : 4681 Heap::kUndefinedValueRootIndex; 4682 __ CompareRoot(rax, nil_value); 4683 Split(equal, if_true, if_false, fall_through); 4684 } else { 4685 Handle<Code> ic = CompareNilICStub::GetUninitialized(isolate(), nil); 4686 CallIC(ic, RelocInfo::CODE_TARGET, expr->CompareOperationFeedbackId()); 4687 __ testq(rax, rax); 4688 Split(not_zero, if_true, if_false, fall_through); 4689 } 4690 context()->Plug(if_true, if_false); 4691 } 4692 4693 4694 void FullCodeGenerator::VisitThisFunction(ThisFunction* expr) { 4695 __ movq(rax, Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); 4696 context()->Plug(rax); 4697 } 4698 4699 4700 Register FullCodeGenerator::result_register() { 4701 return rax; 4702 } 4703 4704 4705 Register FullCodeGenerator::context_register() { 4706 return rsi; 4707 } 4708 4709 4710 void FullCodeGenerator::StoreToFrameField(int frame_offset, Register value) { 4711 ASSERT(IsAligned(frame_offset, kPointerSize)); 4712 __ movq(Operand(rbp, frame_offset), value); 4713 } 4714 4715 4716 void FullCodeGenerator::LoadContextField(Register dst, int context_index) { 4717 __ movq(dst, ContextOperand(rsi, context_index)); 4718 } 4719 4720 4721 void FullCodeGenerator::PushFunctionArgumentForContextAllocation() { 4722 Scope* declaration_scope = scope()->DeclarationScope(); 4723 if (declaration_scope->is_global_scope() || 4724 declaration_scope->is_module_scope()) { 4725 // Contexts nested in the native context have a canonical empty function 4726 // as their closure, not the anonymous closure containing the global 4727 // code. Pass a smi sentinel and let the runtime look up the empty 4728 // function. 4729 __ Push(Smi::FromInt(0)); 4730 } else if (declaration_scope->is_eval_scope()) { 4731 // Contexts created by a call to eval have the same closure as the 4732 // context calling eval, not the anonymous closure containing the eval 4733 // code. Fetch it from the context. 4734 __ push(ContextOperand(rsi, Context::CLOSURE_INDEX)); 4735 } else { 4736 ASSERT(declaration_scope->is_function_scope()); 4737 __ push(Operand(rbp, JavaScriptFrameConstants::kFunctionOffset)); 4738 } 4739 } 4740 4741 4742 // ---------------------------------------------------------------------------- 4743 // Non-local control flow support. 4744 4745 4746 void FullCodeGenerator::EnterFinallyBlock() { 4747 ASSERT(!result_register().is(rdx)); 4748 ASSERT(!result_register().is(rcx)); 4749 // Cook return address on top of stack (smi encoded Code* delta) 4750 __ PopReturnAddressTo(rdx); 4751 __ Move(rcx, masm_->CodeObject()); 4752 __ subq(rdx, rcx); 4753 __ Integer32ToSmi(rdx, rdx); 4754 __ push(rdx); 4755 4756 // Store result register while executing finally block. 4757 __ push(result_register()); 4758 4759 // Store pending message while executing finally block. 4760 ExternalReference pending_message_obj = 4761 ExternalReference::address_of_pending_message_obj(isolate()); 4762 __ Load(rdx, pending_message_obj); 4763 __ push(rdx); 4764 4765 ExternalReference has_pending_message = 4766 ExternalReference::address_of_has_pending_message(isolate()); 4767 __ Load(rdx, has_pending_message); 4768 __ Integer32ToSmi(rdx, rdx); 4769 __ push(rdx); 4770 4771 ExternalReference pending_message_script = 4772 ExternalReference::address_of_pending_message_script(isolate()); 4773 __ Load(rdx, pending_message_script); 4774 __ push(rdx); 4775 } 4776 4777 4778 void FullCodeGenerator::ExitFinallyBlock() { 4779 ASSERT(!result_register().is(rdx)); 4780 ASSERT(!result_register().is(rcx)); 4781 // Restore pending message from stack. 4782 __ pop(rdx); 4783 ExternalReference pending_message_script = 4784 ExternalReference::address_of_pending_message_script(isolate()); 4785 __ Store(pending_message_script, rdx); 4786 4787 __ pop(rdx); 4788 __ SmiToInteger32(rdx, rdx); 4789 ExternalReference has_pending_message = 4790 ExternalReference::address_of_has_pending_message(isolate()); 4791 __ Store(has_pending_message, rdx); 4792 4793 __ pop(rdx); 4794 ExternalReference pending_message_obj = 4795 ExternalReference::address_of_pending_message_obj(isolate()); 4796 __ Store(pending_message_obj, rdx); 4797 4798 // Restore result register from stack. 4799 __ pop(result_register()); 4800 4801 // Uncook return address. 4802 __ pop(rdx); 4803 __ SmiToInteger32(rdx, rdx); 4804 __ Move(rcx, masm_->CodeObject()); 4805 __ addq(rdx, rcx); 4806 __ jmp(rdx); 4807 } 4808 4809 4810 #undef __ 4811 4812 #define __ ACCESS_MASM(masm()) 4813 4814 FullCodeGenerator::NestedStatement* FullCodeGenerator::TryFinally::Exit( 4815 int* stack_depth, 4816 int* context_length) { 4817 // The macros used here must preserve the result register. 4818 4819 // Because the handler block contains the context of the finally 4820 // code, we can restore it directly from there for the finally code 4821 // rather than iteratively unwinding contexts via their previous 4822 // links. 4823 __ Drop(*stack_depth); // Down to the handler block. 4824 if (*context_length > 0) { 4825 // Restore the context to its dedicated register and the stack. 4826 __ movq(rsi, Operand(rsp, StackHandlerConstants::kContextOffset)); 4827 __ movq(Operand(rbp, StandardFrameConstants::kContextOffset), rsi); 4828 } 4829 __ PopTryHandler(); 4830 __ call(finally_entry_); 4831 4832 *stack_depth = 0; 4833 *context_length = 0; 4834 return previous_; 4835 } 4836 4837 4838 #undef __ 4839 4840 4841 static const byte kJnsInstruction = 0x79; 4842 static const byte kJnsOffset = 0x1d; 4843 static const byte kCallInstruction = 0xe8; 4844 static const byte kNopByteOne = 0x66; 4845 static const byte kNopByteTwo = 0x90; 4846 4847 4848 void BackEdgeTable::PatchAt(Code* unoptimized_code, 4849 Address pc, 4850 BackEdgeState target_state, 4851 Code* replacement_code) { 4852 Address call_target_address = pc - kIntSize; 4853 Address jns_instr_address = call_target_address - 3; 4854 Address jns_offset_address = call_target_address - 2; 4855 4856 switch (target_state) { 4857 case INTERRUPT: 4858 // sub <profiling_counter>, <delta> ;; Not changed 4859 // jns ok 4860 // call <interrupt stub> 4861 // ok: 4862 *jns_instr_address = kJnsInstruction; 4863 *jns_offset_address = kJnsOffset; 4864 break; 4865 case ON_STACK_REPLACEMENT: 4866 case OSR_AFTER_STACK_CHECK: 4867 // sub <profiling_counter>, <delta> ;; Not changed 4868 // nop 4869 // nop 4870 // call <on-stack replacment> 4871 // ok: 4872 *jns_instr_address = kNopByteOne; 4873 *jns_offset_address = kNopByteTwo; 4874 break; 4875 } 4876 4877 Assembler::set_target_address_at(call_target_address, 4878 replacement_code->entry()); 4879 unoptimized_code->GetHeap()->incremental_marking()->RecordCodeTargetPatch( 4880 unoptimized_code, call_target_address, replacement_code); 4881 } 4882 4883 4884 BackEdgeTable::BackEdgeState BackEdgeTable::GetBackEdgeState( 4885 Isolate* isolate, 4886 Code* unoptimized_code, 4887 Address pc) { 4888 Address call_target_address = pc - kIntSize; 4889 Address jns_instr_address = call_target_address - 3; 4890 ASSERT_EQ(kCallInstruction, *(call_target_address - 1)); 4891 4892 if (*jns_instr_address == kJnsInstruction) { 4893 ASSERT_EQ(kJnsOffset, *(call_target_address - 2)); 4894 ASSERT_EQ(isolate->builtins()->InterruptCheck()->entry(), 4895 Assembler::target_address_at(call_target_address)); 4896 return INTERRUPT; 4897 } 4898 4899 ASSERT_EQ(kNopByteOne, *jns_instr_address); 4900 ASSERT_EQ(kNopByteTwo, *(call_target_address - 2)); 4901 4902 if (Assembler::target_address_at(call_target_address) == 4903 isolate->builtins()->OnStackReplacement()->entry()) { 4904 return ON_STACK_REPLACEMENT; 4905 } 4906 4907 ASSERT_EQ(isolate->builtins()->OsrAfterStackCheck()->entry(), 4908 Assembler::target_address_at(call_target_address)); 4909 return OSR_AFTER_STACK_CHECK; 4910 } 4911 4912 4913 } } // namespace v8::internal 4914 4915 #endif // V8_TARGET_ARCH_X64 4916