1 // Copyright 2012 the V8 project authors. All rights reserved.7
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 "src/crankshaft/mips/lithium-codegen-mips.h"
29
30 #include "src/base/bits.h"
31 #include "src/code-factory.h"
32 #include "src/code-stubs.h"
33 #include "src/crankshaft/hydrogen-osr.h"
34 #include "src/crankshaft/mips/lithium-gap-resolver-mips.h"
35 #include "src/ic/ic.h"
36 #include "src/ic/stub-cache.h"
37
38 namespace v8 {
39 namespace internal {
40
41
42 class SafepointGenerator final : public CallWrapper {
43 public:
SafepointGenerator(LCodeGen * codegen,LPointerMap * pointers,Safepoint::DeoptMode mode)44 SafepointGenerator(LCodeGen* codegen,
45 LPointerMap* pointers,
46 Safepoint::DeoptMode mode)
47 : codegen_(codegen),
48 pointers_(pointers),
49 deopt_mode_(mode) { }
~SafepointGenerator()50 virtual ~SafepointGenerator() {}
51
BeforeCall(int call_size) const52 void BeforeCall(int call_size) const override {}
53
AfterCall() const54 void AfterCall() const override {
55 codegen_->RecordSafepoint(pointers_, deopt_mode_);
56 }
57
58 private:
59 LCodeGen* codegen_;
60 LPointerMap* pointers_;
61 Safepoint::DeoptMode deopt_mode_;
62 };
63
PushSafepointRegistersScope(LCodeGen * codegen)64 LCodeGen::PushSafepointRegistersScope::PushSafepointRegistersScope(
65 LCodeGen* codegen)
66 : codegen_(codegen) {
67 DCHECK(codegen_->info()->is_calling());
68 DCHECK(codegen_->expected_safepoint_kind_ == Safepoint::kSimple);
69 codegen_->expected_safepoint_kind_ = Safepoint::kWithRegisters;
70
71 StoreRegistersStateStub stub(codegen_->isolate());
72 codegen_->masm_->push(ra);
73 codegen_->masm_->CallStub(&stub);
74 }
75
~PushSafepointRegistersScope()76 LCodeGen::PushSafepointRegistersScope::~PushSafepointRegistersScope() {
77 DCHECK(codegen_->expected_safepoint_kind_ == Safepoint::kWithRegisters);
78 RestoreRegistersStateStub stub(codegen_->isolate());
79 codegen_->masm_->push(ra);
80 codegen_->masm_->CallStub(&stub);
81 codegen_->expected_safepoint_kind_ = Safepoint::kSimple;
82 }
83
84 #define __ masm()->
85
GenerateCode()86 bool LCodeGen::GenerateCode() {
87 LPhase phase("Z_Code generation", chunk());
88 DCHECK(is_unused());
89 status_ = GENERATING;
90
91 // Open a frame scope to indicate that there is a frame on the stack. The
92 // NONE indicates that the scope shouldn't actually generate code to set up
93 // the frame (that is done in GeneratePrologue).
94 FrameScope frame_scope(masm_, StackFrame::NONE);
95
96 return GeneratePrologue() && GenerateBody() && GenerateDeferredCode() &&
97 GenerateJumpTable() && GenerateSafepointTable();
98 }
99
100
FinishCode(Handle<Code> code)101 void LCodeGen::FinishCode(Handle<Code> code) {
102 DCHECK(is_done());
103 code->set_stack_slots(GetTotalFrameSlotCount());
104 code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
105 PopulateDeoptimizationData(code);
106 }
107
108
SaveCallerDoubles()109 void LCodeGen::SaveCallerDoubles() {
110 DCHECK(info()->saves_caller_doubles());
111 DCHECK(NeedsEagerFrame());
112 Comment(";;; Save clobbered callee double registers");
113 int count = 0;
114 BitVector* doubles = chunk()->allocated_double_registers();
115 BitVector::Iterator save_iterator(doubles);
116 while (!save_iterator.Done()) {
117 __ sdc1(DoubleRegister::from_code(save_iterator.Current()),
118 MemOperand(sp, count * kDoubleSize));
119 save_iterator.Advance();
120 count++;
121 }
122 }
123
124
RestoreCallerDoubles()125 void LCodeGen::RestoreCallerDoubles() {
126 DCHECK(info()->saves_caller_doubles());
127 DCHECK(NeedsEagerFrame());
128 Comment(";;; Restore clobbered callee double registers");
129 BitVector* doubles = chunk()->allocated_double_registers();
130 BitVector::Iterator save_iterator(doubles);
131 int count = 0;
132 while (!save_iterator.Done()) {
133 __ ldc1(DoubleRegister::from_code(save_iterator.Current()),
134 MemOperand(sp, count * kDoubleSize));
135 save_iterator.Advance();
136 count++;
137 }
138 }
139
140
GeneratePrologue()141 bool LCodeGen::GeneratePrologue() {
142 DCHECK(is_generating());
143
144 if (info()->IsOptimizing()) {
145 ProfileEntryHookStub::MaybeCallEntryHook(masm_);
146
147 // a1: Callee's JS function.
148 // cp: Callee's context.
149 // fp: Caller's frame pointer.
150 // lr: Caller's pc.
151 }
152
153 info()->set_prologue_offset(masm_->pc_offset());
154 if (NeedsEagerFrame()) {
155 if (info()->IsStub()) {
156 __ StubPrologue(StackFrame::STUB);
157 } else {
158 __ Prologue(info()->GeneratePreagedPrologue());
159 }
160 frame_is_built_ = true;
161 }
162
163 // Reserve space for the stack slots needed by the code.
164 int slots = GetStackSlotCount();
165 if (slots > 0) {
166 if (FLAG_debug_code) {
167 __ Subu(sp, sp, Operand(slots * kPointerSize));
168 __ Push(a0, a1);
169 __ Addu(a0, sp, Operand(slots * kPointerSize));
170 __ li(a1, Operand(kSlotsZapValue));
171 Label loop;
172 __ bind(&loop);
173 __ Subu(a0, a0, Operand(kPointerSize));
174 __ sw(a1, MemOperand(a0, 2 * kPointerSize));
175 __ Branch(&loop, ne, a0, Operand(sp));
176 __ Pop(a0, a1);
177 } else {
178 __ Subu(sp, sp, Operand(slots * kPointerSize));
179 }
180 }
181
182 if (info()->saves_caller_doubles()) {
183 SaveCallerDoubles();
184 }
185 return !is_aborted();
186 }
187
188
DoPrologue(LPrologue * instr)189 void LCodeGen::DoPrologue(LPrologue* instr) {
190 Comment(";;; Prologue begin");
191
192 // Possibly allocate a local context.
193 if (info()->scope()->NeedsContext()) {
194 Comment(";;; Allocate local context");
195 bool need_write_barrier = true;
196 // Argument to NewContext is the function, which is in a1.
197 int slots = info()->scope()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
198 Safepoint::DeoptMode deopt_mode = Safepoint::kNoLazyDeopt;
199 if (info()->scope()->is_script_scope()) {
200 __ push(a1);
201 __ Push(info()->scope()->scope_info());
202 __ CallRuntime(Runtime::kNewScriptContext);
203 deopt_mode = Safepoint::kLazyDeopt;
204 } else {
205 if (slots <= FastNewFunctionContextStub::kMaximumSlots) {
206 FastNewFunctionContextStub stub(isolate());
207 __ li(FastNewFunctionContextDescriptor::SlotsRegister(),
208 Operand(slots));
209 __ CallStub(&stub);
210 // Result of FastNewFunctionContextStub is always in new space.
211 need_write_barrier = false;
212 } else {
213 __ push(a1);
214 __ CallRuntime(Runtime::kNewFunctionContext);
215 }
216 }
217 RecordSafepoint(deopt_mode);
218
219 // Context is returned in both v0. It replaces the context passed to us.
220 // It's saved in the stack and kept live in cp.
221 __ mov(cp, v0);
222 __ sw(v0, MemOperand(fp, StandardFrameConstants::kContextOffset));
223 // Copy any necessary parameters into the context.
224 int num_parameters = info()->scope()->num_parameters();
225 int first_parameter = info()->scope()->has_this_declaration() ? -1 : 0;
226 for (int i = first_parameter; i < num_parameters; i++) {
227 Variable* var = (i == -1) ? info()->scope()->receiver()
228 : info()->scope()->parameter(i);
229 if (var->IsContextSlot()) {
230 int parameter_offset = StandardFrameConstants::kCallerSPOffset +
231 (num_parameters - 1 - i) * kPointerSize;
232 // Load parameter from stack.
233 __ lw(a0, MemOperand(fp, parameter_offset));
234 // Store it in the context.
235 MemOperand target = ContextMemOperand(cp, var->index());
236 __ sw(a0, target);
237 // Update the write barrier. This clobbers a3 and a0.
238 if (need_write_barrier) {
239 __ RecordWriteContextSlot(
240 cp, target.offset(), a0, a3, GetRAState(), kSaveFPRegs);
241 } else if (FLAG_debug_code) {
242 Label done;
243 __ JumpIfInNewSpace(cp, a0, &done);
244 __ Abort(kExpectedNewSpaceObject);
245 __ bind(&done);
246 }
247 }
248 }
249 Comment(";;; End allocate local context");
250 }
251
252 Comment(";;; Prologue end");
253 }
254
255
GenerateOsrPrologue()256 void LCodeGen::GenerateOsrPrologue() {
257 // Generate the OSR entry prologue at the first unknown OSR value, or if there
258 // are none, at the OSR entrypoint instruction.
259 if (osr_pc_offset_ >= 0) return;
260
261 osr_pc_offset_ = masm()->pc_offset();
262
263 // Adjust the frame size, subsuming the unoptimized frame into the
264 // optimized frame.
265 int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
266 DCHECK(slots >= 0);
267 __ Subu(sp, sp, Operand(slots * kPointerSize));
268 }
269
270
GenerateBodyInstructionPre(LInstruction * instr)271 void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
272 if (instr->IsCall()) {
273 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
274 }
275 if (!instr->IsLazyBailout() && !instr->IsGap()) {
276 safepoints_.BumpLastLazySafepointIndex();
277 }
278 }
279
280
GenerateDeferredCode()281 bool LCodeGen::GenerateDeferredCode() {
282 DCHECK(is_generating());
283 if (deferred_.length() > 0) {
284 for (int i = 0; !is_aborted() && i < deferred_.length(); i++) {
285 LDeferredCode* code = deferred_[i];
286
287 HValue* value =
288 instructions_->at(code->instruction_index())->hydrogen_value();
289 RecordAndWritePosition(value->position());
290
291 Comment(";;; <@%d,#%d> "
292 "-------------------- Deferred %s --------------------",
293 code->instruction_index(),
294 code->instr()->hydrogen_value()->id(),
295 code->instr()->Mnemonic());
296 __ bind(code->entry());
297 if (NeedsDeferredFrame()) {
298 Comment(";;; Build frame");
299 DCHECK(!frame_is_built_);
300 DCHECK(info()->IsStub());
301 frame_is_built_ = true;
302 __ li(scratch0(), Operand(Smi::FromInt(StackFrame::STUB)));
303 __ PushCommonFrame(scratch0());
304 Comment(";;; Deferred code");
305 }
306 code->Generate();
307 if (NeedsDeferredFrame()) {
308 Comment(";;; Destroy frame");
309 DCHECK(frame_is_built_);
310 __ PopCommonFrame(scratch0());
311 frame_is_built_ = false;
312 }
313 __ jmp(code->exit());
314 }
315 }
316 // Deferred code is the last part of the instruction sequence. Mark
317 // the generated code as done unless we bailed out.
318 if (!is_aborted()) status_ = DONE;
319 return !is_aborted();
320 }
321
322
GenerateJumpTable()323 bool LCodeGen::GenerateJumpTable() {
324 if (jump_table_.length() > 0) {
325 Label needs_frame, call_deopt_entry;
326
327 Comment(";;; -------------------- Jump table --------------------");
328 Address base = jump_table_[0].address;
329
330 Register entry_offset = t9;
331
332 int length = jump_table_.length();
333 for (int i = 0; i < length; i++) {
334 Deoptimizer::JumpTableEntry* table_entry = &jump_table_[i];
335 __ bind(&table_entry->label);
336
337 DCHECK(table_entry->bailout_type == jump_table_[0].bailout_type);
338 Address entry = table_entry->address;
339 DeoptComment(table_entry->deopt_info);
340
341 // Second-level deopt table entries are contiguous and small, so instead
342 // of loading the full, absolute address of each one, load an immediate
343 // offset which will be added to the base address later.
344 __ li(entry_offset, Operand(entry - base));
345
346 if (table_entry->needs_frame) {
347 DCHECK(!info()->saves_caller_doubles());
348 Comment(";;; call deopt with frame");
349 __ PushCommonFrame();
350 __ Call(&needs_frame);
351 } else {
352 __ Call(&call_deopt_entry);
353 }
354 }
355
356 if (needs_frame.is_linked()) {
357 __ bind(&needs_frame);
358 // This variant of deopt can only be used with stubs. Since we don't
359 // have a function pointer to install in the stack frame that we're
360 // building, install a special marker there instead.
361 __ li(at, Operand(Smi::FromInt(StackFrame::STUB)));
362 __ push(at);
363 DCHECK(info()->IsStub());
364 }
365
366 Comment(";;; call deopt");
367 __ bind(&call_deopt_entry);
368
369 if (info()->saves_caller_doubles()) {
370 DCHECK(info()->IsStub());
371 RestoreCallerDoubles();
372 }
373
374 // Add the base address to the offset previously loaded in entry_offset.
375 __ Addu(entry_offset, entry_offset,
376 Operand(ExternalReference::ForDeoptEntry(base)));
377 __ Jump(entry_offset);
378 }
379 __ RecordComment("]");
380
381 // The deoptimization jump table is the last part of the instruction
382 // sequence. Mark the generated code as done unless we bailed out.
383 if (!is_aborted()) status_ = DONE;
384 return !is_aborted();
385 }
386
387
GenerateSafepointTable()388 bool LCodeGen::GenerateSafepointTable() {
389 DCHECK(is_done());
390 safepoints_.Emit(masm(), GetTotalFrameSlotCount());
391 return !is_aborted();
392 }
393
394
ToRegister(int index) const395 Register LCodeGen::ToRegister(int index) const {
396 return Register::from_code(index);
397 }
398
399
ToDoubleRegister(int index) const400 DoubleRegister LCodeGen::ToDoubleRegister(int index) const {
401 return DoubleRegister::from_code(index);
402 }
403
404
ToRegister(LOperand * op) const405 Register LCodeGen::ToRegister(LOperand* op) const {
406 DCHECK(op->IsRegister());
407 return ToRegister(op->index());
408 }
409
410
EmitLoadRegister(LOperand * op,Register scratch)411 Register LCodeGen::EmitLoadRegister(LOperand* op, Register scratch) {
412 if (op->IsRegister()) {
413 return ToRegister(op->index());
414 } else if (op->IsConstantOperand()) {
415 LConstantOperand* const_op = LConstantOperand::cast(op);
416 HConstant* constant = chunk_->LookupConstant(const_op);
417 Handle<Object> literal = constant->handle(isolate());
418 Representation r = chunk_->LookupLiteralRepresentation(const_op);
419 if (r.IsInteger32()) {
420 AllowDeferredHandleDereference get_number;
421 DCHECK(literal->IsNumber());
422 __ li(scratch, Operand(static_cast<int32_t>(literal->Number())));
423 } else if (r.IsSmi()) {
424 DCHECK(constant->HasSmiValue());
425 __ li(scratch, Operand(Smi::FromInt(constant->Integer32Value())));
426 } else if (r.IsDouble()) {
427 Abort(kEmitLoadRegisterUnsupportedDoubleImmediate);
428 } else {
429 DCHECK(r.IsSmiOrTagged());
430 __ li(scratch, literal);
431 }
432 return scratch;
433 } else if (op->IsStackSlot()) {
434 __ lw(scratch, ToMemOperand(op));
435 return scratch;
436 }
437 UNREACHABLE();
438 return scratch;
439 }
440
441
ToDoubleRegister(LOperand * op) const442 DoubleRegister LCodeGen::ToDoubleRegister(LOperand* op) const {
443 DCHECK(op->IsDoubleRegister());
444 return ToDoubleRegister(op->index());
445 }
446
447
EmitLoadDoubleRegister(LOperand * op,FloatRegister flt_scratch,DoubleRegister dbl_scratch)448 DoubleRegister LCodeGen::EmitLoadDoubleRegister(LOperand* op,
449 FloatRegister flt_scratch,
450 DoubleRegister dbl_scratch) {
451 if (op->IsDoubleRegister()) {
452 return ToDoubleRegister(op->index());
453 } else if (op->IsConstantOperand()) {
454 LConstantOperand* const_op = LConstantOperand::cast(op);
455 HConstant* constant = chunk_->LookupConstant(const_op);
456 Handle<Object> literal = constant->handle(isolate());
457 Representation r = chunk_->LookupLiteralRepresentation(const_op);
458 if (r.IsInteger32()) {
459 DCHECK(literal->IsNumber());
460 __ li(at, Operand(static_cast<int32_t>(literal->Number())));
461 __ mtc1(at, flt_scratch);
462 __ cvt_d_w(dbl_scratch, flt_scratch);
463 return dbl_scratch;
464 } else if (r.IsDouble()) {
465 Abort(kUnsupportedDoubleImmediate);
466 } else if (r.IsTagged()) {
467 Abort(kUnsupportedTaggedImmediate);
468 }
469 } else if (op->IsStackSlot()) {
470 MemOperand mem_op = ToMemOperand(op);
471 __ ldc1(dbl_scratch, mem_op);
472 return dbl_scratch;
473 }
474 UNREACHABLE();
475 return dbl_scratch;
476 }
477
478
ToHandle(LConstantOperand * op) const479 Handle<Object> LCodeGen::ToHandle(LConstantOperand* op) const {
480 HConstant* constant = chunk_->LookupConstant(op);
481 DCHECK(chunk_->LookupLiteralRepresentation(op).IsSmiOrTagged());
482 return constant->handle(isolate());
483 }
484
485
IsInteger32(LConstantOperand * op) const486 bool LCodeGen::IsInteger32(LConstantOperand* op) const {
487 return chunk_->LookupLiteralRepresentation(op).IsSmiOrInteger32();
488 }
489
490
IsSmi(LConstantOperand * op) const491 bool LCodeGen::IsSmi(LConstantOperand* op) const {
492 return chunk_->LookupLiteralRepresentation(op).IsSmi();
493 }
494
495
ToInteger32(LConstantOperand * op) const496 int32_t LCodeGen::ToInteger32(LConstantOperand* op) const {
497 return ToRepresentation(op, Representation::Integer32());
498 }
499
500
ToRepresentation(LConstantOperand * op,const Representation & r) const501 int32_t LCodeGen::ToRepresentation(LConstantOperand* op,
502 const Representation& r) const {
503 HConstant* constant = chunk_->LookupConstant(op);
504 int32_t value = constant->Integer32Value();
505 if (r.IsInteger32()) return value;
506 DCHECK(r.IsSmiOrTagged());
507 return reinterpret_cast<int32_t>(Smi::FromInt(value));
508 }
509
510
ToSmi(LConstantOperand * op) const511 Smi* LCodeGen::ToSmi(LConstantOperand* op) const {
512 HConstant* constant = chunk_->LookupConstant(op);
513 return Smi::FromInt(constant->Integer32Value());
514 }
515
516
ToDouble(LConstantOperand * op) const517 double LCodeGen::ToDouble(LConstantOperand* op) const {
518 HConstant* constant = chunk_->LookupConstant(op);
519 DCHECK(constant->HasDoubleValue());
520 return constant->DoubleValue();
521 }
522
523
ToOperand(LOperand * op)524 Operand LCodeGen::ToOperand(LOperand* op) {
525 if (op->IsConstantOperand()) {
526 LConstantOperand* const_op = LConstantOperand::cast(op);
527 HConstant* constant = chunk()->LookupConstant(const_op);
528 Representation r = chunk_->LookupLiteralRepresentation(const_op);
529 if (r.IsSmi()) {
530 DCHECK(constant->HasSmiValue());
531 return Operand(Smi::FromInt(constant->Integer32Value()));
532 } else if (r.IsInteger32()) {
533 DCHECK(constant->HasInteger32Value());
534 return Operand(constant->Integer32Value());
535 } else if (r.IsDouble()) {
536 Abort(kToOperandUnsupportedDoubleImmediate);
537 }
538 DCHECK(r.IsTagged());
539 return Operand(constant->handle(isolate()));
540 } else if (op->IsRegister()) {
541 return Operand(ToRegister(op));
542 } else if (op->IsDoubleRegister()) {
543 Abort(kToOperandIsDoubleRegisterUnimplemented);
544 return Operand(0);
545 }
546 // Stack slots not implemented, use ToMemOperand instead.
547 UNREACHABLE();
548 return Operand(0);
549 }
550
551
ArgumentsOffsetWithoutFrame(int index)552 static int ArgumentsOffsetWithoutFrame(int index) {
553 DCHECK(index < 0);
554 return -(index + 1) * kPointerSize;
555 }
556
557
ToMemOperand(LOperand * op) const558 MemOperand LCodeGen::ToMemOperand(LOperand* op) const {
559 DCHECK(!op->IsRegister());
560 DCHECK(!op->IsDoubleRegister());
561 DCHECK(op->IsStackSlot() || op->IsDoubleStackSlot());
562 if (NeedsEagerFrame()) {
563 return MemOperand(fp, FrameSlotToFPOffset(op->index()));
564 } else {
565 // Retrieve parameter without eager stack-frame relative to the
566 // stack-pointer.
567 return MemOperand(sp, ArgumentsOffsetWithoutFrame(op->index()));
568 }
569 }
570
571
ToHighMemOperand(LOperand * op) const572 MemOperand LCodeGen::ToHighMemOperand(LOperand* op) const {
573 DCHECK(op->IsDoubleStackSlot());
574 if (NeedsEagerFrame()) {
575 return MemOperand(fp, FrameSlotToFPOffset(op->index()) + kPointerSize);
576 } else {
577 // Retrieve parameter without eager stack-frame relative to the
578 // stack-pointer.
579 return MemOperand(
580 sp, ArgumentsOffsetWithoutFrame(op->index()) + kPointerSize);
581 }
582 }
583
584
WriteTranslation(LEnvironment * environment,Translation * translation)585 void LCodeGen::WriteTranslation(LEnvironment* environment,
586 Translation* translation) {
587 if (environment == NULL) return;
588
589 // The translation includes one command per value in the environment.
590 int translation_size = environment->translation_size();
591
592 WriteTranslation(environment->outer(), translation);
593 WriteTranslationFrame(environment, translation);
594
595 int object_index = 0;
596 int dematerialized_index = 0;
597 for (int i = 0; i < translation_size; ++i) {
598 LOperand* value = environment->values()->at(i);
599 AddToTranslation(
600 environment, translation, value, environment->HasTaggedValueAt(i),
601 environment->HasUint32ValueAt(i), &object_index, &dematerialized_index);
602 }
603 }
604
605
AddToTranslation(LEnvironment * environment,Translation * translation,LOperand * op,bool is_tagged,bool is_uint32,int * object_index_pointer,int * dematerialized_index_pointer)606 void LCodeGen::AddToTranslation(LEnvironment* environment,
607 Translation* translation,
608 LOperand* op,
609 bool is_tagged,
610 bool is_uint32,
611 int* object_index_pointer,
612 int* dematerialized_index_pointer) {
613 if (op == LEnvironment::materialization_marker()) {
614 int object_index = (*object_index_pointer)++;
615 if (environment->ObjectIsDuplicateAt(object_index)) {
616 int dupe_of = environment->ObjectDuplicateOfAt(object_index);
617 translation->DuplicateObject(dupe_of);
618 return;
619 }
620 int object_length = environment->ObjectLengthAt(object_index);
621 if (environment->ObjectIsArgumentsAt(object_index)) {
622 translation->BeginArgumentsObject(object_length);
623 } else {
624 translation->BeginCapturedObject(object_length);
625 }
626 int dematerialized_index = *dematerialized_index_pointer;
627 int env_offset = environment->translation_size() + dematerialized_index;
628 *dematerialized_index_pointer += object_length;
629 for (int i = 0; i < object_length; ++i) {
630 LOperand* value = environment->values()->at(env_offset + i);
631 AddToTranslation(environment,
632 translation,
633 value,
634 environment->HasTaggedValueAt(env_offset + i),
635 environment->HasUint32ValueAt(env_offset + i),
636 object_index_pointer,
637 dematerialized_index_pointer);
638 }
639 return;
640 }
641
642 if (op->IsStackSlot()) {
643 int index = op->index();
644 if (is_tagged) {
645 translation->StoreStackSlot(index);
646 } else if (is_uint32) {
647 translation->StoreUint32StackSlot(index);
648 } else {
649 translation->StoreInt32StackSlot(index);
650 }
651 } else if (op->IsDoubleStackSlot()) {
652 int index = op->index();
653 translation->StoreDoubleStackSlot(index);
654 } else if (op->IsRegister()) {
655 Register reg = ToRegister(op);
656 if (is_tagged) {
657 translation->StoreRegister(reg);
658 } else if (is_uint32) {
659 translation->StoreUint32Register(reg);
660 } else {
661 translation->StoreInt32Register(reg);
662 }
663 } else if (op->IsDoubleRegister()) {
664 DoubleRegister reg = ToDoubleRegister(op);
665 translation->StoreDoubleRegister(reg);
666 } else if (op->IsConstantOperand()) {
667 HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
668 int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
669 translation->StoreLiteral(src_index);
670 } else {
671 UNREACHABLE();
672 }
673 }
674
675
CallCode(Handle<Code> code,RelocInfo::Mode mode,LInstruction * instr)676 void LCodeGen::CallCode(Handle<Code> code,
677 RelocInfo::Mode mode,
678 LInstruction* instr) {
679 CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
680 }
681
682
CallCodeGeneric(Handle<Code> code,RelocInfo::Mode mode,LInstruction * instr,SafepointMode safepoint_mode)683 void LCodeGen::CallCodeGeneric(Handle<Code> code,
684 RelocInfo::Mode mode,
685 LInstruction* instr,
686 SafepointMode safepoint_mode) {
687 DCHECK(instr != NULL);
688 __ Call(code, mode);
689 RecordSafepointWithLazyDeopt(instr, safepoint_mode);
690 }
691
692
CallRuntime(const Runtime::Function * function,int num_arguments,LInstruction * instr,SaveFPRegsMode save_doubles)693 void LCodeGen::CallRuntime(const Runtime::Function* function,
694 int num_arguments,
695 LInstruction* instr,
696 SaveFPRegsMode save_doubles) {
697 DCHECK(instr != NULL);
698
699 __ CallRuntime(function, num_arguments, save_doubles);
700
701 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
702 }
703
704
LoadContextFromDeferred(LOperand * context)705 void LCodeGen::LoadContextFromDeferred(LOperand* context) {
706 if (context->IsRegister()) {
707 __ Move(cp, ToRegister(context));
708 } else if (context->IsStackSlot()) {
709 __ lw(cp, ToMemOperand(context));
710 } else if (context->IsConstantOperand()) {
711 HConstant* constant =
712 chunk_->LookupConstant(LConstantOperand::cast(context));
713 __ li(cp, Handle<Object>::cast(constant->handle(isolate())));
714 } else {
715 UNREACHABLE();
716 }
717 }
718
719
CallRuntimeFromDeferred(Runtime::FunctionId id,int argc,LInstruction * instr,LOperand * context)720 void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
721 int argc,
722 LInstruction* instr,
723 LOperand* context) {
724 LoadContextFromDeferred(context);
725 __ CallRuntimeSaveDoubles(id);
726 RecordSafepointWithRegisters(
727 instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
728 }
729
730
RegisterEnvironmentForDeoptimization(LEnvironment * environment,Safepoint::DeoptMode mode)731 void LCodeGen::RegisterEnvironmentForDeoptimization(LEnvironment* environment,
732 Safepoint::DeoptMode mode) {
733 environment->set_has_been_used();
734 if (!environment->HasBeenRegistered()) {
735 // Physical stack frame layout:
736 // -x ............. -4 0 ..................................... y
737 // [incoming arguments] [spill slots] [pushed outgoing arguments]
738
739 // Layout of the environment:
740 // 0 ..................................................... size-1
741 // [parameters] [locals] [expression stack including arguments]
742
743 // Layout of the translation:
744 // 0 ........................................................ size - 1 + 4
745 // [expression stack including arguments] [locals] [4 words] [parameters]
746 // |>------------ translation_size ------------<|
747
748 int frame_count = 0;
749 int jsframe_count = 0;
750 for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
751 ++frame_count;
752 if (e->frame_type() == JS_FUNCTION) {
753 ++jsframe_count;
754 }
755 }
756 Translation translation(&translations_, frame_count, jsframe_count, zone());
757 WriteTranslation(environment, &translation);
758 int deoptimization_index = deoptimizations_.length();
759 int pc_offset = masm()->pc_offset();
760 environment->Register(deoptimization_index,
761 translation.index(),
762 (mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
763 deoptimizations_.Add(environment, zone());
764 }
765 }
766
DeoptimizeIf(Condition condition,LInstruction * instr,DeoptimizeReason deopt_reason,Deoptimizer::BailoutType bailout_type,Register src1,const Operand & src2)767 void LCodeGen::DeoptimizeIf(Condition condition, LInstruction* instr,
768 DeoptimizeReason deopt_reason,
769 Deoptimizer::BailoutType bailout_type,
770 Register src1, const Operand& src2) {
771 LEnvironment* environment = instr->environment();
772 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
773 DCHECK(environment->HasBeenRegistered());
774 int id = environment->deoptimization_index();
775 Address entry =
776 Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
777 if (entry == NULL) {
778 Abort(kBailoutWasNotPrepared);
779 return;
780 }
781
782 if (FLAG_deopt_every_n_times != 0 && !info()->IsStub()) {
783 Register scratch = scratch0();
784 ExternalReference count = ExternalReference::stress_deopt_count(isolate());
785 Label no_deopt;
786 __ Push(a1, scratch);
787 __ li(scratch, Operand(count));
788 __ lw(a1, MemOperand(scratch));
789 __ Subu(a1, a1, Operand(1));
790 __ Branch(&no_deopt, ne, a1, Operand(zero_reg));
791 __ li(a1, Operand(FLAG_deopt_every_n_times));
792 __ sw(a1, MemOperand(scratch));
793 __ Pop(a1, scratch);
794
795 __ Call(entry, RelocInfo::RUNTIME_ENTRY);
796 __ bind(&no_deopt);
797 __ sw(a1, MemOperand(scratch));
798 __ Pop(a1, scratch);
799 }
800
801 if (info()->ShouldTrapOnDeopt()) {
802 Label skip;
803 if (condition != al) {
804 __ Branch(&skip, NegateCondition(condition), src1, src2);
805 }
806 __ stop("trap_on_deopt");
807 __ bind(&skip);
808 }
809
810 Deoptimizer::DeoptInfo deopt_info = MakeDeoptInfo(instr, deopt_reason, id);
811
812 DCHECK(info()->IsStub() || frame_is_built_);
813 // Go through jump table if we need to handle condition, build frame, or
814 // restore caller doubles.
815 if (condition == al && frame_is_built_ &&
816 !info()->saves_caller_doubles()) {
817 DeoptComment(deopt_info);
818 __ Call(entry, RelocInfo::RUNTIME_ENTRY, condition, src1, src2);
819 } else {
820 Deoptimizer::JumpTableEntry table_entry(entry, deopt_info, bailout_type,
821 !frame_is_built_);
822 // We often have several deopts to the same entry, reuse the last
823 // jump entry if this is the case.
824 if (FLAG_trace_deopt || isolate()->is_profiling() ||
825 jump_table_.is_empty() ||
826 !table_entry.IsEquivalentTo(jump_table_.last())) {
827 jump_table_.Add(table_entry, zone());
828 }
829 __ Branch(&jump_table_.last().label, condition, src1, src2);
830 }
831 }
832
DeoptimizeIf(Condition condition,LInstruction * instr,DeoptimizeReason deopt_reason,Register src1,const Operand & src2)833 void LCodeGen::DeoptimizeIf(Condition condition, LInstruction* instr,
834 DeoptimizeReason deopt_reason, Register src1,
835 const Operand& src2) {
836 Deoptimizer::BailoutType bailout_type = info()->IsStub()
837 ? Deoptimizer::LAZY
838 : Deoptimizer::EAGER;
839 DeoptimizeIf(condition, instr, deopt_reason, bailout_type, src1, src2);
840 }
841
842
RecordSafepointWithLazyDeopt(LInstruction * instr,SafepointMode safepoint_mode)843 void LCodeGen::RecordSafepointWithLazyDeopt(
844 LInstruction* instr, SafepointMode safepoint_mode) {
845 if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
846 RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
847 } else {
848 DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
849 RecordSafepointWithRegisters(
850 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
851 }
852 }
853
854
RecordSafepoint(LPointerMap * pointers,Safepoint::Kind kind,int arguments,Safepoint::DeoptMode deopt_mode)855 void LCodeGen::RecordSafepoint(
856 LPointerMap* pointers,
857 Safepoint::Kind kind,
858 int arguments,
859 Safepoint::DeoptMode deopt_mode) {
860 DCHECK(expected_safepoint_kind_ == kind);
861
862 const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
863 Safepoint safepoint = safepoints_.DefineSafepoint(masm(),
864 kind, arguments, deopt_mode);
865 for (int i = 0; i < operands->length(); i++) {
866 LOperand* pointer = operands->at(i);
867 if (pointer->IsStackSlot()) {
868 safepoint.DefinePointerSlot(pointer->index(), zone());
869 } else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
870 safepoint.DefinePointerRegister(ToRegister(pointer), zone());
871 }
872 }
873 }
874
875
RecordSafepoint(LPointerMap * pointers,Safepoint::DeoptMode deopt_mode)876 void LCodeGen::RecordSafepoint(LPointerMap* pointers,
877 Safepoint::DeoptMode deopt_mode) {
878 RecordSafepoint(pointers, Safepoint::kSimple, 0, deopt_mode);
879 }
880
881
RecordSafepoint(Safepoint::DeoptMode deopt_mode)882 void LCodeGen::RecordSafepoint(Safepoint::DeoptMode deopt_mode) {
883 LPointerMap empty_pointers(zone());
884 RecordSafepoint(&empty_pointers, deopt_mode);
885 }
886
887
RecordSafepointWithRegisters(LPointerMap * pointers,int arguments,Safepoint::DeoptMode deopt_mode)888 void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
889 int arguments,
890 Safepoint::DeoptMode deopt_mode) {
891 RecordSafepoint(
892 pointers, Safepoint::kWithRegisters, arguments, deopt_mode);
893 }
894
895
LabelType(LLabel * label)896 static const char* LabelType(LLabel* label) {
897 if (label->is_loop_header()) return " (loop header)";
898 if (label->is_osr_entry()) return " (OSR entry)";
899 return "";
900 }
901
902
DoLabel(LLabel * label)903 void LCodeGen::DoLabel(LLabel* label) {
904 Comment(";;; <@%d,#%d> -------------------- B%d%s --------------------",
905 current_instruction_,
906 label->hydrogen_value()->id(),
907 label->block_id(),
908 LabelType(label));
909 __ bind(label->label());
910 current_block_ = label->block_id();
911 DoGap(label);
912 }
913
914
DoParallelMove(LParallelMove * move)915 void LCodeGen::DoParallelMove(LParallelMove* move) {
916 resolver_.Resolve(move);
917 }
918
919
DoGap(LGap * gap)920 void LCodeGen::DoGap(LGap* gap) {
921 for (int i = LGap::FIRST_INNER_POSITION;
922 i <= LGap::LAST_INNER_POSITION;
923 i++) {
924 LGap::InnerPosition inner_pos = static_cast<LGap::InnerPosition>(i);
925 LParallelMove* move = gap->GetParallelMove(inner_pos);
926 if (move != NULL) DoParallelMove(move);
927 }
928 }
929
930
DoInstructionGap(LInstructionGap * instr)931 void LCodeGen::DoInstructionGap(LInstructionGap* instr) {
932 DoGap(instr);
933 }
934
935
DoParameter(LParameter * instr)936 void LCodeGen::DoParameter(LParameter* instr) {
937 // Nothing to do.
938 }
939
940
DoUnknownOSRValue(LUnknownOSRValue * instr)941 void LCodeGen::DoUnknownOSRValue(LUnknownOSRValue* instr) {
942 GenerateOsrPrologue();
943 }
944
945
DoModByPowerOf2I(LModByPowerOf2I * instr)946 void LCodeGen::DoModByPowerOf2I(LModByPowerOf2I* instr) {
947 Register dividend = ToRegister(instr->dividend());
948 int32_t divisor = instr->divisor();
949 DCHECK(dividend.is(ToRegister(instr->result())));
950
951 // Theoretically, a variation of the branch-free code for integer division by
952 // a power of 2 (calculating the remainder via an additional multiplication
953 // (which gets simplified to an 'and') and subtraction) should be faster, and
954 // this is exactly what GCC and clang emit. Nevertheless, benchmarks seem to
955 // indicate that positive dividends are heavily favored, so the branching
956 // version performs better.
957 HMod* hmod = instr->hydrogen();
958 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
959 Label dividend_is_not_negative, done;
960
961 if (hmod->CheckFlag(HValue::kLeftCanBeNegative)) {
962 __ Branch(÷nd_is_not_negative, ge, dividend, Operand(zero_reg));
963 // Note: The code below even works when right contains kMinInt.
964 __ subu(dividend, zero_reg, dividend);
965 __ And(dividend, dividend, Operand(mask));
966 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
967 DeoptimizeIf(eq, instr, DeoptimizeReason::kMinusZero, dividend,
968 Operand(zero_reg));
969 }
970 __ Branch(USE_DELAY_SLOT, &done);
971 __ subu(dividend, zero_reg, dividend);
972 }
973
974 __ bind(÷nd_is_not_negative);
975 __ And(dividend, dividend, Operand(mask));
976 __ bind(&done);
977 }
978
979
DoModByConstI(LModByConstI * instr)980 void LCodeGen::DoModByConstI(LModByConstI* instr) {
981 Register dividend = ToRegister(instr->dividend());
982 int32_t divisor = instr->divisor();
983 Register result = ToRegister(instr->result());
984 DCHECK(!dividend.is(result));
985
986 if (divisor == 0) {
987 DeoptimizeIf(al, instr);
988 return;
989 }
990
991 __ TruncatingDiv(result, dividend, Abs(divisor));
992 __ Mul(result, result, Operand(Abs(divisor)));
993 __ Subu(result, dividend, Operand(result));
994
995 // Check for negative zero.
996 HMod* hmod = instr->hydrogen();
997 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
998 Label remainder_not_zero;
999 __ Branch(&remainder_not_zero, ne, result, Operand(zero_reg));
1000 DeoptimizeIf(lt, instr, DeoptimizeReason::kMinusZero, dividend,
1001 Operand(zero_reg));
1002 __ bind(&remainder_not_zero);
1003 }
1004 }
1005
1006
DoModI(LModI * instr)1007 void LCodeGen::DoModI(LModI* instr) {
1008 HMod* hmod = instr->hydrogen();
1009 const Register left_reg = ToRegister(instr->left());
1010 const Register right_reg = ToRegister(instr->right());
1011 const Register result_reg = ToRegister(instr->result());
1012
1013 // div runs in the background while we check for special cases.
1014 __ Mod(result_reg, left_reg, right_reg);
1015
1016 Label done;
1017 // Check for x % 0, we have to deopt in this case because we can't return a
1018 // NaN.
1019 if (hmod->CheckFlag(HValue::kCanBeDivByZero)) {
1020 DeoptimizeIf(eq, instr, DeoptimizeReason::kDivisionByZero, right_reg,
1021 Operand(zero_reg));
1022 }
1023
1024 // Check for kMinInt % -1, div will return kMinInt, which is not what we
1025 // want. We have to deopt if we care about -0, because we can't return that.
1026 if (hmod->CheckFlag(HValue::kCanOverflow)) {
1027 Label no_overflow_possible;
1028 __ Branch(&no_overflow_possible, ne, left_reg, Operand(kMinInt));
1029 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1030 DeoptimizeIf(eq, instr, DeoptimizeReason::kMinusZero, right_reg,
1031 Operand(-1));
1032 } else {
1033 __ Branch(&no_overflow_possible, ne, right_reg, Operand(-1));
1034 __ Branch(USE_DELAY_SLOT, &done);
1035 __ mov(result_reg, zero_reg);
1036 }
1037 __ bind(&no_overflow_possible);
1038 }
1039
1040 // If we care about -0, test if the dividend is <0 and the result is 0.
1041 __ Branch(&done, ge, left_reg, Operand(zero_reg));
1042 if (hmod->CheckFlag(HValue::kBailoutOnMinusZero)) {
1043 DeoptimizeIf(eq, instr, DeoptimizeReason::kMinusZero, result_reg,
1044 Operand(zero_reg));
1045 }
1046 __ bind(&done);
1047 }
1048
1049
DoDivByPowerOf2I(LDivByPowerOf2I * instr)1050 void LCodeGen::DoDivByPowerOf2I(LDivByPowerOf2I* instr) {
1051 Register dividend = ToRegister(instr->dividend());
1052 int32_t divisor = instr->divisor();
1053 Register result = ToRegister(instr->result());
1054 DCHECK(divisor == kMinInt || base::bits::IsPowerOfTwo32(Abs(divisor)));
1055 DCHECK(!result.is(dividend));
1056
1057 // Check for (0 / -x) that will produce negative zero.
1058 HDiv* hdiv = instr->hydrogen();
1059 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1060 DeoptimizeIf(eq, instr, DeoptimizeReason::kMinusZero, dividend,
1061 Operand(zero_reg));
1062 }
1063 // Check for (kMinInt / -1).
1064 if (hdiv->CheckFlag(HValue::kCanOverflow) && divisor == -1) {
1065 DeoptimizeIf(eq, instr, DeoptimizeReason::kOverflow, dividend,
1066 Operand(kMinInt));
1067 }
1068 // Deoptimize if remainder will not be 0.
1069 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32) &&
1070 divisor != 1 && divisor != -1) {
1071 int32_t mask = divisor < 0 ? -(divisor + 1) : (divisor - 1);
1072 __ And(at, dividend, Operand(mask));
1073 DeoptimizeIf(ne, instr, DeoptimizeReason::kLostPrecision, at,
1074 Operand(zero_reg));
1075 }
1076
1077 if (divisor == -1) { // Nice shortcut, not needed for correctness.
1078 __ Subu(result, zero_reg, dividend);
1079 return;
1080 }
1081 uint16_t shift = WhichPowerOf2Abs(divisor);
1082 if (shift == 0) {
1083 __ Move(result, dividend);
1084 } else if (shift == 1) {
1085 __ srl(result, dividend, 31);
1086 __ Addu(result, dividend, Operand(result));
1087 } else {
1088 __ sra(result, dividend, 31);
1089 __ srl(result, result, 32 - shift);
1090 __ Addu(result, dividend, Operand(result));
1091 }
1092 if (shift > 0) __ sra(result, result, shift);
1093 if (divisor < 0) __ Subu(result, zero_reg, result);
1094 }
1095
1096
DoDivByConstI(LDivByConstI * instr)1097 void LCodeGen::DoDivByConstI(LDivByConstI* instr) {
1098 Register dividend = ToRegister(instr->dividend());
1099 int32_t divisor = instr->divisor();
1100 Register result = ToRegister(instr->result());
1101 DCHECK(!dividend.is(result));
1102
1103 if (divisor == 0) {
1104 DeoptimizeIf(al, instr);
1105 return;
1106 }
1107
1108 // Check for (0 / -x) that will produce negative zero.
1109 HDiv* hdiv = instr->hydrogen();
1110 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1111 DeoptimizeIf(eq, instr, DeoptimizeReason::kMinusZero, dividend,
1112 Operand(zero_reg));
1113 }
1114
1115 __ TruncatingDiv(result, dividend, Abs(divisor));
1116 if (divisor < 0) __ Subu(result, zero_reg, result);
1117
1118 if (!hdiv->CheckFlag(HInstruction::kAllUsesTruncatingToInt32)) {
1119 __ Mul(scratch0(), result, Operand(divisor));
1120 __ Subu(scratch0(), scratch0(), dividend);
1121 DeoptimizeIf(ne, instr, DeoptimizeReason::kLostPrecision, scratch0(),
1122 Operand(zero_reg));
1123 }
1124 }
1125
1126
1127 // TODO(svenpanne) Refactor this to avoid code duplication with DoFlooringDivI.
DoDivI(LDivI * instr)1128 void LCodeGen::DoDivI(LDivI* instr) {
1129 HBinaryOperation* hdiv = instr->hydrogen();
1130 Register dividend = ToRegister(instr->dividend());
1131 Register divisor = ToRegister(instr->divisor());
1132 const Register result = ToRegister(instr->result());
1133 Register remainder = ToRegister(instr->temp());
1134
1135 // On MIPS div is asynchronous - it will run in the background while we
1136 // check for special cases.
1137 __ Div(remainder, result, dividend, divisor);
1138
1139 // Check for x / 0.
1140 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1141 DeoptimizeIf(eq, instr, DeoptimizeReason::kDivisionByZero, divisor,
1142 Operand(zero_reg));
1143 }
1144
1145 // Check for (0 / -x) that will produce negative zero.
1146 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1147 Label left_not_zero;
1148 __ Branch(&left_not_zero, ne, dividend, Operand(zero_reg));
1149 DeoptimizeIf(lt, instr, DeoptimizeReason::kMinusZero, divisor,
1150 Operand(zero_reg));
1151 __ bind(&left_not_zero);
1152 }
1153
1154 // Check for (kMinInt / -1).
1155 if (hdiv->CheckFlag(HValue::kCanOverflow) &&
1156 !hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1157 Label left_not_min_int;
1158 __ Branch(&left_not_min_int, ne, dividend, Operand(kMinInt));
1159 DeoptimizeIf(eq, instr, DeoptimizeReason::kOverflow, divisor, Operand(-1));
1160 __ bind(&left_not_min_int);
1161 }
1162
1163 if (!hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1164 DeoptimizeIf(ne, instr, DeoptimizeReason::kLostPrecision, remainder,
1165 Operand(zero_reg));
1166 }
1167 }
1168
1169
DoMultiplyAddD(LMultiplyAddD * instr)1170 void LCodeGen::DoMultiplyAddD(LMultiplyAddD* instr) {
1171 DoubleRegister addend = ToDoubleRegister(instr->addend());
1172 DoubleRegister multiplier = ToDoubleRegister(instr->multiplier());
1173 DoubleRegister multiplicand = ToDoubleRegister(instr->multiplicand());
1174
1175 // This is computed in-place.
1176 DCHECK(addend.is(ToDoubleRegister(instr->result())));
1177
1178 __ madd_d(addend, addend, multiplier, multiplicand);
1179 }
1180
1181
DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I * instr)1182 void LCodeGen::DoFlooringDivByPowerOf2I(LFlooringDivByPowerOf2I* instr) {
1183 Register dividend = ToRegister(instr->dividend());
1184 Register result = ToRegister(instr->result());
1185 int32_t divisor = instr->divisor();
1186 Register scratch = result.is(dividend) ? scratch0() : dividend;
1187 DCHECK(!result.is(dividend) || !scratch.is(dividend));
1188
1189 // If the divisor is 1, return the dividend.
1190 if (divisor == 1) {
1191 __ Move(result, dividend);
1192 return;
1193 }
1194
1195 // If the divisor is positive, things are easy: There can be no deopts and we
1196 // can simply do an arithmetic right shift.
1197 uint16_t shift = WhichPowerOf2Abs(divisor);
1198 if (divisor > 1) {
1199 __ sra(result, dividend, shift);
1200 return;
1201 }
1202
1203 // If the divisor is negative, we have to negate and handle edge cases.
1204
1205 // dividend can be the same register as result so save the value of it
1206 // for checking overflow.
1207 __ Move(scratch, dividend);
1208
1209 __ Subu(result, zero_reg, dividend);
1210 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
1211 DeoptimizeIf(eq, instr, DeoptimizeReason::kMinusZero, result,
1212 Operand(zero_reg));
1213 }
1214
1215 // Dividing by -1 is basically negation, unless we overflow.
1216 __ Xor(scratch, scratch, result);
1217 if (divisor == -1) {
1218 if (instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1219 DeoptimizeIf(ge, instr, DeoptimizeReason::kOverflow, scratch,
1220 Operand(zero_reg));
1221 }
1222 return;
1223 }
1224
1225 // If the negation could not overflow, simply shifting is OK.
1226 if (!instr->hydrogen()->CheckFlag(HValue::kLeftCanBeMinInt)) {
1227 __ sra(result, result, shift);
1228 return;
1229 }
1230
1231 Label no_overflow, done;
1232 __ Branch(&no_overflow, lt, scratch, Operand(zero_reg));
1233 __ li(result, Operand(kMinInt / divisor));
1234 __ Branch(&done);
1235 __ bind(&no_overflow);
1236 __ sra(result, result, shift);
1237 __ bind(&done);
1238 }
1239
1240
DoFlooringDivByConstI(LFlooringDivByConstI * instr)1241 void LCodeGen::DoFlooringDivByConstI(LFlooringDivByConstI* instr) {
1242 Register dividend = ToRegister(instr->dividend());
1243 int32_t divisor = instr->divisor();
1244 Register result = ToRegister(instr->result());
1245 DCHECK(!dividend.is(result));
1246
1247 if (divisor == 0) {
1248 DeoptimizeIf(al, instr);
1249 return;
1250 }
1251
1252 // Check for (0 / -x) that will produce negative zero.
1253 HMathFloorOfDiv* hdiv = instr->hydrogen();
1254 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero) && divisor < 0) {
1255 DeoptimizeIf(eq, instr, DeoptimizeReason::kMinusZero, dividend,
1256 Operand(zero_reg));
1257 }
1258
1259 // Easy case: We need no dynamic check for the dividend and the flooring
1260 // division is the same as the truncating division.
1261 if ((divisor > 0 && !hdiv->CheckFlag(HValue::kLeftCanBeNegative)) ||
1262 (divisor < 0 && !hdiv->CheckFlag(HValue::kLeftCanBePositive))) {
1263 __ TruncatingDiv(result, dividend, Abs(divisor));
1264 if (divisor < 0) __ Subu(result, zero_reg, result);
1265 return;
1266 }
1267
1268 // In the general case we may need to adjust before and after the truncating
1269 // division to get a flooring division.
1270 Register temp = ToRegister(instr->temp());
1271 DCHECK(!temp.is(dividend) && !temp.is(result));
1272 Label needs_adjustment, done;
1273 __ Branch(&needs_adjustment, divisor > 0 ? lt : gt,
1274 dividend, Operand(zero_reg));
1275 __ TruncatingDiv(result, dividend, Abs(divisor));
1276 if (divisor < 0) __ Subu(result, zero_reg, result);
1277 __ jmp(&done);
1278 __ bind(&needs_adjustment);
1279 __ Addu(temp, dividend, Operand(divisor > 0 ? 1 : -1));
1280 __ TruncatingDiv(result, temp, Abs(divisor));
1281 if (divisor < 0) __ Subu(result, zero_reg, result);
1282 __ Subu(result, result, Operand(1));
1283 __ bind(&done);
1284 }
1285
1286
1287 // TODO(svenpanne) Refactor this to avoid code duplication with DoDivI.
DoFlooringDivI(LFlooringDivI * instr)1288 void LCodeGen::DoFlooringDivI(LFlooringDivI* instr) {
1289 HBinaryOperation* hdiv = instr->hydrogen();
1290 Register dividend = ToRegister(instr->dividend());
1291 Register divisor = ToRegister(instr->divisor());
1292 const Register result = ToRegister(instr->result());
1293 Register remainder = scratch0();
1294 // On MIPS div is asynchronous - it will run in the background while we
1295 // check for special cases.
1296 __ Div(remainder, result, dividend, divisor);
1297
1298 // Check for x / 0.
1299 if (hdiv->CheckFlag(HValue::kCanBeDivByZero)) {
1300 DeoptimizeIf(eq, instr, DeoptimizeReason::kDivisionByZero, divisor,
1301 Operand(zero_reg));
1302 }
1303
1304 // Check for (0 / -x) that will produce negative zero.
1305 if (hdiv->CheckFlag(HValue::kBailoutOnMinusZero)) {
1306 Label left_not_zero;
1307 __ Branch(&left_not_zero, ne, dividend, Operand(zero_reg));
1308 DeoptimizeIf(lt, instr, DeoptimizeReason::kMinusZero, divisor,
1309 Operand(zero_reg));
1310 __ bind(&left_not_zero);
1311 }
1312
1313 // Check for (kMinInt / -1).
1314 if (hdiv->CheckFlag(HValue::kCanOverflow) &&
1315 !hdiv->CheckFlag(HValue::kAllUsesTruncatingToInt32)) {
1316 Label left_not_min_int;
1317 __ Branch(&left_not_min_int, ne, dividend, Operand(kMinInt));
1318 DeoptimizeIf(eq, instr, DeoptimizeReason::kOverflow, divisor, Operand(-1));
1319 __ bind(&left_not_min_int);
1320 }
1321
1322 // We performed a truncating division. Correct the result if necessary.
1323 Label done;
1324 __ Branch(&done, eq, remainder, Operand(zero_reg), USE_DELAY_SLOT);
1325 __ Xor(remainder, remainder, Operand(divisor));
1326 __ Branch(&done, ge, remainder, Operand(zero_reg));
1327 __ Subu(result, result, Operand(1));
1328 __ bind(&done);
1329 }
1330
1331
DoMulI(LMulI * instr)1332 void LCodeGen::DoMulI(LMulI* instr) {
1333 Register scratch = scratch0();
1334 Register result = ToRegister(instr->result());
1335 // Note that result may alias left.
1336 Register left = ToRegister(instr->left());
1337 LOperand* right_op = instr->right();
1338
1339 bool bailout_on_minus_zero =
1340 instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero);
1341 bool overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
1342
1343 if (right_op->IsConstantOperand()) {
1344 int32_t constant = ToInteger32(LConstantOperand::cast(right_op));
1345
1346 if (bailout_on_minus_zero && (constant < 0)) {
1347 // The case of a null constant will be handled separately.
1348 // If constant is negative and left is null, the result should be -0.
1349 DeoptimizeIf(eq, instr, DeoptimizeReason::kMinusZero, left,
1350 Operand(zero_reg));
1351 }
1352
1353 switch (constant) {
1354 case -1:
1355 if (overflow) {
1356 Label no_overflow;
1357 __ SubBranchNoOvf(result, zero_reg, Operand(left), &no_overflow);
1358 DeoptimizeIf(al, instr);
1359 __ bind(&no_overflow);
1360 } else {
1361 __ Subu(result, zero_reg, left);
1362 }
1363 break;
1364 case 0:
1365 if (bailout_on_minus_zero) {
1366 // If left is strictly negative and the constant is null, the
1367 // result is -0. Deoptimize if required, otherwise return 0.
1368 DeoptimizeIf(lt, instr, DeoptimizeReason::kMinusZero, left,
1369 Operand(zero_reg));
1370 }
1371 __ mov(result, zero_reg);
1372 break;
1373 case 1:
1374 // Nothing to do.
1375 __ Move(result, left);
1376 break;
1377 default:
1378 // Multiplying by powers of two and powers of two plus or minus
1379 // one can be done faster with shifted operands.
1380 // For other constants we emit standard code.
1381 int32_t mask = constant >> 31;
1382 uint32_t constant_abs = (constant + mask) ^ mask;
1383
1384 if (base::bits::IsPowerOfTwo32(constant_abs)) {
1385 int32_t shift = WhichPowerOf2(constant_abs);
1386 __ sll(result, left, shift);
1387 // Correct the sign of the result if the constant is negative.
1388 if (constant < 0) __ Subu(result, zero_reg, result);
1389 } else if (base::bits::IsPowerOfTwo32(constant_abs - 1)) {
1390 int32_t shift = WhichPowerOf2(constant_abs - 1);
1391 __ Lsa(result, left, left, shift);
1392 // Correct the sign of the result if the constant is negative.
1393 if (constant < 0) __ Subu(result, zero_reg, result);
1394 } else if (base::bits::IsPowerOfTwo32(constant_abs + 1)) {
1395 int32_t shift = WhichPowerOf2(constant_abs + 1);
1396 __ sll(scratch, left, shift);
1397 __ Subu(result, scratch, left);
1398 // Correct the sign of the result if the constant is negative.
1399 if (constant < 0) __ Subu(result, zero_reg, result);
1400 } else {
1401 // Generate standard code.
1402 __ li(at, constant);
1403 __ Mul(result, left, at);
1404 }
1405 }
1406
1407 } else {
1408 DCHECK(right_op->IsRegister());
1409 Register right = ToRegister(right_op);
1410
1411 if (overflow) {
1412 // hi:lo = left * right.
1413 if (instr->hydrogen()->representation().IsSmi()) {
1414 __ SmiUntag(result, left);
1415 __ Mul(scratch, result, result, right);
1416 } else {
1417 __ Mul(scratch, result, left, right);
1418 }
1419 __ sra(at, result, 31);
1420 DeoptimizeIf(ne, instr, DeoptimizeReason::kOverflow, scratch,
1421 Operand(at));
1422 } else {
1423 if (instr->hydrogen()->representation().IsSmi()) {
1424 __ SmiUntag(result, left);
1425 __ Mul(result, result, right);
1426 } else {
1427 __ Mul(result, left, right);
1428 }
1429 }
1430
1431 if (bailout_on_minus_zero) {
1432 Label done;
1433 __ Xor(at, left, right);
1434 __ Branch(&done, ge, at, Operand(zero_reg));
1435 // Bail out if the result is minus zero.
1436 DeoptimizeIf(eq, instr, DeoptimizeReason::kMinusZero, result,
1437 Operand(zero_reg));
1438 __ bind(&done);
1439 }
1440 }
1441 }
1442
1443
DoBitI(LBitI * instr)1444 void LCodeGen::DoBitI(LBitI* instr) {
1445 LOperand* left_op = instr->left();
1446 LOperand* right_op = instr->right();
1447 DCHECK(left_op->IsRegister());
1448 Register left = ToRegister(left_op);
1449 Register result = ToRegister(instr->result());
1450 Operand right(no_reg);
1451
1452 if (right_op->IsStackSlot()) {
1453 right = Operand(EmitLoadRegister(right_op, at));
1454 } else {
1455 DCHECK(right_op->IsRegister() || right_op->IsConstantOperand());
1456 right = ToOperand(right_op);
1457 }
1458
1459 switch (instr->op()) {
1460 case Token::BIT_AND:
1461 __ And(result, left, right);
1462 break;
1463 case Token::BIT_OR:
1464 __ Or(result, left, right);
1465 break;
1466 case Token::BIT_XOR:
1467 if (right_op->IsConstantOperand() && right.immediate() == int32_t(~0)) {
1468 __ Nor(result, zero_reg, left);
1469 } else {
1470 __ Xor(result, left, right);
1471 }
1472 break;
1473 default:
1474 UNREACHABLE();
1475 break;
1476 }
1477 }
1478
1479
DoShiftI(LShiftI * instr)1480 void LCodeGen::DoShiftI(LShiftI* instr) {
1481 // Both 'left' and 'right' are "used at start" (see LCodeGen::DoShift), so
1482 // result may alias either of them.
1483 LOperand* right_op = instr->right();
1484 Register left = ToRegister(instr->left());
1485 Register result = ToRegister(instr->result());
1486 Register scratch = scratch0();
1487
1488 if (right_op->IsRegister()) {
1489 // No need to mask the right operand on MIPS, it is built into the variable
1490 // shift instructions.
1491 switch (instr->op()) {
1492 case Token::ROR:
1493 __ Ror(result, left, Operand(ToRegister(right_op)));
1494 break;
1495 case Token::SAR:
1496 __ srav(result, left, ToRegister(right_op));
1497 break;
1498 case Token::SHR:
1499 __ srlv(result, left, ToRegister(right_op));
1500 if (instr->can_deopt()) {
1501 DeoptimizeIf(lt, instr, DeoptimizeReason::kNegativeValue, result,
1502 Operand(zero_reg));
1503 }
1504 break;
1505 case Token::SHL:
1506 __ sllv(result, left, ToRegister(right_op));
1507 break;
1508 default:
1509 UNREACHABLE();
1510 break;
1511 }
1512 } else {
1513 // Mask the right_op operand.
1514 int value = ToInteger32(LConstantOperand::cast(right_op));
1515 uint8_t shift_count = static_cast<uint8_t>(value & 0x1F);
1516 switch (instr->op()) {
1517 case Token::ROR:
1518 if (shift_count != 0) {
1519 __ Ror(result, left, Operand(shift_count));
1520 } else {
1521 __ Move(result, left);
1522 }
1523 break;
1524 case Token::SAR:
1525 if (shift_count != 0) {
1526 __ sra(result, left, shift_count);
1527 } else {
1528 __ Move(result, left);
1529 }
1530 break;
1531 case Token::SHR:
1532 if (shift_count != 0) {
1533 __ srl(result, left, shift_count);
1534 } else {
1535 if (instr->can_deopt()) {
1536 __ And(at, left, Operand(0x80000000));
1537 DeoptimizeIf(ne, instr, DeoptimizeReason::kNegativeValue, at,
1538 Operand(zero_reg));
1539 }
1540 __ Move(result, left);
1541 }
1542 break;
1543 case Token::SHL:
1544 if (shift_count != 0) {
1545 if (instr->hydrogen_value()->representation().IsSmi() &&
1546 instr->can_deopt()) {
1547 if (shift_count != 1) {
1548 __ sll(result, left, shift_count - 1);
1549 __ SmiTagCheckOverflow(result, result, scratch);
1550 } else {
1551 __ SmiTagCheckOverflow(result, left, scratch);
1552 }
1553 DeoptimizeIf(lt, instr, DeoptimizeReason::kOverflow, scratch,
1554 Operand(zero_reg));
1555 } else {
1556 __ sll(result, left, shift_count);
1557 }
1558 } else {
1559 __ Move(result, left);
1560 }
1561 break;
1562 default:
1563 UNREACHABLE();
1564 break;
1565 }
1566 }
1567 }
1568
1569
DoSubI(LSubI * instr)1570 void LCodeGen::DoSubI(LSubI* instr) {
1571 LOperand* left = instr->left();
1572 LOperand* right = instr->right();
1573 LOperand* result = instr->result();
1574 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
1575
1576 if (!can_overflow) {
1577 if (right->IsStackSlot()) {
1578 Register right_reg = EmitLoadRegister(right, at);
1579 __ Subu(ToRegister(result), ToRegister(left), Operand(right_reg));
1580 } else {
1581 DCHECK(right->IsRegister() || right->IsConstantOperand());
1582 __ Subu(ToRegister(result), ToRegister(left), ToOperand(right));
1583 }
1584 } else { // can_overflow.
1585 Register scratch = scratch0();
1586 Label no_overflow_label;
1587 if (right->IsStackSlot()) {
1588 Register right_reg = EmitLoadRegister(right, scratch);
1589 __ SubBranchNoOvf(ToRegister(result), ToRegister(left),
1590 Operand(right_reg), &no_overflow_label);
1591 } else {
1592 DCHECK(right->IsRegister() || right->IsConstantOperand());
1593 __ SubBranchNoOvf(ToRegister(result), ToRegister(left), ToOperand(right),
1594 &no_overflow_label, scratch);
1595 }
1596 DeoptimizeIf(al, instr);
1597 __ bind(&no_overflow_label);
1598 }
1599 }
1600
1601
DoConstantI(LConstantI * instr)1602 void LCodeGen::DoConstantI(LConstantI* instr) {
1603 __ li(ToRegister(instr->result()), Operand(instr->value()));
1604 }
1605
1606
DoConstantS(LConstantS * instr)1607 void LCodeGen::DoConstantS(LConstantS* instr) {
1608 __ li(ToRegister(instr->result()), Operand(instr->value()));
1609 }
1610
1611
DoConstantD(LConstantD * instr)1612 void LCodeGen::DoConstantD(LConstantD* instr) {
1613 DCHECK(instr->result()->IsDoubleRegister());
1614 DoubleRegister result = ToDoubleRegister(instr->result());
1615 double v = instr->value();
1616 __ Move(result, v);
1617 }
1618
1619
DoConstantE(LConstantE * instr)1620 void LCodeGen::DoConstantE(LConstantE* instr) {
1621 __ li(ToRegister(instr->result()), Operand(instr->value()));
1622 }
1623
1624
DoConstantT(LConstantT * instr)1625 void LCodeGen::DoConstantT(LConstantT* instr) {
1626 Handle<Object> object = instr->value(isolate());
1627 AllowDeferredHandleDereference smi_check;
1628 __ li(ToRegister(instr->result()), object);
1629 }
1630
1631
BuildSeqStringOperand(Register string,LOperand * index,String::Encoding encoding)1632 MemOperand LCodeGen::BuildSeqStringOperand(Register string,
1633 LOperand* index,
1634 String::Encoding encoding) {
1635 if (index->IsConstantOperand()) {
1636 int offset = ToInteger32(LConstantOperand::cast(index));
1637 if (encoding == String::TWO_BYTE_ENCODING) {
1638 offset *= kUC16Size;
1639 }
1640 STATIC_ASSERT(kCharSize == 1);
1641 return FieldMemOperand(string, SeqString::kHeaderSize + offset);
1642 }
1643 Register scratch = scratch0();
1644 DCHECK(!scratch.is(string));
1645 DCHECK(!scratch.is(ToRegister(index)));
1646 if (encoding == String::ONE_BYTE_ENCODING) {
1647 __ Addu(scratch, string, ToRegister(index));
1648 } else {
1649 STATIC_ASSERT(kUC16Size == 2);
1650 __ sll(scratch, ToRegister(index), 1);
1651 __ Addu(scratch, string, scratch);
1652 }
1653 return FieldMemOperand(scratch, SeqString::kHeaderSize);
1654 }
1655
1656
DoSeqStringGetChar(LSeqStringGetChar * instr)1657 void LCodeGen::DoSeqStringGetChar(LSeqStringGetChar* instr) {
1658 String::Encoding encoding = instr->hydrogen()->encoding();
1659 Register string = ToRegister(instr->string());
1660 Register result = ToRegister(instr->result());
1661
1662 if (FLAG_debug_code) {
1663 Register scratch = scratch0();
1664 __ lw(scratch, FieldMemOperand(string, HeapObject::kMapOffset));
1665 __ lbu(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
1666
1667 __ And(scratch, scratch,
1668 Operand(kStringRepresentationMask | kStringEncodingMask));
1669 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1670 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1671 __ Subu(at, scratch, Operand(encoding == String::ONE_BYTE_ENCODING
1672 ? one_byte_seq_type : two_byte_seq_type));
1673 __ Check(eq, kUnexpectedStringType, at, Operand(zero_reg));
1674 }
1675
1676 MemOperand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1677 if (encoding == String::ONE_BYTE_ENCODING) {
1678 __ lbu(result, operand);
1679 } else {
1680 __ lhu(result, operand);
1681 }
1682 }
1683
1684
DoSeqStringSetChar(LSeqStringSetChar * instr)1685 void LCodeGen::DoSeqStringSetChar(LSeqStringSetChar* instr) {
1686 String::Encoding encoding = instr->hydrogen()->encoding();
1687 Register string = ToRegister(instr->string());
1688 Register value = ToRegister(instr->value());
1689
1690 if (FLAG_debug_code) {
1691 Register scratch = scratch0();
1692 Register index = ToRegister(instr->index());
1693 static const uint32_t one_byte_seq_type = kSeqStringTag | kOneByteStringTag;
1694 static const uint32_t two_byte_seq_type = kSeqStringTag | kTwoByteStringTag;
1695 int encoding_mask =
1696 instr->hydrogen()->encoding() == String::ONE_BYTE_ENCODING
1697 ? one_byte_seq_type : two_byte_seq_type;
1698 __ EmitSeqStringSetCharCheck(string, index, value, scratch, encoding_mask);
1699 }
1700
1701 MemOperand operand = BuildSeqStringOperand(string, instr->index(), encoding);
1702 if (encoding == String::ONE_BYTE_ENCODING) {
1703 __ sb(value, operand);
1704 } else {
1705 __ sh(value, operand);
1706 }
1707 }
1708
1709
DoAddI(LAddI * instr)1710 void LCodeGen::DoAddI(LAddI* instr) {
1711 LOperand* left = instr->left();
1712 LOperand* right = instr->right();
1713 LOperand* result = instr->result();
1714 bool can_overflow = instr->hydrogen()->CheckFlag(HValue::kCanOverflow);
1715
1716 if (!can_overflow) {
1717 if (right->IsStackSlot()) {
1718 Register right_reg = EmitLoadRegister(right, at);
1719 __ Addu(ToRegister(result), ToRegister(left), Operand(right_reg));
1720 } else {
1721 DCHECK(right->IsRegister() || right->IsConstantOperand());
1722 __ Addu(ToRegister(result), ToRegister(left), ToOperand(right));
1723 }
1724 } else { // can_overflow.
1725 Register scratch = scratch1();
1726 Label no_overflow_label;
1727 if (right->IsStackSlot()) {
1728 Register right_reg = EmitLoadRegister(right, scratch);
1729 __ AddBranchNoOvf(ToRegister(result), ToRegister(left),
1730 Operand(right_reg), &no_overflow_label);
1731 } else {
1732 DCHECK(right->IsRegister() || right->IsConstantOperand());
1733 __ AddBranchNoOvf(ToRegister(result), ToRegister(left), ToOperand(right),
1734 &no_overflow_label, scratch);
1735 }
1736 DeoptimizeIf(al, instr);
1737 __ bind(&no_overflow_label);
1738 }
1739 }
1740
1741
DoMathMinMax(LMathMinMax * instr)1742 void LCodeGen::DoMathMinMax(LMathMinMax* instr) {
1743 LOperand* left = instr->left();
1744 LOperand* right = instr->right();
1745 HMathMinMax::Operation operation = instr->hydrogen()->operation();
1746 Register scratch = scratch1();
1747 if (instr->hydrogen()->representation().IsSmiOrInteger32()) {
1748 Condition condition = (operation == HMathMinMax::kMathMin) ? le : ge;
1749 Register left_reg = ToRegister(left);
1750 Register right_reg = EmitLoadRegister(right, scratch0());
1751 Register result_reg = ToRegister(instr->result());
1752 Label return_right, done;
1753 __ Slt(scratch, left_reg, Operand(right_reg));
1754 if (condition == ge) {
1755 __ Movz(result_reg, left_reg, scratch);
1756 __ Movn(result_reg, right_reg, scratch);
1757 } else {
1758 DCHECK(condition == le);
1759 __ Movn(result_reg, left_reg, scratch);
1760 __ Movz(result_reg, right_reg, scratch);
1761 }
1762 } else {
1763 DCHECK(instr->hydrogen()->representation().IsDouble());
1764 FPURegister left_reg = ToDoubleRegister(left);
1765 FPURegister right_reg = ToDoubleRegister(right);
1766 FPURegister result_reg = ToDoubleRegister(instr->result());
1767 Label nan, done;
1768 if (operation == HMathMinMax::kMathMax) {
1769 __ MaxNaNCheck_d(result_reg, left_reg, right_reg, &nan);
1770 } else {
1771 DCHECK(operation == HMathMinMax::kMathMin);
1772 __ MinNaNCheck_d(result_reg, left_reg, right_reg, &nan);
1773 }
1774 __ Branch(&done);
1775
1776 __ bind(&nan);
1777 __ LoadRoot(scratch, Heap::kNanValueRootIndex);
1778 __ ldc1(result_reg, FieldMemOperand(scratch, HeapNumber::kValueOffset));
1779
1780 __ bind(&done);
1781 }
1782 }
1783
1784
DoArithmeticD(LArithmeticD * instr)1785 void LCodeGen::DoArithmeticD(LArithmeticD* instr) {
1786 DoubleRegister left = ToDoubleRegister(instr->left());
1787 DoubleRegister right = ToDoubleRegister(instr->right());
1788 DoubleRegister result = ToDoubleRegister(instr->result());
1789 switch (instr->op()) {
1790 case Token::ADD:
1791 __ add_d(result, left, right);
1792 break;
1793 case Token::SUB:
1794 __ sub_d(result, left, right);
1795 break;
1796 case Token::MUL:
1797 __ mul_d(result, left, right);
1798 break;
1799 case Token::DIV:
1800 __ div_d(result, left, right);
1801 break;
1802 case Token::MOD: {
1803 // Save a0-a3 on the stack.
1804 RegList saved_regs = a0.bit() | a1.bit() | a2.bit() | a3.bit();
1805 __ MultiPush(saved_regs);
1806
1807 __ PrepareCallCFunction(0, 2, scratch0());
1808 __ MovToFloatParameters(left, right);
1809 __ CallCFunction(
1810 ExternalReference::mod_two_doubles_operation(isolate()),
1811 0, 2);
1812 // Move the result in the double result register.
1813 __ MovFromFloatResult(result);
1814
1815 // Restore saved register.
1816 __ MultiPop(saved_regs);
1817 break;
1818 }
1819 default:
1820 UNREACHABLE();
1821 break;
1822 }
1823 }
1824
1825
DoArithmeticT(LArithmeticT * instr)1826 void LCodeGen::DoArithmeticT(LArithmeticT* instr) {
1827 DCHECK(ToRegister(instr->context()).is(cp));
1828 DCHECK(ToRegister(instr->left()).is(a1));
1829 DCHECK(ToRegister(instr->right()).is(a0));
1830 DCHECK(ToRegister(instr->result()).is(v0));
1831
1832 Handle<Code> code = CodeFactory::BinaryOpIC(isolate(), instr->op()).code();
1833 CallCode(code, RelocInfo::CODE_TARGET, instr);
1834 // Other arch use a nop here, to signal that there is no inlined
1835 // patchable code. Mips does not need the nop, since our marker
1836 // instruction (andi zero_reg) will never be used in normal code.
1837 }
1838
1839
1840 template<class InstrType>
EmitBranch(InstrType instr,Condition condition,Register src1,const Operand & src2)1841 void LCodeGen::EmitBranch(InstrType instr,
1842 Condition condition,
1843 Register src1,
1844 const Operand& src2) {
1845 int left_block = instr->TrueDestination(chunk_);
1846 int right_block = instr->FalseDestination(chunk_);
1847
1848 int next_block = GetNextEmittedBlock();
1849 if (right_block == left_block || condition == al) {
1850 EmitGoto(left_block);
1851 } else if (left_block == next_block) {
1852 __ Branch(chunk_->GetAssemblyLabel(right_block),
1853 NegateCondition(condition), src1, src2);
1854 } else if (right_block == next_block) {
1855 __ Branch(chunk_->GetAssemblyLabel(left_block), condition, src1, src2);
1856 } else {
1857 __ Branch(chunk_->GetAssemblyLabel(left_block), condition, src1, src2);
1858 __ Branch(chunk_->GetAssemblyLabel(right_block));
1859 }
1860 }
1861
1862
1863 template<class InstrType>
EmitBranchF(InstrType instr,Condition condition,FPURegister src1,FPURegister src2)1864 void LCodeGen::EmitBranchF(InstrType instr,
1865 Condition condition,
1866 FPURegister src1,
1867 FPURegister src2) {
1868 int right_block = instr->FalseDestination(chunk_);
1869 int left_block = instr->TrueDestination(chunk_);
1870
1871 int next_block = GetNextEmittedBlock();
1872 if (right_block == left_block) {
1873 EmitGoto(left_block);
1874 } else if (left_block == next_block) {
1875 __ BranchF(chunk_->GetAssemblyLabel(right_block), NULL,
1876 NegateFpuCondition(condition), src1, src2);
1877 } else if (right_block == next_block) {
1878 __ BranchF(chunk_->GetAssemblyLabel(left_block), NULL,
1879 condition, src1, src2);
1880 } else {
1881 __ BranchF(chunk_->GetAssemblyLabel(left_block), NULL,
1882 condition, src1, src2);
1883 __ Branch(chunk_->GetAssemblyLabel(right_block));
1884 }
1885 }
1886
1887
1888 template <class InstrType>
EmitTrueBranch(InstrType instr,Condition condition,Register src1,const Operand & src2)1889 void LCodeGen::EmitTrueBranch(InstrType instr, Condition condition,
1890 Register src1, const Operand& src2) {
1891 int true_block = instr->TrueDestination(chunk_);
1892 __ Branch(chunk_->GetAssemblyLabel(true_block), condition, src1, src2);
1893 }
1894
1895
1896 template <class InstrType>
EmitFalseBranch(InstrType instr,Condition condition,Register src1,const Operand & src2)1897 void LCodeGen::EmitFalseBranch(InstrType instr, Condition condition,
1898 Register src1, const Operand& src2) {
1899 int false_block = instr->FalseDestination(chunk_);
1900 __ Branch(chunk_->GetAssemblyLabel(false_block), condition, src1, src2);
1901 }
1902
1903
1904 template<class InstrType>
EmitFalseBranchF(InstrType instr,Condition condition,FPURegister src1,FPURegister src2)1905 void LCodeGen::EmitFalseBranchF(InstrType instr,
1906 Condition condition,
1907 FPURegister src1,
1908 FPURegister src2) {
1909 int false_block = instr->FalseDestination(chunk_);
1910 __ BranchF(chunk_->GetAssemblyLabel(false_block), NULL,
1911 condition, src1, src2);
1912 }
1913
1914
DoDebugBreak(LDebugBreak * instr)1915 void LCodeGen::DoDebugBreak(LDebugBreak* instr) {
1916 __ stop("LDebugBreak");
1917 }
1918
1919
DoBranch(LBranch * instr)1920 void LCodeGen::DoBranch(LBranch* instr) {
1921 Representation r = instr->hydrogen()->value()->representation();
1922 if (r.IsInteger32() || r.IsSmi()) {
1923 DCHECK(!info()->IsStub());
1924 Register reg = ToRegister(instr->value());
1925 EmitBranch(instr, ne, reg, Operand(zero_reg));
1926 } else if (r.IsDouble()) {
1927 DCHECK(!info()->IsStub());
1928 DoubleRegister reg = ToDoubleRegister(instr->value());
1929 // Test the double value. Zero and NaN are false.
1930 EmitBranchF(instr, ogl, reg, kDoubleRegZero);
1931 } else {
1932 DCHECK(r.IsTagged());
1933 Register reg = ToRegister(instr->value());
1934 HType type = instr->hydrogen()->value()->type();
1935 if (type.IsBoolean()) {
1936 DCHECK(!info()->IsStub());
1937 __ LoadRoot(at, Heap::kTrueValueRootIndex);
1938 EmitBranch(instr, eq, reg, Operand(at));
1939 } else if (type.IsSmi()) {
1940 DCHECK(!info()->IsStub());
1941 EmitBranch(instr, ne, reg, Operand(zero_reg));
1942 } else if (type.IsJSArray()) {
1943 DCHECK(!info()->IsStub());
1944 EmitBranch(instr, al, zero_reg, Operand(zero_reg));
1945 } else if (type.IsHeapNumber()) {
1946 DCHECK(!info()->IsStub());
1947 DoubleRegister dbl_scratch = double_scratch0();
1948 __ ldc1(dbl_scratch, FieldMemOperand(reg, HeapNumber::kValueOffset));
1949 // Test the double value. Zero and NaN are false.
1950 EmitBranchF(instr, ogl, dbl_scratch, kDoubleRegZero);
1951 } else if (type.IsString()) {
1952 DCHECK(!info()->IsStub());
1953 __ lw(at, FieldMemOperand(reg, String::kLengthOffset));
1954 EmitBranch(instr, ne, at, Operand(zero_reg));
1955 } else {
1956 ToBooleanHints expected = instr->hydrogen()->expected_input_types();
1957 // Avoid deopts in the case where we've never executed this path before.
1958 if (expected == ToBooleanHint::kNone) expected = ToBooleanHint::kAny;
1959
1960 if (expected & ToBooleanHint::kUndefined) {
1961 // undefined -> false.
1962 __ LoadRoot(at, Heap::kUndefinedValueRootIndex);
1963 __ Branch(instr->FalseLabel(chunk_), eq, reg, Operand(at));
1964 }
1965 if (expected & ToBooleanHint::kBoolean) {
1966 // Boolean -> its value.
1967 __ LoadRoot(at, Heap::kTrueValueRootIndex);
1968 __ Branch(instr->TrueLabel(chunk_), eq, reg, Operand(at));
1969 __ LoadRoot(at, Heap::kFalseValueRootIndex);
1970 __ Branch(instr->FalseLabel(chunk_), eq, reg, Operand(at));
1971 }
1972 if (expected & ToBooleanHint::kNull) {
1973 // 'null' -> false.
1974 __ LoadRoot(at, Heap::kNullValueRootIndex);
1975 __ Branch(instr->FalseLabel(chunk_), eq, reg, Operand(at));
1976 }
1977
1978 if (expected & ToBooleanHint::kSmallInteger) {
1979 // Smis: 0 -> false, all other -> true.
1980 __ Branch(instr->FalseLabel(chunk_), eq, reg, Operand(zero_reg));
1981 __ JumpIfSmi(reg, instr->TrueLabel(chunk_));
1982 } else if (expected & ToBooleanHint::kNeedsMap) {
1983 // If we need a map later and have a Smi -> deopt.
1984 __ SmiTst(reg, at);
1985 DeoptimizeIf(eq, instr, DeoptimizeReason::kSmi, at, Operand(zero_reg));
1986 }
1987
1988 const Register map = scratch0();
1989 if (expected & ToBooleanHint::kNeedsMap) {
1990 __ lw(map, FieldMemOperand(reg, HeapObject::kMapOffset));
1991 if (expected & ToBooleanHint::kCanBeUndetectable) {
1992 // Undetectable -> false.
1993 __ lbu(at, FieldMemOperand(map, Map::kBitFieldOffset));
1994 __ And(at, at, Operand(1 << Map::kIsUndetectable));
1995 __ Branch(instr->FalseLabel(chunk_), ne, at, Operand(zero_reg));
1996 }
1997 }
1998
1999 if (expected & ToBooleanHint::kReceiver) {
2000 // spec object -> true.
2001 __ lbu(at, FieldMemOperand(map, Map::kInstanceTypeOffset));
2002 __ Branch(instr->TrueLabel(chunk_),
2003 ge, at, Operand(FIRST_JS_RECEIVER_TYPE));
2004 }
2005
2006 if (expected & ToBooleanHint::kString) {
2007 // String value -> false iff empty.
2008 Label not_string;
2009 __ lbu(at, FieldMemOperand(map, Map::kInstanceTypeOffset));
2010 __ Branch(¬_string, ge , at, Operand(FIRST_NONSTRING_TYPE));
2011 __ lw(at, FieldMemOperand(reg, String::kLengthOffset));
2012 __ Branch(instr->TrueLabel(chunk_), ne, at, Operand(zero_reg));
2013 __ Branch(instr->FalseLabel(chunk_));
2014 __ bind(¬_string);
2015 }
2016
2017 if (expected & ToBooleanHint::kSymbol) {
2018 // Symbol value -> true.
2019 const Register scratch = scratch1();
2020 __ lbu(scratch, FieldMemOperand(map, Map::kInstanceTypeOffset));
2021 __ Branch(instr->TrueLabel(chunk_), eq, scratch, Operand(SYMBOL_TYPE));
2022 }
2023
2024 if (expected & ToBooleanHint::kSimdValue) {
2025 // SIMD value -> true.
2026 const Register scratch = scratch1();
2027 __ lbu(scratch, FieldMemOperand(map, Map::kInstanceTypeOffset));
2028 __ Branch(instr->TrueLabel(chunk_), eq, scratch,
2029 Operand(SIMD128_VALUE_TYPE));
2030 }
2031
2032 if (expected & ToBooleanHint::kHeapNumber) {
2033 // heap number -> false iff +0, -0, or NaN.
2034 DoubleRegister dbl_scratch = double_scratch0();
2035 Label not_heap_number;
2036 __ LoadRoot(at, Heap::kHeapNumberMapRootIndex);
2037 __ Branch(¬_heap_number, ne, map, Operand(at));
2038 __ ldc1(dbl_scratch, FieldMemOperand(reg, HeapNumber::kValueOffset));
2039 __ BranchF(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2040 ne, dbl_scratch, kDoubleRegZero);
2041 // Falls through if dbl_scratch == 0.
2042 __ Branch(instr->FalseLabel(chunk_));
2043 __ bind(¬_heap_number);
2044 }
2045
2046 if (expected != ToBooleanHint::kAny) {
2047 // We've seen something for the first time -> deopt.
2048 // This can only happen if we are not generic already.
2049 DeoptimizeIf(al, instr, DeoptimizeReason::kUnexpectedObject, zero_reg,
2050 Operand(zero_reg));
2051 }
2052 }
2053 }
2054 }
2055
2056
EmitGoto(int block)2057 void LCodeGen::EmitGoto(int block) {
2058 if (!IsNextEmittedBlock(block)) {
2059 __ jmp(chunk_->GetAssemblyLabel(LookupDestination(block)));
2060 }
2061 }
2062
2063
DoGoto(LGoto * instr)2064 void LCodeGen::DoGoto(LGoto* instr) {
2065 EmitGoto(instr->block_id());
2066 }
2067
2068
TokenToCondition(Token::Value op,bool is_unsigned)2069 Condition LCodeGen::TokenToCondition(Token::Value op, bool is_unsigned) {
2070 Condition cond = kNoCondition;
2071 switch (op) {
2072 case Token::EQ:
2073 case Token::EQ_STRICT:
2074 cond = eq;
2075 break;
2076 case Token::NE:
2077 case Token::NE_STRICT:
2078 cond = ne;
2079 break;
2080 case Token::LT:
2081 cond = is_unsigned ? lo : lt;
2082 break;
2083 case Token::GT:
2084 cond = is_unsigned ? hi : gt;
2085 break;
2086 case Token::LTE:
2087 cond = is_unsigned ? ls : le;
2088 break;
2089 case Token::GTE:
2090 cond = is_unsigned ? hs : ge;
2091 break;
2092 case Token::IN:
2093 case Token::INSTANCEOF:
2094 default:
2095 UNREACHABLE();
2096 }
2097 return cond;
2098 }
2099
2100
DoCompareNumericAndBranch(LCompareNumericAndBranch * instr)2101 void LCodeGen::DoCompareNumericAndBranch(LCompareNumericAndBranch* instr) {
2102 LOperand* left = instr->left();
2103 LOperand* right = instr->right();
2104 bool is_unsigned =
2105 instr->hydrogen()->left()->CheckFlag(HInstruction::kUint32) ||
2106 instr->hydrogen()->right()->CheckFlag(HInstruction::kUint32);
2107 Condition cond = TokenToCondition(instr->op(), is_unsigned);
2108
2109 if (left->IsConstantOperand() && right->IsConstantOperand()) {
2110 // We can statically evaluate the comparison.
2111 double left_val = ToDouble(LConstantOperand::cast(left));
2112 double right_val = ToDouble(LConstantOperand::cast(right));
2113 int next_block = Token::EvalComparison(instr->op(), left_val, right_val)
2114 ? instr->TrueDestination(chunk_)
2115 : instr->FalseDestination(chunk_);
2116 EmitGoto(next_block);
2117 } else {
2118 if (instr->is_double()) {
2119 // Compare left and right as doubles and load the
2120 // resulting flags into the normal status register.
2121 FPURegister left_reg = ToDoubleRegister(left);
2122 FPURegister right_reg = ToDoubleRegister(right);
2123
2124 // If a NaN is involved, i.e. the result is unordered,
2125 // jump to false block label.
2126 __ BranchF(NULL, instr->FalseLabel(chunk_), eq,
2127 left_reg, right_reg);
2128
2129 EmitBranchF(instr, cond, left_reg, right_reg);
2130 } else {
2131 Register cmp_left;
2132 Operand cmp_right = Operand(0);
2133
2134 if (right->IsConstantOperand()) {
2135 int32_t value = ToInteger32(LConstantOperand::cast(right));
2136 if (instr->hydrogen_value()->representation().IsSmi()) {
2137 cmp_left = ToRegister(left);
2138 cmp_right = Operand(Smi::FromInt(value));
2139 } else {
2140 cmp_left = ToRegister(left);
2141 cmp_right = Operand(value);
2142 }
2143 } else if (left->IsConstantOperand()) {
2144 int32_t value = ToInteger32(LConstantOperand::cast(left));
2145 if (instr->hydrogen_value()->representation().IsSmi()) {
2146 cmp_left = ToRegister(right);
2147 cmp_right = Operand(Smi::FromInt(value));
2148 } else {
2149 cmp_left = ToRegister(right);
2150 cmp_right = Operand(value);
2151 }
2152 // We commuted the operands, so commute the condition.
2153 cond = CommuteCondition(cond);
2154 } else {
2155 cmp_left = ToRegister(left);
2156 cmp_right = Operand(ToRegister(right));
2157 }
2158
2159 EmitBranch(instr, cond, cmp_left, cmp_right);
2160 }
2161 }
2162 }
2163
2164
DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch * instr)2165 void LCodeGen::DoCmpObjectEqAndBranch(LCmpObjectEqAndBranch* instr) {
2166 Register left = ToRegister(instr->left());
2167 Register right = ToRegister(instr->right());
2168
2169 EmitBranch(instr, eq, left, Operand(right));
2170 }
2171
2172
DoCmpHoleAndBranch(LCmpHoleAndBranch * instr)2173 void LCodeGen::DoCmpHoleAndBranch(LCmpHoleAndBranch* instr) {
2174 if (instr->hydrogen()->representation().IsTagged()) {
2175 Register input_reg = ToRegister(instr->object());
2176 __ li(at, Operand(factory()->the_hole_value()));
2177 EmitBranch(instr, eq, input_reg, Operand(at));
2178 return;
2179 }
2180
2181 DoubleRegister input_reg = ToDoubleRegister(instr->object());
2182 EmitFalseBranchF(instr, eq, input_reg, input_reg);
2183
2184 Register scratch = scratch0();
2185 __ FmoveHigh(scratch, input_reg);
2186 EmitBranch(instr, eq, scratch, Operand(kHoleNanUpper32));
2187 }
2188
2189
EmitIsString(Register input,Register temp1,Label * is_not_string,SmiCheck check_needed=INLINE_SMI_CHECK)2190 Condition LCodeGen::EmitIsString(Register input,
2191 Register temp1,
2192 Label* is_not_string,
2193 SmiCheck check_needed = INLINE_SMI_CHECK) {
2194 if (check_needed == INLINE_SMI_CHECK) {
2195 __ JumpIfSmi(input, is_not_string);
2196 }
2197 __ GetObjectType(input, temp1, temp1);
2198
2199 return lt;
2200 }
2201
2202
DoIsStringAndBranch(LIsStringAndBranch * instr)2203 void LCodeGen::DoIsStringAndBranch(LIsStringAndBranch* instr) {
2204 Register reg = ToRegister(instr->value());
2205 Register temp1 = ToRegister(instr->temp());
2206
2207 SmiCheck check_needed =
2208 instr->hydrogen()->value()->type().IsHeapObject()
2209 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2210 Condition true_cond =
2211 EmitIsString(reg, temp1, instr->FalseLabel(chunk_), check_needed);
2212
2213 EmitBranch(instr, true_cond, temp1,
2214 Operand(FIRST_NONSTRING_TYPE));
2215 }
2216
2217
DoIsSmiAndBranch(LIsSmiAndBranch * instr)2218 void LCodeGen::DoIsSmiAndBranch(LIsSmiAndBranch* instr) {
2219 Register input_reg = EmitLoadRegister(instr->value(), at);
2220 __ And(at, input_reg, kSmiTagMask);
2221 EmitBranch(instr, eq, at, Operand(zero_reg));
2222 }
2223
2224
DoIsUndetectableAndBranch(LIsUndetectableAndBranch * instr)2225 void LCodeGen::DoIsUndetectableAndBranch(LIsUndetectableAndBranch* instr) {
2226 Register input = ToRegister(instr->value());
2227 Register temp = ToRegister(instr->temp());
2228
2229 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2230 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2231 }
2232 __ lw(temp, FieldMemOperand(input, HeapObject::kMapOffset));
2233 __ lbu(temp, FieldMemOperand(temp, Map::kBitFieldOffset));
2234 __ And(at, temp, Operand(1 << Map::kIsUndetectable));
2235 EmitBranch(instr, ne, at, Operand(zero_reg));
2236 }
2237
2238
ComputeCompareCondition(Token::Value op)2239 static Condition ComputeCompareCondition(Token::Value op) {
2240 switch (op) {
2241 case Token::EQ_STRICT:
2242 case Token::EQ:
2243 return eq;
2244 case Token::LT:
2245 return lt;
2246 case Token::GT:
2247 return gt;
2248 case Token::LTE:
2249 return le;
2250 case Token::GTE:
2251 return ge;
2252 default:
2253 UNREACHABLE();
2254 return kNoCondition;
2255 }
2256 }
2257
2258
DoStringCompareAndBranch(LStringCompareAndBranch * instr)2259 void LCodeGen::DoStringCompareAndBranch(LStringCompareAndBranch* instr) {
2260 DCHECK(ToRegister(instr->context()).is(cp));
2261 DCHECK(ToRegister(instr->left()).is(a1));
2262 DCHECK(ToRegister(instr->right()).is(a0));
2263
2264 Handle<Code> code = CodeFactory::StringCompare(isolate(), instr->op()).code();
2265 CallCode(code, RelocInfo::CODE_TARGET, instr);
2266 __ LoadRoot(at, Heap::kTrueValueRootIndex);
2267 EmitBranch(instr, eq, v0, Operand(at));
2268 }
2269
2270
TestType(HHasInstanceTypeAndBranch * instr)2271 static InstanceType TestType(HHasInstanceTypeAndBranch* instr) {
2272 InstanceType from = instr->from();
2273 InstanceType to = instr->to();
2274 if (from == FIRST_TYPE) return to;
2275 DCHECK(from == to || to == LAST_TYPE);
2276 return from;
2277 }
2278
2279
BranchCondition(HHasInstanceTypeAndBranch * instr)2280 static Condition BranchCondition(HHasInstanceTypeAndBranch* instr) {
2281 InstanceType from = instr->from();
2282 InstanceType to = instr->to();
2283 if (from == to) return eq;
2284 if (to == LAST_TYPE) return hs;
2285 if (from == FIRST_TYPE) return ls;
2286 UNREACHABLE();
2287 return eq;
2288 }
2289
2290
DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch * instr)2291 void LCodeGen::DoHasInstanceTypeAndBranch(LHasInstanceTypeAndBranch* instr) {
2292 Register scratch = scratch0();
2293 Register input = ToRegister(instr->value());
2294
2295 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
2296 __ JumpIfSmi(input, instr->FalseLabel(chunk_));
2297 }
2298
2299 __ GetObjectType(input, scratch, scratch);
2300 EmitBranch(instr,
2301 BranchCondition(instr->hydrogen()),
2302 scratch,
2303 Operand(TestType(instr->hydrogen())));
2304 }
2305
2306 // Branches to a label or falls through with the answer in flags. Trashes
2307 // the temp registers, but not the input.
EmitClassOfTest(Label * is_true,Label * is_false,Handle<String> class_name,Register input,Register temp,Register temp2)2308 void LCodeGen::EmitClassOfTest(Label* is_true,
2309 Label* is_false,
2310 Handle<String>class_name,
2311 Register input,
2312 Register temp,
2313 Register temp2) {
2314 DCHECK(!input.is(temp));
2315 DCHECK(!input.is(temp2));
2316 DCHECK(!temp.is(temp2));
2317
2318 __ JumpIfSmi(input, is_false);
2319 __ GetObjectType(input, temp, temp2);
2320 STATIC_ASSERT(LAST_FUNCTION_TYPE == LAST_TYPE);
2321 if (String::Equals(isolate()->factory()->Function_string(), class_name)) {
2322 __ Branch(is_true, hs, temp2, Operand(FIRST_FUNCTION_TYPE));
2323 } else {
2324 __ Branch(is_false, hs, temp2, Operand(FIRST_FUNCTION_TYPE));
2325 }
2326
2327 // Check if the constructor in the map is a function.
2328 Register instance_type = scratch1();
2329 DCHECK(!instance_type.is(temp));
2330 __ GetMapConstructor(temp, temp, temp2, instance_type);
2331
2332 // Objects with a non-function constructor have class 'Object'.
2333 if (String::Equals(class_name, isolate()->factory()->Object_string())) {
2334 __ Branch(is_true, ne, instance_type, Operand(JS_FUNCTION_TYPE));
2335 } else {
2336 __ Branch(is_false, ne, instance_type, Operand(JS_FUNCTION_TYPE));
2337 }
2338
2339 // temp now contains the constructor function. Grab the
2340 // instance class name from there.
2341 __ lw(temp, FieldMemOperand(temp, JSFunction::kSharedFunctionInfoOffset));
2342 __ lw(temp, FieldMemOperand(temp,
2343 SharedFunctionInfo::kInstanceClassNameOffset));
2344 // The class name we are testing against is internalized since it's a literal.
2345 // The name in the constructor is internalized because of the way the context
2346 // is booted. This routine isn't expected to work for random API-created
2347 // classes and it doesn't have to because you can't access it with natives
2348 // syntax. Since both sides are internalized it is sufficient to use an
2349 // identity comparison.
2350
2351 // End with the address of this class_name instance in temp register.
2352 // On MIPS, the caller must do the comparison with Handle<String>class_name.
2353 }
2354
2355
DoClassOfTestAndBranch(LClassOfTestAndBranch * instr)2356 void LCodeGen::DoClassOfTestAndBranch(LClassOfTestAndBranch* instr) {
2357 Register input = ToRegister(instr->value());
2358 Register temp = scratch0();
2359 Register temp2 = ToRegister(instr->temp());
2360 Handle<String> class_name = instr->hydrogen()->class_name();
2361
2362 EmitClassOfTest(instr->TrueLabel(chunk_), instr->FalseLabel(chunk_),
2363 class_name, input, temp, temp2);
2364
2365 EmitBranch(instr, eq, temp, Operand(class_name));
2366 }
2367
2368
DoCmpMapAndBranch(LCmpMapAndBranch * instr)2369 void LCodeGen::DoCmpMapAndBranch(LCmpMapAndBranch* instr) {
2370 Register reg = ToRegister(instr->value());
2371 Register temp = ToRegister(instr->temp());
2372
2373 __ lw(temp, FieldMemOperand(reg, HeapObject::kMapOffset));
2374 EmitBranch(instr, eq, temp, Operand(instr->map()));
2375 }
2376
2377
DoHasInPrototypeChainAndBranch(LHasInPrototypeChainAndBranch * instr)2378 void LCodeGen::DoHasInPrototypeChainAndBranch(
2379 LHasInPrototypeChainAndBranch* instr) {
2380 Register const object = ToRegister(instr->object());
2381 Register const object_map = scratch0();
2382 Register const object_instance_type = scratch1();
2383 Register const object_prototype = object_map;
2384 Register const prototype = ToRegister(instr->prototype());
2385
2386 // The {object} must be a spec object. It's sufficient to know that {object}
2387 // is not a smi, since all other non-spec objects have {null} prototypes and
2388 // will be ruled out below.
2389 if (instr->hydrogen()->ObjectNeedsSmiCheck()) {
2390 __ SmiTst(object, at);
2391 EmitFalseBranch(instr, eq, at, Operand(zero_reg));
2392 }
2393
2394 // Loop through the {object}s prototype chain looking for the {prototype}.
2395 __ lw(object_map, FieldMemOperand(object, HeapObject::kMapOffset));
2396 Label loop;
2397 __ bind(&loop);
2398
2399 // Deoptimize if the object needs to be access checked.
2400 __ lbu(object_instance_type,
2401 FieldMemOperand(object_map, Map::kBitFieldOffset));
2402 __ And(object_instance_type, object_instance_type,
2403 Operand(1 << Map::kIsAccessCheckNeeded));
2404 DeoptimizeIf(ne, instr, DeoptimizeReason::kAccessCheck, object_instance_type,
2405 Operand(zero_reg));
2406 // Deoptimize for proxies.
2407 __ lbu(object_instance_type,
2408 FieldMemOperand(object_map, Map::kInstanceTypeOffset));
2409 DeoptimizeIf(eq, instr, DeoptimizeReason::kProxy, object_instance_type,
2410 Operand(JS_PROXY_TYPE));
2411
2412 __ lw(object_prototype, FieldMemOperand(object_map, Map::kPrototypeOffset));
2413 __ LoadRoot(at, Heap::kNullValueRootIndex);
2414 EmitFalseBranch(instr, eq, object_prototype, Operand(at));
2415 EmitTrueBranch(instr, eq, object_prototype, Operand(prototype));
2416 __ Branch(USE_DELAY_SLOT, &loop);
2417 __ lw(object_map, FieldMemOperand(object_prototype, HeapObject::kMapOffset));
2418 }
2419
2420
DoCmpT(LCmpT * instr)2421 void LCodeGen::DoCmpT(LCmpT* instr) {
2422 DCHECK(ToRegister(instr->context()).is(cp));
2423 Token::Value op = instr->op();
2424
2425 Handle<Code> ic = CodeFactory::CompareIC(isolate(), op).code();
2426 CallCode(ic, RelocInfo::CODE_TARGET, instr);
2427 // On MIPS there is no need for a "no inlined smi code" marker (nop).
2428
2429 Condition condition = ComputeCompareCondition(op);
2430 // A minor optimization that relies on LoadRoot always emitting one
2431 // instruction.
2432 Assembler::BlockTrampolinePoolScope block_trampoline_pool(masm());
2433 Label done, check;
2434 __ Branch(USE_DELAY_SLOT, &done, condition, v0, Operand(zero_reg));
2435 __ bind(&check);
2436 __ LoadRoot(ToRegister(instr->result()), Heap::kTrueValueRootIndex);
2437 DCHECK_EQ(1, masm()->InstructionsGeneratedSince(&check));
2438 __ LoadRoot(ToRegister(instr->result()), Heap::kFalseValueRootIndex);
2439 __ bind(&done);
2440 }
2441
2442
DoReturn(LReturn * instr)2443 void LCodeGen::DoReturn(LReturn* instr) {
2444 if (FLAG_trace && info()->IsOptimizing()) {
2445 // Push the return value on the stack as the parameter.
2446 // Runtime::TraceExit returns its parameter in v0. We're leaving the code
2447 // managed by the register allocator and tearing down the frame, it's
2448 // safe to write to the context register.
2449 __ push(v0);
2450 __ lw(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
2451 __ CallRuntime(Runtime::kTraceExit);
2452 }
2453 if (info()->saves_caller_doubles()) {
2454 RestoreCallerDoubles();
2455 }
2456 if (NeedsEagerFrame()) {
2457 __ mov(sp, fp);
2458 __ Pop(ra, fp);
2459 }
2460 if (instr->has_constant_parameter_count()) {
2461 int parameter_count = ToInteger32(instr->constant_parameter_count());
2462 int32_t sp_delta = (parameter_count + 1) * kPointerSize;
2463 if (sp_delta != 0) {
2464 __ Addu(sp, sp, Operand(sp_delta));
2465 }
2466 } else {
2467 DCHECK(info()->IsStub()); // Functions would need to drop one more value.
2468 Register reg = ToRegister(instr->parameter_count());
2469 // The argument count parameter is a smi
2470 __ SmiUntag(reg);
2471 __ Lsa(sp, sp, reg, kPointerSizeLog2);
2472 }
2473
2474 __ Jump(ra);
2475 }
2476
2477
DoLoadContextSlot(LLoadContextSlot * instr)2478 void LCodeGen::DoLoadContextSlot(LLoadContextSlot* instr) {
2479 Register context = ToRegister(instr->context());
2480 Register result = ToRegister(instr->result());
2481
2482 __ lw(result, ContextMemOperand(context, instr->slot_index()));
2483 if (instr->hydrogen()->RequiresHoleCheck()) {
2484 __ LoadRoot(at, Heap::kTheHoleValueRootIndex);
2485
2486 if (instr->hydrogen()->DeoptimizesOnHole()) {
2487 DeoptimizeIf(eq, instr, DeoptimizeReason::kHole, result, Operand(at));
2488 } else {
2489 Label is_not_hole;
2490 __ Branch(&is_not_hole, ne, result, Operand(at));
2491 __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
2492 __ bind(&is_not_hole);
2493 }
2494 }
2495 }
2496
2497
DoStoreContextSlot(LStoreContextSlot * instr)2498 void LCodeGen::DoStoreContextSlot(LStoreContextSlot* instr) {
2499 Register context = ToRegister(instr->context());
2500 Register value = ToRegister(instr->value());
2501 Register scratch = scratch0();
2502 MemOperand target = ContextMemOperand(context, instr->slot_index());
2503
2504 Label skip_assignment;
2505
2506 if (instr->hydrogen()->RequiresHoleCheck()) {
2507 __ lw(scratch, target);
2508 __ LoadRoot(at, Heap::kTheHoleValueRootIndex);
2509
2510 if (instr->hydrogen()->DeoptimizesOnHole()) {
2511 DeoptimizeIf(eq, instr, DeoptimizeReason::kHole, scratch, Operand(at));
2512 } else {
2513 __ Branch(&skip_assignment, ne, scratch, Operand(at));
2514 }
2515 }
2516
2517 __ sw(value, target);
2518 if (instr->hydrogen()->NeedsWriteBarrier()) {
2519 SmiCheck check_needed =
2520 instr->hydrogen()->value()->type().IsHeapObject()
2521 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
2522 __ RecordWriteContextSlot(context,
2523 target.offset(),
2524 value,
2525 scratch0(),
2526 GetRAState(),
2527 kSaveFPRegs,
2528 EMIT_REMEMBERED_SET,
2529 check_needed);
2530 }
2531
2532 __ bind(&skip_assignment);
2533 }
2534
2535
DoLoadNamedField(LLoadNamedField * instr)2536 void LCodeGen::DoLoadNamedField(LLoadNamedField* instr) {
2537 HObjectAccess access = instr->hydrogen()->access();
2538 int offset = access.offset();
2539 Register object = ToRegister(instr->object());
2540
2541 if (access.IsExternalMemory()) {
2542 Register result = ToRegister(instr->result());
2543 MemOperand operand = MemOperand(object, offset);
2544 __ Load(result, operand, access.representation());
2545 return;
2546 }
2547
2548 if (instr->hydrogen()->representation().IsDouble()) {
2549 DoubleRegister result = ToDoubleRegister(instr->result());
2550 __ ldc1(result, FieldMemOperand(object, offset));
2551 return;
2552 }
2553
2554 Register result = ToRegister(instr->result());
2555 if (!access.IsInobject()) {
2556 __ lw(result, FieldMemOperand(object, JSObject::kPropertiesOffset));
2557 object = result;
2558 }
2559 MemOperand operand = FieldMemOperand(object, offset);
2560 __ Load(result, operand, access.representation());
2561 }
2562
2563
DoLoadFunctionPrototype(LLoadFunctionPrototype * instr)2564 void LCodeGen::DoLoadFunctionPrototype(LLoadFunctionPrototype* instr) {
2565 Register scratch = scratch0();
2566 Register function = ToRegister(instr->function());
2567 Register result = ToRegister(instr->result());
2568
2569 // Get the prototype or initial map from the function.
2570 __ lw(result,
2571 FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
2572
2573 // Check that the function has a prototype or an initial map.
2574 __ LoadRoot(at, Heap::kTheHoleValueRootIndex);
2575 DeoptimizeIf(eq, instr, DeoptimizeReason::kHole, result, Operand(at));
2576
2577 // If the function does not have an initial map, we're done.
2578 Label done;
2579 __ GetObjectType(result, scratch, scratch);
2580 __ Branch(&done, ne, scratch, Operand(MAP_TYPE));
2581
2582 // Get the prototype from the initial map.
2583 __ lw(result, FieldMemOperand(result, Map::kPrototypeOffset));
2584
2585 // All done.
2586 __ bind(&done);
2587 }
2588
2589
DoLoadRoot(LLoadRoot * instr)2590 void LCodeGen::DoLoadRoot(LLoadRoot* instr) {
2591 Register result = ToRegister(instr->result());
2592 __ LoadRoot(result, instr->index());
2593 }
2594
2595
DoAccessArgumentsAt(LAccessArgumentsAt * instr)2596 void LCodeGen::DoAccessArgumentsAt(LAccessArgumentsAt* instr) {
2597 Register arguments = ToRegister(instr->arguments());
2598 Register result = ToRegister(instr->result());
2599 // There are two words between the frame pointer and the last argument.
2600 // Subtracting from length accounts for one of them add one more.
2601 if (instr->length()->IsConstantOperand()) {
2602 int const_length = ToInteger32(LConstantOperand::cast(instr->length()));
2603 if (instr->index()->IsConstantOperand()) {
2604 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
2605 int index = (const_length - const_index) + 1;
2606 __ lw(result, MemOperand(arguments, index * kPointerSize));
2607 } else {
2608 Register index = ToRegister(instr->index());
2609 __ li(at, Operand(const_length + 1));
2610 __ Subu(result, at, index);
2611 __ Lsa(at, arguments, result, kPointerSizeLog2);
2612 __ lw(result, MemOperand(at));
2613 }
2614 } else if (instr->index()->IsConstantOperand()) {
2615 Register length = ToRegister(instr->length());
2616 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
2617 int loc = const_index - 1;
2618 if (loc != 0) {
2619 __ Subu(result, length, Operand(loc));
2620 __ Lsa(at, arguments, result, kPointerSizeLog2);
2621 __ lw(result, MemOperand(at));
2622 } else {
2623 __ Lsa(at, arguments, length, kPointerSizeLog2);
2624 __ lw(result, MemOperand(at));
2625 }
2626 } else {
2627 Register length = ToRegister(instr->length());
2628 Register index = ToRegister(instr->index());
2629 __ Subu(result, length, index);
2630 __ Addu(result, result, 1);
2631 __ Lsa(at, arguments, result, kPointerSizeLog2);
2632 __ lw(result, MemOperand(at));
2633 }
2634 }
2635
2636
DoLoadKeyedExternalArray(LLoadKeyed * instr)2637 void LCodeGen::DoLoadKeyedExternalArray(LLoadKeyed* instr) {
2638 Register external_pointer = ToRegister(instr->elements());
2639 Register key = no_reg;
2640 ElementsKind elements_kind = instr->elements_kind();
2641 bool key_is_constant = instr->key()->IsConstantOperand();
2642 int constant_key = 0;
2643 if (key_is_constant) {
2644 constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
2645 if (constant_key & 0xF0000000) {
2646 Abort(kArrayIndexConstantValueTooBig);
2647 }
2648 } else {
2649 key = ToRegister(instr->key());
2650 }
2651 int element_size_shift = ElementsKindToShiftSize(elements_kind);
2652 int shift_size = (instr->hydrogen()->key()->representation().IsSmi())
2653 ? (element_size_shift - kSmiTagSize) : element_size_shift;
2654 int base_offset = instr->base_offset();
2655
2656 if (elements_kind == FLOAT32_ELEMENTS || elements_kind == FLOAT64_ELEMENTS) {
2657 FPURegister result = ToDoubleRegister(instr->result());
2658 if (key_is_constant) {
2659 __ Addu(scratch0(), external_pointer, constant_key << element_size_shift);
2660 } else {
2661 __ sll(scratch0(), key, shift_size);
2662 __ Addu(scratch0(), scratch0(), external_pointer);
2663 }
2664 if (elements_kind == FLOAT32_ELEMENTS) {
2665 __ lwc1(result, MemOperand(scratch0(), base_offset));
2666 __ cvt_d_s(result, result);
2667 } else { // i.e. elements_kind == EXTERNAL_DOUBLE_ELEMENTS
2668 __ ldc1(result, MemOperand(scratch0(), base_offset));
2669 }
2670 } else {
2671 Register result = ToRegister(instr->result());
2672 MemOperand mem_operand = PrepareKeyedOperand(
2673 key, external_pointer, key_is_constant, constant_key,
2674 element_size_shift, shift_size, base_offset);
2675 switch (elements_kind) {
2676 case INT8_ELEMENTS:
2677 __ lb(result, mem_operand);
2678 break;
2679 case UINT8_ELEMENTS:
2680 case UINT8_CLAMPED_ELEMENTS:
2681 __ lbu(result, mem_operand);
2682 break;
2683 case INT16_ELEMENTS:
2684 __ lh(result, mem_operand);
2685 break;
2686 case UINT16_ELEMENTS:
2687 __ lhu(result, mem_operand);
2688 break;
2689 case INT32_ELEMENTS:
2690 __ lw(result, mem_operand);
2691 break;
2692 case UINT32_ELEMENTS:
2693 __ lw(result, mem_operand);
2694 if (!instr->hydrogen()->CheckFlag(HInstruction::kUint32)) {
2695 DeoptimizeIf(Ugreater_equal, instr, DeoptimizeReason::kNegativeValue,
2696 result, Operand(0x80000000));
2697 }
2698 break;
2699 case FLOAT32_ELEMENTS:
2700 case FLOAT64_ELEMENTS:
2701 case FAST_DOUBLE_ELEMENTS:
2702 case FAST_ELEMENTS:
2703 case FAST_SMI_ELEMENTS:
2704 case FAST_HOLEY_DOUBLE_ELEMENTS:
2705 case FAST_HOLEY_ELEMENTS:
2706 case FAST_HOLEY_SMI_ELEMENTS:
2707 case DICTIONARY_ELEMENTS:
2708 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
2709 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
2710 case FAST_STRING_WRAPPER_ELEMENTS:
2711 case SLOW_STRING_WRAPPER_ELEMENTS:
2712 case NO_ELEMENTS:
2713 UNREACHABLE();
2714 break;
2715 }
2716 }
2717 }
2718
2719
DoLoadKeyedFixedDoubleArray(LLoadKeyed * instr)2720 void LCodeGen::DoLoadKeyedFixedDoubleArray(LLoadKeyed* instr) {
2721 Register elements = ToRegister(instr->elements());
2722 bool key_is_constant = instr->key()->IsConstantOperand();
2723 Register key = no_reg;
2724 DoubleRegister result = ToDoubleRegister(instr->result());
2725 Register scratch = scratch0();
2726
2727 int element_size_shift = ElementsKindToShiftSize(FAST_DOUBLE_ELEMENTS);
2728
2729 int base_offset = instr->base_offset();
2730 if (key_is_constant) {
2731 int constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
2732 if (constant_key & 0xF0000000) {
2733 Abort(kArrayIndexConstantValueTooBig);
2734 }
2735 base_offset += constant_key * kDoubleSize;
2736 }
2737 __ Addu(scratch, elements, Operand(base_offset));
2738
2739 if (!key_is_constant) {
2740 key = ToRegister(instr->key());
2741 int shift_size = (instr->hydrogen()->key()->representation().IsSmi())
2742 ? (element_size_shift - kSmiTagSize) : element_size_shift;
2743 __ Lsa(scratch, scratch, key, shift_size);
2744 }
2745
2746 __ ldc1(result, MemOperand(scratch));
2747
2748 if (instr->hydrogen()->RequiresHoleCheck()) {
2749 __ lw(scratch, MemOperand(scratch, kHoleNanUpper32Offset));
2750 DeoptimizeIf(eq, instr, DeoptimizeReason::kHole, scratch,
2751 Operand(kHoleNanUpper32));
2752 }
2753 }
2754
2755
DoLoadKeyedFixedArray(LLoadKeyed * instr)2756 void LCodeGen::DoLoadKeyedFixedArray(LLoadKeyed* instr) {
2757 Register elements = ToRegister(instr->elements());
2758 Register result = ToRegister(instr->result());
2759 Register scratch = scratch0();
2760 Register store_base = scratch;
2761 int offset = instr->base_offset();
2762
2763 if (instr->key()->IsConstantOperand()) {
2764 LConstantOperand* const_operand = LConstantOperand::cast(instr->key());
2765 offset += ToInteger32(const_operand) * kPointerSize;
2766 store_base = elements;
2767 } else {
2768 Register key = ToRegister(instr->key());
2769 // Even though the HLoadKeyed instruction forces the input
2770 // representation for the key to be an integer, the input gets replaced
2771 // during bound check elimination with the index argument to the bounds
2772 // check, which can be tagged, so that case must be handled here, too.
2773 if (instr->hydrogen()->key()->representation().IsSmi()) {
2774 __ Lsa(scratch, elements, key, kPointerSizeLog2 - kSmiTagSize);
2775 } else {
2776 __ Lsa(scratch, elements, key, kPointerSizeLog2);
2777 }
2778 }
2779 __ lw(result, MemOperand(store_base, offset));
2780
2781 // Check for the hole value.
2782 if (instr->hydrogen()->RequiresHoleCheck()) {
2783 if (IsFastSmiElementsKind(instr->hydrogen()->elements_kind())) {
2784 __ SmiTst(result, scratch);
2785 DeoptimizeIf(ne, instr, DeoptimizeReason::kNotASmi, scratch,
2786 Operand(zero_reg));
2787 } else {
2788 __ LoadRoot(scratch, Heap::kTheHoleValueRootIndex);
2789 DeoptimizeIf(eq, instr, DeoptimizeReason::kHole, result,
2790 Operand(scratch));
2791 }
2792 } else if (instr->hydrogen()->hole_mode() == CONVERT_HOLE_TO_UNDEFINED) {
2793 DCHECK(instr->hydrogen()->elements_kind() == FAST_HOLEY_ELEMENTS);
2794 Label done;
2795 __ LoadRoot(scratch, Heap::kTheHoleValueRootIndex);
2796 __ Branch(&done, ne, result, Operand(scratch));
2797 if (info()->IsStub()) {
2798 // A stub can safely convert the hole to undefined only if the array
2799 // protector cell contains (Smi) Isolate::kProtectorValid. Otherwise
2800 // it needs to bail out.
2801 __ LoadRoot(result, Heap::kArrayProtectorRootIndex);
2802 __ lw(result, FieldMemOperand(result, Cell::kValueOffset));
2803 DeoptimizeIf(ne, instr, DeoptimizeReason::kHole, result,
2804 Operand(Smi::FromInt(Isolate::kProtectorValid)));
2805 }
2806 __ LoadRoot(result, Heap::kUndefinedValueRootIndex);
2807 __ bind(&done);
2808 }
2809 }
2810
2811
DoLoadKeyed(LLoadKeyed * instr)2812 void LCodeGen::DoLoadKeyed(LLoadKeyed* instr) {
2813 if (instr->is_fixed_typed_array()) {
2814 DoLoadKeyedExternalArray(instr);
2815 } else if (instr->hydrogen()->representation().IsDouble()) {
2816 DoLoadKeyedFixedDoubleArray(instr);
2817 } else {
2818 DoLoadKeyedFixedArray(instr);
2819 }
2820 }
2821
2822
PrepareKeyedOperand(Register key,Register base,bool key_is_constant,int constant_key,int element_size,int shift_size,int base_offset)2823 MemOperand LCodeGen::PrepareKeyedOperand(Register key,
2824 Register base,
2825 bool key_is_constant,
2826 int constant_key,
2827 int element_size,
2828 int shift_size,
2829 int base_offset) {
2830 if (key_is_constant) {
2831 return MemOperand(base, (constant_key << element_size) + base_offset);
2832 }
2833
2834 if (base_offset == 0) {
2835 if (shift_size >= 0) {
2836 __ sll(scratch0(), key, shift_size);
2837 __ Addu(scratch0(), base, scratch0());
2838 return MemOperand(scratch0());
2839 } else {
2840 DCHECK_EQ(-1, shift_size);
2841 __ srl(scratch0(), key, 1);
2842 __ Addu(scratch0(), base, scratch0());
2843 return MemOperand(scratch0());
2844 }
2845 }
2846
2847 if (shift_size >= 0) {
2848 __ sll(scratch0(), key, shift_size);
2849 __ Addu(scratch0(), base, scratch0());
2850 return MemOperand(scratch0(), base_offset);
2851 } else {
2852 DCHECK_EQ(-1, shift_size);
2853 __ sra(scratch0(), key, 1);
2854 __ Addu(scratch0(), base, scratch0());
2855 return MemOperand(scratch0(), base_offset);
2856 }
2857 }
2858
2859
DoArgumentsElements(LArgumentsElements * instr)2860 void LCodeGen::DoArgumentsElements(LArgumentsElements* instr) {
2861 Register scratch = scratch0();
2862 Register temp = scratch1();
2863 Register result = ToRegister(instr->result());
2864
2865 if (instr->hydrogen()->from_inlined()) {
2866 __ Subu(result, sp, 2 * kPointerSize);
2867 } else if (instr->hydrogen()->arguments_adaptor()) {
2868 // Check if the calling frame is an arguments adaptor frame.
2869 Label done, adapted;
2870 __ lw(scratch, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
2871 __ lw(result,
2872 MemOperand(scratch, CommonFrameConstants::kContextOrFrameTypeOffset));
2873 __ Xor(temp, result, Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
2874
2875 // Result is the frame pointer for the frame if not adapted and for the real
2876 // frame below the adaptor frame if adapted.
2877 __ Movn(result, fp, temp); // Move only if temp is not equal to zero (ne).
2878 __ Movz(result, scratch, temp); // Move only if temp is equal to zero (eq).
2879 } else {
2880 __ mov(result, fp);
2881 }
2882 }
2883
2884
DoArgumentsLength(LArgumentsLength * instr)2885 void LCodeGen::DoArgumentsLength(LArgumentsLength* instr) {
2886 Register elem = ToRegister(instr->elements());
2887 Register result = ToRegister(instr->result());
2888
2889 Label done;
2890
2891 // If no arguments adaptor frame the number of arguments is fixed.
2892 __ Addu(result, zero_reg, Operand(scope()->num_parameters()));
2893 __ Branch(&done, eq, fp, Operand(elem));
2894
2895 // Arguments adaptor frame present. Get argument length from there.
2896 __ lw(result, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
2897 __ lw(result,
2898 MemOperand(result, ArgumentsAdaptorFrameConstants::kLengthOffset));
2899 __ SmiUntag(result);
2900
2901 // Argument length is in result register.
2902 __ bind(&done);
2903 }
2904
2905
DoWrapReceiver(LWrapReceiver * instr)2906 void LCodeGen::DoWrapReceiver(LWrapReceiver* instr) {
2907 Register receiver = ToRegister(instr->receiver());
2908 Register function = ToRegister(instr->function());
2909 Register result = ToRegister(instr->result());
2910 Register scratch = scratch0();
2911
2912 // If the receiver is null or undefined, we have to pass the global
2913 // object as a receiver to normal functions. Values have to be
2914 // passed unchanged to builtins and strict-mode functions.
2915 Label global_object, result_in_receiver;
2916
2917 if (!instr->hydrogen()->known_function()) {
2918 // Do not transform the receiver to object for strict mode
2919 // functions.
2920 __ lw(scratch,
2921 FieldMemOperand(function, JSFunction::kSharedFunctionInfoOffset));
2922 __ lw(scratch,
2923 FieldMemOperand(scratch, SharedFunctionInfo::kCompilerHintsOffset));
2924
2925 // Do not transform the receiver to object for builtins.
2926 int32_t strict_mode_function_mask =
2927 1 << (SharedFunctionInfo::kStrictModeFunction + kSmiTagSize);
2928 int32_t native_mask = 1 << (SharedFunctionInfo::kNative + kSmiTagSize);
2929 __ And(scratch, scratch, Operand(strict_mode_function_mask | native_mask));
2930 __ Branch(&result_in_receiver, ne, scratch, Operand(zero_reg));
2931 }
2932
2933 // Normal function. Replace undefined or null with global receiver.
2934 __ LoadRoot(scratch, Heap::kNullValueRootIndex);
2935 __ Branch(&global_object, eq, receiver, Operand(scratch));
2936 __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex);
2937 __ Branch(&global_object, eq, receiver, Operand(scratch));
2938
2939 // Deoptimize if the receiver is not a JS object.
2940 __ SmiTst(receiver, scratch);
2941 DeoptimizeIf(eq, instr, DeoptimizeReason::kSmi, scratch, Operand(zero_reg));
2942
2943 __ GetObjectType(receiver, scratch, scratch);
2944 DeoptimizeIf(lt, instr, DeoptimizeReason::kNotAJavaScriptObject, scratch,
2945 Operand(FIRST_JS_RECEIVER_TYPE));
2946
2947 __ Branch(&result_in_receiver);
2948 __ bind(&global_object);
2949 __ lw(result, FieldMemOperand(function, JSFunction::kContextOffset));
2950 __ lw(result, ContextMemOperand(result, Context::NATIVE_CONTEXT_INDEX));
2951 __ lw(result, ContextMemOperand(result, Context::GLOBAL_PROXY_INDEX));
2952
2953 if (result.is(receiver)) {
2954 __ bind(&result_in_receiver);
2955 } else {
2956 Label result_ok;
2957 __ Branch(&result_ok);
2958 __ bind(&result_in_receiver);
2959 __ mov(result, receiver);
2960 __ bind(&result_ok);
2961 }
2962 }
2963
2964
DoApplyArguments(LApplyArguments * instr)2965 void LCodeGen::DoApplyArguments(LApplyArguments* instr) {
2966 Register receiver = ToRegister(instr->receiver());
2967 Register function = ToRegister(instr->function());
2968 Register length = ToRegister(instr->length());
2969 Register elements = ToRegister(instr->elements());
2970 Register scratch = scratch0();
2971 DCHECK(receiver.is(a0)); // Used for parameter count.
2972 DCHECK(function.is(a1)); // Required by InvokeFunction.
2973 DCHECK(ToRegister(instr->result()).is(v0));
2974
2975 // Copy the arguments to this function possibly from the
2976 // adaptor frame below it.
2977 const uint32_t kArgumentsLimit = 1 * KB;
2978 DeoptimizeIf(hi, instr, DeoptimizeReason::kTooManyArguments, length,
2979 Operand(kArgumentsLimit));
2980
2981 // Push the receiver and use the register to keep the original
2982 // number of arguments.
2983 __ push(receiver);
2984 __ Move(receiver, length);
2985 // The arguments are at a one pointer size offset from elements.
2986 __ Addu(elements, elements, Operand(1 * kPointerSize));
2987
2988 // Loop through the arguments pushing them onto the execution
2989 // stack.
2990 Label invoke, loop;
2991 // length is a small non-negative integer, due to the test above.
2992 __ Branch(USE_DELAY_SLOT, &invoke, eq, length, Operand(zero_reg));
2993 __ sll(scratch, length, 2);
2994 __ bind(&loop);
2995 __ Addu(scratch, elements, scratch);
2996 __ lw(scratch, MemOperand(scratch));
2997 __ push(scratch);
2998 __ Subu(length, length, Operand(1));
2999 __ Branch(USE_DELAY_SLOT, &loop, ne, length, Operand(zero_reg));
3000 __ sll(scratch, length, 2);
3001
3002 __ bind(&invoke);
3003
3004 InvokeFlag flag = CALL_FUNCTION;
3005 if (instr->hydrogen()->tail_call_mode() == TailCallMode::kAllow) {
3006 DCHECK(!info()->saves_caller_doubles());
3007 // TODO(ishell): drop current frame before pushing arguments to the stack.
3008 flag = JUMP_FUNCTION;
3009 ParameterCount actual(a0);
3010 // It is safe to use t0, t1 and t2 as scratch registers here given that
3011 // we are not going to return to caller function anyway.
3012 PrepareForTailCall(actual, t0, t1, t2);
3013 }
3014
3015 DCHECK(instr->HasPointerMap());
3016 LPointerMap* pointers = instr->pointer_map();
3017 SafepointGenerator safepoint_generator(this, pointers, Safepoint::kLazyDeopt);
3018 // The number of arguments is stored in receiver which is a0, as expected
3019 // by InvokeFunction.
3020 ParameterCount actual(receiver);
3021 __ InvokeFunction(function, no_reg, actual, flag, safepoint_generator);
3022 }
3023
3024
DoPushArgument(LPushArgument * instr)3025 void LCodeGen::DoPushArgument(LPushArgument* instr) {
3026 LOperand* argument = instr->value();
3027 if (argument->IsDoubleRegister() || argument->IsDoubleStackSlot()) {
3028 Abort(kDoPushArgumentNotImplementedForDoubleType);
3029 } else {
3030 Register argument_reg = EmitLoadRegister(argument, at);
3031 __ push(argument_reg);
3032 }
3033 }
3034
3035
DoDrop(LDrop * instr)3036 void LCodeGen::DoDrop(LDrop* instr) {
3037 __ Drop(instr->count());
3038 }
3039
3040
DoThisFunction(LThisFunction * instr)3041 void LCodeGen::DoThisFunction(LThisFunction* instr) {
3042 Register result = ToRegister(instr->result());
3043 __ lw(result, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
3044 }
3045
3046
DoContext(LContext * instr)3047 void LCodeGen::DoContext(LContext* instr) {
3048 // If there is a non-return use, the context must be moved to a register.
3049 Register result = ToRegister(instr->result());
3050 if (info()->IsOptimizing()) {
3051 __ lw(result, MemOperand(fp, StandardFrameConstants::kContextOffset));
3052 } else {
3053 // If there is no frame, the context must be in cp.
3054 DCHECK(result.is(cp));
3055 }
3056 }
3057
3058
DoDeclareGlobals(LDeclareGlobals * instr)3059 void LCodeGen::DoDeclareGlobals(LDeclareGlobals* instr) {
3060 DCHECK(ToRegister(instr->context()).is(cp));
3061 __ li(scratch0(), instr->hydrogen()->pairs());
3062 __ li(scratch1(), Operand(Smi::FromInt(instr->hydrogen()->flags())));
3063 __ Push(scratch0(), scratch1());
3064 __ li(scratch0(), instr->hydrogen()->feedback_vector());
3065 __ Push(scratch0());
3066 CallRuntime(Runtime::kDeclareGlobals, instr);
3067 }
3068
CallKnownFunction(Handle<JSFunction> function,int formal_parameter_count,int arity,bool is_tail_call,LInstruction * instr)3069 void LCodeGen::CallKnownFunction(Handle<JSFunction> function,
3070 int formal_parameter_count, int arity,
3071 bool is_tail_call, LInstruction* instr) {
3072 bool dont_adapt_arguments =
3073 formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel;
3074 bool can_invoke_directly =
3075 dont_adapt_arguments || formal_parameter_count == arity;
3076
3077 Register function_reg = a1;
3078 LPointerMap* pointers = instr->pointer_map();
3079
3080 if (can_invoke_directly) {
3081 // Change context.
3082 __ lw(cp, FieldMemOperand(function_reg, JSFunction::kContextOffset));
3083
3084 // Always initialize new target and number of actual arguments.
3085 __ LoadRoot(a3, Heap::kUndefinedValueRootIndex);
3086 __ li(a0, Operand(arity));
3087
3088 bool is_self_call = function.is_identical_to(info()->closure());
3089
3090 // Invoke function.
3091 if (is_self_call) {
3092 Handle<Code> self(reinterpret_cast<Code**>(__ CodeObject().location()));
3093 if (is_tail_call) {
3094 __ Jump(self, RelocInfo::CODE_TARGET);
3095 } else {
3096 __ Call(self, RelocInfo::CODE_TARGET);
3097 }
3098 } else {
3099 __ lw(at, FieldMemOperand(function_reg, JSFunction::kCodeEntryOffset));
3100 if (is_tail_call) {
3101 __ Jump(at);
3102 } else {
3103 __ Call(at);
3104 }
3105 }
3106
3107 if (!is_tail_call) {
3108 // Set up deoptimization.
3109 RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
3110 }
3111 } else {
3112 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3113 ParameterCount actual(arity);
3114 ParameterCount expected(formal_parameter_count);
3115 InvokeFlag flag = is_tail_call ? JUMP_FUNCTION : CALL_FUNCTION;
3116 __ InvokeFunction(function_reg, expected, actual, flag, generator);
3117 }
3118 }
3119
3120
DoDeferredMathAbsTaggedHeapNumber(LMathAbs * instr)3121 void LCodeGen::DoDeferredMathAbsTaggedHeapNumber(LMathAbs* instr) {
3122 DCHECK(instr->context() != NULL);
3123 DCHECK(ToRegister(instr->context()).is(cp));
3124 Register input = ToRegister(instr->value());
3125 Register result = ToRegister(instr->result());
3126 Register scratch = scratch0();
3127
3128 // Deoptimize if not a heap number.
3129 __ lw(scratch, FieldMemOperand(input, HeapObject::kMapOffset));
3130 __ LoadRoot(at, Heap::kHeapNumberMapRootIndex);
3131 DeoptimizeIf(ne, instr, DeoptimizeReason::kNotAHeapNumber, scratch,
3132 Operand(at));
3133
3134 Label done;
3135 Register exponent = scratch0();
3136 scratch = no_reg;
3137 __ lw(exponent, FieldMemOperand(input, HeapNumber::kExponentOffset));
3138 // Check the sign of the argument. If the argument is positive, just
3139 // return it.
3140 __ Move(result, input);
3141 __ And(at, exponent, Operand(HeapNumber::kSignMask));
3142 __ Branch(&done, eq, at, Operand(zero_reg));
3143
3144 // Input is negative. Reverse its sign.
3145 // Preserve the value of all registers.
3146 {
3147 PushSafepointRegistersScope scope(this);
3148
3149 // Registers were saved at the safepoint, so we can use
3150 // many scratch registers.
3151 Register tmp1 = input.is(a1) ? a0 : a1;
3152 Register tmp2 = input.is(a2) ? a0 : a2;
3153 Register tmp3 = input.is(a3) ? a0 : a3;
3154 Register tmp4 = input.is(t0) ? a0 : t0;
3155
3156 // exponent: floating point exponent value.
3157
3158 Label allocated, slow;
3159 __ LoadRoot(tmp4, Heap::kHeapNumberMapRootIndex);
3160 __ AllocateHeapNumber(tmp1, tmp2, tmp3, tmp4, &slow);
3161 __ Branch(&allocated);
3162
3163 // Slow case: Call the runtime system to do the number allocation.
3164 __ bind(&slow);
3165
3166 CallRuntimeFromDeferred(Runtime::kAllocateHeapNumber, 0, instr,
3167 instr->context());
3168 // Set the pointer to the new heap number in tmp.
3169 if (!tmp1.is(v0))
3170 __ mov(tmp1, v0);
3171 // Restore input_reg after call to runtime.
3172 __ LoadFromSafepointRegisterSlot(input, input);
3173 __ lw(exponent, FieldMemOperand(input, HeapNumber::kExponentOffset));
3174
3175 __ bind(&allocated);
3176 // exponent: floating point exponent value.
3177 // tmp1: allocated heap number.
3178 __ And(exponent, exponent, Operand(~HeapNumber::kSignMask));
3179 __ sw(exponent, FieldMemOperand(tmp1, HeapNumber::kExponentOffset));
3180 __ lw(tmp2, FieldMemOperand(input, HeapNumber::kMantissaOffset));
3181 __ sw(tmp2, FieldMemOperand(tmp1, HeapNumber::kMantissaOffset));
3182
3183 __ StoreToSafepointRegisterSlot(tmp1, result);
3184 }
3185
3186 __ bind(&done);
3187 }
3188
3189
EmitIntegerMathAbs(LMathAbs * instr)3190 void LCodeGen::EmitIntegerMathAbs(LMathAbs* instr) {
3191 Register input = ToRegister(instr->value());
3192 Register result = ToRegister(instr->result());
3193 Assembler::BlockTrampolinePoolScope block_trampoline_pool(masm_);
3194 Label done;
3195 __ Branch(USE_DELAY_SLOT, &done, ge, input, Operand(zero_reg));
3196 __ mov(result, input);
3197 __ subu(result, zero_reg, input);
3198 // Overflow if result is still negative, i.e. 0x80000000.
3199 DeoptimizeIf(lt, instr, DeoptimizeReason::kOverflow, result,
3200 Operand(zero_reg));
3201 __ bind(&done);
3202 }
3203
3204
DoMathAbs(LMathAbs * instr)3205 void LCodeGen::DoMathAbs(LMathAbs* instr) {
3206 // Class for deferred case.
3207 class DeferredMathAbsTaggedHeapNumber final : public LDeferredCode {
3208 public:
3209 DeferredMathAbsTaggedHeapNumber(LCodeGen* codegen, LMathAbs* instr)
3210 : LDeferredCode(codegen), instr_(instr) { }
3211 void Generate() override {
3212 codegen()->DoDeferredMathAbsTaggedHeapNumber(instr_);
3213 }
3214 LInstruction* instr() override { return instr_; }
3215
3216 private:
3217 LMathAbs* instr_;
3218 };
3219
3220 Representation r = instr->hydrogen()->value()->representation();
3221 if (r.IsDouble()) {
3222 FPURegister input = ToDoubleRegister(instr->value());
3223 FPURegister result = ToDoubleRegister(instr->result());
3224 __ abs_d(result, input);
3225 } else if (r.IsSmiOrInteger32()) {
3226 EmitIntegerMathAbs(instr);
3227 } else {
3228 // Representation is tagged.
3229 DeferredMathAbsTaggedHeapNumber* deferred =
3230 new(zone()) DeferredMathAbsTaggedHeapNumber(this, instr);
3231 Register input = ToRegister(instr->value());
3232 // Smi check.
3233 __ JumpIfNotSmi(input, deferred->entry());
3234 // If smi, handle it directly.
3235 EmitIntegerMathAbs(instr);
3236 __ bind(deferred->exit());
3237 }
3238 }
3239
3240
DoMathFloor(LMathFloor * instr)3241 void LCodeGen::DoMathFloor(LMathFloor* instr) {
3242 DoubleRegister input = ToDoubleRegister(instr->value());
3243 Register result = ToRegister(instr->result());
3244 Register scratch1 = scratch0();
3245 Register except_flag = ToRegister(instr->temp());
3246
3247 __ EmitFPUTruncate(kRoundToMinusInf,
3248 result,
3249 input,
3250 scratch1,
3251 double_scratch0(),
3252 except_flag);
3253
3254 // Deopt if the operation did not succeed.
3255 DeoptimizeIf(ne, instr, DeoptimizeReason::kLostPrecisionOrNaN, except_flag,
3256 Operand(zero_reg));
3257
3258 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3259 // Test for -0.
3260 Label done;
3261 __ Branch(&done, ne, result, Operand(zero_reg));
3262 __ Mfhc1(scratch1, input);
3263 __ And(scratch1, scratch1, Operand(HeapNumber::kSignMask));
3264 DeoptimizeIf(ne, instr, DeoptimizeReason::kMinusZero, scratch1,
3265 Operand(zero_reg));
3266 __ bind(&done);
3267 }
3268 }
3269
3270
DoMathRound(LMathRound * instr)3271 void LCodeGen::DoMathRound(LMathRound* instr) {
3272 DoubleRegister input = ToDoubleRegister(instr->value());
3273 Register result = ToRegister(instr->result());
3274 DoubleRegister double_scratch1 = ToDoubleRegister(instr->temp());
3275 Register scratch = scratch0();
3276 Label done, check_sign_on_zero;
3277
3278 // Extract exponent bits.
3279 __ Mfhc1(result, input);
3280 __ Ext(scratch,
3281 result,
3282 HeapNumber::kExponentShift,
3283 HeapNumber::kExponentBits);
3284
3285 // If the number is in ]-0.5, +0.5[, the result is +/- 0.
3286 Label skip1;
3287 __ Branch(&skip1, gt, scratch, Operand(HeapNumber::kExponentBias - 2));
3288 __ mov(result, zero_reg);
3289 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3290 __ Branch(&check_sign_on_zero);
3291 } else {
3292 __ Branch(&done);
3293 }
3294 __ bind(&skip1);
3295
3296 // The following conversion will not work with numbers
3297 // outside of ]-2^32, 2^32[.
3298 DeoptimizeIf(ge, instr, DeoptimizeReason::kOverflow, scratch,
3299 Operand(HeapNumber::kExponentBias + 32));
3300
3301 // Save the original sign for later comparison.
3302 __ And(scratch, result, Operand(HeapNumber::kSignMask));
3303
3304 __ Move(double_scratch0(), 0.5);
3305 __ add_d(double_scratch0(), input, double_scratch0());
3306
3307 // Check sign of the result: if the sign changed, the input
3308 // value was in ]0.5, 0[ and the result should be -0.
3309 __ Mfhc1(result, double_scratch0());
3310 __ Xor(result, result, Operand(scratch));
3311 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3312 // ARM uses 'mi' here, which is 'lt'
3313 DeoptimizeIf(lt, instr, DeoptimizeReason::kMinusZero, result,
3314 Operand(zero_reg));
3315 } else {
3316 Label skip2;
3317 // ARM uses 'mi' here, which is 'lt'
3318 // Negating it results in 'ge'
3319 __ Branch(&skip2, ge, result, Operand(zero_reg));
3320 __ mov(result, zero_reg);
3321 __ Branch(&done);
3322 __ bind(&skip2);
3323 }
3324
3325 Register except_flag = scratch;
3326 __ EmitFPUTruncate(kRoundToMinusInf,
3327 result,
3328 double_scratch0(),
3329 at,
3330 double_scratch1,
3331 except_flag);
3332
3333 DeoptimizeIf(ne, instr, DeoptimizeReason::kLostPrecisionOrNaN, except_flag,
3334 Operand(zero_reg));
3335
3336 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
3337 // Test for -0.
3338 __ Branch(&done, ne, result, Operand(zero_reg));
3339 __ bind(&check_sign_on_zero);
3340 __ Mfhc1(scratch, input);
3341 __ And(scratch, scratch, Operand(HeapNumber::kSignMask));
3342 DeoptimizeIf(ne, instr, DeoptimizeReason::kMinusZero, scratch,
3343 Operand(zero_reg));
3344 }
3345 __ bind(&done);
3346 }
3347
3348
DoMathFround(LMathFround * instr)3349 void LCodeGen::DoMathFround(LMathFround* instr) {
3350 DoubleRegister input = ToDoubleRegister(instr->value());
3351 DoubleRegister result = ToDoubleRegister(instr->result());
3352 __ cvt_s_d(result.low(), input);
3353 __ cvt_d_s(result, result.low());
3354 }
3355
3356
DoMathSqrt(LMathSqrt * instr)3357 void LCodeGen::DoMathSqrt(LMathSqrt* instr) {
3358 DoubleRegister input = ToDoubleRegister(instr->value());
3359 DoubleRegister result = ToDoubleRegister(instr->result());
3360 __ sqrt_d(result, input);
3361 }
3362
3363
DoMathPowHalf(LMathPowHalf * instr)3364 void LCodeGen::DoMathPowHalf(LMathPowHalf* instr) {
3365 DoubleRegister input = ToDoubleRegister(instr->value());
3366 DoubleRegister result = ToDoubleRegister(instr->result());
3367 DoubleRegister temp = ToDoubleRegister(instr->temp());
3368
3369 DCHECK(!input.is(result));
3370
3371 // Note that according to ECMA-262 15.8.2.13:
3372 // Math.pow(-Infinity, 0.5) == Infinity
3373 // Math.sqrt(-Infinity) == NaN
3374 Label done;
3375 __ Move(temp, static_cast<double>(-V8_INFINITY));
3376 // Set up Infinity.
3377 __ Neg_d(result, temp);
3378 // result is overwritten if the branch is not taken.
3379 __ BranchF(&done, NULL, eq, temp, input);
3380
3381 // Add +0 to convert -0 to +0.
3382 __ add_d(result, input, kDoubleRegZero);
3383 __ sqrt_d(result, result);
3384 __ bind(&done);
3385 }
3386
3387
DoPower(LPower * instr)3388 void LCodeGen::DoPower(LPower* instr) {
3389 Representation exponent_type = instr->hydrogen()->right()->representation();
3390 // Having marked this as a call, we can use any registers.
3391 // Just make sure that the input/output registers are the expected ones.
3392 Register tagged_exponent = MathPowTaggedDescriptor::exponent();
3393 DCHECK(!instr->right()->IsDoubleRegister() ||
3394 ToDoubleRegister(instr->right()).is(f4));
3395 DCHECK(!instr->right()->IsRegister() ||
3396 ToRegister(instr->right()).is(tagged_exponent));
3397 DCHECK(ToDoubleRegister(instr->left()).is(f2));
3398 DCHECK(ToDoubleRegister(instr->result()).is(f0));
3399
3400 if (exponent_type.IsSmi()) {
3401 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3402 __ CallStub(&stub);
3403 } else if (exponent_type.IsTagged()) {
3404 Label no_deopt;
3405 __ JumpIfSmi(tagged_exponent, &no_deopt);
3406 DCHECK(!t3.is(tagged_exponent));
3407 __ lw(t3, FieldMemOperand(tagged_exponent, HeapObject::kMapOffset));
3408 __ LoadRoot(at, Heap::kHeapNumberMapRootIndex);
3409 DeoptimizeIf(ne, instr, DeoptimizeReason::kNotAHeapNumber, t3, Operand(at));
3410 __ bind(&no_deopt);
3411 MathPowStub stub(isolate(), MathPowStub::TAGGED);
3412 __ CallStub(&stub);
3413 } else if (exponent_type.IsInteger32()) {
3414 MathPowStub stub(isolate(), MathPowStub::INTEGER);
3415 __ CallStub(&stub);
3416 } else {
3417 DCHECK(exponent_type.IsDouble());
3418 MathPowStub stub(isolate(), MathPowStub::DOUBLE);
3419 __ CallStub(&stub);
3420 }
3421 }
3422
DoMathCos(LMathCos * instr)3423 void LCodeGen::DoMathCos(LMathCos* instr) {
3424 __ PrepareCallCFunction(0, 1, scratch0());
3425 __ MovToFloatParameter(ToDoubleRegister(instr->value()));
3426 __ CallCFunction(ExternalReference::ieee754_cos_function(isolate()), 0, 1);
3427 __ MovFromFloatResult(ToDoubleRegister(instr->result()));
3428 }
3429
DoMathSin(LMathSin * instr)3430 void LCodeGen::DoMathSin(LMathSin* instr) {
3431 __ PrepareCallCFunction(0, 1, scratch0());
3432 __ MovToFloatParameter(ToDoubleRegister(instr->value()));
3433 __ CallCFunction(ExternalReference::ieee754_sin_function(isolate()), 0, 1);
3434 __ MovFromFloatResult(ToDoubleRegister(instr->result()));
3435 }
3436
DoMathExp(LMathExp * instr)3437 void LCodeGen::DoMathExp(LMathExp* instr) {
3438 __ PrepareCallCFunction(0, 1, scratch0());
3439 __ MovToFloatParameter(ToDoubleRegister(instr->value()));
3440 __ CallCFunction(ExternalReference::ieee754_exp_function(isolate()), 0, 1);
3441 __ MovFromFloatResult(ToDoubleRegister(instr->result()));
3442 }
3443
3444
DoMathLog(LMathLog * instr)3445 void LCodeGen::DoMathLog(LMathLog* instr) {
3446 __ PrepareCallCFunction(0, 1, scratch0());
3447 __ MovToFloatParameter(ToDoubleRegister(instr->value()));
3448 __ CallCFunction(ExternalReference::ieee754_log_function(isolate()), 0, 1);
3449 __ MovFromFloatResult(ToDoubleRegister(instr->result()));
3450 }
3451
3452
DoMathClz32(LMathClz32 * instr)3453 void LCodeGen::DoMathClz32(LMathClz32* instr) {
3454 Register input = ToRegister(instr->value());
3455 Register result = ToRegister(instr->result());
3456 __ Clz(result, input);
3457 }
3458
PrepareForTailCall(const ParameterCount & actual,Register scratch1,Register scratch2,Register scratch3)3459 void LCodeGen::PrepareForTailCall(const ParameterCount& actual,
3460 Register scratch1, Register scratch2,
3461 Register scratch3) {
3462 #if DEBUG
3463 if (actual.is_reg()) {
3464 DCHECK(!AreAliased(actual.reg(), scratch1, scratch2, scratch3));
3465 } else {
3466 DCHECK(!AreAliased(scratch1, scratch2, scratch3));
3467 }
3468 #endif
3469 if (FLAG_code_comments) {
3470 if (actual.is_reg()) {
3471 Comment(";;; PrepareForTailCall, actual: %s {",
3472 RegisterConfiguration::Crankshaft()->GetGeneralRegisterName(
3473 actual.reg().code()));
3474 } else {
3475 Comment(";;; PrepareForTailCall, actual: %d {", actual.immediate());
3476 }
3477 }
3478
3479 // Check if next frame is an arguments adaptor frame.
3480 Register caller_args_count_reg = scratch1;
3481 Label no_arguments_adaptor, formal_parameter_count_loaded;
3482 __ lw(scratch2, MemOperand(fp, StandardFrameConstants::kCallerFPOffset));
3483 __ lw(scratch3, MemOperand(scratch2, StandardFrameConstants::kContextOffset));
3484 __ Branch(&no_arguments_adaptor, ne, scratch3,
3485 Operand(Smi::FromInt(StackFrame::ARGUMENTS_ADAPTOR)));
3486
3487 // Drop current frame and load arguments count from arguments adaptor frame.
3488 __ mov(fp, scratch2);
3489 __ lw(caller_args_count_reg,
3490 MemOperand(fp, ArgumentsAdaptorFrameConstants::kLengthOffset));
3491 __ SmiUntag(caller_args_count_reg);
3492 __ Branch(&formal_parameter_count_loaded);
3493
3494 __ bind(&no_arguments_adaptor);
3495 // Load caller's formal parameter count
3496 __ lw(scratch1, MemOperand(fp, JavaScriptFrameConstants::kFunctionOffset));
3497 __ lw(scratch1,
3498 FieldMemOperand(scratch1, JSFunction::kSharedFunctionInfoOffset));
3499 __ li(caller_args_count_reg, Operand(info()->literal()->parameter_count()));
3500
3501 __ bind(&formal_parameter_count_loaded);
3502 __ PrepareForTailCall(actual, caller_args_count_reg, scratch2, scratch3);
3503
3504 Comment(";;; }");
3505 }
3506
DoInvokeFunction(LInvokeFunction * instr)3507 void LCodeGen::DoInvokeFunction(LInvokeFunction* instr) {
3508 HInvokeFunction* hinstr = instr->hydrogen();
3509 DCHECK(ToRegister(instr->context()).is(cp));
3510 DCHECK(ToRegister(instr->function()).is(a1));
3511 DCHECK(instr->HasPointerMap());
3512
3513 bool is_tail_call = hinstr->tail_call_mode() == TailCallMode::kAllow;
3514
3515 if (is_tail_call) {
3516 DCHECK(!info()->saves_caller_doubles());
3517 ParameterCount actual(instr->arity());
3518 // It is safe to use t0, t1 and t2 as scratch registers here given that
3519 // we are not going to return to caller function anyway.
3520 PrepareForTailCall(actual, t0, t1, t2);
3521 }
3522
3523 Handle<JSFunction> known_function = hinstr->known_function();
3524 if (known_function.is_null()) {
3525 LPointerMap* pointers = instr->pointer_map();
3526 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3527 ParameterCount actual(instr->arity());
3528 InvokeFlag flag = is_tail_call ? JUMP_FUNCTION : CALL_FUNCTION;
3529 __ InvokeFunction(a1, no_reg, actual, flag, generator);
3530 } else {
3531 CallKnownFunction(known_function, hinstr->formal_parameter_count(),
3532 instr->arity(), is_tail_call, instr);
3533 }
3534 }
3535
3536
DoCallWithDescriptor(LCallWithDescriptor * instr)3537 void LCodeGen::DoCallWithDescriptor(LCallWithDescriptor* instr) {
3538 DCHECK(ToRegister(instr->result()).is(v0));
3539
3540 if (instr->hydrogen()->IsTailCall()) {
3541 if (NeedsEagerFrame()) __ LeaveFrame(StackFrame::INTERNAL);
3542
3543 if (instr->target()->IsConstantOperand()) {
3544 LConstantOperand* target = LConstantOperand::cast(instr->target());
3545 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3546 __ Jump(code, RelocInfo::CODE_TARGET);
3547 } else {
3548 DCHECK(instr->target()->IsRegister());
3549 Register target = ToRegister(instr->target());
3550 __ Addu(target, target, Operand(Code::kHeaderSize - kHeapObjectTag));
3551 __ Jump(target);
3552 }
3553 } else {
3554 LPointerMap* pointers = instr->pointer_map();
3555 SafepointGenerator generator(this, pointers, Safepoint::kLazyDeopt);
3556
3557 if (instr->target()->IsConstantOperand()) {
3558 LConstantOperand* target = LConstantOperand::cast(instr->target());
3559 Handle<Code> code = Handle<Code>::cast(ToHandle(target));
3560 generator.BeforeCall(__ CallSize(code, RelocInfo::CODE_TARGET));
3561 __ Call(code, RelocInfo::CODE_TARGET);
3562 } else {
3563 DCHECK(instr->target()->IsRegister());
3564 Register target = ToRegister(instr->target());
3565 generator.BeforeCall(__ CallSize(target));
3566 __ Addu(target, target, Operand(Code::kHeaderSize - kHeapObjectTag));
3567 __ Call(target);
3568 }
3569 generator.AfterCall();
3570 }
3571 }
3572
3573
DoCallNewArray(LCallNewArray * instr)3574 void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
3575 DCHECK(ToRegister(instr->context()).is(cp));
3576 DCHECK(ToRegister(instr->constructor()).is(a1));
3577 DCHECK(ToRegister(instr->result()).is(v0));
3578
3579 __ li(a0, Operand(instr->arity()));
3580 __ li(a2, instr->hydrogen()->site());
3581
3582 ElementsKind kind = instr->hydrogen()->elements_kind();
3583 AllocationSiteOverrideMode override_mode =
3584 (AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
3585 ? DISABLE_ALLOCATION_SITES
3586 : DONT_OVERRIDE;
3587
3588 if (instr->arity() == 0) {
3589 ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
3590 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3591 } else if (instr->arity() == 1) {
3592 Label done;
3593 if (IsFastPackedElementsKind(kind)) {
3594 Label packed_case;
3595 // We might need a change here,
3596 // look at the first argument.
3597 __ lw(t1, MemOperand(sp, 0));
3598 __ Branch(&packed_case, eq, t1, Operand(zero_reg));
3599
3600 ElementsKind holey_kind = GetHoleyElementsKind(kind);
3601 ArraySingleArgumentConstructorStub stub(isolate(),
3602 holey_kind,
3603 override_mode);
3604 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3605 __ jmp(&done);
3606 __ bind(&packed_case);
3607 }
3608
3609 ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
3610 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3611 __ bind(&done);
3612 } else {
3613 ArrayNArgumentsConstructorStub stub(isolate());
3614 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
3615 }
3616 }
3617
3618
DoCallRuntime(LCallRuntime * instr)3619 void LCodeGen::DoCallRuntime(LCallRuntime* instr) {
3620 CallRuntime(instr->function(), instr->arity(), instr);
3621 }
3622
3623
DoStoreCodeEntry(LStoreCodeEntry * instr)3624 void LCodeGen::DoStoreCodeEntry(LStoreCodeEntry* instr) {
3625 Register function = ToRegister(instr->function());
3626 Register code_object = ToRegister(instr->code_object());
3627 __ Addu(code_object, code_object,
3628 Operand(Code::kHeaderSize - kHeapObjectTag));
3629 __ sw(code_object,
3630 FieldMemOperand(function, JSFunction::kCodeEntryOffset));
3631 }
3632
3633
DoInnerAllocatedObject(LInnerAllocatedObject * instr)3634 void LCodeGen::DoInnerAllocatedObject(LInnerAllocatedObject* instr) {
3635 Register result = ToRegister(instr->result());
3636 Register base = ToRegister(instr->base_object());
3637 if (instr->offset()->IsConstantOperand()) {
3638 LConstantOperand* offset = LConstantOperand::cast(instr->offset());
3639 __ Addu(result, base, Operand(ToInteger32(offset)));
3640 } else {
3641 Register offset = ToRegister(instr->offset());
3642 __ Addu(result, base, offset);
3643 }
3644 }
3645
3646
DoStoreNamedField(LStoreNamedField * instr)3647 void LCodeGen::DoStoreNamedField(LStoreNamedField* instr) {
3648 Representation representation = instr->representation();
3649
3650 Register object = ToRegister(instr->object());
3651 Register scratch = scratch0();
3652 HObjectAccess access = instr->hydrogen()->access();
3653 int offset = access.offset();
3654
3655 if (access.IsExternalMemory()) {
3656 Register value = ToRegister(instr->value());
3657 MemOperand operand = MemOperand(object, offset);
3658 __ Store(value, operand, representation);
3659 return;
3660 }
3661
3662 __ AssertNotSmi(object);
3663
3664 DCHECK(!representation.IsSmi() ||
3665 !instr->value()->IsConstantOperand() ||
3666 IsSmi(LConstantOperand::cast(instr->value())));
3667 if (representation.IsDouble()) {
3668 DCHECK(access.IsInobject());
3669 DCHECK(!instr->hydrogen()->has_transition());
3670 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
3671 DoubleRegister value = ToDoubleRegister(instr->value());
3672 __ sdc1(value, FieldMemOperand(object, offset));
3673 return;
3674 }
3675
3676 if (instr->hydrogen()->has_transition()) {
3677 Handle<Map> transition = instr->hydrogen()->transition_map();
3678 AddDeprecationDependency(transition);
3679 __ li(scratch, Operand(transition));
3680 __ sw(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
3681 if (instr->hydrogen()->NeedsWriteBarrierForMap()) {
3682 Register temp = ToRegister(instr->temp());
3683 // Update the write barrier for the map field.
3684 __ RecordWriteForMap(object,
3685 scratch,
3686 temp,
3687 GetRAState(),
3688 kSaveFPRegs);
3689 }
3690 }
3691
3692 // Do the store.
3693 Register value = ToRegister(instr->value());
3694 if (access.IsInobject()) {
3695 MemOperand operand = FieldMemOperand(object, offset);
3696 __ Store(value, operand, representation);
3697 if (instr->hydrogen()->NeedsWriteBarrier()) {
3698 // Update the write barrier for the object for in-object properties.
3699 __ RecordWriteField(object,
3700 offset,
3701 value,
3702 scratch,
3703 GetRAState(),
3704 kSaveFPRegs,
3705 EMIT_REMEMBERED_SET,
3706 instr->hydrogen()->SmiCheckForWriteBarrier(),
3707 instr->hydrogen()->PointersToHereCheckForValue());
3708 }
3709 } else {
3710 __ lw(scratch, FieldMemOperand(object, JSObject::kPropertiesOffset));
3711 MemOperand operand = FieldMemOperand(scratch, offset);
3712 __ Store(value, operand, representation);
3713 if (instr->hydrogen()->NeedsWriteBarrier()) {
3714 // Update the write barrier for the properties array.
3715 // object is used as a scratch register.
3716 __ RecordWriteField(scratch,
3717 offset,
3718 value,
3719 object,
3720 GetRAState(),
3721 kSaveFPRegs,
3722 EMIT_REMEMBERED_SET,
3723 instr->hydrogen()->SmiCheckForWriteBarrier(),
3724 instr->hydrogen()->PointersToHereCheckForValue());
3725 }
3726 }
3727 }
3728
3729
DoBoundsCheck(LBoundsCheck * instr)3730 void LCodeGen::DoBoundsCheck(LBoundsCheck* instr) {
3731 Condition cc = instr->hydrogen()->allow_equality() ? hi : hs;
3732 Operand operand(0);
3733 Register reg;
3734 if (instr->index()->IsConstantOperand()) {
3735 operand = ToOperand(instr->index());
3736 reg = ToRegister(instr->length());
3737 cc = CommuteCondition(cc);
3738 } else {
3739 reg = ToRegister(instr->index());
3740 operand = ToOperand(instr->length());
3741 }
3742 if (FLAG_debug_code && instr->hydrogen()->skip_check()) {
3743 Label done;
3744 __ Branch(&done, NegateCondition(cc), reg, operand);
3745 __ stop("eliminated bounds check failed");
3746 __ bind(&done);
3747 } else {
3748 DeoptimizeIf(cc, instr, DeoptimizeReason::kOutOfBounds, reg, operand);
3749 }
3750 }
3751
3752
DoStoreKeyedExternalArray(LStoreKeyed * instr)3753 void LCodeGen::DoStoreKeyedExternalArray(LStoreKeyed* instr) {
3754 Register external_pointer = ToRegister(instr->elements());
3755 Register key = no_reg;
3756 ElementsKind elements_kind = instr->elements_kind();
3757 bool key_is_constant = instr->key()->IsConstantOperand();
3758 int constant_key = 0;
3759 if (key_is_constant) {
3760 constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
3761 if (constant_key & 0xF0000000) {
3762 Abort(kArrayIndexConstantValueTooBig);
3763 }
3764 } else {
3765 key = ToRegister(instr->key());
3766 }
3767 int element_size_shift = ElementsKindToShiftSize(elements_kind);
3768 int shift_size = (instr->hydrogen()->key()->representation().IsSmi())
3769 ? (element_size_shift - kSmiTagSize) : element_size_shift;
3770 int base_offset = instr->base_offset();
3771
3772 if (elements_kind == FLOAT32_ELEMENTS || elements_kind == FLOAT64_ELEMENTS) {
3773 Register address = scratch0();
3774 FPURegister value(ToDoubleRegister(instr->value()));
3775 if (key_is_constant) {
3776 if (constant_key != 0) {
3777 __ Addu(address, external_pointer,
3778 Operand(constant_key << element_size_shift));
3779 } else {
3780 address = external_pointer;
3781 }
3782 } else {
3783 __ Lsa(address, external_pointer, key, shift_size);
3784 }
3785
3786 if (elements_kind == FLOAT32_ELEMENTS) {
3787 __ cvt_s_d(double_scratch0(), value);
3788 __ swc1(double_scratch0(), MemOperand(address, base_offset));
3789 } else { // Storing doubles, not floats.
3790 __ sdc1(value, MemOperand(address, base_offset));
3791 }
3792 } else {
3793 Register value(ToRegister(instr->value()));
3794 MemOperand mem_operand = PrepareKeyedOperand(
3795 key, external_pointer, key_is_constant, constant_key,
3796 element_size_shift, shift_size,
3797 base_offset);
3798 switch (elements_kind) {
3799 case UINT8_ELEMENTS:
3800 case UINT8_CLAMPED_ELEMENTS:
3801 case INT8_ELEMENTS:
3802 __ sb(value, mem_operand);
3803 break;
3804 case INT16_ELEMENTS:
3805 case UINT16_ELEMENTS:
3806 __ sh(value, mem_operand);
3807 break;
3808 case INT32_ELEMENTS:
3809 case UINT32_ELEMENTS:
3810 __ sw(value, mem_operand);
3811 break;
3812 case FLOAT32_ELEMENTS:
3813 case FLOAT64_ELEMENTS:
3814 case FAST_DOUBLE_ELEMENTS:
3815 case FAST_ELEMENTS:
3816 case FAST_SMI_ELEMENTS:
3817 case FAST_HOLEY_DOUBLE_ELEMENTS:
3818 case FAST_HOLEY_ELEMENTS:
3819 case FAST_HOLEY_SMI_ELEMENTS:
3820 case DICTIONARY_ELEMENTS:
3821 case FAST_SLOPPY_ARGUMENTS_ELEMENTS:
3822 case SLOW_SLOPPY_ARGUMENTS_ELEMENTS:
3823 case FAST_STRING_WRAPPER_ELEMENTS:
3824 case SLOW_STRING_WRAPPER_ELEMENTS:
3825 case NO_ELEMENTS:
3826 UNREACHABLE();
3827 break;
3828 }
3829 }
3830 }
3831
3832
DoStoreKeyedFixedDoubleArray(LStoreKeyed * instr)3833 void LCodeGen::DoStoreKeyedFixedDoubleArray(LStoreKeyed* instr) {
3834 DoubleRegister value = ToDoubleRegister(instr->value());
3835 Register elements = ToRegister(instr->elements());
3836 Register scratch = scratch0();
3837 Register scratch_1 = scratch1();
3838 DoubleRegister double_scratch = double_scratch0();
3839 bool key_is_constant = instr->key()->IsConstantOperand();
3840 int base_offset = instr->base_offset();
3841 Label not_nan, done;
3842
3843 // Calculate the effective address of the slot in the array to store the
3844 // double value.
3845 int element_size_shift = ElementsKindToShiftSize(FAST_DOUBLE_ELEMENTS);
3846 if (key_is_constant) {
3847 int constant_key = ToInteger32(LConstantOperand::cast(instr->key()));
3848 if (constant_key & 0xF0000000) {
3849 Abort(kArrayIndexConstantValueTooBig);
3850 }
3851 __ Addu(scratch, elements,
3852 Operand((constant_key << element_size_shift) + base_offset));
3853 } else {
3854 int shift_size = (instr->hydrogen()->key()->representation().IsSmi())
3855 ? (element_size_shift - kSmiTagSize) : element_size_shift;
3856 __ Addu(scratch, elements, Operand(base_offset));
3857 __ sll(at, ToRegister(instr->key()), shift_size);
3858 __ Addu(scratch, scratch, at);
3859 }
3860
3861 if (instr->NeedsCanonicalization()) {
3862 Label is_nan;
3863 // Check for NaN. All NaNs must be canonicalized.
3864 __ BranchF(NULL, &is_nan, eq, value, value);
3865 __ Branch(¬_nan);
3866
3867 // Only load canonical NaN if the comparison above set the overflow.
3868 __ bind(&is_nan);
3869 __ LoadRoot(scratch_1, Heap::kNanValueRootIndex);
3870 __ ldc1(double_scratch,
3871 FieldMemOperand(scratch_1, HeapNumber::kValueOffset));
3872 __ sdc1(double_scratch, MemOperand(scratch, 0));
3873 __ Branch(&done);
3874 }
3875
3876 __ bind(¬_nan);
3877 __ sdc1(value, MemOperand(scratch, 0));
3878 __ bind(&done);
3879 }
3880
3881
DoStoreKeyedFixedArray(LStoreKeyed * instr)3882 void LCodeGen::DoStoreKeyedFixedArray(LStoreKeyed* instr) {
3883 Register value = ToRegister(instr->value());
3884 Register elements = ToRegister(instr->elements());
3885 Register key = instr->key()->IsRegister() ? ToRegister(instr->key())
3886 : no_reg;
3887 Register scratch = scratch0();
3888 Register store_base = scratch;
3889 int offset = instr->base_offset();
3890
3891 // Do the store.
3892 if (instr->key()->IsConstantOperand()) {
3893 DCHECK(!instr->hydrogen()->NeedsWriteBarrier());
3894 LConstantOperand* const_operand = LConstantOperand::cast(instr->key());
3895 offset += ToInteger32(const_operand) * kPointerSize;
3896 store_base = elements;
3897 } else {
3898 // Even though the HLoadKeyed instruction forces the input
3899 // representation for the key to be an integer, the input gets replaced
3900 // during bound check elimination with the index argument to the bounds
3901 // check, which can be tagged, so that case must be handled here, too.
3902 if (instr->hydrogen()->key()->representation().IsSmi()) {
3903 __ Lsa(scratch, elements, key, kPointerSizeLog2 - kSmiTagSize);
3904 } else {
3905 __ Lsa(scratch, elements, key, kPointerSizeLog2);
3906 }
3907 }
3908 __ sw(value, MemOperand(store_base, offset));
3909
3910 if (instr->hydrogen()->NeedsWriteBarrier()) {
3911 SmiCheck check_needed =
3912 instr->hydrogen()->value()->type().IsHeapObject()
3913 ? OMIT_SMI_CHECK : INLINE_SMI_CHECK;
3914 // Compute address of modified element and store it into key register.
3915 __ Addu(key, store_base, Operand(offset));
3916 __ RecordWrite(elements,
3917 key,
3918 value,
3919 GetRAState(),
3920 kSaveFPRegs,
3921 EMIT_REMEMBERED_SET,
3922 check_needed,
3923 instr->hydrogen()->PointersToHereCheckForValue());
3924 }
3925 }
3926
3927
DoStoreKeyed(LStoreKeyed * instr)3928 void LCodeGen::DoStoreKeyed(LStoreKeyed* instr) {
3929 // By cases: external, fast double
3930 if (instr->is_fixed_typed_array()) {
3931 DoStoreKeyedExternalArray(instr);
3932 } else if (instr->hydrogen()->value()->representation().IsDouble()) {
3933 DoStoreKeyedFixedDoubleArray(instr);
3934 } else {
3935 DoStoreKeyedFixedArray(instr);
3936 }
3937 }
3938
3939
DoMaybeGrowElements(LMaybeGrowElements * instr)3940 void LCodeGen::DoMaybeGrowElements(LMaybeGrowElements* instr) {
3941 class DeferredMaybeGrowElements final : public LDeferredCode {
3942 public:
3943 DeferredMaybeGrowElements(LCodeGen* codegen, LMaybeGrowElements* instr)
3944 : LDeferredCode(codegen), instr_(instr) {}
3945 void Generate() override { codegen()->DoDeferredMaybeGrowElements(instr_); }
3946 LInstruction* instr() override { return instr_; }
3947
3948 private:
3949 LMaybeGrowElements* instr_;
3950 };
3951
3952 Register result = v0;
3953 DeferredMaybeGrowElements* deferred =
3954 new (zone()) DeferredMaybeGrowElements(this, instr);
3955 LOperand* key = instr->key();
3956 LOperand* current_capacity = instr->current_capacity();
3957
3958 DCHECK(instr->hydrogen()->key()->representation().IsInteger32());
3959 DCHECK(instr->hydrogen()->current_capacity()->representation().IsInteger32());
3960 DCHECK(key->IsConstantOperand() || key->IsRegister());
3961 DCHECK(current_capacity->IsConstantOperand() ||
3962 current_capacity->IsRegister());
3963
3964 if (key->IsConstantOperand() && current_capacity->IsConstantOperand()) {
3965 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
3966 int32_t constant_capacity =
3967 ToInteger32(LConstantOperand::cast(current_capacity));
3968 if (constant_key >= constant_capacity) {
3969 // Deferred case.
3970 __ jmp(deferred->entry());
3971 }
3972 } else if (key->IsConstantOperand()) {
3973 int32_t constant_key = ToInteger32(LConstantOperand::cast(key));
3974 __ Branch(deferred->entry(), le, ToRegister(current_capacity),
3975 Operand(constant_key));
3976 } else if (current_capacity->IsConstantOperand()) {
3977 int32_t constant_capacity =
3978 ToInteger32(LConstantOperand::cast(current_capacity));
3979 __ Branch(deferred->entry(), ge, ToRegister(key),
3980 Operand(constant_capacity));
3981 } else {
3982 __ Branch(deferred->entry(), ge, ToRegister(key),
3983 Operand(ToRegister(current_capacity)));
3984 }
3985
3986 if (instr->elements()->IsRegister()) {
3987 __ mov(result, ToRegister(instr->elements()));
3988 } else {
3989 __ lw(result, ToMemOperand(instr->elements()));
3990 }
3991
3992 __ bind(deferred->exit());
3993 }
3994
3995
DoDeferredMaybeGrowElements(LMaybeGrowElements * instr)3996 void LCodeGen::DoDeferredMaybeGrowElements(LMaybeGrowElements* instr) {
3997 // TODO(3095996): Get rid of this. For now, we need to make the
3998 // result register contain a valid pointer because it is already
3999 // contained in the register pointer map.
4000 Register result = v0;
4001 __ mov(result, zero_reg);
4002
4003 // We have to call a stub.
4004 {
4005 PushSafepointRegistersScope scope(this);
4006 if (instr->object()->IsRegister()) {
4007 __ mov(result, ToRegister(instr->object()));
4008 } else {
4009 __ lw(result, ToMemOperand(instr->object()));
4010 }
4011
4012 LOperand* key = instr->key();
4013 if (key->IsConstantOperand()) {
4014 LConstantOperand* constant_key = LConstantOperand::cast(key);
4015 int32_t int_key = ToInteger32(constant_key);
4016 if (Smi::IsValid(int_key)) {
4017 __ li(a3, Operand(Smi::FromInt(int_key)));
4018 } else {
4019 // We should never get here at runtime because there is a smi check on
4020 // the key before this point.
4021 __ stop("expected smi");
4022 }
4023 } else {
4024 __ mov(a3, ToRegister(key));
4025 __ SmiTag(a3);
4026 }
4027
4028 GrowArrayElementsStub stub(isolate(), instr->hydrogen()->kind());
4029 __ mov(a0, result);
4030 __ CallStub(&stub);
4031 RecordSafepointWithLazyDeopt(
4032 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
4033 __ StoreToSafepointRegisterSlot(result, result);
4034 }
4035
4036 // Deopt on smi, which means the elements array changed to dictionary mode.
4037 __ SmiTst(result, at);
4038 DeoptimizeIf(eq, instr, DeoptimizeReason::kSmi, at, Operand(zero_reg));
4039 }
4040
4041
DoTransitionElementsKind(LTransitionElementsKind * instr)4042 void LCodeGen::DoTransitionElementsKind(LTransitionElementsKind* instr) {
4043 Register object_reg = ToRegister(instr->object());
4044 Register scratch = scratch0();
4045
4046 Handle<Map> from_map = instr->original_map();
4047 Handle<Map> to_map = instr->transitioned_map();
4048 ElementsKind from_kind = instr->from_kind();
4049 ElementsKind to_kind = instr->to_kind();
4050
4051 Label not_applicable;
4052 __ lw(scratch, FieldMemOperand(object_reg, HeapObject::kMapOffset));
4053 __ Branch(¬_applicable, ne, scratch, Operand(from_map));
4054
4055 if (IsSimpleMapChangeTransition(from_kind, to_kind)) {
4056 Register new_map_reg = ToRegister(instr->new_map_temp());
4057 __ li(new_map_reg, Operand(to_map));
4058 __ sw(new_map_reg, FieldMemOperand(object_reg, HeapObject::kMapOffset));
4059 // Write barrier.
4060 __ RecordWriteForMap(object_reg,
4061 new_map_reg,
4062 scratch,
4063 GetRAState(),
4064 kDontSaveFPRegs);
4065 } else {
4066 DCHECK(object_reg.is(a0));
4067 DCHECK(ToRegister(instr->context()).is(cp));
4068 PushSafepointRegistersScope scope(this);
4069 __ li(a1, Operand(to_map));
4070 TransitionElementsKindStub stub(isolate(), from_kind, to_kind);
4071 __ CallStub(&stub);
4072 RecordSafepointWithRegisters(
4073 instr->pointer_map(), 0, Safepoint::kLazyDeopt);
4074 }
4075 __ bind(¬_applicable);
4076 }
4077
4078
DoTrapAllocationMemento(LTrapAllocationMemento * instr)4079 void LCodeGen::DoTrapAllocationMemento(LTrapAllocationMemento* instr) {
4080 Register object = ToRegister(instr->object());
4081 Register temp = ToRegister(instr->temp());
4082 Label no_memento_found;
4083 __ TestJSArrayForAllocationMemento(object, temp, &no_memento_found);
4084 DeoptimizeIf(al, instr);
4085 __ bind(&no_memento_found);
4086 }
4087
4088
DoStringAdd(LStringAdd * instr)4089 void LCodeGen::DoStringAdd(LStringAdd* instr) {
4090 DCHECK(ToRegister(instr->context()).is(cp));
4091 DCHECK(ToRegister(instr->left()).is(a1));
4092 DCHECK(ToRegister(instr->right()).is(a0));
4093 StringAddStub stub(isolate(),
4094 instr->hydrogen()->flags(),
4095 instr->hydrogen()->pretenure_flag());
4096 CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
4097 }
4098
4099
DoStringCharCodeAt(LStringCharCodeAt * instr)4100 void LCodeGen::DoStringCharCodeAt(LStringCharCodeAt* instr) {
4101 class DeferredStringCharCodeAt final : public LDeferredCode {
4102 public:
4103 DeferredStringCharCodeAt(LCodeGen* codegen, LStringCharCodeAt* instr)
4104 : LDeferredCode(codegen), instr_(instr) { }
4105 void Generate() override { codegen()->DoDeferredStringCharCodeAt(instr_); }
4106 LInstruction* instr() override { return instr_; }
4107
4108 private:
4109 LStringCharCodeAt* instr_;
4110 };
4111
4112 DeferredStringCharCodeAt* deferred =
4113 new(zone()) DeferredStringCharCodeAt(this, instr);
4114 StringCharLoadGenerator::Generate(masm(),
4115 ToRegister(instr->string()),
4116 ToRegister(instr->index()),
4117 ToRegister(instr->result()),
4118 deferred->entry());
4119 __ bind(deferred->exit());
4120 }
4121
4122
DoDeferredStringCharCodeAt(LStringCharCodeAt * instr)4123 void LCodeGen::DoDeferredStringCharCodeAt(LStringCharCodeAt* instr) {
4124 Register string = ToRegister(instr->string());
4125 Register result = ToRegister(instr->result());
4126 Register scratch = scratch0();
4127
4128 // TODO(3095996): Get rid of this. For now, we need to make the
4129 // result register contain a valid pointer because it is already
4130 // contained in the register pointer map.
4131 __ mov(result, zero_reg);
4132
4133 PushSafepointRegistersScope scope(this);
4134 __ push(string);
4135 // Push the index as a smi. This is safe because of the checks in
4136 // DoStringCharCodeAt above.
4137 if (instr->index()->IsConstantOperand()) {
4138 int const_index = ToInteger32(LConstantOperand::cast(instr->index()));
4139 __ Addu(scratch, zero_reg, Operand(Smi::FromInt(const_index)));
4140 __ push(scratch);
4141 } else {
4142 Register index = ToRegister(instr->index());
4143 __ SmiTag(index);
4144 __ push(index);
4145 }
4146 CallRuntimeFromDeferred(Runtime::kStringCharCodeAtRT, 2, instr,
4147 instr->context());
4148 __ AssertSmi(v0);
4149 __ SmiUntag(v0);
4150 __ StoreToSafepointRegisterSlot(v0, result);
4151 }
4152
4153
DoStringCharFromCode(LStringCharFromCode * instr)4154 void LCodeGen::DoStringCharFromCode(LStringCharFromCode* instr) {
4155 class DeferredStringCharFromCode final : public LDeferredCode {
4156 public:
4157 DeferredStringCharFromCode(LCodeGen* codegen, LStringCharFromCode* instr)
4158 : LDeferredCode(codegen), instr_(instr) { }
4159 void Generate() override {
4160 codegen()->DoDeferredStringCharFromCode(instr_);
4161 }
4162 LInstruction* instr() override { return instr_; }
4163
4164 private:
4165 LStringCharFromCode* instr_;
4166 };
4167
4168 DeferredStringCharFromCode* deferred =
4169 new(zone()) DeferredStringCharFromCode(this, instr);
4170
4171 DCHECK(instr->hydrogen()->value()->representation().IsInteger32());
4172 Register char_code = ToRegister(instr->char_code());
4173 Register result = ToRegister(instr->result());
4174 Register scratch = scratch0();
4175 DCHECK(!char_code.is(result));
4176
4177 __ Branch(deferred->entry(), hi,
4178 char_code, Operand(String::kMaxOneByteCharCode));
4179 __ LoadRoot(result, Heap::kSingleCharacterStringCacheRootIndex);
4180 __ Lsa(result, result, char_code, kPointerSizeLog2);
4181 __ lw(result, FieldMemOperand(result, FixedArray::kHeaderSize));
4182 __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex);
4183 __ Branch(deferred->entry(), eq, result, Operand(scratch));
4184 __ bind(deferred->exit());
4185 }
4186
4187
DoDeferredStringCharFromCode(LStringCharFromCode * instr)4188 void LCodeGen::DoDeferredStringCharFromCode(LStringCharFromCode* instr) {
4189 Register char_code = ToRegister(instr->char_code());
4190 Register result = ToRegister(instr->result());
4191
4192 // TODO(3095996): Get rid of this. For now, we need to make the
4193 // result register contain a valid pointer because it is already
4194 // contained in the register pointer map.
4195 __ mov(result, zero_reg);
4196
4197 PushSafepointRegistersScope scope(this);
4198 __ SmiTag(char_code);
4199 __ push(char_code);
4200 CallRuntimeFromDeferred(Runtime::kStringCharFromCode, 1, instr,
4201 instr->context());
4202 __ StoreToSafepointRegisterSlot(v0, result);
4203 }
4204
4205
DoInteger32ToDouble(LInteger32ToDouble * instr)4206 void LCodeGen::DoInteger32ToDouble(LInteger32ToDouble* instr) {
4207 LOperand* input = instr->value();
4208 DCHECK(input->IsRegister() || input->IsStackSlot());
4209 LOperand* output = instr->result();
4210 DCHECK(output->IsDoubleRegister());
4211 FPURegister single_scratch = double_scratch0().low();
4212 if (input->IsStackSlot()) {
4213 Register scratch = scratch0();
4214 __ lw(scratch, ToMemOperand(input));
4215 __ mtc1(scratch, single_scratch);
4216 } else {
4217 __ mtc1(ToRegister(input), single_scratch);
4218 }
4219 __ cvt_d_w(ToDoubleRegister(output), single_scratch);
4220 }
4221
4222
DoUint32ToDouble(LUint32ToDouble * instr)4223 void LCodeGen::DoUint32ToDouble(LUint32ToDouble* instr) {
4224 LOperand* input = instr->value();
4225 LOperand* output = instr->result();
4226
4227 __ Cvt_d_uw(ToDoubleRegister(output), ToRegister(input), f22);
4228 }
4229
4230
DoNumberTagI(LNumberTagI * instr)4231 void LCodeGen::DoNumberTagI(LNumberTagI* instr) {
4232 class DeferredNumberTagI final : public LDeferredCode {
4233 public:
4234 DeferredNumberTagI(LCodeGen* codegen, LNumberTagI* instr)
4235 : LDeferredCode(codegen), instr_(instr) { }
4236 void Generate() override {
4237 codegen()->DoDeferredNumberTagIU(instr_,
4238 instr_->value(),
4239 instr_->temp1(),
4240 instr_->temp2(),
4241 SIGNED_INT32);
4242 }
4243 LInstruction* instr() override { return instr_; }
4244
4245 private:
4246 LNumberTagI* instr_;
4247 };
4248
4249 Register src = ToRegister(instr->value());
4250 Register dst = ToRegister(instr->result());
4251 Register overflow = scratch0();
4252
4253 DeferredNumberTagI* deferred = new(zone()) DeferredNumberTagI(this, instr);
4254 __ SmiTagCheckOverflow(dst, src, overflow);
4255 __ BranchOnOverflow(deferred->entry(), overflow);
4256 __ bind(deferred->exit());
4257 }
4258
4259
DoNumberTagU(LNumberTagU * instr)4260 void LCodeGen::DoNumberTagU(LNumberTagU* instr) {
4261 class DeferredNumberTagU final : public LDeferredCode {
4262 public:
4263 DeferredNumberTagU(LCodeGen* codegen, LNumberTagU* instr)
4264 : LDeferredCode(codegen), instr_(instr) { }
4265 void Generate() override {
4266 codegen()->DoDeferredNumberTagIU(instr_,
4267 instr_->value(),
4268 instr_->temp1(),
4269 instr_->temp2(),
4270 UNSIGNED_INT32);
4271 }
4272 LInstruction* instr() override { return instr_; }
4273
4274 private:
4275 LNumberTagU* instr_;
4276 };
4277
4278 Register input = ToRegister(instr->value());
4279 Register result = ToRegister(instr->result());
4280
4281 DeferredNumberTagU* deferred = new(zone()) DeferredNumberTagU(this, instr);
4282 __ Branch(deferred->entry(), hi, input, Operand(Smi::kMaxValue));
4283 __ SmiTag(result, input);
4284 __ bind(deferred->exit());
4285 }
4286
4287
DoDeferredNumberTagIU(LInstruction * instr,LOperand * value,LOperand * temp1,LOperand * temp2,IntegerSignedness signedness)4288 void LCodeGen::DoDeferredNumberTagIU(LInstruction* instr,
4289 LOperand* value,
4290 LOperand* temp1,
4291 LOperand* temp2,
4292 IntegerSignedness signedness) {
4293 Label done, slow;
4294 Register src = ToRegister(value);
4295 Register dst = ToRegister(instr->result());
4296 Register tmp1 = scratch0();
4297 Register tmp2 = ToRegister(temp1);
4298 Register tmp3 = ToRegister(temp2);
4299 DoubleRegister dbl_scratch = double_scratch0();
4300
4301 if (signedness == SIGNED_INT32) {
4302 // There was overflow, so bits 30 and 31 of the original integer
4303 // disagree. Try to allocate a heap number in new space and store
4304 // the value in there. If that fails, call the runtime system.
4305 if (dst.is(src)) {
4306 __ SmiUntag(src, dst);
4307 __ Xor(src, src, Operand(0x80000000));
4308 }
4309 __ mtc1(src, dbl_scratch);
4310 __ cvt_d_w(dbl_scratch, dbl_scratch);
4311 } else {
4312 __ Cvt_d_uw(dbl_scratch, src, f22);
4313 }
4314
4315 if (FLAG_inline_new) {
4316 __ LoadRoot(tmp3, Heap::kHeapNumberMapRootIndex);
4317 __ AllocateHeapNumber(dst, tmp1, tmp2, tmp3, &slow);
4318 __ Branch(&done);
4319 }
4320
4321 // Slow case: Call the runtime system to do the number allocation.
4322 __ bind(&slow);
4323 {
4324 // TODO(3095996): Put a valid pointer value in the stack slot where the
4325 // result register is stored, as this register is in the pointer map, but
4326 // contains an integer value.
4327 __ mov(dst, zero_reg);
4328
4329 // Preserve the value of all registers.
4330 PushSafepointRegistersScope scope(this);
4331 // Reset the context register.
4332 if (!dst.is(cp)) {
4333 __ mov(cp, zero_reg);
4334 }
4335 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4336 RecordSafepointWithRegisters(
4337 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4338 __ StoreToSafepointRegisterSlot(v0, dst);
4339 }
4340
4341 // Done. Put the value in dbl_scratch into the value of the allocated heap
4342 // number.
4343 __ bind(&done);
4344 __ sdc1(dbl_scratch, FieldMemOperand(dst, HeapNumber::kValueOffset));
4345 }
4346
4347
DoNumberTagD(LNumberTagD * instr)4348 void LCodeGen::DoNumberTagD(LNumberTagD* instr) {
4349 class DeferredNumberTagD final : public LDeferredCode {
4350 public:
4351 DeferredNumberTagD(LCodeGen* codegen, LNumberTagD* instr)
4352 : LDeferredCode(codegen), instr_(instr) { }
4353 void Generate() override { codegen()->DoDeferredNumberTagD(instr_); }
4354 LInstruction* instr() override { return instr_; }
4355
4356 private:
4357 LNumberTagD* instr_;
4358 };
4359
4360 DoubleRegister input_reg = ToDoubleRegister(instr->value());
4361 Register scratch = scratch0();
4362 Register reg = ToRegister(instr->result());
4363 Register temp1 = ToRegister(instr->temp());
4364 Register temp2 = ToRegister(instr->temp2());
4365
4366 DeferredNumberTagD* deferred = new(zone()) DeferredNumberTagD(this, instr);
4367 if (FLAG_inline_new) {
4368 __ LoadRoot(scratch, Heap::kHeapNumberMapRootIndex);
4369 __ AllocateHeapNumber(reg, temp1, temp2, scratch, deferred->entry());
4370 } else {
4371 __ Branch(deferred->entry());
4372 }
4373 __ bind(deferred->exit());
4374 __ sdc1(input_reg, FieldMemOperand(reg, HeapNumber::kValueOffset));
4375 // Now that we have finished with the object's real address tag it
4376 }
4377
4378
DoDeferredNumberTagD(LNumberTagD * instr)4379 void LCodeGen::DoDeferredNumberTagD(LNumberTagD* instr) {
4380 // TODO(3095996): Get rid of this. For now, we need to make the
4381 // result register contain a valid pointer because it is already
4382 // contained in the register pointer map.
4383 Register reg = ToRegister(instr->result());
4384 __ mov(reg, zero_reg);
4385
4386 PushSafepointRegistersScope scope(this);
4387 // Reset the context register.
4388 if (!reg.is(cp)) {
4389 __ mov(cp, zero_reg);
4390 }
4391 __ CallRuntimeSaveDoubles(Runtime::kAllocateHeapNumber);
4392 RecordSafepointWithRegisters(
4393 instr->pointer_map(), 0, Safepoint::kNoLazyDeopt);
4394 __ StoreToSafepointRegisterSlot(v0, reg);
4395 }
4396
4397
DoSmiTag(LSmiTag * instr)4398 void LCodeGen::DoSmiTag(LSmiTag* instr) {
4399 HChange* hchange = instr->hydrogen();
4400 Register input = ToRegister(instr->value());
4401 Register output = ToRegister(instr->result());
4402 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4403 hchange->value()->CheckFlag(HValue::kUint32)) {
4404 __ And(at, input, Operand(0xc0000000));
4405 DeoptimizeIf(ne, instr, DeoptimizeReason::kOverflow, at, Operand(zero_reg));
4406 }
4407 if (hchange->CheckFlag(HValue::kCanOverflow) &&
4408 !hchange->value()->CheckFlag(HValue::kUint32)) {
4409 __ SmiTagCheckOverflow(output, input, at);
4410 DeoptimizeIf(lt, instr, DeoptimizeReason::kOverflow, at, Operand(zero_reg));
4411 } else {
4412 __ SmiTag(output, input);
4413 }
4414 }
4415
4416
DoSmiUntag(LSmiUntag * instr)4417 void LCodeGen::DoSmiUntag(LSmiUntag* instr) {
4418 Register scratch = scratch0();
4419 Register input = ToRegister(instr->value());
4420 Register result = ToRegister(instr->result());
4421 if (instr->needs_check()) {
4422 STATIC_ASSERT(kHeapObjectTag == 1);
4423 // If the input is a HeapObject, value of scratch won't be zero.
4424 __ And(scratch, input, Operand(kHeapObjectTag));
4425 __ SmiUntag(result, input);
4426 DeoptimizeIf(ne, instr, DeoptimizeReason::kNotASmi, scratch,
4427 Operand(zero_reg));
4428 } else {
4429 __ SmiUntag(result, input);
4430 }
4431 }
4432
4433
EmitNumberUntagD(LNumberUntagD * instr,Register input_reg,DoubleRegister result_reg,NumberUntagDMode mode)4434 void LCodeGen::EmitNumberUntagD(LNumberUntagD* instr, Register input_reg,
4435 DoubleRegister result_reg,
4436 NumberUntagDMode mode) {
4437 bool can_convert_undefined_to_nan = instr->truncating();
4438 bool deoptimize_on_minus_zero = instr->hydrogen()->deoptimize_on_minus_zero();
4439
4440 Register scratch = scratch0();
4441 Label convert, load_smi, done;
4442 if (mode == NUMBER_CANDIDATE_IS_ANY_TAGGED) {
4443 // Smi check.
4444 __ UntagAndJumpIfSmi(scratch, input_reg, &load_smi);
4445 // Heap number map check.
4446 __ lw(scratch, FieldMemOperand(input_reg, HeapObject::kMapOffset));
4447 __ LoadRoot(at, Heap::kHeapNumberMapRootIndex);
4448 if (can_convert_undefined_to_nan) {
4449 __ Branch(&convert, ne, scratch, Operand(at));
4450 } else {
4451 DeoptimizeIf(ne, instr, DeoptimizeReason::kNotAHeapNumber, scratch,
4452 Operand(at));
4453 }
4454 // Load heap number.
4455 __ ldc1(result_reg, FieldMemOperand(input_reg, HeapNumber::kValueOffset));
4456 if (deoptimize_on_minus_zero) {
4457 __ mfc1(at, result_reg.low());
4458 __ Branch(&done, ne, at, Operand(zero_reg));
4459 __ Mfhc1(scratch, result_reg);
4460 DeoptimizeIf(eq, instr, DeoptimizeReason::kMinusZero, scratch,
4461 Operand(HeapNumber::kSignMask));
4462 }
4463 __ Branch(&done);
4464 if (can_convert_undefined_to_nan) {
4465 __ bind(&convert);
4466 // Convert undefined (and hole) to NaN.
4467 __ LoadRoot(at, Heap::kUndefinedValueRootIndex);
4468 DeoptimizeIf(ne, instr, DeoptimizeReason::kNotAHeapNumberUndefined,
4469 input_reg, Operand(at));
4470 __ LoadRoot(scratch, Heap::kNanValueRootIndex);
4471 __ ldc1(result_reg, FieldMemOperand(scratch, HeapNumber::kValueOffset));
4472 __ Branch(&done);
4473 }
4474 } else {
4475 __ SmiUntag(scratch, input_reg);
4476 DCHECK(mode == NUMBER_CANDIDATE_IS_SMI);
4477 }
4478 // Smi to double register conversion
4479 __ bind(&load_smi);
4480 // scratch: untagged value of input_reg
4481 __ mtc1(scratch, result_reg);
4482 __ cvt_d_w(result_reg, result_reg);
4483 __ bind(&done);
4484 }
4485
4486
DoDeferredTaggedToI(LTaggedToI * instr)4487 void LCodeGen::DoDeferredTaggedToI(LTaggedToI* instr) {
4488 Register input_reg = ToRegister(instr->value());
4489 Register scratch1 = scratch0();
4490 Register scratch2 = ToRegister(instr->temp());
4491 DoubleRegister double_scratch = double_scratch0();
4492 DoubleRegister double_scratch2 = ToDoubleRegister(instr->temp2());
4493
4494 DCHECK(!scratch1.is(input_reg) && !scratch1.is(scratch2));
4495 DCHECK(!scratch2.is(input_reg) && !scratch2.is(scratch1));
4496
4497 Label done;
4498
4499 // The input is a tagged HeapObject.
4500 // Heap number map check.
4501 __ lw(scratch1, FieldMemOperand(input_reg, HeapObject::kMapOffset));
4502 __ LoadRoot(at, Heap::kHeapNumberMapRootIndex);
4503 // This 'at' value and scratch1 map value are used for tests in both clauses
4504 // of the if.
4505
4506 if (instr->truncating()) {
4507 Label truncate;
4508 __ Branch(USE_DELAY_SLOT, &truncate, eq, scratch1, Operand(at));
4509 __ mov(scratch2, input_reg); // In delay slot.
4510 __ lbu(scratch1, FieldMemOperand(scratch1, Map::kInstanceTypeOffset));
4511 DeoptimizeIf(ne, instr, DeoptimizeReason::kNotANumberOrOddball, scratch1,
4512 Operand(ODDBALL_TYPE));
4513 __ bind(&truncate);
4514 __ TruncateHeapNumberToI(input_reg, scratch2);
4515 } else {
4516 DeoptimizeIf(ne, instr, DeoptimizeReason::kNotAHeapNumber, scratch1,
4517 Operand(at));
4518
4519 // Load the double value.
4520 __ ldc1(double_scratch,
4521 FieldMemOperand(input_reg, HeapNumber::kValueOffset));
4522
4523 Register except_flag = scratch2;
4524 __ EmitFPUTruncate(kRoundToZero,
4525 input_reg,
4526 double_scratch,
4527 scratch1,
4528 double_scratch2,
4529 except_flag,
4530 kCheckForInexactConversion);
4531
4532 DeoptimizeIf(ne, instr, DeoptimizeReason::kLostPrecisionOrNaN, except_flag,
4533 Operand(zero_reg));
4534
4535 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4536 __ Branch(&done, ne, input_reg, Operand(zero_reg));
4537
4538 __ Mfhc1(scratch1, double_scratch);
4539 __ And(scratch1, scratch1, Operand(HeapNumber::kSignMask));
4540 DeoptimizeIf(ne, instr, DeoptimizeReason::kMinusZero, scratch1,
4541 Operand(zero_reg));
4542 }
4543 }
4544 __ bind(&done);
4545 }
4546
4547
DoTaggedToI(LTaggedToI * instr)4548 void LCodeGen::DoTaggedToI(LTaggedToI* instr) {
4549 class DeferredTaggedToI final : public LDeferredCode {
4550 public:
4551 DeferredTaggedToI(LCodeGen* codegen, LTaggedToI* instr)
4552 : LDeferredCode(codegen), instr_(instr) { }
4553 void Generate() override { codegen()->DoDeferredTaggedToI(instr_); }
4554 LInstruction* instr() override { return instr_; }
4555
4556 private:
4557 LTaggedToI* instr_;
4558 };
4559
4560 LOperand* input = instr->value();
4561 DCHECK(input->IsRegister());
4562 DCHECK(input->Equals(instr->result()));
4563
4564 Register input_reg = ToRegister(input);
4565
4566 if (instr->hydrogen()->value()->representation().IsSmi()) {
4567 __ SmiUntag(input_reg);
4568 } else {
4569 DeferredTaggedToI* deferred = new(zone()) DeferredTaggedToI(this, instr);
4570
4571 // Let the deferred code handle the HeapObject case.
4572 __ JumpIfNotSmi(input_reg, deferred->entry());
4573
4574 // Smi to int32 conversion.
4575 __ SmiUntag(input_reg);
4576 __ bind(deferred->exit());
4577 }
4578 }
4579
4580
DoNumberUntagD(LNumberUntagD * instr)4581 void LCodeGen::DoNumberUntagD(LNumberUntagD* instr) {
4582 LOperand* input = instr->value();
4583 DCHECK(input->IsRegister());
4584 LOperand* result = instr->result();
4585 DCHECK(result->IsDoubleRegister());
4586
4587 Register input_reg = ToRegister(input);
4588 DoubleRegister result_reg = ToDoubleRegister(result);
4589
4590 HValue* value = instr->hydrogen()->value();
4591 NumberUntagDMode mode = value->representation().IsSmi()
4592 ? NUMBER_CANDIDATE_IS_SMI : NUMBER_CANDIDATE_IS_ANY_TAGGED;
4593
4594 EmitNumberUntagD(instr, input_reg, result_reg, mode);
4595 }
4596
4597
DoDoubleToI(LDoubleToI * instr)4598 void LCodeGen::DoDoubleToI(LDoubleToI* instr) {
4599 Register result_reg = ToRegister(instr->result());
4600 Register scratch1 = scratch0();
4601 DoubleRegister double_input = ToDoubleRegister(instr->value());
4602
4603 if (instr->truncating()) {
4604 __ TruncateDoubleToI(result_reg, double_input);
4605 } else {
4606 Register except_flag = LCodeGen::scratch1();
4607
4608 __ EmitFPUTruncate(kRoundToMinusInf,
4609 result_reg,
4610 double_input,
4611 scratch1,
4612 double_scratch0(),
4613 except_flag,
4614 kCheckForInexactConversion);
4615
4616 // Deopt if the operation did not succeed (except_flag != 0).
4617 DeoptimizeIf(ne, instr, DeoptimizeReason::kLostPrecisionOrNaN, except_flag,
4618 Operand(zero_reg));
4619
4620 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4621 Label done;
4622 __ Branch(&done, ne, result_reg, Operand(zero_reg));
4623 __ Mfhc1(scratch1, double_input);
4624 __ And(scratch1, scratch1, Operand(HeapNumber::kSignMask));
4625 DeoptimizeIf(ne, instr, DeoptimizeReason::kMinusZero, scratch1,
4626 Operand(zero_reg));
4627 __ bind(&done);
4628 }
4629 }
4630 }
4631
4632
DoDoubleToSmi(LDoubleToSmi * instr)4633 void LCodeGen::DoDoubleToSmi(LDoubleToSmi* instr) {
4634 Register result_reg = ToRegister(instr->result());
4635 Register scratch1 = LCodeGen::scratch0();
4636 DoubleRegister double_input = ToDoubleRegister(instr->value());
4637
4638 if (instr->truncating()) {
4639 __ TruncateDoubleToI(result_reg, double_input);
4640 } else {
4641 Register except_flag = LCodeGen::scratch1();
4642
4643 __ EmitFPUTruncate(kRoundToMinusInf,
4644 result_reg,
4645 double_input,
4646 scratch1,
4647 double_scratch0(),
4648 except_flag,
4649 kCheckForInexactConversion);
4650
4651 // Deopt if the operation did not succeed (except_flag != 0).
4652 DeoptimizeIf(ne, instr, DeoptimizeReason::kLostPrecisionOrNaN, except_flag,
4653 Operand(zero_reg));
4654
4655 if (instr->hydrogen()->CheckFlag(HValue::kBailoutOnMinusZero)) {
4656 Label done;
4657 __ Branch(&done, ne, result_reg, Operand(zero_reg));
4658 __ Mfhc1(scratch1, double_input);
4659 __ And(scratch1, scratch1, Operand(HeapNumber::kSignMask));
4660 DeoptimizeIf(ne, instr, DeoptimizeReason::kMinusZero, scratch1,
4661 Operand(zero_reg));
4662 __ bind(&done);
4663 }
4664 }
4665 __ SmiTagCheckOverflow(result_reg, result_reg, scratch1);
4666 DeoptimizeIf(lt, instr, DeoptimizeReason::kOverflow, scratch1,
4667 Operand(zero_reg));
4668 }
4669
4670
DoCheckSmi(LCheckSmi * instr)4671 void LCodeGen::DoCheckSmi(LCheckSmi* instr) {
4672 LOperand* input = instr->value();
4673 __ SmiTst(ToRegister(input), at);
4674 DeoptimizeIf(ne, instr, DeoptimizeReason::kNotASmi, at, Operand(zero_reg));
4675 }
4676
4677
DoCheckNonSmi(LCheckNonSmi * instr)4678 void LCodeGen::DoCheckNonSmi(LCheckNonSmi* instr) {
4679 if (!instr->hydrogen()->value()->type().IsHeapObject()) {
4680 LOperand* input = instr->value();
4681 __ SmiTst(ToRegister(input), at);
4682 DeoptimizeIf(eq, instr, DeoptimizeReason::kSmi, at, Operand(zero_reg));
4683 }
4684 }
4685
4686
DoCheckArrayBufferNotNeutered(LCheckArrayBufferNotNeutered * instr)4687 void LCodeGen::DoCheckArrayBufferNotNeutered(
4688 LCheckArrayBufferNotNeutered* instr) {
4689 Register view = ToRegister(instr->view());
4690 Register scratch = scratch0();
4691
4692 __ lw(scratch, FieldMemOperand(view, JSArrayBufferView::kBufferOffset));
4693 __ lw(scratch, FieldMemOperand(scratch, JSArrayBuffer::kBitFieldOffset));
4694 __ And(at, scratch, 1 << JSArrayBuffer::WasNeutered::kShift);
4695 DeoptimizeIf(ne, instr, DeoptimizeReason::kOutOfBounds, at,
4696 Operand(zero_reg));
4697 }
4698
4699
DoCheckInstanceType(LCheckInstanceType * instr)4700 void LCodeGen::DoCheckInstanceType(LCheckInstanceType* instr) {
4701 Register input = ToRegister(instr->value());
4702 Register scratch = scratch0();
4703
4704 __ GetObjectType(input, scratch, scratch);
4705
4706 if (instr->hydrogen()->is_interval_check()) {
4707 InstanceType first;
4708 InstanceType last;
4709 instr->hydrogen()->GetCheckInterval(&first, &last);
4710
4711 // If there is only one type in the interval check for equality.
4712 if (first == last) {
4713 DeoptimizeIf(ne, instr, DeoptimizeReason::kWrongInstanceType, scratch,
4714 Operand(first));
4715 } else {
4716 DeoptimizeIf(lo, instr, DeoptimizeReason::kWrongInstanceType, scratch,
4717 Operand(first));
4718 // Omit check for the last type.
4719 if (last != LAST_TYPE) {
4720 DeoptimizeIf(hi, instr, DeoptimizeReason::kWrongInstanceType, scratch,
4721 Operand(last));
4722 }
4723 }
4724 } else {
4725 uint8_t mask;
4726 uint8_t tag;
4727 instr->hydrogen()->GetCheckMaskAndTag(&mask, &tag);
4728
4729 if (base::bits::IsPowerOfTwo32(mask)) {
4730 DCHECK(tag == 0 || base::bits::IsPowerOfTwo32(tag));
4731 __ And(at, scratch, mask);
4732 DeoptimizeIf(tag == 0 ? ne : eq, instr,
4733 DeoptimizeReason::kWrongInstanceType, at, Operand(zero_reg));
4734 } else {
4735 __ And(scratch, scratch, Operand(mask));
4736 DeoptimizeIf(ne, instr, DeoptimizeReason::kWrongInstanceType, scratch,
4737 Operand(tag));
4738 }
4739 }
4740 }
4741
4742
DoCheckValue(LCheckValue * instr)4743 void LCodeGen::DoCheckValue(LCheckValue* instr) {
4744 Register reg = ToRegister(instr->value());
4745 Handle<HeapObject> object = instr->hydrogen()->object().handle();
4746 AllowDeferredHandleDereference smi_check;
4747 if (isolate()->heap()->InNewSpace(*object)) {
4748 Register reg = ToRegister(instr->value());
4749 Handle<Cell> cell = isolate()->factory()->NewCell(object);
4750 __ li(at, Operand(cell));
4751 __ lw(at, FieldMemOperand(at, Cell::kValueOffset));
4752 DeoptimizeIf(ne, instr, DeoptimizeReason::kValueMismatch, reg, Operand(at));
4753 } else {
4754 DeoptimizeIf(ne, instr, DeoptimizeReason::kValueMismatch, reg,
4755 Operand(object));
4756 }
4757 }
4758
4759
DoDeferredInstanceMigration(LCheckMaps * instr,Register object)4760 void LCodeGen::DoDeferredInstanceMigration(LCheckMaps* instr, Register object) {
4761 {
4762 PushSafepointRegistersScope scope(this);
4763 __ push(object);
4764 __ mov(cp, zero_reg);
4765 __ CallRuntimeSaveDoubles(Runtime::kTryMigrateInstance);
4766 RecordSafepointWithRegisters(
4767 instr->pointer_map(), 1, Safepoint::kNoLazyDeopt);
4768 __ StoreToSafepointRegisterSlot(v0, scratch0());
4769 }
4770 __ SmiTst(scratch0(), at);
4771 DeoptimizeIf(eq, instr, DeoptimizeReason::kInstanceMigrationFailed, at,
4772 Operand(zero_reg));
4773 }
4774
4775
DoCheckMaps(LCheckMaps * instr)4776 void LCodeGen::DoCheckMaps(LCheckMaps* instr) {
4777 class DeferredCheckMaps final : public LDeferredCode {
4778 public:
4779 DeferredCheckMaps(LCodeGen* codegen, LCheckMaps* instr, Register object)
4780 : LDeferredCode(codegen), instr_(instr), object_(object) {
4781 SetExit(check_maps());
4782 }
4783 void Generate() override {
4784 codegen()->DoDeferredInstanceMigration(instr_, object_);
4785 }
4786 Label* check_maps() { return &check_maps_; }
4787 LInstruction* instr() override { return instr_; }
4788
4789 private:
4790 LCheckMaps* instr_;
4791 Label check_maps_;
4792 Register object_;
4793 };
4794
4795 if (instr->hydrogen()->IsStabilityCheck()) {
4796 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
4797 for (int i = 0; i < maps->size(); ++i) {
4798 AddStabilityDependency(maps->at(i).handle());
4799 }
4800 return;
4801 }
4802
4803 Register map_reg = scratch0();
4804 LOperand* input = instr->value();
4805 DCHECK(input->IsRegister());
4806 Register reg = ToRegister(input);
4807 __ lw(map_reg, FieldMemOperand(reg, HeapObject::kMapOffset));
4808
4809 DeferredCheckMaps* deferred = NULL;
4810 if (instr->hydrogen()->HasMigrationTarget()) {
4811 deferred = new(zone()) DeferredCheckMaps(this, instr, reg);
4812 __ bind(deferred->check_maps());
4813 }
4814
4815 const UniqueSet<Map>* maps = instr->hydrogen()->maps();
4816 Label success;
4817 for (int i = 0; i < maps->size() - 1; i++) {
4818 Handle<Map> map = maps->at(i).handle();
4819 __ CompareMapAndBranch(map_reg, map, &success, eq, &success);
4820 }
4821 Handle<Map> map = maps->at(maps->size() - 1).handle();
4822 // Do the CompareMap() directly within the Branch() and DeoptimizeIf().
4823 if (instr->hydrogen()->HasMigrationTarget()) {
4824 __ Branch(deferred->entry(), ne, map_reg, Operand(map));
4825 } else {
4826 DeoptimizeIf(ne, instr, DeoptimizeReason::kWrongMap, map_reg, Operand(map));
4827 }
4828
4829 __ bind(&success);
4830 }
4831
4832
DoClampDToUint8(LClampDToUint8 * instr)4833 void LCodeGen::DoClampDToUint8(LClampDToUint8* instr) {
4834 DoubleRegister value_reg = ToDoubleRegister(instr->unclamped());
4835 Register result_reg = ToRegister(instr->result());
4836 DoubleRegister temp_reg = ToDoubleRegister(instr->temp());
4837 __ ClampDoubleToUint8(result_reg, value_reg, temp_reg);
4838 }
4839
4840
DoClampIToUint8(LClampIToUint8 * instr)4841 void LCodeGen::DoClampIToUint8(LClampIToUint8* instr) {
4842 Register unclamped_reg = ToRegister(instr->unclamped());
4843 Register result_reg = ToRegister(instr->result());
4844 __ ClampUint8(result_reg, unclamped_reg);
4845 }
4846
4847
DoClampTToUint8(LClampTToUint8 * instr)4848 void LCodeGen::DoClampTToUint8(LClampTToUint8* instr) {
4849 Register scratch = scratch0();
4850 Register input_reg = ToRegister(instr->unclamped());
4851 Register result_reg = ToRegister(instr->result());
4852 DoubleRegister temp_reg = ToDoubleRegister(instr->temp());
4853 Label is_smi, done, heap_number;
4854
4855 // Both smi and heap number cases are handled.
4856 __ UntagAndJumpIfSmi(scratch, input_reg, &is_smi);
4857
4858 // Check for heap number
4859 __ lw(scratch, FieldMemOperand(input_reg, HeapObject::kMapOffset));
4860 __ Branch(&heap_number, eq, scratch, Operand(factory()->heap_number_map()));
4861
4862 // Check for undefined. Undefined is converted to zero for clamping
4863 // conversions.
4864 DeoptimizeIf(ne, instr, DeoptimizeReason::kNotAHeapNumberUndefined, input_reg,
4865 Operand(factory()->undefined_value()));
4866 __ mov(result_reg, zero_reg);
4867 __ jmp(&done);
4868
4869 // Heap number
4870 __ bind(&heap_number);
4871 __ ldc1(double_scratch0(), FieldMemOperand(input_reg,
4872 HeapNumber::kValueOffset));
4873 __ ClampDoubleToUint8(result_reg, double_scratch0(), temp_reg);
4874 __ jmp(&done);
4875
4876 __ bind(&is_smi);
4877 __ ClampUint8(result_reg, scratch);
4878
4879 __ bind(&done);
4880 }
4881
4882
DoAllocate(LAllocate * instr)4883 void LCodeGen::DoAllocate(LAllocate* instr) {
4884 class DeferredAllocate final : public LDeferredCode {
4885 public:
4886 DeferredAllocate(LCodeGen* codegen, LAllocate* instr)
4887 : LDeferredCode(codegen), instr_(instr) { }
4888 void Generate() override { codegen()->DoDeferredAllocate(instr_); }
4889 LInstruction* instr() override { return instr_; }
4890
4891 private:
4892 LAllocate* instr_;
4893 };
4894
4895 DeferredAllocate* deferred =
4896 new(zone()) DeferredAllocate(this, instr);
4897
4898 Register result = ToRegister(instr->result());
4899 Register scratch = ToRegister(instr->temp1());
4900 Register scratch2 = ToRegister(instr->temp2());
4901
4902 // Allocate memory for the object.
4903 AllocationFlags flags = NO_ALLOCATION_FLAGS;
4904 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
4905 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
4906 }
4907 if (instr->hydrogen()->IsOldSpaceAllocation()) {
4908 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
4909 flags = static_cast<AllocationFlags>(flags | PRETENURE);
4910 }
4911
4912 if (instr->hydrogen()->IsAllocationFoldingDominator()) {
4913 flags = static_cast<AllocationFlags>(flags | ALLOCATION_FOLDING_DOMINATOR);
4914 }
4915 DCHECK(!instr->hydrogen()->IsAllocationFolded());
4916
4917 if (instr->size()->IsConstantOperand()) {
4918 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
4919 CHECK(size <= kMaxRegularHeapObjectSize);
4920 __ Allocate(size, result, scratch, scratch2, deferred->entry(), flags);
4921 } else {
4922 Register size = ToRegister(instr->size());
4923 __ Allocate(size, result, scratch, scratch2, deferred->entry(), flags);
4924 }
4925
4926 __ bind(deferred->exit());
4927
4928 if (instr->hydrogen()->MustPrefillWithFiller()) {
4929 STATIC_ASSERT(kHeapObjectTag == 1);
4930 if (instr->size()->IsConstantOperand()) {
4931 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
4932 __ li(scratch, Operand(size - kHeapObjectTag));
4933 } else {
4934 __ Subu(scratch, ToRegister(instr->size()), Operand(kHeapObjectTag));
4935 }
4936 __ li(scratch2, Operand(isolate()->factory()->one_pointer_filler_map()));
4937 Label loop;
4938 __ bind(&loop);
4939 __ Subu(scratch, scratch, Operand(kPointerSize));
4940 __ Addu(at, result, Operand(scratch));
4941 __ sw(scratch2, MemOperand(at));
4942 __ Branch(&loop, ge, scratch, Operand(zero_reg));
4943 }
4944 }
4945
4946
DoDeferredAllocate(LAllocate * instr)4947 void LCodeGen::DoDeferredAllocate(LAllocate* instr) {
4948 Register result = ToRegister(instr->result());
4949
4950 // TODO(3095996): Get rid of this. For now, we need to make the
4951 // result register contain a valid pointer because it is already
4952 // contained in the register pointer map.
4953 __ mov(result, zero_reg);
4954
4955 PushSafepointRegistersScope scope(this);
4956 if (instr->size()->IsRegister()) {
4957 Register size = ToRegister(instr->size());
4958 DCHECK(!size.is(result));
4959 __ SmiTag(size);
4960 __ push(size);
4961 } else {
4962 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
4963 if (size >= 0 && size <= Smi::kMaxValue) {
4964 __ Push(Smi::FromInt(size));
4965 } else {
4966 // We should never get here at runtime => abort
4967 __ stop("invalid allocation size");
4968 return;
4969 }
4970 }
4971
4972 int flags = AllocateDoubleAlignFlag::encode(
4973 instr->hydrogen()->MustAllocateDoubleAligned());
4974 if (instr->hydrogen()->IsOldSpaceAllocation()) {
4975 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
4976 flags = AllocateTargetSpace::update(flags, OLD_SPACE);
4977 } else {
4978 flags = AllocateTargetSpace::update(flags, NEW_SPACE);
4979 }
4980 __ Push(Smi::FromInt(flags));
4981
4982 CallRuntimeFromDeferred(
4983 Runtime::kAllocateInTargetSpace, 2, instr, instr->context());
4984 __ StoreToSafepointRegisterSlot(v0, result);
4985
4986 if (instr->hydrogen()->IsAllocationFoldingDominator()) {
4987 AllocationFlags allocation_flags = NO_ALLOCATION_FLAGS;
4988 if (instr->hydrogen()->IsOldSpaceAllocation()) {
4989 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
4990 allocation_flags = static_cast<AllocationFlags>(flags | PRETENURE);
4991 }
4992 // If the allocation folding dominator allocate triggered a GC, allocation
4993 // happend in the runtime. We have to reset the top pointer to virtually
4994 // undo the allocation.
4995 ExternalReference allocation_top =
4996 AllocationUtils::GetAllocationTopReference(isolate(), allocation_flags);
4997 Register top_address = scratch0();
4998 __ Subu(v0, v0, Operand(kHeapObjectTag));
4999 __ li(top_address, Operand(allocation_top));
5000 __ sw(v0, MemOperand(top_address));
5001 __ Addu(v0, v0, Operand(kHeapObjectTag));
5002 }
5003 }
5004
DoFastAllocate(LFastAllocate * instr)5005 void LCodeGen::DoFastAllocate(LFastAllocate* instr) {
5006 DCHECK(instr->hydrogen()->IsAllocationFolded());
5007 DCHECK(!instr->hydrogen()->IsAllocationFoldingDominator());
5008 Register result = ToRegister(instr->result());
5009 Register scratch1 = ToRegister(instr->temp1());
5010 Register scratch2 = ToRegister(instr->temp2());
5011
5012 AllocationFlags flags = ALLOCATION_FOLDED;
5013 if (instr->hydrogen()->MustAllocateDoubleAligned()) {
5014 flags = static_cast<AllocationFlags>(flags | DOUBLE_ALIGNMENT);
5015 }
5016 if (instr->hydrogen()->IsOldSpaceAllocation()) {
5017 DCHECK(!instr->hydrogen()->IsNewSpaceAllocation());
5018 flags = static_cast<AllocationFlags>(flags | PRETENURE);
5019 }
5020 if (instr->size()->IsConstantOperand()) {
5021 int32_t size = ToInteger32(LConstantOperand::cast(instr->size()));
5022 CHECK(size <= kMaxRegularHeapObjectSize);
5023 __ FastAllocate(size, result, scratch1, scratch2, flags);
5024 } else {
5025 Register size = ToRegister(instr->size());
5026 __ FastAllocate(size, result, scratch1, scratch2, flags);
5027 }
5028 }
5029
5030
DoTypeof(LTypeof * instr)5031 void LCodeGen::DoTypeof(LTypeof* instr) {
5032 DCHECK(ToRegister(instr->value()).is(a3));
5033 DCHECK(ToRegister(instr->result()).is(v0));
5034 Label end, do_call;
5035 Register value_register = ToRegister(instr->value());
5036 __ JumpIfNotSmi(value_register, &do_call);
5037 __ li(v0, Operand(isolate()->factory()->number_string()));
5038 __ jmp(&end);
5039 __ bind(&do_call);
5040 Callable callable = CodeFactory::Typeof(isolate());
5041 CallCode(callable.code(), RelocInfo::CODE_TARGET, instr);
5042 __ bind(&end);
5043 }
5044
5045
DoTypeofIsAndBranch(LTypeofIsAndBranch * instr)5046 void LCodeGen::DoTypeofIsAndBranch(LTypeofIsAndBranch* instr) {
5047 Register input = ToRegister(instr->value());
5048
5049 Register cmp1 = no_reg;
5050 Operand cmp2 = Operand(no_reg);
5051
5052 Condition final_branch_condition = EmitTypeofIs(instr->TrueLabel(chunk_),
5053 instr->FalseLabel(chunk_),
5054 input,
5055 instr->type_literal(),
5056 &cmp1,
5057 &cmp2);
5058
5059 DCHECK(cmp1.is_valid());
5060 DCHECK(!cmp2.is_reg() || cmp2.rm().is_valid());
5061
5062 if (final_branch_condition != kNoCondition) {
5063 EmitBranch(instr, final_branch_condition, cmp1, cmp2);
5064 }
5065 }
5066
5067
EmitTypeofIs(Label * true_label,Label * false_label,Register input,Handle<String> type_name,Register * cmp1,Operand * cmp2)5068 Condition LCodeGen::EmitTypeofIs(Label* true_label,
5069 Label* false_label,
5070 Register input,
5071 Handle<String> type_name,
5072 Register* cmp1,
5073 Operand* cmp2) {
5074 // This function utilizes the delay slot heavily. This is used to load
5075 // values that are always usable without depending on the type of the input
5076 // register.
5077 Condition final_branch_condition = kNoCondition;
5078 Register scratch = scratch0();
5079 Factory* factory = isolate()->factory();
5080 if (String::Equals(type_name, factory->number_string())) {
5081 __ JumpIfSmi(input, true_label);
5082 __ lw(input, FieldMemOperand(input, HeapObject::kMapOffset));
5083 __ LoadRoot(at, Heap::kHeapNumberMapRootIndex);
5084 *cmp1 = input;
5085 *cmp2 = Operand(at);
5086 final_branch_condition = eq;
5087
5088 } else if (String::Equals(type_name, factory->string_string())) {
5089 __ JumpIfSmi(input, false_label);
5090 __ GetObjectType(input, input, scratch);
5091 *cmp1 = scratch;
5092 *cmp2 = Operand(FIRST_NONSTRING_TYPE);
5093 final_branch_condition = lt;
5094
5095 } else if (String::Equals(type_name, factory->symbol_string())) {
5096 __ JumpIfSmi(input, false_label);
5097 __ GetObjectType(input, input, scratch);
5098 *cmp1 = scratch;
5099 *cmp2 = Operand(SYMBOL_TYPE);
5100 final_branch_condition = eq;
5101
5102 } else if (String::Equals(type_name, factory->boolean_string())) {
5103 __ LoadRoot(at, Heap::kTrueValueRootIndex);
5104 __ Branch(USE_DELAY_SLOT, true_label, eq, at, Operand(input));
5105 __ LoadRoot(at, Heap::kFalseValueRootIndex);
5106 *cmp1 = at;
5107 *cmp2 = Operand(input);
5108 final_branch_condition = eq;
5109
5110 } else if (String::Equals(type_name, factory->undefined_string())) {
5111 __ LoadRoot(at, Heap::kNullValueRootIndex);
5112 __ Branch(USE_DELAY_SLOT, false_label, eq, at, Operand(input));
5113 // The first instruction of JumpIfSmi is an And - it is safe in the delay
5114 // slot.
5115 __ JumpIfSmi(input, false_label);
5116 // Check for undetectable objects => true.
5117 __ lw(input, FieldMemOperand(input, HeapObject::kMapOffset));
5118 __ lbu(at, FieldMemOperand(input, Map::kBitFieldOffset));
5119 __ And(at, at, 1 << Map::kIsUndetectable);
5120 *cmp1 = at;
5121 *cmp2 = Operand(zero_reg);
5122 final_branch_condition = ne;
5123
5124 } else if (String::Equals(type_name, factory->function_string())) {
5125 __ JumpIfSmi(input, false_label);
5126 __ lw(scratch, FieldMemOperand(input, HeapObject::kMapOffset));
5127 __ lbu(scratch, FieldMemOperand(scratch, Map::kBitFieldOffset));
5128 __ And(scratch, scratch,
5129 Operand((1 << Map::kIsCallable) | (1 << Map::kIsUndetectable)));
5130 *cmp1 = scratch;
5131 *cmp2 = Operand(1 << Map::kIsCallable);
5132 final_branch_condition = eq;
5133
5134 } else if (String::Equals(type_name, factory->object_string())) {
5135 __ JumpIfSmi(input, false_label);
5136 __ LoadRoot(at, Heap::kNullValueRootIndex);
5137 __ Branch(USE_DELAY_SLOT, true_label, eq, at, Operand(input));
5138 STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
5139 __ GetObjectType(input, scratch, scratch1());
5140 __ Branch(false_label, lt, scratch1(), Operand(FIRST_JS_RECEIVER_TYPE));
5141 // Check for callable or undetectable objects => false.
5142 __ lbu(scratch, FieldMemOperand(scratch, Map::kBitFieldOffset));
5143 __ And(at, scratch,
5144 Operand((1 << Map::kIsCallable) | (1 << Map::kIsUndetectable)));
5145 *cmp1 = at;
5146 *cmp2 = Operand(zero_reg);
5147 final_branch_condition = eq;
5148
5149 // clang-format off
5150 #define SIMD128_TYPE(TYPE, Type, type, lane_count, lane_type) \
5151 } else if (String::Equals(type_name, factory->type##_string())) { \
5152 __ JumpIfSmi(input, false_label); \
5153 __ lw(input, FieldMemOperand(input, HeapObject::kMapOffset)); \
5154 __ LoadRoot(at, Heap::k##Type##MapRootIndex); \
5155 *cmp1 = input; \
5156 *cmp2 = Operand(at); \
5157 final_branch_condition = eq;
5158 SIMD128_TYPES(SIMD128_TYPE)
5159 #undef SIMD128_TYPE
5160 // clang-format on
5161
5162 } else {
5163 *cmp1 = at;
5164 *cmp2 = Operand(zero_reg); // Set to valid regs, to avoid caller assertion.
5165 __ Branch(false_label);
5166 }
5167
5168 return final_branch_condition;
5169 }
5170
5171
EnsureSpaceForLazyDeopt(int space_needed)5172 void LCodeGen::EnsureSpaceForLazyDeopt(int space_needed) {
5173 if (info()->ShouldEnsureSpaceForLazyDeopt()) {
5174 // Ensure that we have enough space after the previous lazy-bailout
5175 // instruction for patching the code here.
5176 int current_pc = masm()->pc_offset();
5177 if (current_pc < last_lazy_deopt_pc_ + space_needed) {
5178 int padding_size = last_lazy_deopt_pc_ + space_needed - current_pc;
5179 DCHECK_EQ(0, padding_size % Assembler::kInstrSize);
5180 while (padding_size > 0) {
5181 __ nop();
5182 padding_size -= Assembler::kInstrSize;
5183 }
5184 }
5185 }
5186 last_lazy_deopt_pc_ = masm()->pc_offset();
5187 }
5188
5189
DoLazyBailout(LLazyBailout * instr)5190 void LCodeGen::DoLazyBailout(LLazyBailout* instr) {
5191 last_lazy_deopt_pc_ = masm()->pc_offset();
5192 DCHECK(instr->HasEnvironment());
5193 LEnvironment* env = instr->environment();
5194 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5195 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5196 }
5197
5198
DoDeoptimize(LDeoptimize * instr)5199 void LCodeGen::DoDeoptimize(LDeoptimize* instr) {
5200 Deoptimizer::BailoutType type = instr->hydrogen()->type();
5201 // TODO(danno): Stubs expect all deopts to be lazy for historical reasons (the
5202 // needed return address), even though the implementation of LAZY and EAGER is
5203 // now identical. When LAZY is eventually completely folded into EAGER, remove
5204 // the special case below.
5205 if (info()->IsStub() && type == Deoptimizer::EAGER) {
5206 type = Deoptimizer::LAZY;
5207 }
5208
5209 DeoptimizeIf(al, instr, instr->hydrogen()->reason(), type, zero_reg,
5210 Operand(zero_reg));
5211 }
5212
5213
DoDummy(LDummy * instr)5214 void LCodeGen::DoDummy(LDummy* instr) {
5215 // Nothing to see here, move on!
5216 }
5217
5218
DoDummyUse(LDummyUse * instr)5219 void LCodeGen::DoDummyUse(LDummyUse* instr) {
5220 // Nothing to see here, move on!
5221 }
5222
5223
DoDeferredStackCheck(LStackCheck * instr)5224 void LCodeGen::DoDeferredStackCheck(LStackCheck* instr) {
5225 PushSafepointRegistersScope scope(this);
5226 LoadContextFromDeferred(instr->context());
5227 __ CallRuntimeSaveDoubles(Runtime::kStackGuard);
5228 RecordSafepointWithLazyDeopt(
5229 instr, RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
5230 DCHECK(instr->HasEnvironment());
5231 LEnvironment* env = instr->environment();
5232 safepoints_.RecordLazyDeoptimizationIndex(env->deoptimization_index());
5233 }
5234
5235
DoStackCheck(LStackCheck * instr)5236 void LCodeGen::DoStackCheck(LStackCheck* instr) {
5237 class DeferredStackCheck final : public LDeferredCode {
5238 public:
5239 DeferredStackCheck(LCodeGen* codegen, LStackCheck* instr)
5240 : LDeferredCode(codegen), instr_(instr) { }
5241 void Generate() override { codegen()->DoDeferredStackCheck(instr_); }
5242 LInstruction* instr() override { return instr_; }
5243
5244 private:
5245 LStackCheck* instr_;
5246 };
5247
5248 DCHECK(instr->HasEnvironment());
5249 LEnvironment* env = instr->environment();
5250 // There is no LLazyBailout instruction for stack-checks. We have to
5251 // prepare for lazy deoptimization explicitly here.
5252 if (instr->hydrogen()->is_function_entry()) {
5253 // Perform stack overflow check.
5254 Label done;
5255 __ LoadRoot(at, Heap::kStackLimitRootIndex);
5256 __ Branch(&done, hs, sp, Operand(at));
5257 DCHECK(instr->context()->IsRegister());
5258 DCHECK(ToRegister(instr->context()).is(cp));
5259 CallCode(isolate()->builtins()->StackCheck(),
5260 RelocInfo::CODE_TARGET,
5261 instr);
5262 __ bind(&done);
5263 } else {
5264 DCHECK(instr->hydrogen()->is_backwards_branch());
5265 // Perform stack overflow check if this goto needs it before jumping.
5266 DeferredStackCheck* deferred_stack_check =
5267 new(zone()) DeferredStackCheck(this, instr);
5268 __ LoadRoot(at, Heap::kStackLimitRootIndex);
5269 __ Branch(deferred_stack_check->entry(), lo, sp, Operand(at));
5270 EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
5271 __ bind(instr->done_label());
5272 deferred_stack_check->SetExit(instr->done_label());
5273 RegisterEnvironmentForDeoptimization(env, Safepoint::kLazyDeopt);
5274 // Don't record a deoptimization index for the safepoint here.
5275 // This will be done explicitly when emitting call and the safepoint in
5276 // the deferred code.
5277 }
5278 }
5279
5280
DoOsrEntry(LOsrEntry * instr)5281 void LCodeGen::DoOsrEntry(LOsrEntry* instr) {
5282 // This is a pseudo-instruction that ensures that the environment here is
5283 // properly registered for deoptimization and records the assembler's PC
5284 // offset.
5285 LEnvironment* environment = instr->environment();
5286
5287 // If the environment were already registered, we would have no way of
5288 // backpatching it with the spill slot operands.
5289 DCHECK(!environment->HasBeenRegistered());
5290 RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
5291
5292 GenerateOsrPrologue();
5293 }
5294
5295
DoForInPrepareMap(LForInPrepareMap * instr)5296 void LCodeGen::DoForInPrepareMap(LForInPrepareMap* instr) {
5297 Register result = ToRegister(instr->result());
5298 Register object = ToRegister(instr->object());
5299
5300 Label use_cache, call_runtime;
5301 DCHECK(object.is(a0));
5302 __ CheckEnumCache(&call_runtime);
5303
5304 __ lw(result, FieldMemOperand(object, HeapObject::kMapOffset));
5305 __ Branch(&use_cache);
5306
5307 // Get the set of properties to enumerate.
5308 __ bind(&call_runtime);
5309 __ push(object);
5310 CallRuntime(Runtime::kForInEnumerate, instr);
5311 __ bind(&use_cache);
5312 }
5313
5314
DoForInCacheArray(LForInCacheArray * instr)5315 void LCodeGen::DoForInCacheArray(LForInCacheArray* instr) {
5316 Register map = ToRegister(instr->map());
5317 Register result = ToRegister(instr->result());
5318 Label load_cache, done;
5319 __ EnumLength(result, map);
5320 __ Branch(&load_cache, ne, result, Operand(Smi::kZero));
5321 __ li(result, Operand(isolate()->factory()->empty_fixed_array()));
5322 __ jmp(&done);
5323
5324 __ bind(&load_cache);
5325 __ LoadInstanceDescriptors(map, result);
5326 __ lw(result,
5327 FieldMemOperand(result, DescriptorArray::kEnumCacheOffset));
5328 __ lw(result,
5329 FieldMemOperand(result, FixedArray::SizeFor(instr->idx())));
5330 DeoptimizeIf(eq, instr, DeoptimizeReason::kNoCache, result,
5331 Operand(zero_reg));
5332
5333 __ bind(&done);
5334 }
5335
5336
DoCheckMapValue(LCheckMapValue * instr)5337 void LCodeGen::DoCheckMapValue(LCheckMapValue* instr) {
5338 Register object = ToRegister(instr->value());
5339 Register map = ToRegister(instr->map());
5340 __ lw(scratch0(), FieldMemOperand(object, HeapObject::kMapOffset));
5341 DeoptimizeIf(ne, instr, DeoptimizeReason::kWrongMap, map,
5342 Operand(scratch0()));
5343 }
5344
5345
DoDeferredLoadMutableDouble(LLoadFieldByIndex * instr,Register result,Register object,Register index)5346 void LCodeGen::DoDeferredLoadMutableDouble(LLoadFieldByIndex* instr,
5347 Register result,
5348 Register object,
5349 Register index) {
5350 PushSafepointRegistersScope scope(this);
5351 __ Push(object, index);
5352 __ mov(cp, zero_reg);
5353 __ CallRuntimeSaveDoubles(Runtime::kLoadMutableDouble);
5354 RecordSafepointWithRegisters(
5355 instr->pointer_map(), 2, Safepoint::kNoLazyDeopt);
5356 __ StoreToSafepointRegisterSlot(v0, result);
5357 }
5358
5359
DoLoadFieldByIndex(LLoadFieldByIndex * instr)5360 void LCodeGen::DoLoadFieldByIndex(LLoadFieldByIndex* instr) {
5361 class DeferredLoadMutableDouble final : public LDeferredCode {
5362 public:
5363 DeferredLoadMutableDouble(LCodeGen* codegen,
5364 LLoadFieldByIndex* instr,
5365 Register result,
5366 Register object,
5367 Register index)
5368 : LDeferredCode(codegen),
5369 instr_(instr),
5370 result_(result),
5371 object_(object),
5372 index_(index) {
5373 }
5374 void Generate() override {
5375 codegen()->DoDeferredLoadMutableDouble(instr_, result_, object_, index_);
5376 }
5377 LInstruction* instr() override { return instr_; }
5378
5379 private:
5380 LLoadFieldByIndex* instr_;
5381 Register result_;
5382 Register object_;
5383 Register index_;
5384 };
5385
5386 Register object = ToRegister(instr->object());
5387 Register index = ToRegister(instr->index());
5388 Register result = ToRegister(instr->result());
5389 Register scratch = scratch0();
5390
5391 DeferredLoadMutableDouble* deferred;
5392 deferred = new(zone()) DeferredLoadMutableDouble(
5393 this, instr, result, object, index);
5394
5395 Label out_of_object, done;
5396
5397 __ And(scratch, index, Operand(Smi::FromInt(1)));
5398 __ Branch(deferred->entry(), ne, scratch, Operand(zero_reg));
5399 __ sra(index, index, 1);
5400
5401 __ Branch(USE_DELAY_SLOT, &out_of_object, lt, index, Operand(zero_reg));
5402 __ sll(scratch, index, kPointerSizeLog2 - kSmiTagSize); // In delay slot.
5403
5404 STATIC_ASSERT(kPointerSizeLog2 > kSmiTagSize);
5405 __ Addu(scratch, object, scratch);
5406 __ lw(result, FieldMemOperand(scratch, JSObject::kHeaderSize));
5407
5408 __ Branch(&done);
5409
5410 __ bind(&out_of_object);
5411 __ lw(result, FieldMemOperand(object, JSObject::kPropertiesOffset));
5412 // Index is equal to negated out of object property index plus 1.
5413 __ Subu(scratch, result, scratch);
5414 __ lw(result, FieldMemOperand(scratch,
5415 FixedArray::kHeaderSize - kPointerSize));
5416 __ bind(deferred->exit());
5417 __ bind(&done);
5418 }
5419
5420 #undef __
5421
5422 } // namespace internal
5423 } // namespace v8
5424