972530ee355974af4d593e50d1a26b77dd5d5deb
[platform/upstream/nodejs.git] / deps / v8 / src / mips / macro-assembler-mips.cc
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <limits.h>  // For LONG_MIN, LONG_MAX.
6
7 #include "src/v8.h"
8
9 #if V8_TARGET_ARCH_MIPS
10
11 #include "src/base/bits.h"
12 #include "src/base/division-by-constant.h"
13 #include "src/bootstrapper.h"
14 #include "src/codegen.h"
15 #include "src/cpu-profiler.h"
16 #include "src/debug.h"
17 #include "src/isolate-inl.h"
18 #include "src/runtime/runtime.h"
19
20 namespace v8 {
21 namespace internal {
22
23 MacroAssembler::MacroAssembler(Isolate* arg_isolate, void* buffer, int size)
24     : Assembler(arg_isolate, buffer, size),
25       generating_stub_(false),
26       has_frame_(false),
27       has_double_zero_reg_set_(false) {
28   if (isolate() != NULL) {
29     code_object_ = Handle<Object>(isolate()->heap()->undefined_value(),
30                                   isolate());
31   }
32 }
33
34
35 void MacroAssembler::Load(Register dst,
36                           const MemOperand& src,
37                           Representation r) {
38   DCHECK(!r.IsDouble());
39   if (r.IsInteger8()) {
40     lb(dst, src);
41   } else if (r.IsUInteger8()) {
42     lbu(dst, src);
43   } else if (r.IsInteger16()) {
44     lh(dst, src);
45   } else if (r.IsUInteger16()) {
46     lhu(dst, src);
47   } else {
48     lw(dst, src);
49   }
50 }
51
52
53 void MacroAssembler::Store(Register src,
54                            const MemOperand& dst,
55                            Representation r) {
56   DCHECK(!r.IsDouble());
57   if (r.IsInteger8() || r.IsUInteger8()) {
58     sb(src, dst);
59   } else if (r.IsInteger16() || r.IsUInteger16()) {
60     sh(src, dst);
61   } else {
62     if (r.IsHeapObject()) {
63       AssertNotSmi(src);
64     } else if (r.IsSmi()) {
65       AssertSmi(src);
66     }
67     sw(src, dst);
68   }
69 }
70
71
72 void MacroAssembler::LoadRoot(Register destination,
73                               Heap::RootListIndex index) {
74   lw(destination, MemOperand(s6, index << kPointerSizeLog2));
75 }
76
77
78 void MacroAssembler::LoadRoot(Register destination,
79                               Heap::RootListIndex index,
80                               Condition cond,
81                               Register src1, const Operand& src2) {
82   Branch(2, NegateCondition(cond), src1, src2);
83   lw(destination, MemOperand(s6, index << kPointerSizeLog2));
84 }
85
86
87 void MacroAssembler::StoreRoot(Register source,
88                                Heap::RootListIndex index) {
89   sw(source, MemOperand(s6, index << kPointerSizeLog2));
90 }
91
92
93 void MacroAssembler::StoreRoot(Register source,
94                                Heap::RootListIndex index,
95                                Condition cond,
96                                Register src1, const Operand& src2) {
97   Branch(2, NegateCondition(cond), src1, src2);
98   sw(source, MemOperand(s6, index << kPointerSizeLog2));
99 }
100
101
102 // Push and pop all registers that can hold pointers.
103 void MacroAssembler::PushSafepointRegisters() {
104   // Safepoints expect a block of kNumSafepointRegisters values on the
105   // stack, so adjust the stack for unsaved registers.
106   const int num_unsaved = kNumSafepointRegisters - kNumSafepointSavedRegisters;
107   DCHECK(num_unsaved >= 0);
108   if (num_unsaved > 0) {
109     Subu(sp, sp, Operand(num_unsaved * kPointerSize));
110   }
111   MultiPush(kSafepointSavedRegisters);
112 }
113
114
115 void MacroAssembler::PopSafepointRegisters() {
116   const int num_unsaved = kNumSafepointRegisters - kNumSafepointSavedRegisters;
117   MultiPop(kSafepointSavedRegisters);
118   if (num_unsaved > 0) {
119     Addu(sp, sp, Operand(num_unsaved * kPointerSize));
120   }
121 }
122
123
124 void MacroAssembler::StoreToSafepointRegisterSlot(Register src, Register dst) {
125   sw(src, SafepointRegisterSlot(dst));
126 }
127
128
129 void MacroAssembler::LoadFromSafepointRegisterSlot(Register dst, Register src) {
130   lw(dst, SafepointRegisterSlot(src));
131 }
132
133
134 int MacroAssembler::SafepointRegisterStackIndex(int reg_code) {
135   // The registers are pushed starting with the highest encoding,
136   // which means that lowest encodings are closest to the stack pointer.
137   return kSafepointRegisterStackIndexMap[reg_code];
138 }
139
140
141 MemOperand MacroAssembler::SafepointRegisterSlot(Register reg) {
142   return MemOperand(sp, SafepointRegisterStackIndex(reg.code()) * kPointerSize);
143 }
144
145
146 MemOperand MacroAssembler::SafepointRegistersAndDoublesSlot(Register reg) {
147   UNIMPLEMENTED_MIPS();
148   // General purpose registers are pushed last on the stack.
149   int doubles_size = FPURegister::NumAllocatableRegisters() * kDoubleSize;
150   int register_offset = SafepointRegisterStackIndex(reg.code()) * kPointerSize;
151   return MemOperand(sp, doubles_size + register_offset);
152 }
153
154
155 void MacroAssembler::InNewSpace(Register object,
156                                 Register scratch,
157                                 Condition cc,
158                                 Label* branch) {
159   DCHECK(cc == eq || cc == ne);
160   And(scratch, object, Operand(ExternalReference::new_space_mask(isolate())));
161   Branch(branch, cc, scratch,
162          Operand(ExternalReference::new_space_start(isolate())));
163 }
164
165
166 void MacroAssembler::RecordWriteField(
167     Register object,
168     int offset,
169     Register value,
170     Register dst,
171     RAStatus ra_status,
172     SaveFPRegsMode save_fp,
173     RememberedSetAction remembered_set_action,
174     SmiCheck smi_check,
175     PointersToHereCheck pointers_to_here_check_for_value) {
176   DCHECK(!AreAliased(value, dst, t8, object));
177   // First, check if a write barrier is even needed. The tests below
178   // catch stores of Smis.
179   Label done;
180
181   // Skip barrier if writing a smi.
182   if (smi_check == INLINE_SMI_CHECK) {
183     JumpIfSmi(value, &done);
184   }
185
186   // Although the object register is tagged, the offset is relative to the start
187   // of the object, so so offset must be a multiple of kPointerSize.
188   DCHECK(IsAligned(offset, kPointerSize));
189
190   Addu(dst, object, Operand(offset - kHeapObjectTag));
191   if (emit_debug_code()) {
192     Label ok;
193     And(t8, dst, Operand((1 << kPointerSizeLog2) - 1));
194     Branch(&ok, eq, t8, Operand(zero_reg));
195     stop("Unaligned cell in write barrier");
196     bind(&ok);
197   }
198
199   RecordWrite(object,
200               dst,
201               value,
202               ra_status,
203               save_fp,
204               remembered_set_action,
205               OMIT_SMI_CHECK,
206               pointers_to_here_check_for_value);
207
208   bind(&done);
209
210   // Clobber clobbered input registers when running with the debug-code flag
211   // turned on to provoke errors.
212   if (emit_debug_code()) {
213     li(value, Operand(bit_cast<int32_t>(kZapValue + 4)));
214     li(dst, Operand(bit_cast<int32_t>(kZapValue + 8)));
215   }
216 }
217
218
219 // Will clobber 4 registers: object, map, dst, ip.  The
220 // register 'object' contains a heap object pointer.
221 void MacroAssembler::RecordWriteForMap(Register object,
222                                        Register map,
223                                        Register dst,
224                                        RAStatus ra_status,
225                                        SaveFPRegsMode fp_mode) {
226   if (emit_debug_code()) {
227     DCHECK(!dst.is(at));
228     lw(dst, FieldMemOperand(map, HeapObject::kMapOffset));
229     Check(eq,
230           kWrongAddressOrValuePassedToRecordWrite,
231           dst,
232           Operand(isolate()->factory()->meta_map()));
233   }
234
235   if (!FLAG_incremental_marking) {
236     return;
237   }
238
239   if (emit_debug_code()) {
240     lw(at, FieldMemOperand(object, HeapObject::kMapOffset));
241     Check(eq,
242           kWrongAddressOrValuePassedToRecordWrite,
243           map,
244           Operand(at));
245   }
246
247   Label done;
248
249   // A single check of the map's pages interesting flag suffices, since it is
250   // only set during incremental collection, and then it's also guaranteed that
251   // the from object's page's interesting flag is also set.  This optimization
252   // relies on the fact that maps can never be in new space.
253   CheckPageFlag(map,
254                 map,  // Used as scratch.
255                 MemoryChunk::kPointersToHereAreInterestingMask,
256                 eq,
257                 &done);
258
259   Addu(dst, object, Operand(HeapObject::kMapOffset - kHeapObjectTag));
260   if (emit_debug_code()) {
261     Label ok;
262     And(at, dst, Operand((1 << kPointerSizeLog2) - 1));
263     Branch(&ok, eq, at, Operand(zero_reg));
264     stop("Unaligned cell in write barrier");
265     bind(&ok);
266   }
267
268   // Record the actual write.
269   if (ra_status == kRAHasNotBeenSaved) {
270     push(ra);
271   }
272   RecordWriteStub stub(isolate(), object, map, dst, OMIT_REMEMBERED_SET,
273                        fp_mode);
274   CallStub(&stub);
275   if (ra_status == kRAHasNotBeenSaved) {
276     pop(ra);
277   }
278
279   bind(&done);
280
281   // Count number of write barriers in generated code.
282   isolate()->counters()->write_barriers_static()->Increment();
283   IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1, at, dst);
284
285   // Clobber clobbered registers when running with the debug-code flag
286   // turned on to provoke errors.
287   if (emit_debug_code()) {
288     li(dst, Operand(bit_cast<int32_t>(kZapValue + 12)));
289     li(map, Operand(bit_cast<int32_t>(kZapValue + 16)));
290   }
291 }
292
293
294 // Will clobber 4 registers: object, address, scratch, ip.  The
295 // register 'object' contains a heap object pointer.  The heap object
296 // tag is shifted away.
297 void MacroAssembler::RecordWrite(
298     Register object,
299     Register address,
300     Register value,
301     RAStatus ra_status,
302     SaveFPRegsMode fp_mode,
303     RememberedSetAction remembered_set_action,
304     SmiCheck smi_check,
305     PointersToHereCheck pointers_to_here_check_for_value) {
306   DCHECK(!AreAliased(object, address, value, t8));
307   DCHECK(!AreAliased(object, address, value, t9));
308
309   if (emit_debug_code()) {
310     lw(at, MemOperand(address));
311     Assert(
312         eq, kWrongAddressOrValuePassedToRecordWrite, at, Operand(value));
313   }
314
315   if (remembered_set_action == OMIT_REMEMBERED_SET &&
316       !FLAG_incremental_marking) {
317     return;
318   }
319
320   // First, check if a write barrier is even needed. The tests below
321   // catch stores of smis and stores into the young generation.
322   Label done;
323
324   if (smi_check == INLINE_SMI_CHECK) {
325     DCHECK_EQ(0, kSmiTag);
326     JumpIfSmi(value, &done);
327   }
328
329   if (pointers_to_here_check_for_value != kPointersToHereAreAlwaysInteresting) {
330     CheckPageFlag(value,
331                   value,  // Used as scratch.
332                   MemoryChunk::kPointersToHereAreInterestingMask,
333                   eq,
334                   &done);
335   }
336   CheckPageFlag(object,
337                 value,  // Used as scratch.
338                 MemoryChunk::kPointersFromHereAreInterestingMask,
339                 eq,
340                 &done);
341
342   // Record the actual write.
343   if (ra_status == kRAHasNotBeenSaved) {
344     push(ra);
345   }
346   RecordWriteStub stub(isolate(), object, value, address, remembered_set_action,
347                        fp_mode);
348   CallStub(&stub);
349   if (ra_status == kRAHasNotBeenSaved) {
350     pop(ra);
351   }
352
353   bind(&done);
354
355   // Count number of write barriers in generated code.
356   isolate()->counters()->write_barriers_static()->Increment();
357   IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1, at,
358                    value);
359
360   // Clobber clobbered registers when running with the debug-code flag
361   // turned on to provoke errors.
362   if (emit_debug_code()) {
363     li(address, Operand(bit_cast<int32_t>(kZapValue + 12)));
364     li(value, Operand(bit_cast<int32_t>(kZapValue + 16)));
365   }
366 }
367
368
369 void MacroAssembler::RememberedSetHelper(Register object,  // For debug tests.
370                                          Register address,
371                                          Register scratch,
372                                          SaveFPRegsMode fp_mode,
373                                          RememberedSetFinalAction and_then) {
374   Label done;
375   if (emit_debug_code()) {
376     Label ok;
377     JumpIfNotInNewSpace(object, scratch, &ok);
378     stop("Remembered set pointer is in new space");
379     bind(&ok);
380   }
381   // Load store buffer top.
382   ExternalReference store_buffer =
383       ExternalReference::store_buffer_top(isolate());
384   li(t8, Operand(store_buffer));
385   lw(scratch, MemOperand(t8));
386   // Store pointer to buffer and increment buffer top.
387   sw(address, MemOperand(scratch));
388   Addu(scratch, scratch, kPointerSize);
389   // Write back new top of buffer.
390   sw(scratch, MemOperand(t8));
391   // Call stub on end of buffer.
392   // Check for end of buffer.
393   And(t8, scratch, Operand(StoreBuffer::kStoreBufferOverflowBit));
394   if (and_then == kFallThroughAtEnd) {
395     Branch(&done, eq, t8, Operand(zero_reg));
396   } else {
397     DCHECK(and_then == kReturnAtEnd);
398     Ret(eq, t8, Operand(zero_reg));
399   }
400   push(ra);
401   StoreBufferOverflowStub store_buffer_overflow(isolate(), fp_mode);
402   CallStub(&store_buffer_overflow);
403   pop(ra);
404   bind(&done);
405   if (and_then == kReturnAtEnd) {
406     Ret();
407   }
408 }
409
410
411 // -----------------------------------------------------------------------------
412 // Allocation support.
413
414
415 void MacroAssembler::CheckAccessGlobalProxy(Register holder_reg,
416                                             Register scratch,
417                                             Label* miss) {
418   Label same_contexts;
419
420   DCHECK(!holder_reg.is(scratch));
421   DCHECK(!holder_reg.is(at));
422   DCHECK(!scratch.is(at));
423
424   // Load current lexical context from the stack frame.
425   lw(scratch, MemOperand(fp, StandardFrameConstants::kContextOffset));
426   // In debug mode, make sure the lexical context is set.
427 #ifdef DEBUG
428   Check(ne, kWeShouldNotHaveAnEmptyLexicalContext,
429       scratch, Operand(zero_reg));
430 #endif
431
432   // Load the native context of the current context.
433   int offset =
434       Context::kHeaderSize + Context::GLOBAL_OBJECT_INDEX * kPointerSize;
435   lw(scratch, FieldMemOperand(scratch, offset));
436   lw(scratch, FieldMemOperand(scratch, GlobalObject::kNativeContextOffset));
437
438   // Check the context is a native context.
439   if (emit_debug_code()) {
440     push(holder_reg);  // Temporarily save holder on the stack.
441     // Read the first word and compare to the native_context_map.
442     lw(holder_reg, FieldMemOperand(scratch, HeapObject::kMapOffset));
443     LoadRoot(at, Heap::kNativeContextMapRootIndex);
444     Check(eq, kJSGlobalObjectNativeContextShouldBeANativeContext,
445           holder_reg, Operand(at));
446     pop(holder_reg);  // Restore holder.
447   }
448
449   // Check if both contexts are the same.
450   lw(at, FieldMemOperand(holder_reg, JSGlobalProxy::kNativeContextOffset));
451   Branch(&same_contexts, eq, scratch, Operand(at));
452
453   // Check the context is a native context.
454   if (emit_debug_code()) {
455     push(holder_reg);  // Temporarily save holder on the stack.
456     mov(holder_reg, at);  // Move at to its holding place.
457     LoadRoot(at, Heap::kNullValueRootIndex);
458     Check(ne, kJSGlobalProxyContextShouldNotBeNull,
459           holder_reg, Operand(at));
460
461     lw(holder_reg, FieldMemOperand(holder_reg, HeapObject::kMapOffset));
462     LoadRoot(at, Heap::kNativeContextMapRootIndex);
463     Check(eq, kJSGlobalObjectNativeContextShouldBeANativeContext,
464           holder_reg, Operand(at));
465     // Restore at is not needed. at is reloaded below.
466     pop(holder_reg);  // Restore holder.
467     // Restore at to holder's context.
468     lw(at, FieldMemOperand(holder_reg, JSGlobalProxy::kNativeContextOffset));
469   }
470
471   // Check that the security token in the calling global object is
472   // compatible with the security token in the receiving global
473   // object.
474   int token_offset = Context::kHeaderSize +
475                      Context::SECURITY_TOKEN_INDEX * kPointerSize;
476
477   lw(scratch, FieldMemOperand(scratch, token_offset));
478   lw(at, FieldMemOperand(at, token_offset));
479   Branch(miss, ne, scratch, Operand(at));
480
481   bind(&same_contexts);
482 }
483
484
485 // Compute the hash code from the untagged key.  This must be kept in sync with
486 // ComputeIntegerHash in utils.h and KeyedLoadGenericStub in
487 // code-stub-hydrogen.cc
488 void MacroAssembler::GetNumberHash(Register reg0, Register scratch) {
489   // First of all we assign the hash seed to scratch.
490   LoadRoot(scratch, Heap::kHashSeedRootIndex);
491   SmiUntag(scratch);
492
493   // Xor original key with a seed.
494   xor_(reg0, reg0, scratch);
495
496   // Compute the hash code from the untagged key.  This must be kept in sync
497   // with ComputeIntegerHash in utils.h.
498   //
499   // hash = ~hash + (hash << 15);
500   nor(scratch, reg0, zero_reg);
501   sll(at, reg0, 15);
502   addu(reg0, scratch, at);
503
504   // hash = hash ^ (hash >> 12);
505   srl(at, reg0, 12);
506   xor_(reg0, reg0, at);
507
508   // hash = hash + (hash << 2);
509   sll(at, reg0, 2);
510   addu(reg0, reg0, at);
511
512   // hash = hash ^ (hash >> 4);
513   srl(at, reg0, 4);
514   xor_(reg0, reg0, at);
515
516   // hash = hash * 2057;
517   sll(scratch, reg0, 11);
518   sll(at, reg0, 3);
519   addu(reg0, reg0, at);
520   addu(reg0, reg0, scratch);
521
522   // hash = hash ^ (hash >> 16);
523   srl(at, reg0, 16);
524   xor_(reg0, reg0, at);
525 }
526
527
528 void MacroAssembler::LoadFromNumberDictionary(Label* miss,
529                                               Register elements,
530                                               Register key,
531                                               Register result,
532                                               Register reg0,
533                                               Register reg1,
534                                               Register reg2) {
535   // Register use:
536   //
537   // elements - holds the slow-case elements of the receiver on entry.
538   //            Unchanged unless 'result' is the same register.
539   //
540   // key      - holds the smi key on entry.
541   //            Unchanged unless 'result' is the same register.
542   //
543   //
544   // result   - holds the result on exit if the load succeeded.
545   //            Allowed to be the same as 'key' or 'result'.
546   //            Unchanged on bailout so 'key' or 'result' can be used
547   //            in further computation.
548   //
549   // Scratch registers:
550   //
551   // reg0 - holds the untagged key on entry and holds the hash once computed.
552   //
553   // reg1 - Used to hold the capacity mask of the dictionary.
554   //
555   // reg2 - Used for the index into the dictionary.
556   // at   - Temporary (avoid MacroAssembler instructions also using 'at').
557   Label done;
558
559   GetNumberHash(reg0, reg1);
560
561   // Compute the capacity mask.
562   lw(reg1, FieldMemOperand(elements, SeededNumberDictionary::kCapacityOffset));
563   sra(reg1, reg1, kSmiTagSize);
564   Subu(reg1, reg1, Operand(1));
565
566   // Generate an unrolled loop that performs a few probes before giving up.
567   for (int i = 0; i < kNumberDictionaryProbes; i++) {
568     // Use reg2 for index calculations and keep the hash intact in reg0.
569     mov(reg2, reg0);
570     // Compute the masked index: (hash + i + i * i) & mask.
571     if (i > 0) {
572       Addu(reg2, reg2, Operand(SeededNumberDictionary::GetProbeOffset(i)));
573     }
574     and_(reg2, reg2, reg1);
575
576     // Scale the index by multiplying by the element size.
577     DCHECK(SeededNumberDictionary::kEntrySize == 3);
578     sll(at, reg2, 1);  // 2x.
579     addu(reg2, reg2, at);  // reg2 = reg2 * 3.
580
581     // Check if the key is identical to the name.
582     sll(at, reg2, kPointerSizeLog2);
583     addu(reg2, elements, at);
584
585     lw(at, FieldMemOperand(reg2, SeededNumberDictionary::kElementsStartOffset));
586     if (i != kNumberDictionaryProbes - 1) {
587       Branch(&done, eq, key, Operand(at));
588     } else {
589       Branch(miss, ne, key, Operand(at));
590     }
591   }
592
593   bind(&done);
594   // Check that the value is a field property.
595   // reg2: elements + (index * kPointerSize).
596   const int kDetailsOffset =
597       SeededNumberDictionary::kElementsStartOffset + 2 * kPointerSize;
598   lw(reg1, FieldMemOperand(reg2, kDetailsOffset));
599   DCHECK_EQ(DATA, 0);
600   And(at, reg1, Operand(Smi::FromInt(PropertyDetails::TypeField::kMask)));
601   Branch(miss, ne, at, Operand(zero_reg));
602
603   // Get the value at the masked, scaled index and return.
604   const int kValueOffset =
605       SeededNumberDictionary::kElementsStartOffset + kPointerSize;
606   lw(result, FieldMemOperand(reg2, kValueOffset));
607 }
608
609
610 // ---------------------------------------------------------------------------
611 // Instruction macros.
612
613 void MacroAssembler::Addu(Register rd, Register rs, const Operand& rt) {
614   if (rt.is_reg()) {
615     addu(rd, rs, rt.rm());
616   } else {
617     if (is_int16(rt.imm32_) && !MustUseReg(rt.rmode_)) {
618       addiu(rd, rs, rt.imm32_);
619     } else {
620       // li handles the relocation.
621       DCHECK(!rs.is(at));
622       li(at, rt);
623       addu(rd, rs, at);
624     }
625   }
626 }
627
628
629 void MacroAssembler::Subu(Register rd, Register rs, const Operand& rt) {
630   if (rt.is_reg()) {
631     subu(rd, rs, rt.rm());
632   } else {
633     if (is_int16(rt.imm32_) && !MustUseReg(rt.rmode_)) {
634       addiu(rd, rs, -rt.imm32_);  // No subiu instr, use addiu(x, y, -imm).
635     } else {
636       // li handles the relocation.
637       DCHECK(!rs.is(at));
638       li(at, rt);
639       subu(rd, rs, at);
640     }
641   }
642 }
643
644
645 void MacroAssembler::Mul(Register rd, Register rs, const Operand& rt) {
646   if (rt.is_reg()) {
647     if (IsMipsArchVariant(kLoongson)) {
648       mult(rs, rt.rm());
649       mflo(rd);
650     } else {
651       mul(rd, rs, rt.rm());
652     }
653   } else {
654     // li handles the relocation.
655     DCHECK(!rs.is(at));
656     li(at, rt);
657     if (IsMipsArchVariant(kLoongson)) {
658       mult(rs, at);
659       mflo(rd);
660     } else {
661       mul(rd, rs, at);
662     }
663   }
664 }
665
666
667 void MacroAssembler::Mul(Register rd_hi, Register rd_lo,
668     Register rs, const Operand& rt) {
669   if (rt.is_reg()) {
670     if (!IsMipsArchVariant(kMips32r6)) {
671       mult(rs, rt.rm());
672       mflo(rd_lo);
673       mfhi(rd_hi);
674     } else {
675       if (rd_lo.is(rs)) {
676         DCHECK(!rd_hi.is(rs));
677         DCHECK(!rd_hi.is(rt.rm()) && !rd_lo.is(rt.rm()));
678         muh(rd_hi, rs, rt.rm());
679         mul(rd_lo, rs, rt.rm());
680       } else {
681         DCHECK(!rd_hi.is(rt.rm()) && !rd_lo.is(rt.rm()));
682         mul(rd_lo, rs, rt.rm());
683         muh(rd_hi, rs, rt.rm());
684       }
685     }
686   } else {
687     // li handles the relocation.
688     DCHECK(!rs.is(at));
689     li(at, rt);
690     if (!IsMipsArchVariant(kMips32r6)) {
691       mult(rs, at);
692       mflo(rd_lo);
693       mfhi(rd_hi);
694     } else {
695       if (rd_lo.is(rs)) {
696         DCHECK(!rd_hi.is(rs));
697         DCHECK(!rd_hi.is(at) && !rd_lo.is(at));
698         muh(rd_hi, rs, at);
699         mul(rd_lo, rs, at);
700       } else {
701         DCHECK(!rd_hi.is(at) && !rd_lo.is(at));
702         mul(rd_lo, rs, at);
703         muh(rd_hi, rs, at);
704       }
705     }
706   }
707 }
708
709
710 void MacroAssembler::Mulh(Register rd, Register rs, const Operand& rt) {
711   if (rt.is_reg()) {
712     if (!IsMipsArchVariant(kMips32r6)) {
713       mult(rs, rt.rm());
714       mfhi(rd);
715     } else {
716       muh(rd, rs, rt.rm());
717     }
718   } else {
719     // li handles the relocation.
720     DCHECK(!rs.is(at));
721     li(at, rt);
722     if (!IsMipsArchVariant(kMips32r6)) {
723       mult(rs, at);
724       mfhi(rd);
725     } else {
726       muh(rd, rs, at);
727     }
728   }
729 }
730
731
732 void MacroAssembler::Mult(Register rs, const Operand& rt) {
733   if (rt.is_reg()) {
734     mult(rs, rt.rm());
735   } else {
736     // li handles the relocation.
737     DCHECK(!rs.is(at));
738     li(at, rt);
739     mult(rs, at);
740   }
741 }
742
743
744 void MacroAssembler::Mulhu(Register rd, Register rs, const Operand& rt) {
745   if (rt.is_reg()) {
746     if (!IsMipsArchVariant(kMips32r6)) {
747       multu(rs, rt.rm());
748       mfhi(rd);
749     } else {
750       muhu(rd, rs, rt.rm());
751     }
752   } else {
753     // li handles the relocation.
754     DCHECK(!rs.is(at));
755     li(at, rt);
756     if (!IsMipsArchVariant(kMips32r6)) {
757       multu(rs, at);
758       mfhi(rd);
759     } else {
760       muhu(rd, rs, at);
761     }
762   }
763 }
764
765
766 void MacroAssembler::Multu(Register rs, const Operand& rt) {
767   if (rt.is_reg()) {
768     multu(rs, rt.rm());
769   } else {
770     // li handles the relocation.
771     DCHECK(!rs.is(at));
772     li(at, rt);
773     multu(rs, at);
774   }
775 }
776
777
778 void MacroAssembler::Div(Register rs, const Operand& rt) {
779   if (rt.is_reg()) {
780     div(rs, rt.rm());
781   } else {
782     // li handles the relocation.
783     DCHECK(!rs.is(at));
784     li(at, rt);
785     div(rs, at);
786   }
787 }
788
789
790 void MacroAssembler::Div(Register rem, Register res,
791     Register rs, const Operand& rt) {
792   if (rt.is_reg()) {
793     if (!IsMipsArchVariant(kMips32r6)) {
794       div(rs, rt.rm());
795       mflo(res);
796       mfhi(rem);
797     } else {
798       div(res, rs, rt.rm());
799       mod(rem, rs, rt.rm());
800     }
801   } else {
802     // li handles the relocation.
803     DCHECK(!rs.is(at));
804     li(at, rt);
805     if (!IsMipsArchVariant(kMips32r6)) {
806       div(rs, at);
807       mflo(res);
808       mfhi(rem);
809     } else {
810       div(res, rs, at);
811       mod(rem, rs, at);
812     }
813   }
814 }
815
816
817 void MacroAssembler::Div(Register res, Register rs, const Operand& rt) {
818   if (rt.is_reg()) {
819     if (!IsMipsArchVariant(kMips32r6)) {
820       div(rs, rt.rm());
821       mflo(res);
822     } else {
823       div(res, rs, rt.rm());
824     }
825   } else {
826     // li handles the relocation.
827     DCHECK(!rs.is(at));
828     li(at, rt);
829     if (!IsMipsArchVariant(kMips32r6)) {
830       div(rs, at);
831       mflo(res);
832     } else {
833       div(res, rs, at);
834     }
835   }
836 }
837
838
839 void MacroAssembler::Mod(Register rd, Register rs, const Operand& rt) {
840   if (rt.is_reg()) {
841     if (!IsMipsArchVariant(kMips32r6)) {
842       div(rs, rt.rm());
843       mfhi(rd);
844     } else {
845       mod(rd, rs, rt.rm());
846     }
847   } else {
848     // li handles the relocation.
849     DCHECK(!rs.is(at));
850     li(at, rt);
851     if (!IsMipsArchVariant(kMips32r6)) {
852       div(rs, at);
853       mfhi(rd);
854     } else {
855       mod(rd, rs, at);
856     }
857   }
858 }
859
860
861 void MacroAssembler::Modu(Register rd, Register rs, const Operand& rt) {
862   if (rt.is_reg()) {
863     if (!IsMipsArchVariant(kMips32r6)) {
864       divu(rs, rt.rm());
865       mfhi(rd);
866     } else {
867       modu(rd, rs, rt.rm());
868     }
869   } else {
870     // li handles the relocation.
871     DCHECK(!rs.is(at));
872     li(at, rt);
873     if (!IsMipsArchVariant(kMips32r6)) {
874       divu(rs, at);
875       mfhi(rd);
876     } else {
877       modu(rd, rs, at);
878     }
879   }
880 }
881
882
883 void MacroAssembler::Divu(Register rs, const Operand& rt) {
884   if (rt.is_reg()) {
885     divu(rs, rt.rm());
886   } else {
887     // li handles the relocation.
888     DCHECK(!rs.is(at));
889     li(at, rt);
890     divu(rs, at);
891   }
892 }
893
894
895 void MacroAssembler::Divu(Register res, Register rs, const Operand& rt) {
896   if (rt.is_reg()) {
897     if (!IsMipsArchVariant(kMips32r6)) {
898       divu(rs, rt.rm());
899       mflo(res);
900     } else {
901       divu(res, rs, rt.rm());
902     }
903   } else {
904     // li handles the relocation.
905     DCHECK(!rs.is(at));
906     li(at, rt);
907     if (!IsMipsArchVariant(kMips32r6)) {
908       divu(rs, at);
909       mflo(res);
910     } else {
911       divu(res, rs, at);
912     }
913   }
914 }
915
916
917 void MacroAssembler::And(Register rd, Register rs, const Operand& rt) {
918   if (rt.is_reg()) {
919     and_(rd, rs, rt.rm());
920   } else {
921     if (is_uint16(rt.imm32_) && !MustUseReg(rt.rmode_)) {
922       andi(rd, rs, rt.imm32_);
923     } else {
924       // li handles the relocation.
925       DCHECK(!rs.is(at));
926       li(at, rt);
927       and_(rd, rs, at);
928     }
929   }
930 }
931
932
933 void MacroAssembler::Or(Register rd, Register rs, const Operand& rt) {
934   if (rt.is_reg()) {
935     or_(rd, rs, rt.rm());
936   } else {
937     if (is_uint16(rt.imm32_) && !MustUseReg(rt.rmode_)) {
938       ori(rd, rs, rt.imm32_);
939     } else {
940       // li handles the relocation.
941       DCHECK(!rs.is(at));
942       li(at, rt);
943       or_(rd, rs, at);
944     }
945   }
946 }
947
948
949 void MacroAssembler::Xor(Register rd, Register rs, const Operand& rt) {
950   if (rt.is_reg()) {
951     xor_(rd, rs, rt.rm());
952   } else {
953     if (is_uint16(rt.imm32_) && !MustUseReg(rt.rmode_)) {
954       xori(rd, rs, rt.imm32_);
955     } else {
956       // li handles the relocation.
957       DCHECK(!rs.is(at));
958       li(at, rt);
959       xor_(rd, rs, at);
960     }
961   }
962 }
963
964
965 void MacroAssembler::Nor(Register rd, Register rs, const Operand& rt) {
966   if (rt.is_reg()) {
967     nor(rd, rs, rt.rm());
968   } else {
969     // li handles the relocation.
970     DCHECK(!rs.is(at));
971     li(at, rt);
972     nor(rd, rs, at);
973   }
974 }
975
976
977 void MacroAssembler::Neg(Register rs, const Operand& rt) {
978   DCHECK(rt.is_reg());
979   DCHECK(!at.is(rs));
980   DCHECK(!at.is(rt.rm()));
981   li(at, -1);
982   xor_(rs, rt.rm(), at);
983 }
984
985
986 void MacroAssembler::Slt(Register rd, Register rs, const Operand& rt) {
987   if (rt.is_reg()) {
988     slt(rd, rs, rt.rm());
989   } else {
990     if (is_int16(rt.imm32_) && !MustUseReg(rt.rmode_)) {
991       slti(rd, rs, rt.imm32_);
992     } else {
993       // li handles the relocation.
994       DCHECK(!rs.is(at));
995       li(at, rt);
996       slt(rd, rs, at);
997     }
998   }
999 }
1000
1001
1002 void MacroAssembler::Sltu(Register rd, Register rs, const Operand& rt) {
1003   if (rt.is_reg()) {
1004     sltu(rd, rs, rt.rm());
1005   } else {
1006     if (is_uint16(rt.imm32_) && !MustUseReg(rt.rmode_)) {
1007       sltiu(rd, rs, rt.imm32_);
1008     } else {
1009       // li handles the relocation.
1010       DCHECK(!rs.is(at));
1011       li(at, rt);
1012       sltu(rd, rs, at);
1013     }
1014   }
1015 }
1016
1017
1018 void MacroAssembler::Ror(Register rd, Register rs, const Operand& rt) {
1019   if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
1020     if (rt.is_reg()) {
1021       rotrv(rd, rs, rt.rm());
1022     } else {
1023       rotr(rd, rs, rt.imm32_);
1024     }
1025   } else {
1026     if (rt.is_reg()) {
1027       subu(at, zero_reg, rt.rm());
1028       sllv(at, rs, at);
1029       srlv(rd, rs, rt.rm());
1030       or_(rd, rd, at);
1031     } else {
1032       if (rt.imm32_ == 0) {
1033         srl(rd, rs, 0);
1034       } else {
1035         srl(at, rs, rt.imm32_);
1036         sll(rd, rs, (0x20 - rt.imm32_) & 0x1f);
1037         or_(rd, rd, at);
1038       }
1039     }
1040   }
1041 }
1042
1043
1044 void MacroAssembler::Pref(int32_t hint, const MemOperand& rs) {
1045   if (IsMipsArchVariant(kLoongson)) {
1046     lw(zero_reg, rs);
1047   } else {
1048     pref(hint, rs);
1049   }
1050 }
1051
1052
1053 // ------------Pseudo-instructions-------------
1054
1055 void MacroAssembler::Ulw(Register rd, const MemOperand& rs) {
1056   lwr(rd, rs);
1057   lwl(rd, MemOperand(rs.rm(), rs.offset() + 3));
1058 }
1059
1060
1061 void MacroAssembler::Usw(Register rd, const MemOperand& rs) {
1062   swr(rd, rs);
1063   swl(rd, MemOperand(rs.rm(), rs.offset() + 3));
1064 }
1065
1066
1067 void MacroAssembler::li(Register dst, Handle<Object> value, LiFlags mode) {
1068   AllowDeferredHandleDereference smi_check;
1069   if (value->IsSmi()) {
1070     li(dst, Operand(value), mode);
1071   } else {
1072     DCHECK(value->IsHeapObject());
1073     if (isolate()->heap()->InNewSpace(*value)) {
1074       Handle<Cell> cell = isolate()->factory()->NewCell(value);
1075       li(dst, Operand(cell));
1076       lw(dst, FieldMemOperand(dst, Cell::kValueOffset));
1077     } else {
1078       li(dst, Operand(value));
1079     }
1080   }
1081 }
1082
1083
1084 void MacroAssembler::li(Register rd, Operand j, LiFlags mode) {
1085   DCHECK(!j.is_reg());
1086   BlockTrampolinePoolScope block_trampoline_pool(this);
1087   if (!MustUseReg(j.rmode_) && mode == OPTIMIZE_SIZE) {
1088     // Normal load of an immediate value which does not need Relocation Info.
1089     if (is_int16(j.imm32_)) {
1090       addiu(rd, zero_reg, j.imm32_);
1091     } else if (!(j.imm32_ & kHiMask)) {
1092       ori(rd, zero_reg, j.imm32_);
1093     } else if (!(j.imm32_ & kImm16Mask)) {
1094       lui(rd, (j.imm32_ >> kLuiShift) & kImm16Mask);
1095     } else {
1096       lui(rd, (j.imm32_ >> kLuiShift) & kImm16Mask);
1097       ori(rd, rd, (j.imm32_ & kImm16Mask));
1098     }
1099   } else {
1100     if (MustUseReg(j.rmode_)) {
1101       RecordRelocInfo(j.rmode_, j.imm32_);
1102     }
1103     // We always need the same number of instructions as we may need to patch
1104     // this code to load another value which may need 2 instructions to load.
1105     lui(rd, (j.imm32_ >> kLuiShift) & kImm16Mask);
1106     ori(rd, rd, (j.imm32_ & kImm16Mask));
1107   }
1108 }
1109
1110
1111 void MacroAssembler::MultiPush(RegList regs) {
1112   int16_t num_to_push = NumberOfBitsSet(regs);
1113   int16_t stack_offset = num_to_push * kPointerSize;
1114
1115   Subu(sp, sp, Operand(stack_offset));
1116   for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
1117     if ((regs & (1 << i)) != 0) {
1118       stack_offset -= kPointerSize;
1119       sw(ToRegister(i), MemOperand(sp, stack_offset));
1120     }
1121   }
1122 }
1123
1124
1125 void MacroAssembler::MultiPushReversed(RegList regs) {
1126   int16_t num_to_push = NumberOfBitsSet(regs);
1127   int16_t stack_offset = num_to_push * kPointerSize;
1128
1129   Subu(sp, sp, Operand(stack_offset));
1130   for (int16_t i = 0; i < kNumRegisters; i++) {
1131     if ((regs & (1 << i)) != 0) {
1132       stack_offset -= kPointerSize;
1133       sw(ToRegister(i), MemOperand(sp, stack_offset));
1134     }
1135   }
1136 }
1137
1138
1139 void MacroAssembler::MultiPop(RegList regs) {
1140   int16_t stack_offset = 0;
1141
1142   for (int16_t i = 0; i < kNumRegisters; i++) {
1143     if ((regs & (1 << i)) != 0) {
1144       lw(ToRegister(i), MemOperand(sp, stack_offset));
1145       stack_offset += kPointerSize;
1146     }
1147   }
1148   addiu(sp, sp, stack_offset);
1149 }
1150
1151
1152 void MacroAssembler::MultiPopReversed(RegList regs) {
1153   int16_t stack_offset = 0;
1154
1155   for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
1156     if ((regs & (1 << i)) != 0) {
1157       lw(ToRegister(i), MemOperand(sp, stack_offset));
1158       stack_offset += kPointerSize;
1159     }
1160   }
1161   addiu(sp, sp, stack_offset);
1162 }
1163
1164
1165 void MacroAssembler::MultiPushFPU(RegList regs) {
1166   int16_t num_to_push = NumberOfBitsSet(regs);
1167   int16_t stack_offset = num_to_push * kDoubleSize;
1168
1169   Subu(sp, sp, Operand(stack_offset));
1170   for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
1171     if ((regs & (1 << i)) != 0) {
1172       stack_offset -= kDoubleSize;
1173       sdc1(FPURegister::from_code(i), MemOperand(sp, stack_offset));
1174     }
1175   }
1176 }
1177
1178
1179 void MacroAssembler::MultiPushReversedFPU(RegList regs) {
1180   int16_t num_to_push = NumberOfBitsSet(regs);
1181   int16_t stack_offset = num_to_push * kDoubleSize;
1182
1183   Subu(sp, sp, Operand(stack_offset));
1184   for (int16_t i = 0; i < kNumRegisters; i++) {
1185     if ((regs & (1 << i)) != 0) {
1186       stack_offset -= kDoubleSize;
1187       sdc1(FPURegister::from_code(i), MemOperand(sp, stack_offset));
1188     }
1189   }
1190 }
1191
1192
1193 void MacroAssembler::MultiPopFPU(RegList regs) {
1194   int16_t stack_offset = 0;
1195
1196   for (int16_t i = 0; i < kNumRegisters; i++) {
1197     if ((regs & (1 << i)) != 0) {
1198       ldc1(FPURegister::from_code(i), MemOperand(sp, stack_offset));
1199       stack_offset += kDoubleSize;
1200     }
1201   }
1202   addiu(sp, sp, stack_offset);
1203 }
1204
1205
1206 void MacroAssembler::MultiPopReversedFPU(RegList regs) {
1207   int16_t stack_offset = 0;
1208
1209   for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
1210     if ((regs & (1 << i)) != 0) {
1211       ldc1(FPURegister::from_code(i), MemOperand(sp, stack_offset));
1212       stack_offset += kDoubleSize;
1213     }
1214   }
1215   addiu(sp, sp, stack_offset);
1216 }
1217
1218
1219 void MacroAssembler::FlushICache(Register address, unsigned instructions) {
1220   RegList saved_regs = kJSCallerSaved | ra.bit();
1221   MultiPush(saved_regs);
1222   AllowExternalCallThatCantCauseGC scope(this);
1223
1224   // Save to a0 in case address == t0.
1225   Move(a0, address);
1226   PrepareCallCFunction(2, t0);
1227
1228   li(a1, instructions * kInstrSize);
1229   CallCFunction(ExternalReference::flush_icache_function(isolate()), 2);
1230   MultiPop(saved_regs);
1231 }
1232
1233
1234 void MacroAssembler::Ext(Register rt,
1235                          Register rs,
1236                          uint16_t pos,
1237                          uint16_t size) {
1238   DCHECK(pos < 32);
1239   DCHECK(pos + size < 33);
1240
1241   if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
1242     ext_(rt, rs, pos, size);
1243   } else {
1244     // Move rs to rt and shift it left then right to get the
1245     // desired bitfield on the right side and zeroes on the left.
1246     int shift_left = 32 - (pos + size);
1247     sll(rt, rs, shift_left);  // Acts as a move if shift_left == 0.
1248
1249     int shift_right = 32 - size;
1250     if (shift_right > 0) {
1251       srl(rt, rt, shift_right);
1252     }
1253   }
1254 }
1255
1256
1257 void MacroAssembler::Ins(Register rt,
1258                          Register rs,
1259                          uint16_t pos,
1260                          uint16_t size) {
1261   DCHECK(pos < 32);
1262   DCHECK(pos + size <= 32);
1263   DCHECK(size != 0);
1264
1265   if (IsMipsArchVariant(kMips32r2) || IsMipsArchVariant(kMips32r6)) {
1266     ins_(rt, rs, pos, size);
1267   } else {
1268     DCHECK(!rt.is(t8) && !rs.is(t8));
1269     Subu(at, zero_reg, Operand(1));
1270     srl(at, at, 32 - size);
1271     and_(t8, rs, at);
1272     sll(t8, t8, pos);
1273     sll(at, at, pos);
1274     nor(at, at, zero_reg);
1275     and_(at, rt, at);
1276     or_(rt, t8, at);
1277   }
1278 }
1279
1280
1281 void MacroAssembler::Cvt_d_uw(FPURegister fd,
1282                               FPURegister fs,
1283                               FPURegister scratch) {
1284   // Move the data from fs to t8.
1285   mfc1(t8, fs);
1286   Cvt_d_uw(fd, t8, scratch);
1287 }
1288
1289
1290 void MacroAssembler::Cvt_d_uw(FPURegister fd,
1291                               Register rs,
1292                               FPURegister scratch) {
1293   // Convert rs to a FP value in fd (and fd + 1).
1294   // We do this by converting rs minus the MSB to avoid sign conversion,
1295   // then adding 2^31 to the result (if needed).
1296
1297   DCHECK(!fd.is(scratch));
1298   DCHECK(!rs.is(t9));
1299   DCHECK(!rs.is(at));
1300
1301   // Save rs's MSB to t9.
1302   Ext(t9, rs, 31, 1);
1303   // Remove rs's MSB.
1304   Ext(at, rs, 0, 31);
1305   // Move the result to fd.
1306   mtc1(at, fd);
1307
1308   // Convert fd to a real FP value.
1309   cvt_d_w(fd, fd);
1310
1311   Label conversion_done;
1312
1313   // If rs's MSB was 0, it's done.
1314   // Otherwise we need to add that to the FP register.
1315   Branch(&conversion_done, eq, t9, Operand(zero_reg));
1316
1317   // Load 2^31 into f20 as its float representation.
1318   li(at, 0x41E00000);
1319   mtc1(zero_reg, scratch);
1320   Mthc1(at, scratch);
1321   // Add it to fd.
1322   add_d(fd, fd, scratch);
1323
1324   bind(&conversion_done);
1325 }
1326
1327
1328 void MacroAssembler::Trunc_uw_d(FPURegister fd,
1329                                 FPURegister fs,
1330                                 FPURegister scratch) {
1331   Trunc_uw_d(fs, t8, scratch);
1332   mtc1(t8, fd);
1333 }
1334
1335
1336 void MacroAssembler::Trunc_w_d(FPURegister fd, FPURegister fs) {
1337   if (IsMipsArchVariant(kLoongson) && fd.is(fs)) {
1338     Mfhc1(t8, fs);
1339     trunc_w_d(fd, fs);
1340     Mthc1(t8, fs);
1341   } else {
1342     trunc_w_d(fd, fs);
1343   }
1344 }
1345
1346
1347 void MacroAssembler::Round_w_d(FPURegister fd, FPURegister fs) {
1348   if (IsMipsArchVariant(kLoongson) && fd.is(fs)) {
1349     Mfhc1(t8, fs);
1350     round_w_d(fd, fs);
1351     Mthc1(t8, fs);
1352   } else {
1353     round_w_d(fd, fs);
1354   }
1355 }
1356
1357
1358 void MacroAssembler::Floor_w_d(FPURegister fd, FPURegister fs) {
1359   if (IsMipsArchVariant(kLoongson) && fd.is(fs)) {
1360     Mfhc1(t8, fs);
1361     floor_w_d(fd, fs);
1362     Mthc1(t8, fs);
1363   } else {
1364     floor_w_d(fd, fs);
1365   }
1366 }
1367
1368
1369 void MacroAssembler::Ceil_w_d(FPURegister fd, FPURegister fs) {
1370   if (IsMipsArchVariant(kLoongson) && fd.is(fs)) {
1371     Mfhc1(t8, fs);
1372     ceil_w_d(fd, fs);
1373     Mthc1(t8, fs);
1374   } else {
1375     ceil_w_d(fd, fs);
1376   }
1377 }
1378
1379
1380 void MacroAssembler::Trunc_uw_d(FPURegister fd,
1381                                 Register rs,
1382                                 FPURegister scratch) {
1383   DCHECK(!fd.is(scratch));
1384   DCHECK(!rs.is(at));
1385
1386   // Load 2^31 into scratch as its float representation.
1387   li(at, 0x41E00000);
1388   mtc1(zero_reg, scratch);
1389   Mthc1(at, scratch);
1390   // Test if scratch > fd.
1391   // If fd < 2^31 we can convert it normally.
1392   Label simple_convert;
1393   BranchF(&simple_convert, NULL, lt, fd, scratch);
1394
1395   // First we subtract 2^31 from fd, then trunc it to rs
1396   // and add 2^31 to rs.
1397   sub_d(scratch, fd, scratch);
1398   trunc_w_d(scratch, scratch);
1399   mfc1(rs, scratch);
1400   Or(rs, rs, 1 << 31);
1401
1402   Label done;
1403   Branch(&done);
1404   // Simple conversion.
1405   bind(&simple_convert);
1406   trunc_w_d(scratch, fd);
1407   mfc1(rs, scratch);
1408
1409   bind(&done);
1410 }
1411
1412
1413 void MacroAssembler::Mthc1(Register rt, FPURegister fs) {
1414   if (IsFp64Mode()) {
1415     mthc1(rt, fs);
1416   } else {
1417     mtc1(rt, fs.high());
1418   }
1419 }
1420
1421
1422 void MacroAssembler::Mfhc1(Register rt, FPURegister fs) {
1423   if (IsFp64Mode()) {
1424     mfhc1(rt, fs);
1425   } else {
1426     mfc1(rt, fs.high());
1427   }
1428 }
1429
1430
1431 void MacroAssembler::BranchF(Label* target,
1432                              Label* nan,
1433                              Condition cc,
1434                              FPURegister cmp1,
1435                              FPURegister cmp2,
1436                              BranchDelaySlot bd) {
1437   BlockTrampolinePoolScope block_trampoline_pool(this);
1438   if (cc == al) {
1439     Branch(bd, target);
1440     return;
1441   }
1442
1443   DCHECK(nan || target);
1444   // Check for unordered (NaN) cases.
1445   if (nan) {
1446     if (!IsMipsArchVariant(kMips32r6)) {
1447       c(UN, D, cmp1, cmp2);
1448       bc1t(nan);
1449     } else {
1450       // Use kDoubleCompareReg for comparison result. It has to be unavailable
1451       // to lithium register allocator.
1452       DCHECK(!cmp1.is(kDoubleCompareReg) && !cmp2.is(kDoubleCompareReg));
1453       cmp(UN, L, kDoubleCompareReg, cmp1, cmp2);
1454       bc1nez(nan, kDoubleCompareReg);
1455     }
1456   }
1457
1458   if (!IsMipsArchVariant(kMips32r6)) {
1459     if (target) {
1460       // Here NaN cases were either handled by this function or are assumed to
1461       // have been handled by the caller.
1462       switch (cc) {
1463         case lt:
1464           c(OLT, D, cmp1, cmp2);
1465           bc1t(target);
1466           break;
1467         case gt:
1468           c(ULE, D, cmp1, cmp2);
1469           bc1f(target);
1470           break;
1471         case ge:
1472           c(ULT, D, cmp1, cmp2);
1473           bc1f(target);
1474           break;
1475         case le:
1476           c(OLE, D, cmp1, cmp2);
1477           bc1t(target);
1478           break;
1479         case eq:
1480           c(EQ, D, cmp1, cmp2);
1481           bc1t(target);
1482           break;
1483         case ueq:
1484           c(UEQ, D, cmp1, cmp2);
1485           bc1t(target);
1486           break;
1487         case ne:
1488           c(EQ, D, cmp1, cmp2);
1489           bc1f(target);
1490           break;
1491         case nue:
1492           c(UEQ, D, cmp1, cmp2);
1493           bc1f(target);
1494           break;
1495         default:
1496           CHECK(0);
1497       }
1498     }
1499   } else {
1500     if (target) {
1501       // Here NaN cases were either handled by this function or are assumed to
1502       // have been handled by the caller.
1503       // Unsigned conditions are treated as their signed counterpart.
1504       // Use kDoubleCompareReg for comparison result, it is
1505       // valid in fp64 (FR = 1) mode which is implied for mips32r6.
1506       DCHECK(!cmp1.is(kDoubleCompareReg) && !cmp2.is(kDoubleCompareReg));
1507       switch (cc) {
1508         case lt:
1509           cmp(OLT, L, kDoubleCompareReg, cmp1, cmp2);
1510           bc1nez(target, kDoubleCompareReg);
1511           break;
1512         case gt:
1513           cmp(ULE, L, kDoubleCompareReg, cmp1, cmp2);
1514           bc1eqz(target, kDoubleCompareReg);
1515           break;
1516         case ge:
1517           cmp(ULT, L, kDoubleCompareReg, cmp1, cmp2);
1518           bc1eqz(target, kDoubleCompareReg);
1519           break;
1520         case le:
1521           cmp(OLE, L, kDoubleCompareReg, cmp1, cmp2);
1522           bc1nez(target, kDoubleCompareReg);
1523           break;
1524         case eq:
1525           cmp(EQ, L, kDoubleCompareReg, cmp1, cmp2);
1526           bc1nez(target, kDoubleCompareReg);
1527           break;
1528         case ueq:
1529           cmp(UEQ, L, kDoubleCompareReg, cmp1, cmp2);
1530           bc1nez(target, kDoubleCompareReg);
1531           break;
1532         case ne:
1533           cmp(EQ, L, kDoubleCompareReg, cmp1, cmp2);
1534           bc1eqz(target, kDoubleCompareReg);
1535           break;
1536         case nue:
1537           cmp(UEQ, L, kDoubleCompareReg, cmp1, cmp2);
1538           bc1eqz(target, kDoubleCompareReg);
1539           break;
1540         default:
1541           CHECK(0);
1542       }
1543     }
1544   }
1545
1546   if (bd == PROTECT) {
1547     nop();
1548   }
1549 }
1550
1551
1552 void MacroAssembler::Move(FPURegister dst, float imm) {
1553   li(at, Operand(bit_cast<int32_t>(imm)));
1554   mtc1(at, dst);
1555 }
1556
1557
1558 void MacroAssembler::Move(FPURegister dst, double imm) {
1559   static const DoubleRepresentation minus_zero(-0.0);
1560   static const DoubleRepresentation zero(0.0);
1561   DoubleRepresentation value_rep(imm);
1562   // Handle special values first.
1563   if (value_rep == zero && has_double_zero_reg_set_) {
1564     mov_d(dst, kDoubleRegZero);
1565   } else if (value_rep == minus_zero && has_double_zero_reg_set_) {
1566     neg_d(dst, kDoubleRegZero);
1567   } else {
1568     uint32_t lo, hi;
1569     DoubleAsTwoUInt32(imm, &lo, &hi);
1570     // Move the low part of the double into the lower of the corresponding FPU
1571     // register of FPU register pair.
1572     if (lo != 0) {
1573       li(at, Operand(lo));
1574       mtc1(at, dst);
1575     } else {
1576       mtc1(zero_reg, dst);
1577     }
1578     // Move the high part of the double into the higher of the corresponding FPU
1579     // register of FPU register pair.
1580     if (hi != 0) {
1581       li(at, Operand(hi));
1582       Mthc1(at, dst);
1583     } else {
1584       Mthc1(zero_reg, dst);
1585     }
1586     if (dst.is(kDoubleRegZero)) has_double_zero_reg_set_ = true;
1587   }
1588 }
1589
1590
1591 void MacroAssembler::Movz(Register rd, Register rs, Register rt) {
1592   if (IsMipsArchVariant(kLoongson) || IsMipsArchVariant(kMips32r6)) {
1593     Label done;
1594     Branch(&done, ne, rt, Operand(zero_reg));
1595     mov(rd, rs);
1596     bind(&done);
1597   } else {
1598     movz(rd, rs, rt);
1599   }
1600 }
1601
1602
1603 void MacroAssembler::Movn(Register rd, Register rs, Register rt) {
1604   if (IsMipsArchVariant(kLoongson) || IsMipsArchVariant(kMips32r6)) {
1605     Label done;
1606     Branch(&done, eq, rt, Operand(zero_reg));
1607     mov(rd, rs);
1608     bind(&done);
1609   } else {
1610     movn(rd, rs, rt);
1611   }
1612 }
1613
1614
1615 void MacroAssembler::Movt(Register rd, Register rs, uint16_t cc) {
1616   if (IsMipsArchVariant(kLoongson)) {
1617     // Tests an FP condition code and then conditionally move rs to rd.
1618     // We do not currently use any FPU cc bit other than bit 0.
1619     DCHECK(cc == 0);
1620     DCHECK(!(rs.is(t8) || rd.is(t8)));
1621     Label done;
1622     Register scratch = t8;
1623     // For testing purposes we need to fetch content of the FCSR register and
1624     // than test its cc (floating point condition code) bit (for cc = 0, it is
1625     // 24. bit of the FCSR).
1626     cfc1(scratch, FCSR);
1627     // For the MIPS I, II and III architectures, the contents of scratch is
1628     // UNPREDICTABLE for the instruction immediately following CFC1.
1629     nop();
1630     srl(scratch, scratch, 16);
1631     andi(scratch, scratch, 0x0080);
1632     Branch(&done, eq, scratch, Operand(zero_reg));
1633     mov(rd, rs);
1634     bind(&done);
1635   } else {
1636     movt(rd, rs, cc);
1637   }
1638 }
1639
1640
1641 void MacroAssembler::Movf(Register rd, Register rs, uint16_t cc) {
1642   if (IsMipsArchVariant(kLoongson)) {
1643     // Tests an FP condition code and then conditionally move rs to rd.
1644     // We do not currently use any FPU cc bit other than bit 0.
1645     DCHECK(cc == 0);
1646     DCHECK(!(rs.is(t8) || rd.is(t8)));
1647     Label done;
1648     Register scratch = t8;
1649     // For testing purposes we need to fetch content of the FCSR register and
1650     // than test its cc (floating point condition code) bit (for cc = 0, it is
1651     // 24. bit of the FCSR).
1652     cfc1(scratch, FCSR);
1653     // For the MIPS I, II and III architectures, the contents of scratch is
1654     // UNPREDICTABLE for the instruction immediately following CFC1.
1655     nop();
1656     srl(scratch, scratch, 16);
1657     andi(scratch, scratch, 0x0080);
1658     Branch(&done, ne, scratch, Operand(zero_reg));
1659     mov(rd, rs);
1660     bind(&done);
1661   } else {
1662     movf(rd, rs, cc);
1663   }
1664 }
1665
1666
1667 void MacroAssembler::Clz(Register rd, Register rs) {
1668   if (IsMipsArchVariant(kLoongson)) {
1669     DCHECK(!(rd.is(t8) || rd.is(t9)) && !(rs.is(t8) || rs.is(t9)));
1670     Register mask = t8;
1671     Register scratch = t9;
1672     Label loop, end;
1673     mov(at, rs);
1674     mov(rd, zero_reg);
1675     lui(mask, 0x8000);
1676     bind(&loop);
1677     and_(scratch, at, mask);
1678     Branch(&end, ne, scratch, Operand(zero_reg));
1679     addiu(rd, rd, 1);
1680     Branch(&loop, ne, mask, Operand(zero_reg), USE_DELAY_SLOT);
1681     srl(mask, mask, 1);
1682     bind(&end);
1683   } else {
1684     clz(rd, rs);
1685   }
1686 }
1687
1688
1689 void MacroAssembler::EmitFPUTruncate(FPURoundingMode rounding_mode,
1690                                      Register result,
1691                                      DoubleRegister double_input,
1692                                      Register scratch,
1693                                      DoubleRegister double_scratch,
1694                                      Register except_flag,
1695                                      CheckForInexactConversion check_inexact) {
1696   DCHECK(!result.is(scratch));
1697   DCHECK(!double_input.is(double_scratch));
1698   DCHECK(!except_flag.is(scratch));
1699
1700   Label done;
1701
1702   // Clear the except flag (0 = no exception)
1703   mov(except_flag, zero_reg);
1704
1705   // Test for values that can be exactly represented as a signed 32-bit integer.
1706   cvt_w_d(double_scratch, double_input);
1707   mfc1(result, double_scratch);
1708   cvt_d_w(double_scratch, double_scratch);
1709   BranchF(&done, NULL, eq, double_input, double_scratch);
1710
1711   int32_t except_mask = kFCSRFlagMask;  // Assume interested in all exceptions.
1712
1713   if (check_inexact == kDontCheckForInexactConversion) {
1714     // Ignore inexact exceptions.
1715     except_mask &= ~kFCSRInexactFlagMask;
1716   }
1717
1718   // Save FCSR.
1719   cfc1(scratch, FCSR);
1720   // Disable FPU exceptions.
1721   ctc1(zero_reg, FCSR);
1722
1723   // Do operation based on rounding mode.
1724   switch (rounding_mode) {
1725     case kRoundToNearest:
1726       Round_w_d(double_scratch, double_input);
1727       break;
1728     case kRoundToZero:
1729       Trunc_w_d(double_scratch, double_input);
1730       break;
1731     case kRoundToPlusInf:
1732       Ceil_w_d(double_scratch, double_input);
1733       break;
1734     case kRoundToMinusInf:
1735       Floor_w_d(double_scratch, double_input);
1736       break;
1737   }  // End of switch-statement.
1738
1739   // Retrieve FCSR.
1740   cfc1(except_flag, FCSR);
1741   // Restore FCSR.
1742   ctc1(scratch, FCSR);
1743   // Move the converted value into the result register.
1744   mfc1(result, double_scratch);
1745
1746   // Check for fpu exceptions.
1747   And(except_flag, except_flag, Operand(except_mask));
1748
1749   bind(&done);
1750 }
1751
1752
1753 void MacroAssembler::TryInlineTruncateDoubleToI(Register result,
1754                                                 DoubleRegister double_input,
1755                                                 Label* done) {
1756   DoubleRegister single_scratch = kLithiumScratchDouble.low();
1757   Register scratch = at;
1758   Register scratch2 = t9;
1759
1760   // Clear cumulative exception flags and save the FCSR.
1761   cfc1(scratch2, FCSR);
1762   ctc1(zero_reg, FCSR);
1763   // Try a conversion to a signed integer.
1764   trunc_w_d(single_scratch, double_input);
1765   mfc1(result, single_scratch);
1766   // Retrieve and restore the FCSR.
1767   cfc1(scratch, FCSR);
1768   ctc1(scratch2, FCSR);
1769   // Check for overflow and NaNs.
1770   And(scratch,
1771       scratch,
1772       kFCSROverflowFlagMask | kFCSRUnderflowFlagMask | kFCSRInvalidOpFlagMask);
1773   // If we had no exceptions we are done.
1774   Branch(done, eq, scratch, Operand(zero_reg));
1775 }
1776
1777
1778 void MacroAssembler::TruncateDoubleToI(Register result,
1779                                        DoubleRegister double_input) {
1780   Label done;
1781
1782   TryInlineTruncateDoubleToI(result, double_input, &done);
1783
1784   // If we fell through then inline version didn't succeed - call stub instead.
1785   push(ra);
1786   Subu(sp, sp, Operand(kDoubleSize));  // Put input on stack.
1787   sdc1(double_input, MemOperand(sp, 0));
1788
1789   DoubleToIStub stub(isolate(), sp, result, 0, true, true);
1790   CallStub(&stub);
1791
1792   Addu(sp, sp, Operand(kDoubleSize));
1793   pop(ra);
1794
1795   bind(&done);
1796 }
1797
1798
1799 void MacroAssembler::TruncateHeapNumberToI(Register result, Register object) {
1800   Label done;
1801   DoubleRegister double_scratch = f12;
1802   DCHECK(!result.is(object));
1803
1804   ldc1(double_scratch,
1805        MemOperand(object, HeapNumber::kValueOffset - kHeapObjectTag));
1806   TryInlineTruncateDoubleToI(result, double_scratch, &done);
1807
1808   // If we fell through then inline version didn't succeed - call stub instead.
1809   push(ra);
1810   DoubleToIStub stub(isolate(),
1811                      object,
1812                      result,
1813                      HeapNumber::kValueOffset - kHeapObjectTag,
1814                      true,
1815                      true);
1816   CallStub(&stub);
1817   pop(ra);
1818
1819   bind(&done);
1820 }
1821
1822
1823 void MacroAssembler::TruncateNumberToI(Register object,
1824                                        Register result,
1825                                        Register heap_number_map,
1826                                        Register scratch,
1827                                        Label* not_number) {
1828   Label done;
1829   DCHECK(!result.is(object));
1830
1831   UntagAndJumpIfSmi(result, object, &done);
1832   JumpIfNotHeapNumber(object, heap_number_map, scratch, not_number);
1833   TruncateHeapNumberToI(result, object);
1834
1835   bind(&done);
1836 }
1837
1838
1839 void MacroAssembler::GetLeastBitsFromSmi(Register dst,
1840                                          Register src,
1841                                          int num_least_bits) {
1842   Ext(dst, src, kSmiTagSize, num_least_bits);
1843 }
1844
1845
1846 void MacroAssembler::GetLeastBitsFromInt32(Register dst,
1847                                            Register src,
1848                                            int num_least_bits) {
1849   And(dst, src, Operand((1 << num_least_bits) - 1));
1850 }
1851
1852
1853 // Emulated condtional branches do not emit a nop in the branch delay slot.
1854 //
1855 // BRANCH_ARGS_CHECK checks that conditional jump arguments are correct.
1856 #define BRANCH_ARGS_CHECK(cond, rs, rt) DCHECK(                                \
1857     (cond == cc_always && rs.is(zero_reg) && rt.rm().is(zero_reg)) ||          \
1858     (cond != cc_always && (!rs.is(zero_reg) || !rt.rm().is(zero_reg))))
1859
1860
1861 void MacroAssembler::Branch(int16_t offset, BranchDelaySlot bdslot) {
1862   BranchShort(offset, bdslot);
1863 }
1864
1865
1866 void MacroAssembler::Branch(int16_t offset, Condition cond, Register rs,
1867                             const Operand& rt,
1868                             BranchDelaySlot bdslot) {
1869   BranchShort(offset, cond, rs, rt, bdslot);
1870 }
1871
1872
1873 void MacroAssembler::Branch(Label* L, BranchDelaySlot bdslot) {
1874   if (L->is_bound()) {
1875     if (is_near(L)) {
1876       BranchShort(L, bdslot);
1877     } else {
1878       Jr(L, bdslot);
1879     }
1880   } else {
1881     if (is_trampoline_emitted()) {
1882       Jr(L, bdslot);
1883     } else {
1884       BranchShort(L, bdslot);
1885     }
1886   }
1887 }
1888
1889
1890 void MacroAssembler::Branch(Label* L, Condition cond, Register rs,
1891                             const Operand& rt,
1892                             BranchDelaySlot bdslot) {
1893   if (L->is_bound()) {
1894     if (is_near(L)) {
1895       BranchShort(L, cond, rs, rt, bdslot);
1896     } else {
1897       if (cond != cc_always) {
1898         Label skip;
1899         Condition neg_cond = NegateCondition(cond);
1900         BranchShort(&skip, neg_cond, rs, rt);
1901         Jr(L, bdslot);
1902         bind(&skip);
1903       } else {
1904         Jr(L, bdslot);
1905       }
1906     }
1907   } else {
1908     if (is_trampoline_emitted()) {
1909       if (cond != cc_always) {
1910         Label skip;
1911         Condition neg_cond = NegateCondition(cond);
1912         BranchShort(&skip, neg_cond, rs, rt);
1913         Jr(L, bdslot);
1914         bind(&skip);
1915       } else {
1916         Jr(L, bdslot);
1917       }
1918     } else {
1919       BranchShort(L, cond, rs, rt, bdslot);
1920     }
1921   }
1922 }
1923
1924
1925 void MacroAssembler::Branch(Label* L,
1926                             Condition cond,
1927                             Register rs,
1928                             Heap::RootListIndex index,
1929                             BranchDelaySlot bdslot) {
1930   LoadRoot(at, index);
1931   Branch(L, cond, rs, Operand(at), bdslot);
1932 }
1933
1934
1935 void MacroAssembler::BranchShort(int16_t offset, BranchDelaySlot bdslot) {
1936   b(offset);
1937
1938   // Emit a nop in the branch delay slot if required.
1939   if (bdslot == PROTECT)
1940     nop();
1941 }
1942
1943
1944 void MacroAssembler::BranchShort(int16_t offset, Condition cond, Register rs,
1945                                  const Operand& rt,
1946                                  BranchDelaySlot bdslot) {
1947   BRANCH_ARGS_CHECK(cond, rs, rt);
1948   DCHECK(!rs.is(zero_reg));
1949   Register r2 = no_reg;
1950   Register scratch = at;
1951
1952   if (rt.is_reg()) {
1953     // NOTE: 'at' can be clobbered by Branch but it is legal to use it as rs or
1954     // rt.
1955     BlockTrampolinePoolScope block_trampoline_pool(this);
1956     r2 = rt.rm_;
1957     switch (cond) {
1958       case cc_always:
1959         b(offset);
1960         break;
1961       case eq:
1962         beq(rs, r2, offset);
1963         break;
1964       case ne:
1965         bne(rs, r2, offset);
1966         break;
1967       // Signed comparison.
1968       case greater:
1969         if (r2.is(zero_reg)) {
1970           bgtz(rs, offset);
1971         } else {
1972           slt(scratch, r2, rs);
1973           bne(scratch, zero_reg, offset);
1974         }
1975         break;
1976       case greater_equal:
1977         if (r2.is(zero_reg)) {
1978           bgez(rs, offset);
1979         } else {
1980           slt(scratch, rs, r2);
1981           beq(scratch, zero_reg, offset);
1982         }
1983         break;
1984       case less:
1985         if (r2.is(zero_reg)) {
1986           bltz(rs, offset);
1987         } else {
1988           slt(scratch, rs, r2);
1989           bne(scratch, zero_reg, offset);
1990         }
1991         break;
1992       case less_equal:
1993         if (r2.is(zero_reg)) {
1994           blez(rs, offset);
1995         } else {
1996           slt(scratch, r2, rs);
1997           beq(scratch, zero_reg, offset);
1998         }
1999         break;
2000       // Unsigned comparison.
2001       case Ugreater:
2002         if (r2.is(zero_reg)) {
2003           bne(rs, zero_reg, offset);
2004         } else {
2005           sltu(scratch, r2, rs);
2006           bne(scratch, zero_reg, offset);
2007         }
2008         break;
2009       case Ugreater_equal:
2010         if (r2.is(zero_reg)) {
2011           b(offset);
2012         } else {
2013           sltu(scratch, rs, r2);
2014           beq(scratch, zero_reg, offset);
2015         }
2016         break;
2017       case Uless:
2018         if (r2.is(zero_reg)) {
2019           // No code needs to be emitted.
2020           return;
2021         } else {
2022           sltu(scratch, rs, r2);
2023           bne(scratch, zero_reg, offset);
2024         }
2025         break;
2026       case Uless_equal:
2027         if (r2.is(zero_reg)) {
2028           beq(rs, zero_reg, offset);
2029         } else {
2030           sltu(scratch, r2, rs);
2031           beq(scratch, zero_reg, offset);
2032         }
2033         break;
2034       default:
2035         UNREACHABLE();
2036     }
2037   } else {
2038     // Be careful to always use shifted_branch_offset only just before the
2039     // branch instruction, as the location will be remember for patching the
2040     // target.
2041     BlockTrampolinePoolScope block_trampoline_pool(this);
2042     switch (cond) {
2043       case cc_always:
2044         b(offset);
2045         break;
2046       case eq:
2047         if (rt.imm32_ == 0) {
2048           beq(rs, zero_reg, offset);
2049         } else {
2050           // We don't want any other register but scratch clobbered.
2051           DCHECK(!scratch.is(rs));
2052           r2 = scratch;
2053           li(r2, rt);
2054           beq(rs, r2, offset);
2055         }
2056         break;
2057       case ne:
2058         if (rt.imm32_ == 0) {
2059           bne(rs, zero_reg, offset);
2060         } else {
2061           // We don't want any other register but scratch clobbered.
2062           DCHECK(!scratch.is(rs));
2063           r2 = scratch;
2064           li(r2, rt);
2065           bne(rs, r2, offset);
2066         }
2067         break;
2068       // Signed comparison.
2069       case greater:
2070         if (rt.imm32_ == 0) {
2071           bgtz(rs, offset);
2072         } else {
2073           r2 = scratch;
2074           li(r2, rt);
2075           slt(scratch, r2, rs);
2076           bne(scratch, zero_reg, offset);
2077         }
2078         break;
2079       case greater_equal:
2080         if (rt.imm32_ == 0) {
2081           bgez(rs, offset);
2082         } else if (is_int16(rt.imm32_)) {
2083           slti(scratch, rs, rt.imm32_);
2084           beq(scratch, zero_reg, offset);
2085         } else {
2086           r2 = scratch;
2087           li(r2, rt);
2088           slt(scratch, rs, r2);
2089           beq(scratch, zero_reg, offset);
2090         }
2091         break;
2092       case less:
2093         if (rt.imm32_ == 0) {
2094           bltz(rs, offset);
2095         } else if (is_int16(rt.imm32_)) {
2096           slti(scratch, rs, rt.imm32_);
2097           bne(scratch, zero_reg, offset);
2098         } else {
2099           r2 = scratch;
2100           li(r2, rt);
2101           slt(scratch, rs, r2);
2102           bne(scratch, zero_reg, offset);
2103         }
2104         break;
2105       case less_equal:
2106         if (rt.imm32_ == 0) {
2107           blez(rs, offset);
2108         } else {
2109           r2 = scratch;
2110           li(r2, rt);
2111           slt(scratch, r2, rs);
2112           beq(scratch, zero_reg, offset);
2113        }
2114        break;
2115       // Unsigned comparison.
2116       case Ugreater:
2117         if (rt.imm32_ == 0) {
2118           bne(rs, zero_reg, offset);
2119         } else {
2120           r2 = scratch;
2121           li(r2, rt);
2122           sltu(scratch, r2, rs);
2123           bne(scratch, zero_reg, offset);
2124         }
2125         break;
2126       case Ugreater_equal:
2127         if (rt.imm32_ == 0) {
2128           b(offset);
2129         } else if (is_int16(rt.imm32_)) {
2130           sltiu(scratch, rs, rt.imm32_);
2131           beq(scratch, zero_reg, offset);
2132         } else {
2133           r2 = scratch;
2134           li(r2, rt);
2135           sltu(scratch, rs, r2);
2136           beq(scratch, zero_reg, offset);
2137         }
2138         break;
2139       case Uless:
2140         if (rt.imm32_ == 0) {
2141           // No code needs to be emitted.
2142           return;
2143         } else if (is_int16(rt.imm32_)) {
2144           sltiu(scratch, rs, rt.imm32_);
2145           bne(scratch, zero_reg, offset);
2146         } else {
2147           r2 = scratch;
2148           li(r2, rt);
2149           sltu(scratch, rs, r2);
2150           bne(scratch, zero_reg, offset);
2151         }
2152         break;
2153       case Uless_equal:
2154         if (rt.imm32_ == 0) {
2155           beq(rs, zero_reg, offset);
2156         } else {
2157           r2 = scratch;
2158           li(r2, rt);
2159           sltu(scratch, r2, rs);
2160           beq(scratch, zero_reg, offset);
2161         }
2162         break;
2163       default:
2164         UNREACHABLE();
2165     }
2166   }
2167   // Emit a nop in the branch delay slot if required.
2168   if (bdslot == PROTECT)
2169     nop();
2170 }
2171
2172
2173 void MacroAssembler::BranchShort(Label* L, BranchDelaySlot bdslot) {
2174   // We use branch_offset as an argument for the branch instructions to be sure
2175   // it is called just before generating the branch instruction, as needed.
2176
2177   b(shifted_branch_offset(L, false));
2178
2179   // Emit a nop in the branch delay slot if required.
2180   if (bdslot == PROTECT)
2181     nop();
2182 }
2183
2184
2185 void MacroAssembler::BranchShort(Label* L, Condition cond, Register rs,
2186                                  const Operand& rt,
2187                                  BranchDelaySlot bdslot) {
2188   BRANCH_ARGS_CHECK(cond, rs, rt);
2189
2190   int32_t offset = 0;
2191   Register r2 = no_reg;
2192   Register scratch = at;
2193   if (rt.is_reg()) {
2194     BlockTrampolinePoolScope block_trampoline_pool(this);
2195     r2 = rt.rm_;
2196     // Be careful to always use shifted_branch_offset only just before the
2197     // branch instruction, as the location will be remember for patching the
2198     // target.
2199     switch (cond) {
2200       case cc_always:
2201         offset = shifted_branch_offset(L, false);
2202         b(offset);
2203         break;
2204       case eq:
2205         offset = shifted_branch_offset(L, false);
2206         beq(rs, r2, offset);
2207         break;
2208       case ne:
2209         offset = shifted_branch_offset(L, false);
2210         bne(rs, r2, offset);
2211         break;
2212       // Signed comparison.
2213       case greater:
2214         if (r2.is(zero_reg)) {
2215           offset = shifted_branch_offset(L, false);
2216           bgtz(rs, offset);
2217         } else {
2218           slt(scratch, r2, rs);
2219           offset = shifted_branch_offset(L, false);
2220           bne(scratch, zero_reg, offset);
2221         }
2222         break;
2223       case greater_equal:
2224         if (r2.is(zero_reg)) {
2225           offset = shifted_branch_offset(L, false);
2226           bgez(rs, offset);
2227         } else {
2228           slt(scratch, rs, r2);
2229           offset = shifted_branch_offset(L, false);
2230           beq(scratch, zero_reg, offset);
2231         }
2232         break;
2233       case less:
2234         if (r2.is(zero_reg)) {
2235           offset = shifted_branch_offset(L, false);
2236           bltz(rs, offset);
2237         } else {
2238           slt(scratch, rs, r2);
2239           offset = shifted_branch_offset(L, false);
2240           bne(scratch, zero_reg, offset);
2241         }
2242         break;
2243       case less_equal:
2244         if (r2.is(zero_reg)) {
2245           offset = shifted_branch_offset(L, false);
2246           blez(rs, offset);
2247         } else {
2248           slt(scratch, r2, rs);
2249           offset = shifted_branch_offset(L, false);
2250           beq(scratch, zero_reg, offset);
2251         }
2252         break;
2253       // Unsigned comparison.
2254       case Ugreater:
2255         if (r2.is(zero_reg)) {
2256           offset = shifted_branch_offset(L, false);
2257           bne(rs, zero_reg, offset);
2258         } else {
2259           sltu(scratch, r2, rs);
2260           offset = shifted_branch_offset(L, false);
2261           bne(scratch, zero_reg, offset);
2262         }
2263         break;
2264       case Ugreater_equal:
2265         if (r2.is(zero_reg)) {
2266           offset = shifted_branch_offset(L, false);
2267           b(offset);
2268         } else {
2269           sltu(scratch, rs, r2);
2270           offset = shifted_branch_offset(L, false);
2271           beq(scratch, zero_reg, offset);
2272         }
2273         break;
2274       case Uless:
2275         if (r2.is(zero_reg)) {
2276           // No code needs to be emitted.
2277           return;
2278         } else {
2279           sltu(scratch, rs, r2);
2280           offset = shifted_branch_offset(L, false);
2281           bne(scratch, zero_reg, offset);
2282         }
2283         break;
2284       case Uless_equal:
2285         if (r2.is(zero_reg)) {
2286           offset = shifted_branch_offset(L, false);
2287           beq(rs, zero_reg, offset);
2288         } else {
2289           sltu(scratch, r2, rs);
2290           offset = shifted_branch_offset(L, false);
2291           beq(scratch, zero_reg, offset);
2292         }
2293         break;
2294       default:
2295         UNREACHABLE();
2296     }
2297   } else {
2298     // Be careful to always use shifted_branch_offset only just before the
2299     // branch instruction, as the location will be remember for patching the
2300     // target.
2301     BlockTrampolinePoolScope block_trampoline_pool(this);
2302     switch (cond) {
2303       case cc_always:
2304         offset = shifted_branch_offset(L, false);
2305         b(offset);
2306         break;
2307       case eq:
2308         if (rt.imm32_ == 0) {
2309           offset = shifted_branch_offset(L, false);
2310           beq(rs, zero_reg, offset);
2311         } else {
2312           DCHECK(!scratch.is(rs));
2313           r2 = scratch;
2314           li(r2, rt);
2315           offset = shifted_branch_offset(L, false);
2316           beq(rs, r2, offset);
2317         }
2318         break;
2319       case ne:
2320         if (rt.imm32_ == 0) {
2321           offset = shifted_branch_offset(L, false);
2322           bne(rs, zero_reg, offset);
2323         } else {
2324           DCHECK(!scratch.is(rs));
2325           r2 = scratch;
2326           li(r2, rt);
2327           offset = shifted_branch_offset(L, false);
2328           bne(rs, r2, offset);
2329         }
2330         break;
2331       // Signed comparison.
2332       case greater:
2333         if (rt.imm32_ == 0) {
2334           offset = shifted_branch_offset(L, false);
2335           bgtz(rs, offset);
2336         } else {
2337           DCHECK(!scratch.is(rs));
2338           r2 = scratch;
2339           li(r2, rt);
2340           slt(scratch, r2, rs);
2341           offset = shifted_branch_offset(L, false);
2342           bne(scratch, zero_reg, offset);
2343         }
2344         break;
2345       case greater_equal:
2346         if (rt.imm32_ == 0) {
2347           offset = shifted_branch_offset(L, false);
2348           bgez(rs, offset);
2349         } else if (is_int16(rt.imm32_)) {
2350           slti(scratch, rs, rt.imm32_);
2351           offset = shifted_branch_offset(L, false);
2352           beq(scratch, zero_reg, offset);
2353         } else {
2354           DCHECK(!scratch.is(rs));
2355           r2 = scratch;
2356           li(r2, rt);
2357           slt(scratch, rs, r2);
2358           offset = shifted_branch_offset(L, false);
2359           beq(scratch, zero_reg, offset);
2360         }
2361         break;
2362       case less:
2363         if (rt.imm32_ == 0) {
2364           offset = shifted_branch_offset(L, false);
2365           bltz(rs, offset);
2366         } else if (is_int16(rt.imm32_)) {
2367           slti(scratch, rs, rt.imm32_);
2368           offset = shifted_branch_offset(L, false);
2369           bne(scratch, zero_reg, offset);
2370         } else {
2371           DCHECK(!scratch.is(rs));
2372           r2 = scratch;
2373           li(r2, rt);
2374           slt(scratch, rs, r2);
2375           offset = shifted_branch_offset(L, false);
2376           bne(scratch, zero_reg, offset);
2377         }
2378         break;
2379       case less_equal:
2380         if (rt.imm32_ == 0) {
2381           offset = shifted_branch_offset(L, false);
2382           blez(rs, offset);
2383         } else {
2384           DCHECK(!scratch.is(rs));
2385           r2 = scratch;
2386           li(r2, rt);
2387           slt(scratch, r2, rs);
2388           offset = shifted_branch_offset(L, false);
2389           beq(scratch, zero_reg, offset);
2390         }
2391         break;
2392       // Unsigned comparison.
2393       case Ugreater:
2394         if (rt.imm32_ == 0) {
2395           offset = shifted_branch_offset(L, false);
2396           bne(rs, zero_reg, offset);
2397         } else {
2398           DCHECK(!scratch.is(rs));
2399           r2 = scratch;
2400           li(r2, rt);
2401           sltu(scratch, r2, rs);
2402           offset = shifted_branch_offset(L, false);
2403           bne(scratch, zero_reg, offset);
2404         }
2405         break;
2406       case Ugreater_equal:
2407         if (rt.imm32_ == 0) {
2408           offset = shifted_branch_offset(L, false);
2409           b(offset);
2410         } else if (is_int16(rt.imm32_)) {
2411           sltiu(scratch, rs, rt.imm32_);
2412           offset = shifted_branch_offset(L, false);
2413           beq(scratch, zero_reg, offset);
2414         } else {
2415           DCHECK(!scratch.is(rs));
2416           r2 = scratch;
2417           li(r2, rt);
2418           sltu(scratch, rs, r2);
2419           offset = shifted_branch_offset(L, false);
2420           beq(scratch, zero_reg, offset);
2421         }
2422         break;
2423      case Uless:
2424         if (rt.imm32_ == 0) {
2425           // No code needs to be emitted.
2426           return;
2427         } else if (is_int16(rt.imm32_)) {
2428           sltiu(scratch, rs, rt.imm32_);
2429           offset = shifted_branch_offset(L, false);
2430           bne(scratch, zero_reg, offset);
2431         } else {
2432           DCHECK(!scratch.is(rs));
2433           r2 = scratch;
2434           li(r2, rt);
2435           sltu(scratch, rs, r2);
2436           offset = shifted_branch_offset(L, false);
2437           bne(scratch, zero_reg, offset);
2438         }
2439         break;
2440       case Uless_equal:
2441         if (rt.imm32_ == 0) {
2442           offset = shifted_branch_offset(L, false);
2443           beq(rs, zero_reg, offset);
2444         } else {
2445           DCHECK(!scratch.is(rs));
2446           r2 = scratch;
2447           li(r2, rt);
2448           sltu(scratch, r2, rs);
2449           offset = shifted_branch_offset(L, false);
2450           beq(scratch, zero_reg, offset);
2451         }
2452         break;
2453       default:
2454         UNREACHABLE();
2455     }
2456   }
2457   // Check that offset could actually hold on an int16_t.
2458   DCHECK(is_int16(offset));
2459   // Emit a nop in the branch delay slot if required.
2460   if (bdslot == PROTECT)
2461     nop();
2462 }
2463
2464
2465 void MacroAssembler::BranchAndLink(int16_t offset, BranchDelaySlot bdslot) {
2466   BranchAndLinkShort(offset, bdslot);
2467 }
2468
2469
2470 void MacroAssembler::BranchAndLink(int16_t offset, Condition cond, Register rs,
2471                                    const Operand& rt,
2472                                    BranchDelaySlot bdslot) {
2473   BranchAndLinkShort(offset, cond, rs, rt, bdslot);
2474 }
2475
2476
2477 void MacroAssembler::BranchAndLink(Label* L, BranchDelaySlot bdslot) {
2478   if (L->is_bound()) {
2479     if (is_near(L)) {
2480       BranchAndLinkShort(L, bdslot);
2481     } else {
2482       Jalr(L, bdslot);
2483     }
2484   } else {
2485     if (is_trampoline_emitted()) {
2486       Jalr(L, bdslot);
2487     } else {
2488       BranchAndLinkShort(L, bdslot);
2489     }
2490   }
2491 }
2492
2493
2494 void MacroAssembler::BranchAndLink(Label* L, Condition cond, Register rs,
2495                                    const Operand& rt,
2496                                    BranchDelaySlot bdslot) {
2497   if (L->is_bound()) {
2498     if (is_near(L)) {
2499       BranchAndLinkShort(L, cond, rs, rt, bdslot);
2500     } else {
2501       Label skip;
2502       Condition neg_cond = NegateCondition(cond);
2503       BranchShort(&skip, neg_cond, rs, rt);
2504       Jalr(L, bdslot);
2505       bind(&skip);
2506     }
2507   } else {
2508     if (is_trampoline_emitted()) {
2509       Label skip;
2510       Condition neg_cond = NegateCondition(cond);
2511       BranchShort(&skip, neg_cond, rs, rt);
2512       Jalr(L, bdslot);
2513       bind(&skip);
2514     } else {
2515       BranchAndLinkShort(L, cond, rs, rt, bdslot);
2516     }
2517   }
2518 }
2519
2520
2521 // We need to use a bgezal or bltzal, but they can't be used directly with the
2522 // slt instructions. We could use sub or add instead but we would miss overflow
2523 // cases, so we keep slt and add an intermediate third instruction.
2524 void MacroAssembler::BranchAndLinkShort(int16_t offset,
2525                                         BranchDelaySlot bdslot) {
2526   bal(offset);
2527
2528   // Emit a nop in the branch delay slot if required.
2529   if (bdslot == PROTECT)
2530     nop();
2531 }
2532
2533
2534 void MacroAssembler::BranchAndLinkShort(int16_t offset, Condition cond,
2535                                         Register rs, const Operand& rt,
2536                                         BranchDelaySlot bdslot) {
2537   BRANCH_ARGS_CHECK(cond, rs, rt);
2538   Register r2 = no_reg;
2539   Register scratch = at;
2540
2541   if (rt.is_reg()) {
2542     r2 = rt.rm_;
2543   } else if (cond != cc_always) {
2544     r2 = scratch;
2545     li(r2, rt);
2546   }
2547
2548   if (!IsMipsArchVariant(kMips32r6)) {
2549     BlockTrampolinePoolScope block_trampoline_pool(this);
2550     switch (cond) {
2551       case cc_always:
2552         bal(offset);
2553         break;
2554       case eq:
2555         bne(rs, r2, 2);
2556         nop();
2557         bal(offset);
2558         break;
2559       case ne:
2560         beq(rs, r2, 2);
2561         nop();
2562         bal(offset);
2563         break;
2564
2565       // Signed comparison.
2566       case greater:
2567         slt(scratch, r2, rs);
2568         addiu(scratch, scratch, -1);
2569         bgezal(scratch, offset);
2570         break;
2571       case greater_equal:
2572         slt(scratch, rs, r2);
2573         addiu(scratch, scratch, -1);
2574         bltzal(scratch, offset);
2575         break;
2576       case less:
2577         slt(scratch, rs, r2);
2578         addiu(scratch, scratch, -1);
2579         bgezal(scratch, offset);
2580         break;
2581       case less_equal:
2582         slt(scratch, r2, rs);
2583         addiu(scratch, scratch, -1);
2584         bltzal(scratch, offset);
2585         break;
2586
2587       // Unsigned comparison.
2588       case Ugreater:
2589         sltu(scratch, r2, rs);
2590         addiu(scratch, scratch, -1);
2591         bgezal(scratch, offset);
2592         break;
2593       case Ugreater_equal:
2594         sltu(scratch, rs, r2);
2595         addiu(scratch, scratch, -1);
2596         bltzal(scratch, offset);
2597         break;
2598       case Uless:
2599         sltu(scratch, rs, r2);
2600         addiu(scratch, scratch, -1);
2601         bgezal(scratch, offset);
2602         break;
2603       case Uless_equal:
2604         sltu(scratch, r2, rs);
2605         addiu(scratch, scratch, -1);
2606         bltzal(scratch, offset);
2607         break;
2608
2609       default:
2610         UNREACHABLE();
2611     }
2612   } else {
2613     BlockTrampolinePoolScope block_trampoline_pool(this);
2614     switch (cond) {
2615       case cc_always:
2616         bal(offset);
2617         break;
2618       case eq:
2619         bne(rs, r2, 2);
2620         nop();
2621         bal(offset);
2622         break;
2623       case ne:
2624         beq(rs, r2, 2);
2625         nop();
2626         bal(offset);
2627         break;
2628
2629       // Signed comparison.
2630       case greater:
2631         // rs > rt
2632         slt(scratch, r2, rs);
2633         beq(scratch, zero_reg, 2);
2634         nop();
2635         bal(offset);
2636         break;
2637       case greater_equal:
2638         // rs >= rt
2639         slt(scratch, rs, r2);
2640         bne(scratch, zero_reg, 2);
2641         nop();
2642         bal(offset);
2643         break;
2644       case less:
2645         // rs < r2
2646         slt(scratch, rs, r2);
2647         bne(scratch, zero_reg, 2);
2648         nop();
2649         bal(offset);
2650         break;
2651       case less_equal:
2652         // rs <= r2
2653         slt(scratch, r2, rs);
2654         bne(scratch, zero_reg, 2);
2655         nop();
2656         bal(offset);
2657         break;
2658
2659
2660       // Unsigned comparison.
2661       case Ugreater:
2662         // rs > rt
2663         sltu(scratch, r2, rs);
2664         beq(scratch, zero_reg, 2);
2665         nop();
2666         bal(offset);
2667         break;
2668       case Ugreater_equal:
2669         // rs >= rt
2670         sltu(scratch, rs, r2);
2671         bne(scratch, zero_reg, 2);
2672         nop();
2673         bal(offset);
2674         break;
2675       case Uless:
2676         // rs < r2
2677         sltu(scratch, rs, r2);
2678         bne(scratch, zero_reg, 2);
2679         nop();
2680         bal(offset);
2681         break;
2682       case Uless_equal:
2683         // rs <= r2
2684         sltu(scratch, r2, rs);
2685         bne(scratch, zero_reg, 2);
2686         nop();
2687         bal(offset);
2688         break;
2689       default:
2690         UNREACHABLE();
2691     }
2692   }
2693
2694   // Emit a nop in the branch delay slot if required.
2695   if (bdslot == PROTECT)
2696     nop();
2697 }
2698
2699
2700 void MacroAssembler::BranchAndLinkShort(Label* L, BranchDelaySlot bdslot) {
2701   bal(shifted_branch_offset(L, false));
2702
2703   // Emit a nop in the branch delay slot if required.
2704   if (bdslot == PROTECT)
2705     nop();
2706 }
2707
2708
2709 void MacroAssembler::BranchAndLinkShort(Label* L, Condition cond, Register rs,
2710                                         const Operand& rt,
2711                                         BranchDelaySlot bdslot) {
2712   BRANCH_ARGS_CHECK(cond, rs, rt);
2713
2714   int32_t offset = 0;
2715   Register r2 = no_reg;
2716   Register scratch = at;
2717   if (rt.is_reg()) {
2718     r2 = rt.rm_;
2719   } else if (cond != cc_always) {
2720     r2 = scratch;
2721     li(r2, rt);
2722   }
2723
2724   if (!IsMipsArchVariant(kMips32r6)) {
2725     BlockTrampolinePoolScope block_trampoline_pool(this);
2726     switch (cond) {
2727       case cc_always:
2728         offset = shifted_branch_offset(L, false);
2729         bal(offset);
2730         break;
2731       case eq:
2732         bne(rs, r2, 2);
2733         nop();
2734         offset = shifted_branch_offset(L, false);
2735         bal(offset);
2736         break;
2737       case ne:
2738         beq(rs, r2, 2);
2739         nop();
2740         offset = shifted_branch_offset(L, false);
2741         bal(offset);
2742         break;
2743
2744       // Signed comparison.
2745       case greater:
2746         slt(scratch, r2, rs);
2747         addiu(scratch, scratch, -1);
2748         offset = shifted_branch_offset(L, false);
2749         bgezal(scratch, offset);
2750         break;
2751       case greater_equal:
2752         slt(scratch, rs, r2);
2753         addiu(scratch, scratch, -1);
2754         offset = shifted_branch_offset(L, false);
2755         bltzal(scratch, offset);
2756         break;
2757       case less:
2758         slt(scratch, rs, r2);
2759         addiu(scratch, scratch, -1);
2760         offset = shifted_branch_offset(L, false);
2761         bgezal(scratch, offset);
2762         break;
2763       case less_equal:
2764         slt(scratch, r2, rs);
2765         addiu(scratch, scratch, -1);
2766         offset = shifted_branch_offset(L, false);
2767         bltzal(scratch, offset);
2768         break;
2769
2770       // Unsigned comparison.
2771       case Ugreater:
2772         sltu(scratch, r2, rs);
2773         addiu(scratch, scratch, -1);
2774         offset = shifted_branch_offset(L, false);
2775         bgezal(scratch, offset);
2776         break;
2777       case Ugreater_equal:
2778         sltu(scratch, rs, r2);
2779         addiu(scratch, scratch, -1);
2780         offset = shifted_branch_offset(L, false);
2781         bltzal(scratch, offset);
2782         break;
2783       case Uless:
2784         sltu(scratch, rs, r2);
2785         addiu(scratch, scratch, -1);
2786         offset = shifted_branch_offset(L, false);
2787         bgezal(scratch, offset);
2788         break;
2789       case Uless_equal:
2790         sltu(scratch, r2, rs);
2791         addiu(scratch, scratch, -1);
2792         offset = shifted_branch_offset(L, false);
2793         bltzal(scratch, offset);
2794         break;
2795
2796       default:
2797         UNREACHABLE();
2798     }
2799   } else {
2800     BlockTrampolinePoolScope block_trampoline_pool(this);
2801     switch (cond) {
2802       case cc_always:
2803         offset = shifted_branch_offset(L, false);
2804         bal(offset);
2805         break;
2806       case eq:
2807         bne(rs, r2, 2);
2808         nop();
2809         offset = shifted_branch_offset(L, false);
2810         bal(offset);
2811         break;
2812       case ne:
2813         beq(rs, r2, 2);
2814         nop();
2815         offset = shifted_branch_offset(L, false);
2816         bal(offset);
2817         break;
2818
2819       // Signed comparison.
2820       case greater:
2821         // rs > rt
2822         slt(scratch, r2, rs);
2823         beq(scratch, zero_reg, 2);
2824         nop();
2825         offset = shifted_branch_offset(L, false);
2826         bal(offset);
2827         break;
2828       case greater_equal:
2829         // rs >= rt
2830         slt(scratch, rs, r2);
2831         bne(scratch, zero_reg, 2);
2832         nop();
2833         offset = shifted_branch_offset(L, false);
2834         bal(offset);
2835         break;
2836       case less:
2837         // rs < r2
2838         slt(scratch, rs, r2);
2839         bne(scratch, zero_reg, 2);
2840         nop();
2841         offset = shifted_branch_offset(L, false);
2842         bal(offset);
2843         break;
2844       case less_equal:
2845         // rs <= r2
2846         slt(scratch, r2, rs);
2847         bne(scratch, zero_reg, 2);
2848         nop();
2849         offset = shifted_branch_offset(L, false);
2850         bal(offset);
2851         break;
2852
2853
2854       // Unsigned comparison.
2855       case Ugreater:
2856         // rs > rt
2857         sltu(scratch, r2, rs);
2858         beq(scratch, zero_reg, 2);
2859         nop();
2860         offset = shifted_branch_offset(L, false);
2861         bal(offset);
2862         break;
2863       case Ugreater_equal:
2864         // rs >= rt
2865         sltu(scratch, rs, r2);
2866         bne(scratch, zero_reg, 2);
2867         nop();
2868         offset = shifted_branch_offset(L, false);
2869         bal(offset);
2870         break;
2871       case Uless:
2872         // rs < r2
2873         sltu(scratch, rs, r2);
2874         bne(scratch, zero_reg, 2);
2875         nop();
2876         offset = shifted_branch_offset(L, false);
2877         bal(offset);
2878         break;
2879       case Uless_equal:
2880         // rs <= r2
2881         sltu(scratch, r2, rs);
2882         bne(scratch, zero_reg, 2);
2883         nop();
2884         offset = shifted_branch_offset(L, false);
2885         bal(offset);
2886         break;
2887
2888       default:
2889         UNREACHABLE();
2890     }
2891   }
2892
2893   // Check that offset could actually hold on an int16_t.
2894   DCHECK(is_int16(offset));
2895
2896   // Emit a nop in the branch delay slot if required.
2897   if (bdslot == PROTECT)
2898     nop();
2899 }
2900
2901
2902 void MacroAssembler::Jump(Register target,
2903                           Condition cond,
2904                           Register rs,
2905                           const Operand& rt,
2906                           BranchDelaySlot bd) {
2907   BlockTrampolinePoolScope block_trampoline_pool(this);
2908   if (cond == cc_always) {
2909     jr(target);
2910   } else {
2911     BRANCH_ARGS_CHECK(cond, rs, rt);
2912     Branch(2, NegateCondition(cond), rs, rt);
2913     jr(target);
2914   }
2915   // Emit a nop in the branch delay slot if required.
2916   if (bd == PROTECT)
2917     nop();
2918 }
2919
2920
2921 void MacroAssembler::Jump(intptr_t target,
2922                           RelocInfo::Mode rmode,
2923                           Condition cond,
2924                           Register rs,
2925                           const Operand& rt,
2926                           BranchDelaySlot bd) {
2927   Label skip;
2928   if (cond != cc_always) {
2929     Branch(USE_DELAY_SLOT, &skip, NegateCondition(cond), rs, rt);
2930   }
2931   // The first instruction of 'li' may be placed in the delay slot.
2932   // This is not an issue, t9 is expected to be clobbered anyway.
2933   li(t9, Operand(target, rmode));
2934   Jump(t9, al, zero_reg, Operand(zero_reg), bd);
2935   bind(&skip);
2936 }
2937
2938
2939 void MacroAssembler::Jump(Address target,
2940                           RelocInfo::Mode rmode,
2941                           Condition cond,
2942                           Register rs,
2943                           const Operand& rt,
2944                           BranchDelaySlot bd) {
2945   DCHECK(!RelocInfo::IsCodeTarget(rmode));
2946   Jump(reinterpret_cast<intptr_t>(target), rmode, cond, rs, rt, bd);
2947 }
2948
2949
2950 void MacroAssembler::Jump(Handle<Code> code,
2951                           RelocInfo::Mode rmode,
2952                           Condition cond,
2953                           Register rs,
2954                           const Operand& rt,
2955                           BranchDelaySlot bd) {
2956   DCHECK(RelocInfo::IsCodeTarget(rmode));
2957   AllowDeferredHandleDereference embedding_raw_address;
2958   Jump(reinterpret_cast<intptr_t>(code.location()), rmode, cond, rs, rt, bd);
2959 }
2960
2961
2962 int MacroAssembler::CallSize(Register target,
2963                              Condition cond,
2964                              Register rs,
2965                              const Operand& rt,
2966                              BranchDelaySlot bd) {
2967   int size = 0;
2968
2969   if (cond == cc_always) {
2970     size += 1;
2971   } else {
2972     size += 3;
2973   }
2974
2975   if (bd == PROTECT)
2976     size += 1;
2977
2978   return size * kInstrSize;
2979 }
2980
2981
2982 // Note: To call gcc-compiled C code on mips, you must call thru t9.
2983 void MacroAssembler::Call(Register target,
2984                           Condition cond,
2985                           Register rs,
2986                           const Operand& rt,
2987                           BranchDelaySlot bd) {
2988   BlockTrampolinePoolScope block_trampoline_pool(this);
2989   Label start;
2990   bind(&start);
2991   if (cond == cc_always) {
2992     jalr(target);
2993   } else {
2994     BRANCH_ARGS_CHECK(cond, rs, rt);
2995     Branch(2, NegateCondition(cond), rs, rt);
2996     jalr(target);
2997   }
2998   // Emit a nop in the branch delay slot if required.
2999   if (bd == PROTECT)
3000     nop();
3001
3002   DCHECK_EQ(CallSize(target, cond, rs, rt, bd),
3003             SizeOfCodeGeneratedSince(&start));
3004 }
3005
3006
3007 int MacroAssembler::CallSize(Address target,
3008                              RelocInfo::Mode rmode,
3009                              Condition cond,
3010                              Register rs,
3011                              const Operand& rt,
3012                              BranchDelaySlot bd) {
3013   int size = CallSize(t9, cond, rs, rt, bd);
3014   return size + 2 * kInstrSize;
3015 }
3016
3017
3018 void MacroAssembler::Call(Address target,
3019                           RelocInfo::Mode rmode,
3020                           Condition cond,
3021                           Register rs,
3022                           const Operand& rt,
3023                           BranchDelaySlot bd) {
3024   BlockTrampolinePoolScope block_trampoline_pool(this);
3025   Label start;
3026   bind(&start);
3027   int32_t target_int = reinterpret_cast<int32_t>(target);
3028   // Must record previous source positions before the
3029   // li() generates a new code target.
3030   positions_recorder()->WriteRecordedPositions();
3031   li(t9, Operand(target_int, rmode), CONSTANT_SIZE);
3032   Call(t9, cond, rs, rt, bd);
3033   DCHECK_EQ(CallSize(target, rmode, cond, rs, rt, bd),
3034             SizeOfCodeGeneratedSince(&start));
3035 }
3036
3037
3038 int MacroAssembler::CallSize(Handle<Code> code,
3039                              RelocInfo::Mode rmode,
3040                              TypeFeedbackId ast_id,
3041                              Condition cond,
3042                              Register rs,
3043                              const Operand& rt,
3044                              BranchDelaySlot bd) {
3045   AllowDeferredHandleDereference using_raw_address;
3046   return CallSize(reinterpret_cast<Address>(code.location()),
3047       rmode, cond, rs, rt, bd);
3048 }
3049
3050
3051 void MacroAssembler::Call(Handle<Code> code,
3052                           RelocInfo::Mode rmode,
3053                           TypeFeedbackId ast_id,
3054                           Condition cond,
3055                           Register rs,
3056                           const Operand& rt,
3057                           BranchDelaySlot bd) {
3058   BlockTrampolinePoolScope block_trampoline_pool(this);
3059   Label start;
3060   bind(&start);
3061   DCHECK(RelocInfo::IsCodeTarget(rmode));
3062   if (rmode == RelocInfo::CODE_TARGET && !ast_id.IsNone()) {
3063     SetRecordedAstId(ast_id);
3064     rmode = RelocInfo::CODE_TARGET_WITH_ID;
3065   }
3066   AllowDeferredHandleDereference embedding_raw_address;
3067   Call(reinterpret_cast<Address>(code.location()), rmode, cond, rs, rt, bd);
3068   DCHECK_EQ(CallSize(code, rmode, ast_id, cond, rs, rt, bd),
3069             SizeOfCodeGeneratedSince(&start));
3070 }
3071
3072
3073 void MacroAssembler::Ret(Condition cond,
3074                          Register rs,
3075                          const Operand& rt,
3076                          BranchDelaySlot bd) {
3077   Jump(ra, cond, rs, rt, bd);
3078 }
3079
3080
3081 void MacroAssembler::J(Label* L, BranchDelaySlot bdslot) {
3082   BlockTrampolinePoolScope block_trampoline_pool(this);
3083
3084   uint32_t imm28;
3085   imm28 = jump_address(L);
3086   imm28 &= kImm28Mask;
3087   { BlockGrowBufferScope block_buf_growth(this);
3088     // Buffer growth (and relocation) must be blocked for internal references
3089     // until associated instructions are emitted and available to be patched.
3090     RecordRelocInfo(RelocInfo::INTERNAL_REFERENCE_ENCODED);
3091     j(imm28);
3092   }
3093   // Emit a nop in the branch delay slot if required.
3094   if (bdslot == PROTECT)
3095     nop();
3096 }
3097
3098
3099 void MacroAssembler::Jr(Label* L, BranchDelaySlot bdslot) {
3100   BlockTrampolinePoolScope block_trampoline_pool(this);
3101
3102   uint32_t imm32;
3103   imm32 = jump_address(L);
3104   { BlockGrowBufferScope block_buf_growth(this);
3105     // Buffer growth (and relocation) must be blocked for internal references
3106     // until associated instructions are emitted and available to be patched.
3107     RecordRelocInfo(RelocInfo::INTERNAL_REFERENCE_ENCODED);
3108     lui(at, (imm32 & kHiMask) >> kLuiShift);
3109     ori(at, at, (imm32 & kImm16Mask));
3110   }
3111   jr(at);
3112
3113   // Emit a nop in the branch delay slot if required.
3114   if (bdslot == PROTECT)
3115     nop();
3116 }
3117
3118
3119 void MacroAssembler::Jalr(Label* L, BranchDelaySlot bdslot) {
3120   BlockTrampolinePoolScope block_trampoline_pool(this);
3121
3122   uint32_t imm32;
3123   imm32 = jump_address(L);
3124   { BlockGrowBufferScope block_buf_growth(this);
3125     // Buffer growth (and relocation) must be blocked for internal references
3126     // until associated instructions are emitted and available to be patched.
3127     RecordRelocInfo(RelocInfo::INTERNAL_REFERENCE_ENCODED);
3128     lui(at, (imm32 & kHiMask) >> kLuiShift);
3129     ori(at, at, (imm32 & kImm16Mask));
3130   }
3131   jalr(at);
3132
3133   // Emit a nop in the branch delay slot if required.
3134   if (bdslot == PROTECT)
3135     nop();
3136 }
3137
3138
3139 void MacroAssembler::DropAndRet(int drop) {
3140   Ret(USE_DELAY_SLOT);
3141   addiu(sp, sp, drop * kPointerSize);
3142 }
3143
3144 void MacroAssembler::DropAndRet(int drop,
3145                                 Condition cond,
3146                                 Register r1,
3147                                 const Operand& r2) {
3148   // Both Drop and Ret need to be conditional.
3149   Label skip;
3150   if (cond != cc_always) {
3151     Branch(&skip, NegateCondition(cond), r1, r2);
3152   }
3153
3154   Drop(drop);
3155   Ret();
3156
3157   if (cond != cc_always) {
3158     bind(&skip);
3159   }
3160 }
3161
3162
3163 void MacroAssembler::Drop(int count,
3164                           Condition cond,
3165                           Register reg,
3166                           const Operand& op) {
3167   if (count <= 0) {
3168     return;
3169   }
3170
3171   Label skip;
3172
3173   if (cond != al) {
3174      Branch(&skip, NegateCondition(cond), reg, op);
3175   }
3176
3177   addiu(sp, sp, count * kPointerSize);
3178
3179   if (cond != al) {
3180     bind(&skip);
3181   }
3182 }
3183
3184
3185
3186 void MacroAssembler::Swap(Register reg1,
3187                           Register reg2,
3188                           Register scratch) {
3189   if (scratch.is(no_reg)) {
3190     Xor(reg1, reg1, Operand(reg2));
3191     Xor(reg2, reg2, Operand(reg1));
3192     Xor(reg1, reg1, Operand(reg2));
3193   } else {
3194     mov(scratch, reg1);
3195     mov(reg1, reg2);
3196     mov(reg2, scratch);
3197   }
3198 }
3199
3200
3201 void MacroAssembler::Call(Label* target) {
3202   BranchAndLink(target);
3203 }
3204
3205
3206 void MacroAssembler::Push(Handle<Object> handle) {
3207   li(at, Operand(handle));
3208   push(at);
3209 }
3210
3211
3212 void MacroAssembler::DebugBreak() {
3213   PrepareCEntryArgs(0);
3214   PrepareCEntryFunction(ExternalReference(Runtime::kDebugBreak, isolate()));
3215   CEntryStub ces(isolate(), 1);
3216   DCHECK(AllowThisStubCall(&ces));
3217   Call(ces.GetCode(), RelocInfo::DEBUG_BREAK);
3218 }
3219
3220
3221 // ---------------------------------------------------------------------------
3222 // Exception handling.
3223
3224 void MacroAssembler::PushTryHandler(StackHandler::Kind kind,
3225                                     int handler_index) {
3226   // Adjust this code if not the case.
3227   STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
3228   STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0 * kPointerSize);
3229   STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
3230   STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
3231   STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
3232   STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
3233
3234   // For the JSEntry handler, we must preserve a0-a3 and s0.
3235   // t1-t3 are available. We will build up the handler from the bottom by
3236   // pushing on the stack.
3237   // Set up the code object (t1) and the state (t2) for pushing.
3238   unsigned state =
3239       StackHandler::IndexField::encode(handler_index) |
3240       StackHandler::KindField::encode(kind);
3241   li(t1, Operand(CodeObject()), CONSTANT_SIZE);
3242   li(t2, Operand(state));
3243
3244   // Push the frame pointer, context, state, and code object.
3245   if (kind == StackHandler::JS_ENTRY) {
3246     DCHECK_EQ(static_cast<Smi*>(0), Smi::FromInt(0));
3247     // The second zero_reg indicates no context.
3248     // The first zero_reg is the NULL frame pointer.
3249     // The operands are reversed to match the order of MultiPush/Pop.
3250     Push(zero_reg, zero_reg, t2, t1);
3251   } else {
3252     MultiPush(t1.bit() | t2.bit() | cp.bit() | fp.bit());
3253   }
3254
3255   // Link the current handler as the next handler.
3256   li(t2, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
3257   lw(t1, MemOperand(t2));
3258   push(t1);
3259   // Set this new handler as the current one.
3260   sw(sp, MemOperand(t2));
3261 }
3262
3263
3264 void MacroAssembler::PopTryHandler() {
3265   STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
3266   pop(a1);
3267   Addu(sp, sp, Operand(StackHandlerConstants::kSize - kPointerSize));
3268   li(at, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
3269   sw(a1, MemOperand(at));
3270 }
3271
3272
3273 void MacroAssembler::JumpToHandlerEntry() {
3274   // Compute the handler entry address and jump to it.  The handler table is
3275   // a fixed array of (smi-tagged) code offsets.
3276   // v0 = exception, a1 = code object, a2 = state.
3277   lw(a3, FieldMemOperand(a1, Code::kHandlerTableOffset));  // Handler table.
3278   Addu(a3, a3, Operand(FixedArray::kHeaderSize - kHeapObjectTag));
3279   srl(a2, a2, StackHandler::kKindWidth);  // Handler index.
3280   sll(a2, a2, kPointerSizeLog2);
3281   Addu(a2, a3, a2);
3282   lw(a2, MemOperand(a2));  // Smi-tagged offset.
3283   Addu(a1, a1, Operand(Code::kHeaderSize - kHeapObjectTag));  // Code start.
3284   sra(t9, a2, kSmiTagSize);
3285   Addu(t9, t9, a1);
3286   Jump(t9);  // Jump.
3287 }
3288
3289
3290 void MacroAssembler::Throw(Register value) {
3291   // Adjust this code if not the case.
3292   STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
3293   STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
3294   STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
3295   STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
3296   STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
3297   STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
3298
3299   // The exception is expected in v0.
3300   Move(v0, value);
3301
3302   // Drop the stack pointer to the top of the top handler.
3303   li(a3, Operand(ExternalReference(Isolate::kHandlerAddress,
3304                                    isolate())));
3305   lw(sp, MemOperand(a3));
3306
3307   // Restore the next handler.
3308   pop(a2);
3309   sw(a2, MemOperand(a3));
3310
3311   // Get the code object (a1) and state (a2).  Restore the context and frame
3312   // pointer.
3313   MultiPop(a1.bit() | a2.bit() | cp.bit() | fp.bit());
3314
3315   // If the handler is a JS frame, restore the context to the frame.
3316   // (kind == ENTRY) == (fp == 0) == (cp == 0), so we could test either fp
3317   // or cp.
3318   Label done;
3319   Branch(&done, eq, cp, Operand(zero_reg));
3320   sw(cp, MemOperand(fp, StandardFrameConstants::kContextOffset));
3321   bind(&done);
3322
3323   JumpToHandlerEntry();
3324 }
3325
3326
3327 void MacroAssembler::ThrowUncatchable(Register value) {
3328   // Adjust this code if not the case.
3329   STATIC_ASSERT(StackHandlerConstants::kSize == 5 * kPointerSize);
3330   STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0 * kPointerSize);
3331   STATIC_ASSERT(StackHandlerConstants::kCodeOffset == 1 * kPointerSize);
3332   STATIC_ASSERT(StackHandlerConstants::kStateOffset == 2 * kPointerSize);
3333   STATIC_ASSERT(StackHandlerConstants::kContextOffset == 3 * kPointerSize);
3334   STATIC_ASSERT(StackHandlerConstants::kFPOffset == 4 * kPointerSize);
3335
3336   // The exception is expected in v0.
3337   if (!value.is(v0)) {
3338     mov(v0, value);
3339   }
3340   // Drop the stack pointer to the top of the top stack handler.
3341   li(a3, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
3342   lw(sp, MemOperand(a3));
3343
3344   // Unwind the handlers until the ENTRY handler is found.
3345   Label fetch_next, check_kind;
3346   jmp(&check_kind);
3347   bind(&fetch_next);
3348   lw(sp, MemOperand(sp, StackHandlerConstants::kNextOffset));
3349
3350   bind(&check_kind);
3351   STATIC_ASSERT(StackHandler::JS_ENTRY == 0);
3352   lw(a2, MemOperand(sp, StackHandlerConstants::kStateOffset));
3353   And(a2, a2, Operand(StackHandler::KindField::kMask));
3354   Branch(&fetch_next, ne, a2, Operand(zero_reg));
3355
3356   // Set the top handler address to next handler past the top ENTRY handler.
3357   pop(a2);
3358   sw(a2, MemOperand(a3));
3359
3360   // Get the code object (a1) and state (a2).  Clear the context and frame
3361   // pointer (0 was saved in the handler).
3362   MultiPop(a1.bit() | a2.bit() | cp.bit() | fp.bit());
3363
3364   JumpToHandlerEntry();
3365 }
3366
3367
3368 void MacroAssembler::Allocate(int object_size,
3369                               Register result,
3370                               Register scratch1,
3371                               Register scratch2,
3372                               Label* gc_required,
3373                               AllocationFlags flags) {
3374   DCHECK(object_size <= Page::kMaxRegularHeapObjectSize);
3375   if (!FLAG_inline_new) {
3376     if (emit_debug_code()) {
3377       // Trash the registers to simulate an allocation failure.
3378       li(result, 0x7091);
3379       li(scratch1, 0x7191);
3380       li(scratch2, 0x7291);
3381     }
3382     jmp(gc_required);
3383     return;
3384   }
3385
3386   DCHECK(!result.is(scratch1));
3387   DCHECK(!result.is(scratch2));
3388   DCHECK(!scratch1.is(scratch2));
3389   DCHECK(!scratch1.is(t9));
3390   DCHECK(!scratch2.is(t9));
3391   DCHECK(!result.is(t9));
3392
3393   // Make object size into bytes.
3394   if ((flags & SIZE_IN_WORDS) != 0) {
3395     object_size *= kPointerSize;
3396   }
3397   DCHECK_EQ(0, object_size & kObjectAlignmentMask);
3398
3399   // Check relative positions of allocation top and limit addresses.
3400   // ARM adds additional checks to make sure the ldm instruction can be
3401   // used. On MIPS we don't have ldm so we don't need additional checks either.
3402   ExternalReference allocation_top =
3403       AllocationUtils::GetAllocationTopReference(isolate(), flags);
3404   ExternalReference allocation_limit =
3405       AllocationUtils::GetAllocationLimitReference(isolate(), flags);
3406
3407   intptr_t top   =
3408       reinterpret_cast<intptr_t>(allocation_top.address());
3409   intptr_t limit =
3410       reinterpret_cast<intptr_t>(allocation_limit.address());
3411   DCHECK((limit - top) == kPointerSize);
3412
3413   // Set up allocation top address and object size registers.
3414   Register topaddr = scratch1;
3415   li(topaddr, Operand(allocation_top));
3416
3417   // This code stores a temporary value in t9.
3418   if ((flags & RESULT_CONTAINS_TOP) == 0) {
3419     // Load allocation top into result and allocation limit into t9.
3420     lw(result, MemOperand(topaddr));
3421     lw(t9, MemOperand(topaddr, kPointerSize));
3422   } else {
3423     if (emit_debug_code()) {
3424       // Assert that result actually contains top on entry. t9 is used
3425       // immediately below so this use of t9 does not cause difference with
3426       // respect to register content between debug and release mode.
3427       lw(t9, MemOperand(topaddr));
3428       Check(eq, kUnexpectedAllocationTop, result, Operand(t9));
3429     }
3430     // Load allocation limit into t9. Result already contains allocation top.
3431     lw(t9, MemOperand(topaddr, limit - top));
3432   }
3433
3434   if ((flags & DOUBLE_ALIGNMENT) != 0) {
3435     // Align the next allocation. Storing the filler map without checking top is
3436     // safe in new-space because the limit of the heap is aligned there.
3437     DCHECK((flags & PRETENURE_OLD_POINTER_SPACE) == 0);
3438     DCHECK(kPointerAlignment * 2 == kDoubleAlignment);
3439     And(scratch2, result, Operand(kDoubleAlignmentMask));
3440     Label aligned;
3441     Branch(&aligned, eq, scratch2, Operand(zero_reg));
3442     if ((flags & PRETENURE_OLD_DATA_SPACE) != 0) {
3443       Branch(gc_required, Ugreater_equal, result, Operand(t9));
3444     }
3445     li(scratch2, Operand(isolate()->factory()->one_pointer_filler_map()));
3446     sw(scratch2, MemOperand(result));
3447     Addu(result, result, Operand(kDoubleSize / 2));
3448     bind(&aligned);
3449   }
3450
3451   // Calculate new top and bail out if new space is exhausted. Use result
3452   // to calculate the new top.
3453   Addu(scratch2, result, Operand(object_size));
3454   Branch(gc_required, Ugreater, scratch2, Operand(t9));
3455   sw(scratch2, MemOperand(topaddr));
3456
3457   // Tag object if requested.
3458   if ((flags & TAG_OBJECT) != 0) {
3459     Addu(result, result, Operand(kHeapObjectTag));
3460   }
3461 }
3462
3463
3464 void MacroAssembler::Allocate(Register object_size,
3465                               Register result,
3466                               Register scratch1,
3467                               Register scratch2,
3468                               Label* gc_required,
3469                               AllocationFlags flags) {
3470   if (!FLAG_inline_new) {
3471     if (emit_debug_code()) {
3472       // Trash the registers to simulate an allocation failure.
3473       li(result, 0x7091);
3474       li(scratch1, 0x7191);
3475       li(scratch2, 0x7291);
3476     }
3477     jmp(gc_required);
3478     return;
3479   }
3480
3481   DCHECK(!result.is(scratch1));
3482   DCHECK(!result.is(scratch2));
3483   DCHECK(!scratch1.is(scratch2));
3484   DCHECK(!object_size.is(t9));
3485   DCHECK(!scratch1.is(t9) && !scratch2.is(t9) && !result.is(t9));
3486
3487   // Check relative positions of allocation top and limit addresses.
3488   // ARM adds additional checks to make sure the ldm instruction can be
3489   // used. On MIPS we don't have ldm so we don't need additional checks either.
3490   ExternalReference allocation_top =
3491       AllocationUtils::GetAllocationTopReference(isolate(), flags);
3492   ExternalReference allocation_limit =
3493       AllocationUtils::GetAllocationLimitReference(isolate(), flags);
3494   intptr_t top   =
3495       reinterpret_cast<intptr_t>(allocation_top.address());
3496   intptr_t limit =
3497       reinterpret_cast<intptr_t>(allocation_limit.address());
3498   DCHECK((limit - top) == kPointerSize);
3499
3500   // Set up allocation top address and object size registers.
3501   Register topaddr = scratch1;
3502   li(topaddr, Operand(allocation_top));
3503
3504   // This code stores a temporary value in t9.
3505   if ((flags & RESULT_CONTAINS_TOP) == 0) {
3506     // Load allocation top into result and allocation limit into t9.
3507     lw(result, MemOperand(topaddr));
3508     lw(t9, MemOperand(topaddr, kPointerSize));
3509   } else {
3510     if (emit_debug_code()) {
3511       // Assert that result actually contains top on entry. t9 is used
3512       // immediately below so this use of t9 does not cause difference with
3513       // respect to register content between debug and release mode.
3514       lw(t9, MemOperand(topaddr));
3515       Check(eq, kUnexpectedAllocationTop, result, Operand(t9));
3516     }
3517     // Load allocation limit into t9. Result already contains allocation top.
3518     lw(t9, MemOperand(topaddr, limit - top));
3519   }
3520
3521   if ((flags & DOUBLE_ALIGNMENT) != 0) {
3522     // Align the next allocation. Storing the filler map without checking top is
3523     // safe in new-space because the limit of the heap is aligned there.
3524     DCHECK((flags & PRETENURE_OLD_POINTER_SPACE) == 0);
3525     DCHECK(kPointerAlignment * 2 == kDoubleAlignment);
3526     And(scratch2, result, Operand(kDoubleAlignmentMask));
3527     Label aligned;
3528     Branch(&aligned, eq, scratch2, Operand(zero_reg));
3529     if ((flags & PRETENURE_OLD_DATA_SPACE) != 0) {
3530       Branch(gc_required, Ugreater_equal, result, Operand(t9));
3531     }
3532     li(scratch2, Operand(isolate()->factory()->one_pointer_filler_map()));
3533     sw(scratch2, MemOperand(result));
3534     Addu(result, result, Operand(kDoubleSize / 2));
3535     bind(&aligned);
3536   }
3537
3538   // Calculate new top and bail out if new space is exhausted. Use result
3539   // to calculate the new top. Object size may be in words so a shift is
3540   // required to get the number of bytes.
3541   if ((flags & SIZE_IN_WORDS) != 0) {
3542     sll(scratch2, object_size, kPointerSizeLog2);
3543     Addu(scratch2, result, scratch2);
3544   } else {
3545     Addu(scratch2, result, Operand(object_size));
3546   }
3547   Branch(gc_required, Ugreater, scratch2, Operand(t9));
3548
3549   // Update allocation top. result temporarily holds the new top.
3550   if (emit_debug_code()) {
3551     And(t9, scratch2, Operand(kObjectAlignmentMask));
3552     Check(eq, kUnalignedAllocationInNewSpace, t9, Operand(zero_reg));
3553   }
3554   sw(scratch2, MemOperand(topaddr));
3555
3556   // Tag object if requested.
3557   if ((flags & TAG_OBJECT) != 0) {
3558     Addu(result, result, Operand(kHeapObjectTag));
3559   }
3560 }
3561
3562
3563 void MacroAssembler::UndoAllocationInNewSpace(Register object,
3564                                               Register scratch) {
3565   ExternalReference new_space_allocation_top =
3566       ExternalReference::new_space_allocation_top_address(isolate());
3567
3568   // Make sure the object has no tag before resetting top.
3569   And(object, object, Operand(~kHeapObjectTagMask));
3570 #ifdef DEBUG
3571   // Check that the object un-allocated is below the current top.
3572   li(scratch, Operand(new_space_allocation_top));
3573   lw(scratch, MemOperand(scratch));
3574   Check(less, kUndoAllocationOfNonAllocatedMemory,
3575       object, Operand(scratch));
3576 #endif
3577   // Write the address of the object to un-allocate as the current top.
3578   li(scratch, Operand(new_space_allocation_top));
3579   sw(object, MemOperand(scratch));
3580 }
3581
3582
3583 void MacroAssembler::AllocateTwoByteString(Register result,
3584                                            Register length,
3585                                            Register scratch1,
3586                                            Register scratch2,
3587                                            Register scratch3,
3588                                            Label* gc_required) {
3589   // Calculate the number of bytes needed for the characters in the string while
3590   // observing object alignment.
3591   DCHECK((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
3592   sll(scratch1, length, 1);  // Length in bytes, not chars.
3593   addiu(scratch1, scratch1,
3594        kObjectAlignmentMask + SeqTwoByteString::kHeaderSize);
3595   And(scratch1, scratch1, Operand(~kObjectAlignmentMask));
3596
3597   // Allocate two-byte string in new space.
3598   Allocate(scratch1,
3599            result,
3600            scratch2,
3601            scratch3,
3602            gc_required,
3603            TAG_OBJECT);
3604
3605   // Set the map, length and hash field.
3606   InitializeNewString(result,
3607                       length,
3608                       Heap::kStringMapRootIndex,
3609                       scratch1,
3610                       scratch2);
3611 }
3612
3613
3614 void MacroAssembler::AllocateOneByteString(Register result, Register length,
3615                                            Register scratch1, Register scratch2,
3616                                            Register scratch3,
3617                                            Label* gc_required) {
3618   // Calculate the number of bytes needed for the characters in the string
3619   // while observing object alignment.
3620   DCHECK((SeqOneByteString::kHeaderSize & kObjectAlignmentMask) == 0);
3621   DCHECK(kCharSize == 1);
3622   addiu(scratch1, length, kObjectAlignmentMask + SeqOneByteString::kHeaderSize);
3623   And(scratch1, scratch1, Operand(~kObjectAlignmentMask));
3624
3625   // Allocate one-byte string in new space.
3626   Allocate(scratch1,
3627            result,
3628            scratch2,
3629            scratch3,
3630            gc_required,
3631            TAG_OBJECT);
3632
3633   // Set the map, length and hash field.
3634   InitializeNewString(result, length, Heap::kOneByteStringMapRootIndex,
3635                       scratch1, scratch2);
3636 }
3637
3638
3639 void MacroAssembler::AllocateTwoByteConsString(Register result,
3640                                                Register length,
3641                                                Register scratch1,
3642                                                Register scratch2,
3643                                                Label* gc_required) {
3644   Allocate(ConsString::kSize, result, scratch1, scratch2, gc_required,
3645            TAG_OBJECT);
3646   InitializeNewString(result,
3647                       length,
3648                       Heap::kConsStringMapRootIndex,
3649                       scratch1,
3650                       scratch2);
3651 }
3652
3653
3654 void MacroAssembler::AllocateOneByteConsString(Register result, Register length,
3655                                                Register scratch1,
3656                                                Register scratch2,
3657                                                Label* gc_required) {
3658   Allocate(ConsString::kSize,
3659            result,
3660            scratch1,
3661            scratch2,
3662            gc_required,
3663            TAG_OBJECT);
3664
3665   InitializeNewString(result, length, Heap::kConsOneByteStringMapRootIndex,
3666                       scratch1, scratch2);
3667 }
3668
3669
3670 void MacroAssembler::AllocateTwoByteSlicedString(Register result,
3671                                                  Register length,
3672                                                  Register scratch1,
3673                                                  Register scratch2,
3674                                                  Label* gc_required) {
3675   Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
3676            TAG_OBJECT);
3677
3678   InitializeNewString(result,
3679                       length,
3680                       Heap::kSlicedStringMapRootIndex,
3681                       scratch1,
3682                       scratch2);
3683 }
3684
3685
3686 void MacroAssembler::AllocateOneByteSlicedString(Register result,
3687                                                  Register length,
3688                                                  Register scratch1,
3689                                                  Register scratch2,
3690                                                  Label* gc_required) {
3691   Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
3692            TAG_OBJECT);
3693
3694   InitializeNewString(result, length, Heap::kSlicedOneByteStringMapRootIndex,
3695                       scratch1, scratch2);
3696 }
3697
3698
3699 void MacroAssembler::JumpIfNotUniqueNameInstanceType(Register reg,
3700                                                      Label* not_unique_name) {
3701   STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
3702   Label succeed;
3703   And(at, reg, Operand(kIsNotStringMask | kIsNotInternalizedMask));
3704   Branch(&succeed, eq, at, Operand(zero_reg));
3705   Branch(not_unique_name, ne, reg, Operand(SYMBOL_TYPE));
3706
3707   bind(&succeed);
3708 }
3709
3710
3711 // Allocates a heap number or jumps to the label if the young space is full and
3712 // a scavenge is needed.
3713 void MacroAssembler::AllocateHeapNumber(Register result,
3714                                         Register scratch1,
3715                                         Register scratch2,
3716                                         Register heap_number_map,
3717                                         Label* need_gc,
3718                                         TaggingMode tagging_mode,
3719                                         MutableMode mode) {
3720   // Allocate an object in the heap for the heap number and tag it as a heap
3721   // object.
3722   Allocate(HeapNumber::kSize, result, scratch1, scratch2, need_gc,
3723            tagging_mode == TAG_RESULT ? TAG_OBJECT : NO_ALLOCATION_FLAGS);
3724
3725   Heap::RootListIndex map_index = mode == MUTABLE
3726       ? Heap::kMutableHeapNumberMapRootIndex
3727       : Heap::kHeapNumberMapRootIndex;
3728   AssertIsRoot(heap_number_map, map_index);
3729
3730   // Store heap number map in the allocated object.
3731   if (tagging_mode == TAG_RESULT) {
3732     sw(heap_number_map, FieldMemOperand(result, HeapObject::kMapOffset));
3733   } else {
3734     sw(heap_number_map, MemOperand(result, HeapObject::kMapOffset));
3735   }
3736 }
3737
3738
3739 void MacroAssembler::AllocateHeapNumberWithValue(Register result,
3740                                                  FPURegister value,
3741                                                  Register scratch1,
3742                                                  Register scratch2,
3743                                                  Label* gc_required) {
3744   LoadRoot(t8, Heap::kHeapNumberMapRootIndex);
3745   AllocateHeapNumber(result, scratch1, scratch2, t8, gc_required);
3746   sdc1(value, FieldMemOperand(result, HeapNumber::kValueOffset));
3747 }
3748
3749
3750 // Copies a fixed number of fields of heap objects from src to dst.
3751 void MacroAssembler::CopyFields(Register dst,
3752                                 Register src,
3753                                 RegList temps,
3754                                 int field_count) {
3755   DCHECK((temps & dst.bit()) == 0);
3756   DCHECK((temps & src.bit()) == 0);
3757   // Primitive implementation using only one temporary register.
3758
3759   Register tmp = no_reg;
3760   // Find a temp register in temps list.
3761   for (int i = 0; i < kNumRegisters; i++) {
3762     if ((temps & (1 << i)) != 0) {
3763       tmp.code_ = i;
3764       break;
3765     }
3766   }
3767   DCHECK(!tmp.is(no_reg));
3768
3769   for (int i = 0; i < field_count; i++) {
3770     lw(tmp, FieldMemOperand(src, i * kPointerSize));
3771     sw(tmp, FieldMemOperand(dst, i * kPointerSize));
3772   }
3773 }
3774
3775
3776 void MacroAssembler::CopyBytes(Register src,
3777                                Register dst,
3778                                Register length,
3779                                Register scratch) {
3780   Label align_loop_1, word_loop, byte_loop, byte_loop_1, done;
3781
3782   // Align src before copying in word size chunks.
3783   Branch(&byte_loop, le, length, Operand(kPointerSize));
3784   bind(&align_loop_1);
3785   And(scratch, src, kPointerSize - 1);
3786   Branch(&word_loop, eq, scratch, Operand(zero_reg));
3787   lbu(scratch, MemOperand(src));
3788   Addu(src, src, 1);
3789   sb(scratch, MemOperand(dst));
3790   Addu(dst, dst, 1);
3791   Subu(length, length, Operand(1));
3792   Branch(&align_loop_1, ne, length, Operand(zero_reg));
3793
3794   // Copy bytes in word size chunks.
3795   bind(&word_loop);
3796   if (emit_debug_code()) {
3797     And(scratch, src, kPointerSize - 1);
3798     Assert(eq, kExpectingAlignmentForCopyBytes,
3799         scratch, Operand(zero_reg));
3800   }
3801   Branch(&byte_loop, lt, length, Operand(kPointerSize));
3802   lw(scratch, MemOperand(src));
3803   Addu(src, src, kPointerSize);
3804
3805   // TODO(kalmard) check if this can be optimized to use sw in most cases.
3806   // Can't use unaligned access - copy byte by byte.
3807   if (kArchEndian == kLittle) {
3808     sb(scratch, MemOperand(dst, 0));
3809     srl(scratch, scratch, 8);
3810     sb(scratch, MemOperand(dst, 1));
3811     srl(scratch, scratch, 8);
3812     sb(scratch, MemOperand(dst, 2));
3813     srl(scratch, scratch, 8);
3814     sb(scratch, MemOperand(dst, 3));
3815   } else {
3816     sb(scratch, MemOperand(dst, 3));
3817     srl(scratch, scratch, 8);
3818     sb(scratch, MemOperand(dst, 2));
3819     srl(scratch, scratch, 8);
3820     sb(scratch, MemOperand(dst, 1));
3821     srl(scratch, scratch, 8);
3822     sb(scratch, MemOperand(dst, 0));
3823   }
3824
3825   Addu(dst, dst, 4);
3826
3827   Subu(length, length, Operand(kPointerSize));
3828   Branch(&word_loop);
3829
3830   // Copy the last bytes if any left.
3831   bind(&byte_loop);
3832   Branch(&done, eq, length, Operand(zero_reg));
3833   bind(&byte_loop_1);
3834   lbu(scratch, MemOperand(src));
3835   Addu(src, src, 1);
3836   sb(scratch, MemOperand(dst));
3837   Addu(dst, dst, 1);
3838   Subu(length, length, Operand(1));
3839   Branch(&byte_loop_1, ne, length, Operand(zero_reg));
3840   bind(&done);
3841 }
3842
3843
3844 void MacroAssembler::InitializeFieldsWithFiller(Register start_offset,
3845                                                 Register end_offset,
3846                                                 Register filler) {
3847   Label loop, entry;
3848   Branch(&entry);
3849   bind(&loop);
3850   sw(filler, MemOperand(start_offset));
3851   Addu(start_offset, start_offset, kPointerSize);
3852   bind(&entry);
3853   Branch(&loop, lt, start_offset, Operand(end_offset));
3854 }
3855
3856
3857 void MacroAssembler::CheckFastElements(Register map,
3858                                        Register scratch,
3859                                        Label* fail) {
3860   STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
3861   STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
3862   STATIC_ASSERT(FAST_ELEMENTS == 2);
3863   STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
3864   lbu(scratch, FieldMemOperand(map, Map::kBitField2Offset));
3865   Branch(fail, hi, scratch,
3866          Operand(Map::kMaximumBitField2FastHoleyElementValue));
3867 }
3868
3869
3870 void MacroAssembler::CheckFastObjectElements(Register map,
3871                                              Register scratch,
3872                                              Label* fail) {
3873   STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
3874   STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
3875   STATIC_ASSERT(FAST_ELEMENTS == 2);
3876   STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
3877   lbu(scratch, FieldMemOperand(map, Map::kBitField2Offset));
3878   Branch(fail, ls, scratch,
3879          Operand(Map::kMaximumBitField2FastHoleySmiElementValue));
3880   Branch(fail, hi, scratch,
3881          Operand(Map::kMaximumBitField2FastHoleyElementValue));
3882 }
3883
3884
3885 void MacroAssembler::CheckFastSmiElements(Register map,
3886                                           Register scratch,
3887                                           Label* fail) {
3888   STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
3889   STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
3890   lbu(scratch, FieldMemOperand(map, Map::kBitField2Offset));
3891   Branch(fail, hi, scratch,
3892          Operand(Map::kMaximumBitField2FastHoleySmiElementValue));
3893 }
3894
3895
3896 void MacroAssembler::StoreNumberToDoubleElements(Register value_reg,
3897                                                  Register key_reg,
3898                                                  Register elements_reg,
3899                                                  Register scratch1,
3900                                                  Register scratch2,
3901                                                  Register scratch3,
3902                                                  Label* fail,
3903                                                  int elements_offset) {
3904   Label smi_value, maybe_nan, have_double_value, is_nan, done;
3905   Register mantissa_reg = scratch2;
3906   Register exponent_reg = scratch3;
3907
3908   // Handle smi values specially.
3909   JumpIfSmi(value_reg, &smi_value);
3910
3911   // Ensure that the object is a heap number
3912   CheckMap(value_reg,
3913            scratch1,
3914            Heap::kHeapNumberMapRootIndex,
3915            fail,
3916            DONT_DO_SMI_CHECK);
3917
3918   // Check for nan: all NaN values have a value greater (signed) than 0x7ff00000
3919   // in the exponent.
3920   li(scratch1, Operand(kHoleNanUpper32 & HeapNumber::kExponentMask));
3921   lw(exponent_reg, FieldMemOperand(value_reg, HeapNumber::kExponentOffset));
3922   Branch(&maybe_nan, ge, exponent_reg, Operand(scratch1));
3923
3924   lw(mantissa_reg, FieldMemOperand(value_reg, HeapNumber::kMantissaOffset));
3925
3926   bind(&have_double_value);
3927   sll(scratch1, key_reg, kDoubleSizeLog2 - kSmiTagSize);
3928   Addu(scratch1, scratch1, elements_reg);
3929   sw(mantissa_reg,
3930       FieldMemOperand(scratch1, FixedDoubleArray::kHeaderSize - elements_offset
3931           + kHoleNanLower32Offset));
3932   sw(exponent_reg,
3933       FieldMemOperand(scratch1, FixedDoubleArray::kHeaderSize - elements_offset
3934           + kHoleNanUpper32Offset));
3935   jmp(&done);
3936
3937   bind(&maybe_nan);
3938   // Could be NaN or Infinity. If fraction is not zero, it's NaN, otherwise
3939   // it's an Infinity, and the non-NaN code path applies.
3940   Branch(&is_nan, gt, exponent_reg, Operand(scratch1));
3941   lw(mantissa_reg, FieldMemOperand(value_reg, HeapNumber::kMantissaOffset));
3942   Branch(&have_double_value, eq, mantissa_reg, Operand(zero_reg));
3943   bind(&is_nan);
3944   // Load canonical NaN for storing into the double array.
3945   LoadRoot(at, Heap::kNanValueRootIndex);
3946   lw(mantissa_reg, FieldMemOperand(at, HeapNumber::kMantissaOffset));
3947   lw(exponent_reg, FieldMemOperand(at, HeapNumber::kExponentOffset));
3948   jmp(&have_double_value);
3949
3950   bind(&smi_value);
3951   Addu(scratch1, elements_reg,
3952       Operand(FixedDoubleArray::kHeaderSize - kHeapObjectTag -
3953               elements_offset));
3954   sll(scratch2, key_reg, kDoubleSizeLog2 - kSmiTagSize);
3955   Addu(scratch1, scratch1, scratch2);
3956   // scratch1 is now effective address of the double element
3957
3958   Register untagged_value = elements_reg;
3959   SmiUntag(untagged_value, value_reg);
3960   mtc1(untagged_value, f2);
3961   cvt_d_w(f0, f2);
3962   sdc1(f0, MemOperand(scratch1, 0));
3963   bind(&done);
3964 }
3965
3966
3967 void MacroAssembler::CompareMapAndBranch(Register obj,
3968                                          Register scratch,
3969                                          Handle<Map> map,
3970                                          Label* early_success,
3971                                          Condition cond,
3972                                          Label* branch_to) {
3973   lw(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
3974   CompareMapAndBranch(scratch, map, early_success, cond, branch_to);
3975 }
3976
3977
3978 void MacroAssembler::CompareMapAndBranch(Register obj_map,
3979                                          Handle<Map> map,
3980                                          Label* early_success,
3981                                          Condition cond,
3982                                          Label* branch_to) {
3983   Branch(branch_to, cond, obj_map, Operand(map));
3984 }
3985
3986
3987 void MacroAssembler::CheckMap(Register obj,
3988                               Register scratch,
3989                               Handle<Map> map,
3990                               Label* fail,
3991                               SmiCheckType smi_check_type) {
3992   if (smi_check_type == DO_SMI_CHECK) {
3993     JumpIfSmi(obj, fail);
3994   }
3995   Label success;
3996   CompareMapAndBranch(obj, scratch, map, &success, ne, fail);
3997   bind(&success);
3998 }
3999
4000
4001 void MacroAssembler::DispatchWeakMap(Register obj, Register scratch1,
4002                                      Register scratch2, Handle<WeakCell> cell,
4003                                      Handle<Code> success,
4004                                      SmiCheckType smi_check_type) {
4005   Label fail;
4006   if (smi_check_type == DO_SMI_CHECK) {
4007     JumpIfSmi(obj, &fail);
4008   }
4009   lw(scratch1, FieldMemOperand(obj, HeapObject::kMapOffset));
4010   GetWeakValue(scratch2, cell);
4011   Jump(success, RelocInfo::CODE_TARGET, eq, scratch1, Operand(scratch2));
4012   bind(&fail);
4013 }
4014
4015
4016 void MacroAssembler::CheckMap(Register obj,
4017                               Register scratch,
4018                               Heap::RootListIndex index,
4019                               Label* fail,
4020                               SmiCheckType smi_check_type) {
4021   if (smi_check_type == DO_SMI_CHECK) {
4022     JumpIfSmi(obj, fail);
4023   }
4024   lw(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
4025   LoadRoot(at, index);
4026   Branch(fail, ne, scratch, Operand(at));
4027 }
4028
4029
4030 void MacroAssembler::GetWeakValue(Register value, Handle<WeakCell> cell) {
4031   li(value, Operand(cell));
4032   lw(value, FieldMemOperand(value, WeakCell::kValueOffset));
4033 }
4034
4035
4036 void MacroAssembler::LoadWeakValue(Register value, Handle<WeakCell> cell,
4037                                    Label* miss) {
4038   GetWeakValue(value, cell);
4039   JumpIfSmi(value, miss);
4040 }
4041
4042
4043 void MacroAssembler::MovFromFloatResult(DoubleRegister dst) {
4044   if (IsMipsSoftFloatABI) {
4045     if (kArchEndian == kLittle) {
4046       Move(dst, v0, v1);
4047     } else {
4048       Move(dst, v1, v0);
4049     }
4050   } else {
4051     Move(dst, f0);  // Reg f0 is o32 ABI FP return value.
4052   }
4053 }
4054
4055
4056 void MacroAssembler::MovFromFloatParameter(DoubleRegister dst) {
4057   if (IsMipsSoftFloatABI) {
4058     if (kArchEndian == kLittle) {
4059       Move(dst, a0, a1);
4060     } else {
4061       Move(dst, a1, a0);
4062     }
4063   } else {
4064     Move(dst, f12);  // Reg f12 is o32 ABI FP first argument value.
4065   }
4066 }
4067
4068
4069 void MacroAssembler::MovToFloatParameter(DoubleRegister src) {
4070   if (!IsMipsSoftFloatABI) {
4071     Move(f12, src);
4072   } else {
4073     if (kArchEndian == kLittle) {
4074       Move(a0, a1, src);
4075     } else {
4076       Move(a1, a0, src);
4077     }
4078   }
4079 }
4080
4081
4082 void MacroAssembler::MovToFloatResult(DoubleRegister src) {
4083   if (!IsMipsSoftFloatABI) {
4084     Move(f0, src);
4085   } else {
4086     if (kArchEndian == kLittle) {
4087       Move(v0, v1, src);
4088     } else {
4089       Move(v1, v0, src);
4090     }
4091   }
4092 }
4093
4094
4095 void MacroAssembler::MovToFloatParameters(DoubleRegister src1,
4096                                           DoubleRegister src2) {
4097   if (!IsMipsSoftFloatABI) {
4098     if (src2.is(f12)) {
4099       DCHECK(!src1.is(f14));
4100       Move(f14, src2);
4101       Move(f12, src1);
4102     } else {
4103       Move(f12, src1);
4104       Move(f14, src2);
4105     }
4106   } else {
4107     if (kArchEndian == kLittle) {
4108       Move(a0, a1, src1);
4109       Move(a2, a3, src2);
4110     } else {
4111       Move(a1, a0, src1);
4112       Move(a3, a2, src2);
4113     }
4114   }
4115 }
4116
4117
4118 // -----------------------------------------------------------------------------
4119 // JavaScript invokes.
4120
4121 void MacroAssembler::InvokePrologue(const ParameterCount& expected,
4122                                     const ParameterCount& actual,
4123                                     Handle<Code> code_constant,
4124                                     Register code_reg,
4125                                     Label* done,
4126                                     bool* definitely_mismatches,
4127                                     InvokeFlag flag,
4128                                     const CallWrapper& call_wrapper) {
4129   bool definitely_matches = false;
4130   *definitely_mismatches = false;
4131   Label regular_invoke;
4132
4133   // Check whether the expected and actual arguments count match. If not,
4134   // setup registers according to contract with ArgumentsAdaptorTrampoline:
4135   //  a0: actual arguments count
4136   //  a1: function (passed through to callee)
4137   //  a2: expected arguments count
4138
4139   // The code below is made a lot easier because the calling code already sets
4140   // up actual and expected registers according to the contract if values are
4141   // passed in registers.
4142   DCHECK(actual.is_immediate() || actual.reg().is(a0));
4143   DCHECK(expected.is_immediate() || expected.reg().is(a2));
4144   DCHECK((!code_constant.is_null() && code_reg.is(no_reg)) || code_reg.is(a3));
4145
4146   if (expected.is_immediate()) {
4147     DCHECK(actual.is_immediate());
4148     if (expected.immediate() == actual.immediate()) {
4149       definitely_matches = true;
4150     } else {
4151       li(a0, Operand(actual.immediate()));
4152       const int sentinel = SharedFunctionInfo::kDontAdaptArgumentsSentinel;
4153       if (expected.immediate() == sentinel) {
4154         // Don't worry about adapting arguments for builtins that
4155         // don't want that done. Skip adaption code by making it look
4156         // like we have a match between expected and actual number of
4157         // arguments.
4158         definitely_matches = true;
4159       } else {
4160         *definitely_mismatches = true;
4161         li(a2, Operand(expected.immediate()));
4162       }
4163     }
4164   } else if (actual.is_immediate()) {
4165     Branch(&regular_invoke, eq, expected.reg(), Operand(actual.immediate()));
4166     li(a0, Operand(actual.immediate()));
4167   } else {
4168     Branch(&regular_invoke, eq, expected.reg(), Operand(actual.reg()));
4169   }
4170
4171   if (!definitely_matches) {
4172     if (!code_constant.is_null()) {
4173       li(a3, Operand(code_constant));
4174       addiu(a3, a3, Code::kHeaderSize - kHeapObjectTag);
4175     }
4176
4177     Handle<Code> adaptor =
4178         isolate()->builtins()->ArgumentsAdaptorTrampoline();
4179     if (flag == CALL_FUNCTION) {
4180       call_wrapper.BeforeCall(CallSize(adaptor));
4181       Call(adaptor);
4182       call_wrapper.AfterCall();
4183       if (!*definitely_mismatches) {
4184         Branch(done);
4185       }
4186     } else {
4187       Jump(adaptor, RelocInfo::CODE_TARGET);
4188     }
4189     bind(&regular_invoke);
4190   }
4191 }
4192
4193
4194 void MacroAssembler::InvokeCode(Register code,
4195                                 const ParameterCount& expected,
4196                                 const ParameterCount& actual,
4197                                 InvokeFlag flag,
4198                                 const CallWrapper& call_wrapper) {
4199   // You can't call a function without a valid frame.
4200   DCHECK(flag == JUMP_FUNCTION || has_frame());
4201
4202   Label done;
4203
4204   bool definitely_mismatches = false;
4205   InvokePrologue(expected, actual, Handle<Code>::null(), code,
4206                  &done, &definitely_mismatches, flag,
4207                  call_wrapper);
4208   if (!definitely_mismatches) {
4209     if (flag == CALL_FUNCTION) {
4210       call_wrapper.BeforeCall(CallSize(code));
4211       Call(code);
4212       call_wrapper.AfterCall();
4213     } else {
4214       DCHECK(flag == JUMP_FUNCTION);
4215       Jump(code);
4216     }
4217     // Continue here if InvokePrologue does handle the invocation due to
4218     // mismatched parameter counts.
4219     bind(&done);
4220   }
4221 }
4222
4223
4224 void MacroAssembler::InvokeFunction(Register function,
4225                                     const ParameterCount& actual,
4226                                     InvokeFlag flag,
4227                                     const CallWrapper& call_wrapper) {
4228   // You can't call a function without a valid frame.
4229   DCHECK(flag == JUMP_FUNCTION || has_frame());
4230
4231   // Contract with called JS functions requires that function is passed in a1.
4232   DCHECK(function.is(a1));
4233   Register expected_reg = a2;
4234   Register code_reg = a3;
4235
4236   lw(code_reg, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
4237   lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
4238   lw(expected_reg,
4239       FieldMemOperand(code_reg,
4240                       SharedFunctionInfo::kFormalParameterCountOffset));
4241   sra(expected_reg, expected_reg, kSmiTagSize);
4242   lw(code_reg, FieldMemOperand(a1, JSFunction::kCodeEntryOffset));
4243
4244   ParameterCount expected(expected_reg);
4245   InvokeCode(code_reg, expected, actual, flag, call_wrapper);
4246 }
4247
4248
4249 void MacroAssembler::InvokeFunction(Register function,
4250                                     const ParameterCount& expected,
4251                                     const ParameterCount& actual,
4252                                     InvokeFlag flag,
4253                                     const CallWrapper& call_wrapper) {
4254   // You can't call a function without a valid frame.
4255   DCHECK(flag == JUMP_FUNCTION || has_frame());
4256
4257   // Contract with called JS functions requires that function is passed in a1.
4258   DCHECK(function.is(a1));
4259
4260   // Get the function and setup the context.
4261   lw(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
4262
4263   // We call indirectly through the code field in the function to
4264   // allow recompilation to take effect without changing any of the
4265   // call sites.
4266   lw(a3, FieldMemOperand(a1, JSFunction::kCodeEntryOffset));
4267   InvokeCode(a3, expected, actual, flag, call_wrapper);
4268 }
4269
4270
4271 void MacroAssembler::InvokeFunction(Handle<JSFunction> function,
4272                                     const ParameterCount& expected,
4273                                     const ParameterCount& actual,
4274                                     InvokeFlag flag,
4275                                     const CallWrapper& call_wrapper) {
4276   li(a1, function);
4277   InvokeFunction(a1, expected, actual, flag, call_wrapper);
4278 }
4279
4280
4281 void MacroAssembler::IsObjectJSObjectType(Register heap_object,
4282                                           Register map,
4283                                           Register scratch,
4284                                           Label* fail) {
4285   lw(map, FieldMemOperand(heap_object, HeapObject::kMapOffset));
4286   IsInstanceJSObjectType(map, scratch, fail);
4287 }
4288
4289
4290 void MacroAssembler::IsInstanceJSObjectType(Register map,
4291                                             Register scratch,
4292                                             Label* fail) {
4293   lbu(scratch, FieldMemOperand(map, Map::kInstanceTypeOffset));
4294   Branch(fail, lt, scratch, Operand(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
4295   Branch(fail, gt, scratch, Operand(LAST_NONCALLABLE_SPEC_OBJECT_TYPE));
4296 }
4297
4298
4299 void MacroAssembler::IsObjectJSStringType(Register object,
4300                                           Register scratch,
4301                                           Label* fail) {
4302   DCHECK(kNotStringTag != 0);
4303
4304   lw(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
4305   lbu(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
4306   And(scratch, scratch, Operand(kIsNotStringMask));
4307   Branch(fail, ne, scratch, Operand(zero_reg));
4308 }
4309
4310
4311 void MacroAssembler::IsObjectNameType(Register object,
4312                                       Register scratch,
4313                                       Label* fail) {
4314   lw(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
4315   lbu(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
4316   Branch(fail, hi, scratch, Operand(LAST_NAME_TYPE));
4317 }
4318
4319
4320 // ---------------------------------------------------------------------------
4321 // Support functions.
4322
4323
4324 void MacroAssembler::TryGetFunctionPrototype(Register function,
4325                                              Register result,
4326                                              Register scratch,
4327                                              Label* miss,
4328                                              bool miss_on_bound_function) {
4329   Label non_instance;
4330   if (miss_on_bound_function) {
4331     // Check that the receiver isn't a smi.
4332     JumpIfSmi(function, miss);
4333
4334     // Check that the function really is a function.  Load map into result reg.
4335     GetObjectType(function, result, scratch);
4336     Branch(miss, ne, scratch, Operand(JS_FUNCTION_TYPE));
4337
4338     lw(scratch,
4339        FieldMemOperand(function, JSFunction::kSharedFunctionInfoOffset));
4340     lw(scratch,
4341        FieldMemOperand(scratch, SharedFunctionInfo::kCompilerHintsOffset));
4342     And(scratch, scratch,
4343         Operand(Smi::FromInt(1 << SharedFunctionInfo::kBoundFunction)));
4344     Branch(miss, ne, scratch, Operand(zero_reg));
4345
4346     // Make sure that the function has an instance prototype.
4347     lbu(scratch, FieldMemOperand(result, Map::kBitFieldOffset));
4348     And(scratch, scratch, Operand(1 << Map::kHasNonInstancePrototype));
4349     Branch(&non_instance, ne, scratch, Operand(zero_reg));
4350   }
4351
4352   // Get the prototype or initial map from the function.
4353   lw(result,
4354      FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
4355
4356   // If the prototype or initial map is the hole, don't return it and
4357   // simply miss the cache instead. This will allow us to allocate a
4358   // prototype object on-demand in the runtime system.
4359   LoadRoot(t8, Heap::kTheHoleValueRootIndex);
4360   Branch(miss, eq, result, Operand(t8));
4361
4362   // If the function does not have an initial map, we're done.
4363   Label done;
4364   GetObjectType(result, scratch, scratch);
4365   Branch(&done, ne, scratch, Operand(MAP_TYPE));
4366
4367   // Get the prototype from the initial map.
4368   lw(result, FieldMemOperand(result, Map::kPrototypeOffset));
4369
4370   if (miss_on_bound_function) {
4371     jmp(&done);
4372
4373     // Non-instance prototype: Fetch prototype from constructor field
4374     // in initial map.
4375     bind(&non_instance);
4376     lw(result, FieldMemOperand(result, Map::kConstructorOffset));
4377   }
4378
4379   // All done.
4380   bind(&done);
4381 }
4382
4383
4384 void MacroAssembler::GetObjectType(Register object,
4385                                    Register map,
4386                                    Register type_reg) {
4387   lw(map, FieldMemOperand(object, HeapObject::kMapOffset));
4388   lbu(type_reg, FieldMemOperand(map, Map::kInstanceTypeOffset));
4389 }
4390
4391
4392 // -----------------------------------------------------------------------------
4393 // Runtime calls.
4394
4395 void MacroAssembler::CallStub(CodeStub* stub,
4396                               TypeFeedbackId ast_id,
4397                               Condition cond,
4398                               Register r1,
4399                               const Operand& r2,
4400                               BranchDelaySlot bd) {
4401   DCHECK(AllowThisStubCall(stub));  // Stub calls are not allowed in some stubs.
4402   Call(stub->GetCode(), RelocInfo::CODE_TARGET, ast_id,
4403        cond, r1, r2, bd);
4404 }
4405
4406
4407 void MacroAssembler::TailCallStub(CodeStub* stub,
4408                                   Condition cond,
4409                                   Register r1,
4410                                   const Operand& r2,
4411                                   BranchDelaySlot bd) {
4412   Jump(stub->GetCode(), RelocInfo::CODE_TARGET, cond, r1, r2, bd);
4413 }
4414
4415
4416 bool MacroAssembler::AllowThisStubCall(CodeStub* stub) {
4417   return has_frame_ || !stub->SometimesSetsUpAFrame();
4418 }
4419
4420
4421 void MacroAssembler::IndexFromHash(Register hash, Register index) {
4422   // If the hash field contains an array index pick it out. The assert checks
4423   // that the constants for the maximum number of digits for an array index
4424   // cached in the hash field and the number of bits reserved for it does not
4425   // conflict.
4426   DCHECK(TenToThe(String::kMaxCachedArrayIndexLength) <
4427          (1 << String::kArrayIndexValueBits));
4428   DecodeFieldToSmi<String::ArrayIndexValueBits>(index, hash);
4429 }
4430
4431
4432 void MacroAssembler::ObjectToDoubleFPURegister(Register object,
4433                                                FPURegister result,
4434                                                Register scratch1,
4435                                                Register scratch2,
4436                                                Register heap_number_map,
4437                                                Label* not_number,
4438                                                ObjectToDoubleFlags flags) {
4439   Label done;
4440   if ((flags & OBJECT_NOT_SMI) == 0) {
4441     Label not_smi;
4442     JumpIfNotSmi(object, &not_smi);
4443     // Remove smi tag and convert to double.
4444     sra(scratch1, object, kSmiTagSize);
4445     mtc1(scratch1, result);
4446     cvt_d_w(result, result);
4447     Branch(&done);
4448     bind(&not_smi);
4449   }
4450   // Check for heap number and load double value from it.
4451   lw(scratch1, FieldMemOperand(object, HeapObject::kMapOffset));
4452   Branch(not_number, ne, scratch1, Operand(heap_number_map));
4453
4454   if ((flags & AVOID_NANS_AND_INFINITIES) != 0) {
4455     // If exponent is all ones the number is either a NaN or +/-Infinity.
4456     Register exponent = scratch1;
4457     Register mask_reg = scratch2;
4458     lw(exponent, FieldMemOperand(object, HeapNumber::kExponentOffset));
4459     li(mask_reg, HeapNumber::kExponentMask);
4460
4461     And(exponent, exponent, mask_reg);
4462     Branch(not_number, eq, exponent, Operand(mask_reg));
4463   }
4464   ldc1(result, FieldMemOperand(object, HeapNumber::kValueOffset));
4465   bind(&done);
4466 }
4467
4468
4469 void MacroAssembler::SmiToDoubleFPURegister(Register smi,
4470                                             FPURegister value,
4471                                             Register scratch1) {
4472   sra(scratch1, smi, kSmiTagSize);
4473   mtc1(scratch1, value);
4474   cvt_d_w(value, value);
4475 }
4476
4477
4478 void MacroAssembler::AdduAndCheckForOverflow(Register dst, Register left,
4479                                              const Operand& right,
4480                                              Register overflow_dst,
4481                                              Register scratch) {
4482   if (right.is_reg()) {
4483     AdduAndCheckForOverflow(dst, left, right.rm(), overflow_dst, scratch);
4484   } else {
4485     if (dst.is(left)) {
4486       mov(scratch, left);                   // Preserve left.
4487       addiu(dst, left, right.immediate());  // Left is overwritten.
4488       xor_(scratch, dst, scratch);          // Original left.
4489       // Load right since xori takes uint16 as immediate.
4490       addiu(t9, zero_reg, right.immediate());
4491       xor_(overflow_dst, dst, t9);
4492       and_(overflow_dst, overflow_dst, scratch);
4493     } else {
4494       addiu(dst, left, right.immediate());
4495       xor_(overflow_dst, dst, left);
4496       // Load right since xori takes uint16 as immediate.
4497       addiu(t9, zero_reg, right.immediate());
4498       xor_(scratch, dst, t9);
4499       and_(overflow_dst, scratch, overflow_dst);
4500     }
4501   }
4502 }
4503
4504
4505 void MacroAssembler::AdduAndCheckForOverflow(Register dst, Register left,
4506                                              Register right,
4507                                              Register overflow_dst,
4508                                              Register scratch) {
4509   DCHECK(!dst.is(overflow_dst));
4510   DCHECK(!dst.is(scratch));
4511   DCHECK(!overflow_dst.is(scratch));
4512   DCHECK(!overflow_dst.is(left));
4513   DCHECK(!overflow_dst.is(right));
4514
4515   if (left.is(right) && dst.is(left)) {
4516     DCHECK(!dst.is(t9));
4517     DCHECK(!scratch.is(t9));
4518     DCHECK(!left.is(t9));
4519     DCHECK(!right.is(t9));
4520     DCHECK(!overflow_dst.is(t9));
4521     mov(t9, right);
4522     right = t9;
4523   }
4524
4525   if (dst.is(left)) {
4526     mov(scratch, left);  // Preserve left.
4527     addu(dst, left, right);  // Left is overwritten.
4528     xor_(scratch, dst, scratch);  // Original left.
4529     xor_(overflow_dst, dst, right);
4530     and_(overflow_dst, overflow_dst, scratch);
4531   } else if (dst.is(right)) {
4532     mov(scratch, right);  // Preserve right.
4533     addu(dst, left, right);  // Right is overwritten.
4534     xor_(scratch, dst, scratch);  // Original right.
4535     xor_(overflow_dst, dst, left);
4536     and_(overflow_dst, overflow_dst, scratch);
4537   } else {
4538     addu(dst, left, right);
4539     xor_(overflow_dst, dst, left);
4540     xor_(scratch, dst, right);
4541     and_(overflow_dst, scratch, overflow_dst);
4542   }
4543 }
4544
4545
4546 void MacroAssembler::SubuAndCheckForOverflow(Register dst, Register left,
4547                                              const Operand& right,
4548                                              Register overflow_dst,
4549                                              Register scratch) {
4550   if (right.is_reg()) {
4551     SubuAndCheckForOverflow(dst, left, right.rm(), overflow_dst, scratch);
4552   } else {
4553     if (dst.is(left)) {
4554       mov(scratch, left);                      // Preserve left.
4555       addiu(dst, left, -(right.immediate()));  // Left is overwritten.
4556       xor_(overflow_dst, dst, scratch);        // scratch is original left.
4557       // Load right since xori takes uint16 as immediate.
4558       addiu(t9, zero_reg, right.immediate());
4559       xor_(scratch, scratch, t9);  // scratch is original left.
4560       and_(overflow_dst, scratch, overflow_dst);
4561     } else {
4562       addiu(dst, left, -(right.immediate()));
4563       xor_(overflow_dst, dst, left);
4564       // Load right since xori takes uint16 as immediate.
4565       addiu(t9, zero_reg, right.immediate());
4566       xor_(scratch, left, t9);
4567       and_(overflow_dst, scratch, overflow_dst);
4568     }
4569   }
4570 }
4571
4572
4573 void MacroAssembler::SubuAndCheckForOverflow(Register dst, Register left,
4574                                              Register right,
4575                                              Register overflow_dst,
4576                                              Register scratch) {
4577   DCHECK(!dst.is(overflow_dst));
4578   DCHECK(!dst.is(scratch));
4579   DCHECK(!overflow_dst.is(scratch));
4580   DCHECK(!overflow_dst.is(left));
4581   DCHECK(!overflow_dst.is(right));
4582   DCHECK(!scratch.is(left));
4583   DCHECK(!scratch.is(right));
4584
4585   // This happens with some crankshaft code. Since Subu works fine if
4586   // left == right, let's not make that restriction here.
4587   if (left.is(right)) {
4588     mov(dst, zero_reg);
4589     mov(overflow_dst, zero_reg);
4590     return;
4591   }
4592
4593   if (dst.is(left)) {
4594     mov(scratch, left);  // Preserve left.
4595     subu(dst, left, right);  // Left is overwritten.
4596     xor_(overflow_dst, dst, scratch);  // scratch is original left.
4597     xor_(scratch, scratch, right);  // scratch is original left.
4598     and_(overflow_dst, scratch, overflow_dst);
4599   } else if (dst.is(right)) {
4600     mov(scratch, right);  // Preserve right.
4601     subu(dst, left, right);  // Right is overwritten.
4602     xor_(overflow_dst, dst, left);
4603     xor_(scratch, left, scratch);  // Original right.
4604     and_(overflow_dst, scratch, overflow_dst);
4605   } else {
4606     subu(dst, left, right);
4607     xor_(overflow_dst, dst, left);
4608     xor_(scratch, left, right);
4609     and_(overflow_dst, scratch, overflow_dst);
4610   }
4611 }
4612
4613
4614 void MacroAssembler::CallRuntime(const Runtime::Function* f,
4615                                  int num_arguments,
4616                                  SaveFPRegsMode save_doubles) {
4617   // All parameters are on the stack. v0 has the return value after call.
4618
4619   // If the expected number of arguments of the runtime function is
4620   // constant, we check that the actual number of arguments match the
4621   // expectation.
4622   CHECK(f->nargs < 0 || f->nargs == num_arguments);
4623
4624   // TODO(1236192): Most runtime routines don't need the number of
4625   // arguments passed in because it is constant. At some point we
4626   // should remove this need and make the runtime routine entry code
4627   // smarter.
4628   PrepareCEntryArgs(num_arguments);
4629   PrepareCEntryFunction(ExternalReference(f, isolate()));
4630   CEntryStub stub(isolate(), 1, save_doubles);
4631   CallStub(&stub);
4632 }
4633
4634
4635 void MacroAssembler::CallExternalReference(const ExternalReference& ext,
4636                                            int num_arguments,
4637                                            BranchDelaySlot bd) {
4638   PrepareCEntryArgs(num_arguments);
4639   PrepareCEntryFunction(ext);
4640
4641   CEntryStub stub(isolate(), 1);
4642   CallStub(&stub, TypeFeedbackId::None(), al, zero_reg, Operand(zero_reg), bd);
4643 }
4644
4645
4646 void MacroAssembler::TailCallExternalReference(const ExternalReference& ext,
4647                                                int num_arguments,
4648                                                int result_size) {
4649   // TODO(1236192): Most runtime routines don't need the number of
4650   // arguments passed in because it is constant. At some point we
4651   // should remove this need and make the runtime routine entry code
4652   // smarter.
4653   PrepareCEntryArgs(num_arguments);
4654   JumpToExternalReference(ext);
4655 }
4656
4657
4658 void MacroAssembler::TailCallRuntime(Runtime::FunctionId fid,
4659                                      int num_arguments,
4660                                      int result_size) {
4661   TailCallExternalReference(ExternalReference(fid, isolate()),
4662                             num_arguments,
4663                             result_size);
4664 }
4665
4666
4667 void MacroAssembler::JumpToExternalReference(const ExternalReference& builtin,
4668                                              BranchDelaySlot bd) {
4669   PrepareCEntryFunction(builtin);
4670   CEntryStub stub(isolate(), 1);
4671   Jump(stub.GetCode(),
4672        RelocInfo::CODE_TARGET,
4673        al,
4674        zero_reg,
4675        Operand(zero_reg),
4676        bd);
4677 }
4678
4679
4680 void MacroAssembler::InvokeBuiltin(Builtins::JavaScript id,
4681                                    InvokeFlag flag,
4682                                    const CallWrapper& call_wrapper) {
4683   // You can't call a builtin without a valid frame.
4684   DCHECK(flag == JUMP_FUNCTION || has_frame());
4685
4686   GetBuiltinEntry(t9, id);
4687   if (flag == CALL_FUNCTION) {
4688     call_wrapper.BeforeCall(CallSize(t9));
4689     Call(t9);
4690     call_wrapper.AfterCall();
4691   } else {
4692     DCHECK(flag == JUMP_FUNCTION);
4693     Jump(t9);
4694   }
4695 }
4696
4697
4698 void MacroAssembler::GetBuiltinFunction(Register target,
4699                                         Builtins::JavaScript id) {
4700   // Load the builtins object into target register.
4701   lw(target, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
4702   lw(target, FieldMemOperand(target, GlobalObject::kBuiltinsOffset));
4703   // Load the JavaScript builtin function from the builtins object.
4704   lw(target, FieldMemOperand(target,
4705                           JSBuiltinsObject::OffsetOfFunctionWithId(id)));
4706 }
4707
4708
4709 void MacroAssembler::GetBuiltinEntry(Register target, Builtins::JavaScript id) {
4710   DCHECK(!target.is(a1));
4711   GetBuiltinFunction(a1, id);
4712   // Load the code entry point from the builtins object.
4713   lw(target, FieldMemOperand(a1, JSFunction::kCodeEntryOffset));
4714 }
4715
4716
4717 void MacroAssembler::SetCounter(StatsCounter* counter, int value,
4718                                 Register scratch1, Register scratch2) {
4719   if (FLAG_native_code_counters && counter->Enabled()) {
4720     li(scratch1, Operand(value));
4721     li(scratch2, Operand(ExternalReference(counter)));
4722     sw(scratch1, MemOperand(scratch2));
4723   }
4724 }
4725
4726
4727 void MacroAssembler::IncrementCounter(StatsCounter* counter, int value,
4728                                       Register scratch1, Register scratch2) {
4729   DCHECK(value > 0);
4730   if (FLAG_native_code_counters && counter->Enabled()) {
4731     li(scratch2, Operand(ExternalReference(counter)));
4732     lw(scratch1, MemOperand(scratch2));
4733     Addu(scratch1, scratch1, Operand(value));
4734     sw(scratch1, MemOperand(scratch2));
4735   }
4736 }
4737
4738
4739 void MacroAssembler::DecrementCounter(StatsCounter* counter, int value,
4740                                       Register scratch1, Register scratch2) {
4741   DCHECK(value > 0);
4742   if (FLAG_native_code_counters && counter->Enabled()) {
4743     li(scratch2, Operand(ExternalReference(counter)));
4744     lw(scratch1, MemOperand(scratch2));
4745     Subu(scratch1, scratch1, Operand(value));
4746     sw(scratch1, MemOperand(scratch2));
4747   }
4748 }
4749
4750
4751 // -----------------------------------------------------------------------------
4752 // Debugging.
4753
4754 void MacroAssembler::Assert(Condition cc, BailoutReason reason,
4755                             Register rs, Operand rt) {
4756   if (emit_debug_code())
4757     Check(cc, reason, rs, rt);
4758 }
4759
4760
4761 void MacroAssembler::AssertFastElements(Register elements) {
4762   if (emit_debug_code()) {
4763     DCHECK(!elements.is(at));
4764     Label ok;
4765     push(elements);
4766     lw(elements, FieldMemOperand(elements, HeapObject::kMapOffset));
4767     LoadRoot(at, Heap::kFixedArrayMapRootIndex);
4768     Branch(&ok, eq, elements, Operand(at));
4769     LoadRoot(at, Heap::kFixedDoubleArrayMapRootIndex);
4770     Branch(&ok, eq, elements, Operand(at));
4771     LoadRoot(at, Heap::kFixedCOWArrayMapRootIndex);
4772     Branch(&ok, eq, elements, Operand(at));
4773     Abort(kJSObjectWithFastElementsMapHasSlowElements);
4774     bind(&ok);
4775     pop(elements);
4776   }
4777 }
4778
4779
4780 void MacroAssembler::Check(Condition cc, BailoutReason reason,
4781                            Register rs, Operand rt) {
4782   Label L;
4783   Branch(&L, cc, rs, rt);
4784   Abort(reason);
4785   // Will not return here.
4786   bind(&L);
4787 }
4788
4789
4790 void MacroAssembler::Abort(BailoutReason reason) {
4791   Label abort_start;
4792   bind(&abort_start);
4793 #ifdef DEBUG
4794   const char* msg = GetBailoutReason(reason);
4795   if (msg != NULL) {
4796     RecordComment("Abort message: ");
4797     RecordComment(msg);
4798   }
4799
4800   if (FLAG_trap_on_abort) {
4801     stop(msg);
4802     return;
4803   }
4804 #endif
4805
4806   li(a0, Operand(Smi::FromInt(reason)));
4807   push(a0);
4808   // Disable stub call restrictions to always allow calls to abort.
4809   if (!has_frame_) {
4810     // We don't actually want to generate a pile of code for this, so just
4811     // claim there is a stack frame, without generating one.
4812     FrameScope scope(this, StackFrame::NONE);
4813     CallRuntime(Runtime::kAbort, 1);
4814   } else {
4815     CallRuntime(Runtime::kAbort, 1);
4816   }
4817   // Will not return here.
4818   if (is_trampoline_pool_blocked()) {
4819     // If the calling code cares about the exact number of
4820     // instructions generated, we insert padding here to keep the size
4821     // of the Abort macro constant.
4822     // Currently in debug mode with debug_code enabled the number of
4823     // generated instructions is 10, so we use this as a maximum value.
4824     static const int kExpectedAbortInstructions = 10;
4825     int abort_instructions = InstructionsGeneratedSince(&abort_start);
4826     DCHECK(abort_instructions <= kExpectedAbortInstructions);
4827     while (abort_instructions++ < kExpectedAbortInstructions) {
4828       nop();
4829     }
4830   }
4831 }
4832
4833
4834 void MacroAssembler::LoadContext(Register dst, int context_chain_length) {
4835   if (context_chain_length > 0) {
4836     // Move up the chain of contexts to the context containing the slot.
4837     lw(dst, MemOperand(cp, Context::SlotOffset(Context::PREVIOUS_INDEX)));
4838     for (int i = 1; i < context_chain_length; i++) {
4839       lw(dst, MemOperand(dst, Context::SlotOffset(Context::PREVIOUS_INDEX)));
4840     }
4841   } else {
4842     // Slot is in the current function context.  Move it into the
4843     // destination register in case we store into it (the write barrier
4844     // cannot be allowed to destroy the context in esi).
4845     Move(dst, cp);
4846   }
4847 }
4848
4849
4850 void MacroAssembler::LoadTransitionedArrayMapConditional(
4851     ElementsKind expected_kind,
4852     ElementsKind transitioned_kind,
4853     Register map_in_out,
4854     Register scratch,
4855     Label* no_map_match) {
4856   // Load the global or builtins object from the current context.
4857   lw(scratch,
4858      MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
4859   lw(scratch, FieldMemOperand(scratch, GlobalObject::kNativeContextOffset));
4860
4861   // Check that the function's map is the same as the expected cached map.
4862   lw(scratch,
4863      MemOperand(scratch,
4864                 Context::SlotOffset(Context::JS_ARRAY_MAPS_INDEX)));
4865   size_t offset = expected_kind * kPointerSize +
4866       FixedArrayBase::kHeaderSize;
4867   lw(at, FieldMemOperand(scratch, offset));
4868   Branch(no_map_match, ne, map_in_out, Operand(at));
4869
4870   // Use the transitioned cached map.
4871   offset = transitioned_kind * kPointerSize +
4872       FixedArrayBase::kHeaderSize;
4873   lw(map_in_out, FieldMemOperand(scratch, offset));
4874 }
4875
4876
4877 void MacroAssembler::LoadGlobalFunction(int index, Register function) {
4878   // Load the global or builtins object from the current context.
4879   lw(function,
4880      MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
4881   // Load the native context from the global or builtins object.
4882   lw(function, FieldMemOperand(function,
4883                                GlobalObject::kNativeContextOffset));
4884   // Load the function from the native context.
4885   lw(function, MemOperand(function, Context::SlotOffset(index)));
4886 }
4887
4888
4889 void MacroAssembler::LoadGlobalFunctionInitialMap(Register function,
4890                                                   Register map,
4891                                                   Register scratch) {
4892   // Load the initial map. The global functions all have initial maps.
4893   lw(map, FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
4894   if (emit_debug_code()) {
4895     Label ok, fail;
4896     CheckMap(map, scratch, Heap::kMetaMapRootIndex, &fail, DO_SMI_CHECK);
4897     Branch(&ok);
4898     bind(&fail);
4899     Abort(kGlobalFunctionsMustHaveInitialMap);
4900     bind(&ok);
4901   }
4902 }
4903
4904
4905 void MacroAssembler::StubPrologue() {
4906     Push(ra, fp, cp);
4907     Push(Smi::FromInt(StackFrame::STUB));
4908     // Adjust FP to point to saved FP.
4909     Addu(fp, sp, Operand(StandardFrameConstants::kFixedFrameSizeFromFp));
4910 }
4911
4912
4913 void MacroAssembler::Prologue(bool code_pre_aging) {
4914   PredictableCodeSizeScope predictible_code_size_scope(
4915       this, kNoCodeAgeSequenceLength);
4916   // The following three instructions must remain together and unmodified
4917   // for code aging to work properly.
4918   if (code_pre_aging) {
4919     // Pre-age the code.
4920     Code* stub = Code::GetPreAgedCodeAgeStub(isolate());
4921     nop(Assembler::CODE_AGE_MARKER_NOP);
4922     // Load the stub address to t9 and call it,
4923     // GetCodeAgeAndParity() extracts the stub address from this instruction.
4924     li(t9,
4925        Operand(reinterpret_cast<uint32_t>(stub->instruction_start())),
4926        CONSTANT_SIZE);
4927     nop();  // Prevent jalr to jal optimization.
4928     jalr(t9, a0);
4929     nop();  // Branch delay slot nop.
4930     nop();  // Pad the empty space.
4931   } else {
4932     Push(ra, fp, cp, a1);
4933     nop(Assembler::CODE_AGE_SEQUENCE_NOP);
4934     // Adjust fp to point to caller's fp.
4935     Addu(fp, sp, Operand(StandardFrameConstants::kFixedFrameSizeFromFp));
4936   }
4937 }
4938
4939
4940 void MacroAssembler::EnterFrame(StackFrame::Type type,
4941                                 bool load_constant_pool_pointer_reg) {
4942   // Out-of-line constant pool not implemented on mips.
4943   UNREACHABLE();
4944 }
4945
4946
4947 void MacroAssembler::EnterFrame(StackFrame::Type type) {
4948   addiu(sp, sp, -5 * kPointerSize);
4949   li(t8, Operand(Smi::FromInt(type)));
4950   li(t9, Operand(CodeObject()), CONSTANT_SIZE);
4951   sw(ra, MemOperand(sp, 4 * kPointerSize));
4952   sw(fp, MemOperand(sp, 3 * kPointerSize));
4953   sw(cp, MemOperand(sp, 2 * kPointerSize));
4954   sw(t8, MemOperand(sp, 1 * kPointerSize));
4955   sw(t9, MemOperand(sp, 0 * kPointerSize));
4956   // Adjust FP to point to saved FP.
4957   Addu(fp, sp,
4958        Operand(StandardFrameConstants::kFixedFrameSizeFromFp + kPointerSize));
4959 }
4960
4961
4962 void MacroAssembler::LeaveFrame(StackFrame::Type type) {
4963   mov(sp, fp);
4964   lw(fp, MemOperand(sp, 0 * kPointerSize));
4965   lw(ra, MemOperand(sp, 1 * kPointerSize));
4966   addiu(sp, sp, 2 * kPointerSize);
4967 }
4968
4969
4970 void MacroAssembler::EnterExitFrame(bool save_doubles,
4971                                     int stack_space) {
4972   // Set up the frame structure on the stack.
4973   STATIC_ASSERT(2 * kPointerSize == ExitFrameConstants::kCallerSPDisplacement);
4974   STATIC_ASSERT(1 * kPointerSize == ExitFrameConstants::kCallerPCOffset);
4975   STATIC_ASSERT(0 * kPointerSize == ExitFrameConstants::kCallerFPOffset);
4976
4977   // This is how the stack will look:
4978   // fp + 2 (==kCallerSPDisplacement) - old stack's end
4979   // [fp + 1 (==kCallerPCOffset)] - saved old ra
4980   // [fp + 0 (==kCallerFPOffset)] - saved old fp
4981   // [fp - 1 (==kSPOffset)] - sp of the called function
4982   // [fp - 2 (==kCodeOffset)] - CodeObject
4983   // fp - (2 + stack_space + alignment) == sp == [fp - kSPOffset] - top of the
4984   //   new stack (will contain saved ra)
4985
4986   // Save registers.
4987   addiu(sp, sp, -4 * kPointerSize);
4988   sw(ra, MemOperand(sp, 3 * kPointerSize));
4989   sw(fp, MemOperand(sp, 2 * kPointerSize));
4990   addiu(fp, sp, 2 * kPointerSize);  // Set up new frame pointer.
4991
4992   if (emit_debug_code()) {
4993     sw(zero_reg, MemOperand(fp, ExitFrameConstants::kSPOffset));
4994   }
4995
4996   // Accessed from ExitFrame::code_slot.
4997   li(t8, Operand(CodeObject()), CONSTANT_SIZE);
4998   sw(t8, MemOperand(fp, ExitFrameConstants::kCodeOffset));
4999
5000   // Save the frame pointer and the context in top.
5001   li(t8, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
5002   sw(fp, MemOperand(t8));
5003   li(t8, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
5004   sw(cp, MemOperand(t8));
5005
5006   const int frame_alignment = MacroAssembler::ActivationFrameAlignment();
5007   if (save_doubles) {
5008     // The stack  must be allign to 0 modulo 8 for stores with sdc1.
5009     DCHECK(kDoubleSize == frame_alignment);
5010     if (frame_alignment > 0) {
5011       DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
5012       And(sp, sp, Operand(-frame_alignment));  // Align stack.
5013     }
5014     int space = FPURegister::kMaxNumRegisters * kDoubleSize;
5015     Subu(sp, sp, Operand(space));
5016     // Remember: we only need to save every 2nd double FPU value.
5017     for (int i = 0; i < FPURegister::kMaxNumRegisters; i+=2) {
5018       FPURegister reg = FPURegister::from_code(i);
5019       sdc1(reg, MemOperand(sp, i * kDoubleSize));
5020     }
5021   }
5022
5023   // Reserve place for the return address, stack space and an optional slot
5024   // (used by the DirectCEntryStub to hold the return value if a struct is
5025   // returned) and align the frame preparing for calling the runtime function.
5026   DCHECK(stack_space >= 0);
5027   Subu(sp, sp, Operand((stack_space + 2) * kPointerSize));
5028   if (frame_alignment > 0) {
5029     DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
5030     And(sp, sp, Operand(-frame_alignment));  // Align stack.
5031   }
5032
5033   // Set the exit frame sp value to point just before the return address
5034   // location.
5035   addiu(at, sp, kPointerSize);
5036   sw(at, MemOperand(fp, ExitFrameConstants::kSPOffset));
5037 }
5038
5039
5040 void MacroAssembler::LeaveExitFrame(bool save_doubles, Register argument_count,
5041                                     bool restore_context, bool do_return,
5042                                     bool argument_count_is_length) {
5043   // Optionally restore all double registers.
5044   if (save_doubles) {
5045     // Remember: we only need to restore every 2nd double FPU value.
5046     lw(t8, MemOperand(fp, ExitFrameConstants::kSPOffset));
5047     for (int i = 0; i < FPURegister::kMaxNumRegisters; i+=2) {
5048       FPURegister reg = FPURegister::from_code(i);
5049       ldc1(reg, MemOperand(t8, i  * kDoubleSize + kPointerSize));
5050     }
5051   }
5052
5053   // Clear top frame.
5054   li(t8, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
5055   sw(zero_reg, MemOperand(t8));
5056
5057   // Restore current context from top and clear it in debug mode.
5058   if (restore_context) {
5059     li(t8, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
5060     lw(cp, MemOperand(t8));
5061   }
5062 #ifdef DEBUG
5063   li(t8, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
5064   sw(a3, MemOperand(t8));
5065 #endif
5066
5067   // Pop the arguments, restore registers, and return.
5068   mov(sp, fp);  // Respect ABI stack constraint.
5069   lw(fp, MemOperand(sp, ExitFrameConstants::kCallerFPOffset));
5070   lw(ra, MemOperand(sp, ExitFrameConstants::kCallerPCOffset));
5071
5072   if (argument_count.is_valid()) {
5073     if (argument_count_is_length) {
5074       addu(sp, sp, argument_count);
5075     } else {
5076       sll(t8, argument_count, kPointerSizeLog2);
5077       addu(sp, sp, t8);
5078     }
5079   }
5080
5081   if (do_return) {
5082     Ret(USE_DELAY_SLOT);
5083     // If returning, the instruction in the delay slot will be the addiu below.
5084   }
5085   addiu(sp, sp, 8);
5086 }
5087
5088
5089 void MacroAssembler::InitializeNewString(Register string,
5090                                          Register length,
5091                                          Heap::RootListIndex map_index,
5092                                          Register scratch1,
5093                                          Register scratch2) {
5094   sll(scratch1, length, kSmiTagSize);
5095   LoadRoot(scratch2, map_index);
5096   sw(scratch1, FieldMemOperand(string, String::kLengthOffset));
5097   li(scratch1, Operand(String::kEmptyHashField));
5098   sw(scratch2, FieldMemOperand(string, HeapObject::kMapOffset));
5099   sw(scratch1, FieldMemOperand(string, String::kHashFieldOffset));
5100 }
5101
5102
5103 int MacroAssembler::ActivationFrameAlignment() {
5104 #if V8_HOST_ARCH_MIPS
5105   // Running on the real platform. Use the alignment as mandated by the local
5106   // environment.
5107   // Note: This will break if we ever start generating snapshots on one Mips
5108   // platform for another Mips platform with a different alignment.
5109   return base::OS::ActivationFrameAlignment();
5110 #else  // V8_HOST_ARCH_MIPS
5111   // If we are using the simulator then we should always align to the expected
5112   // alignment. As the simulator is used to generate snapshots we do not know
5113   // if the target platform will need alignment, so this is controlled from a
5114   // flag.
5115   return FLAG_sim_stack_alignment;
5116 #endif  // V8_HOST_ARCH_MIPS
5117 }
5118
5119
5120 void MacroAssembler::AssertStackIsAligned() {
5121   if (emit_debug_code()) {
5122       const int frame_alignment = ActivationFrameAlignment();
5123       const int frame_alignment_mask = frame_alignment - 1;
5124
5125       if (frame_alignment > kPointerSize) {
5126         Label alignment_as_expected;
5127         DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
5128         andi(at, sp, frame_alignment_mask);
5129         Branch(&alignment_as_expected, eq, at, Operand(zero_reg));
5130         // Don't use Check here, as it will call Runtime_Abort re-entering here.
5131         stop("Unexpected stack alignment");
5132         bind(&alignment_as_expected);
5133       }
5134     }
5135 }
5136
5137
5138 void MacroAssembler::JumpIfNotPowerOfTwoOrZero(
5139     Register reg,
5140     Register scratch,
5141     Label* not_power_of_two_or_zero) {
5142   Subu(scratch, reg, Operand(1));
5143   Branch(USE_DELAY_SLOT, not_power_of_two_or_zero, lt,
5144          scratch, Operand(zero_reg));
5145   and_(at, scratch, reg);  // In the delay slot.
5146   Branch(not_power_of_two_or_zero, ne, at, Operand(zero_reg));
5147 }
5148
5149
5150 void MacroAssembler::SmiTagCheckOverflow(Register reg, Register overflow) {
5151   DCHECK(!reg.is(overflow));
5152   mov(overflow, reg);  // Save original value.
5153   SmiTag(reg);
5154   xor_(overflow, overflow, reg);  // Overflow if (value ^ 2 * value) < 0.
5155 }
5156
5157
5158 void MacroAssembler::SmiTagCheckOverflow(Register dst,
5159                                          Register src,
5160                                          Register overflow) {
5161   if (dst.is(src)) {
5162     // Fall back to slower case.
5163     SmiTagCheckOverflow(dst, overflow);
5164   } else {
5165     DCHECK(!dst.is(src));
5166     DCHECK(!dst.is(overflow));
5167     DCHECK(!src.is(overflow));
5168     SmiTag(dst, src);
5169     xor_(overflow, dst, src);  // Overflow if (value ^ 2 * value) < 0.
5170   }
5171 }
5172
5173
5174 void MacroAssembler::UntagAndJumpIfSmi(Register dst,
5175                                        Register src,
5176                                        Label* smi_case) {
5177   JumpIfSmi(src, smi_case, at, USE_DELAY_SLOT);
5178   SmiUntag(dst, src);
5179 }
5180
5181
5182 void MacroAssembler::UntagAndJumpIfNotSmi(Register dst,
5183                                           Register src,
5184                                           Label* non_smi_case) {
5185   JumpIfNotSmi(src, non_smi_case, at, USE_DELAY_SLOT);
5186   SmiUntag(dst, src);
5187 }
5188
5189 void MacroAssembler::JumpIfSmi(Register value,
5190                                Label* smi_label,
5191                                Register scratch,
5192                                BranchDelaySlot bd) {
5193   DCHECK_EQ(0, kSmiTag);
5194   andi(scratch, value, kSmiTagMask);
5195   Branch(bd, smi_label, eq, scratch, Operand(zero_reg));
5196 }
5197
5198 void MacroAssembler::JumpIfNotSmi(Register value,
5199                                   Label* not_smi_label,
5200                                   Register scratch,
5201                                   BranchDelaySlot bd) {
5202   DCHECK_EQ(0, kSmiTag);
5203   andi(scratch, value, kSmiTagMask);
5204   Branch(bd, not_smi_label, ne, scratch, Operand(zero_reg));
5205 }
5206
5207
5208 void MacroAssembler::JumpIfNotBothSmi(Register reg1,
5209                                       Register reg2,
5210                                       Label* on_not_both_smi) {
5211   STATIC_ASSERT(kSmiTag == 0);
5212   DCHECK_EQ(1, kSmiTagMask);
5213   or_(at, reg1, reg2);
5214   JumpIfNotSmi(at, on_not_both_smi);
5215 }
5216
5217
5218 void MacroAssembler::JumpIfEitherSmi(Register reg1,
5219                                      Register reg2,
5220                                      Label* on_either_smi) {
5221   STATIC_ASSERT(kSmiTag == 0);
5222   DCHECK_EQ(1, kSmiTagMask);
5223   // Both Smi tags must be 1 (not Smi).
5224   and_(at, reg1, reg2);
5225   JumpIfSmi(at, on_either_smi);
5226 }
5227
5228
5229 void MacroAssembler::AssertNotSmi(Register object) {
5230   if (emit_debug_code()) {
5231     STATIC_ASSERT(kSmiTag == 0);
5232     andi(at, object, kSmiTagMask);
5233     Check(ne, kOperandIsASmi, at, Operand(zero_reg));
5234   }
5235 }
5236
5237
5238 void MacroAssembler::AssertSmi(Register object) {
5239   if (emit_debug_code()) {
5240     STATIC_ASSERT(kSmiTag == 0);
5241     andi(at, object, kSmiTagMask);
5242     Check(eq, kOperandIsASmi, at, Operand(zero_reg));
5243   }
5244 }
5245
5246
5247 void MacroAssembler::AssertString(Register object) {
5248   if (emit_debug_code()) {
5249     STATIC_ASSERT(kSmiTag == 0);
5250     SmiTst(object, t0);
5251     Check(ne, kOperandIsASmiAndNotAString, t0, Operand(zero_reg));
5252     push(object);
5253     lw(object, FieldMemOperand(object, HeapObject::kMapOffset));
5254     lbu(object, FieldMemOperand(object, Map::kInstanceTypeOffset));
5255     Check(lo, kOperandIsNotAString, object, Operand(FIRST_NONSTRING_TYPE));
5256     pop(object);
5257   }
5258 }
5259
5260
5261 void MacroAssembler::AssertName(Register object) {
5262   if (emit_debug_code()) {
5263     STATIC_ASSERT(kSmiTag == 0);
5264     SmiTst(object, t0);
5265     Check(ne, kOperandIsASmiAndNotAName, t0, Operand(zero_reg));
5266     push(object);
5267     lw(object, FieldMemOperand(object, HeapObject::kMapOffset));
5268     lbu(object, FieldMemOperand(object, Map::kInstanceTypeOffset));
5269     Check(le, kOperandIsNotAName, object, Operand(LAST_NAME_TYPE));
5270     pop(object);
5271   }
5272 }
5273
5274
5275 void MacroAssembler::AssertUndefinedOrAllocationSite(Register object,
5276                                                      Register scratch) {
5277   if (emit_debug_code()) {
5278     Label done_checking;
5279     AssertNotSmi(object);
5280     LoadRoot(scratch, Heap::kUndefinedValueRootIndex);
5281     Branch(&done_checking, eq, object, Operand(scratch));
5282     push(object);
5283     lw(object, FieldMemOperand(object, HeapObject::kMapOffset));
5284     LoadRoot(scratch, Heap::kAllocationSiteMapRootIndex);
5285     Assert(eq, kExpectedUndefinedOrCell, object, Operand(scratch));
5286     pop(object);
5287     bind(&done_checking);
5288   }
5289 }
5290
5291
5292 void MacroAssembler::AssertIsRoot(Register reg, Heap::RootListIndex index) {
5293   if (emit_debug_code()) {
5294     DCHECK(!reg.is(at));
5295     LoadRoot(at, index);
5296     Check(eq, kHeapNumberMapRegisterClobbered, reg, Operand(at));
5297   }
5298 }
5299
5300
5301 void MacroAssembler::JumpIfNotHeapNumber(Register object,
5302                                          Register heap_number_map,
5303                                          Register scratch,
5304                                          Label* on_not_heap_number) {
5305   lw(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
5306   AssertIsRoot(heap_number_map, Heap::kHeapNumberMapRootIndex);
5307   Branch(on_not_heap_number, ne, scratch, Operand(heap_number_map));
5308 }
5309
5310
5311 void MacroAssembler::LookupNumberStringCache(Register object,
5312                                              Register result,
5313                                              Register scratch1,
5314                                              Register scratch2,
5315                                              Register scratch3,
5316                                              Label* not_found) {
5317   // Use of registers. Register result is used as a temporary.
5318   Register number_string_cache = result;
5319   Register mask = scratch3;
5320
5321   // Load the number string cache.
5322   LoadRoot(number_string_cache, Heap::kNumberStringCacheRootIndex);
5323
5324   // Make the hash mask from the length of the number string cache. It
5325   // contains two elements (number and string) for each cache entry.
5326   lw(mask, FieldMemOperand(number_string_cache, FixedArray::kLengthOffset));
5327   // Divide length by two (length is a smi).
5328   sra(mask, mask, kSmiTagSize + 1);
5329   Addu(mask, mask, -1);  // Make mask.
5330
5331   // Calculate the entry in the number string cache. The hash value in the
5332   // number string cache for smis is just the smi value, and the hash for
5333   // doubles is the xor of the upper and lower words. See
5334   // Heap::GetNumberStringCache.
5335   Label is_smi;
5336   Label load_result_from_cache;
5337   JumpIfSmi(object, &is_smi);
5338   CheckMap(object,
5339            scratch1,
5340            Heap::kHeapNumberMapRootIndex,
5341            not_found,
5342            DONT_DO_SMI_CHECK);
5343
5344   STATIC_ASSERT(8 == kDoubleSize);
5345   Addu(scratch1,
5346        object,
5347        Operand(HeapNumber::kValueOffset - kHeapObjectTag));
5348   lw(scratch2, MemOperand(scratch1, kPointerSize));
5349   lw(scratch1, MemOperand(scratch1, 0));
5350   Xor(scratch1, scratch1, Operand(scratch2));
5351   And(scratch1, scratch1, Operand(mask));
5352
5353   // Calculate address of entry in string cache: each entry consists
5354   // of two pointer sized fields.
5355   sll(scratch1, scratch1, kPointerSizeLog2 + 1);
5356   Addu(scratch1, number_string_cache, scratch1);
5357
5358   Register probe = mask;
5359   lw(probe, FieldMemOperand(scratch1, FixedArray::kHeaderSize));
5360   JumpIfSmi(probe, not_found);
5361   ldc1(f12, FieldMemOperand(object, HeapNumber::kValueOffset));
5362   ldc1(f14, FieldMemOperand(probe, HeapNumber::kValueOffset));
5363   BranchF(&load_result_from_cache, NULL, eq, f12, f14);
5364   Branch(not_found);
5365
5366   bind(&is_smi);
5367   Register scratch = scratch1;
5368   sra(scratch, object, 1);   // Shift away the tag.
5369   And(scratch, mask, Operand(scratch));
5370
5371   // Calculate address of entry in string cache: each entry consists
5372   // of two pointer sized fields.
5373   sll(scratch, scratch, kPointerSizeLog2 + 1);
5374   Addu(scratch, number_string_cache, scratch);
5375
5376   // Check if the entry is the smi we are looking for.
5377   lw(probe, FieldMemOperand(scratch, FixedArray::kHeaderSize));
5378   Branch(not_found, ne, object, Operand(probe));
5379
5380   // Get the result from the cache.
5381   bind(&load_result_from_cache);
5382   lw(result, FieldMemOperand(scratch, FixedArray::kHeaderSize + kPointerSize));
5383
5384   IncrementCounter(isolate()->counters()->number_to_string_native(),
5385                    1,
5386                    scratch1,
5387                    scratch2);
5388 }
5389
5390
5391 void MacroAssembler::JumpIfNonSmisNotBothSequentialOneByteStrings(
5392     Register first, Register second, Register scratch1, Register scratch2,
5393     Label* failure) {
5394   // Test that both first and second are sequential one-byte strings.
5395   // Assume that they are non-smis.
5396   lw(scratch1, FieldMemOperand(first, HeapObject::kMapOffset));
5397   lw(scratch2, FieldMemOperand(second, HeapObject::kMapOffset));
5398   lbu(scratch1, FieldMemOperand(scratch1, Map::kInstanceTypeOffset));
5399   lbu(scratch2, FieldMemOperand(scratch2, Map::kInstanceTypeOffset));
5400
5401   JumpIfBothInstanceTypesAreNotSequentialOneByte(scratch1, scratch2, scratch1,
5402                                                  scratch2, failure);
5403 }
5404
5405
5406 void MacroAssembler::JumpIfNotBothSequentialOneByteStrings(Register first,
5407                                                            Register second,
5408                                                            Register scratch1,
5409                                                            Register scratch2,
5410                                                            Label* failure) {
5411   // Check that neither is a smi.
5412   STATIC_ASSERT(kSmiTag == 0);
5413   And(scratch1, first, Operand(second));
5414   JumpIfSmi(scratch1, failure);
5415   JumpIfNonSmisNotBothSequentialOneByteStrings(first, second, scratch1,
5416                                                scratch2, failure);
5417 }
5418
5419
5420 void MacroAssembler::JumpIfBothInstanceTypesAreNotSequentialOneByte(
5421     Register first, Register second, Register scratch1, Register scratch2,
5422     Label* failure) {
5423   const int kFlatOneByteStringMask =
5424       kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask;
5425   const int kFlatOneByteStringTag =
5426       kStringTag | kOneByteStringTag | kSeqStringTag;
5427   DCHECK(kFlatOneByteStringTag <= 0xffff);  // Ensure this fits 16-bit immed.
5428   andi(scratch1, first, kFlatOneByteStringMask);
5429   Branch(failure, ne, scratch1, Operand(kFlatOneByteStringTag));
5430   andi(scratch2, second, kFlatOneByteStringMask);
5431   Branch(failure, ne, scratch2, Operand(kFlatOneByteStringTag));
5432 }
5433
5434
5435 void MacroAssembler::JumpIfInstanceTypeIsNotSequentialOneByte(Register type,
5436                                                               Register scratch,
5437                                                               Label* failure) {
5438   const int kFlatOneByteStringMask =
5439       kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask;
5440   const int kFlatOneByteStringTag =
5441       kStringTag | kOneByteStringTag | kSeqStringTag;
5442   And(scratch, type, Operand(kFlatOneByteStringMask));
5443   Branch(failure, ne, scratch, Operand(kFlatOneByteStringTag));
5444 }
5445
5446
5447 static const int kRegisterPassedArguments = 4;
5448
5449 int MacroAssembler::CalculateStackPassedWords(int num_reg_arguments,
5450                                               int num_double_arguments) {
5451   int stack_passed_words = 0;
5452   num_reg_arguments += 2 * num_double_arguments;
5453
5454   // Up to four simple arguments are passed in registers a0..a3.
5455   if (num_reg_arguments > kRegisterPassedArguments) {
5456     stack_passed_words += num_reg_arguments - kRegisterPassedArguments;
5457   }
5458   stack_passed_words += kCArgSlotCount;
5459   return stack_passed_words;
5460 }
5461
5462
5463 void MacroAssembler::EmitSeqStringSetCharCheck(Register string,
5464                                                Register index,
5465                                                Register value,
5466                                                Register scratch,
5467                                                uint32_t encoding_mask) {
5468   Label is_object;
5469   SmiTst(string, at);
5470   Check(ne, kNonObject, at, Operand(zero_reg));
5471
5472   lw(at, FieldMemOperand(string, HeapObject::kMapOffset));
5473   lbu(at, FieldMemOperand(at, Map::kInstanceTypeOffset));
5474
5475   andi(at, at, kStringRepresentationMask | kStringEncodingMask);
5476   li(scratch, Operand(encoding_mask));
5477   Check(eq, kUnexpectedStringType, at, Operand(scratch));
5478
5479   // The index is assumed to be untagged coming in, tag it to compare with the
5480   // string length without using a temp register, it is restored at the end of
5481   // this function.
5482   Label index_tag_ok, index_tag_bad;
5483   TrySmiTag(index, scratch, &index_tag_bad);
5484   Branch(&index_tag_ok);
5485   bind(&index_tag_bad);
5486   Abort(kIndexIsTooLarge);
5487   bind(&index_tag_ok);
5488
5489   lw(at, FieldMemOperand(string, String::kLengthOffset));
5490   Check(lt, kIndexIsTooLarge, index, Operand(at));
5491
5492   DCHECK(Smi::FromInt(0) == 0);
5493   Check(ge, kIndexIsNegative, index, Operand(zero_reg));
5494
5495   SmiUntag(index, index);
5496 }
5497
5498
5499 void MacroAssembler::PrepareCallCFunction(int num_reg_arguments,
5500                                           int num_double_arguments,
5501                                           Register scratch) {
5502   int frame_alignment = ActivationFrameAlignment();
5503
5504   // Up to four simple arguments are passed in registers a0..a3.
5505   // Those four arguments must have reserved argument slots on the stack for
5506   // mips, even though those argument slots are not normally used.
5507   // Remaining arguments are pushed on the stack, above (higher address than)
5508   // the argument slots.
5509   int stack_passed_arguments = CalculateStackPassedWords(
5510       num_reg_arguments, num_double_arguments);
5511   if (frame_alignment > kPointerSize) {
5512     // Make stack end at alignment and make room for num_arguments - 4 words
5513     // and the original value of sp.
5514     mov(scratch, sp);
5515     Subu(sp, sp, Operand((stack_passed_arguments + 1) * kPointerSize));
5516     DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
5517     And(sp, sp, Operand(-frame_alignment));
5518     sw(scratch, MemOperand(sp, stack_passed_arguments * kPointerSize));
5519   } else {
5520     Subu(sp, sp, Operand(stack_passed_arguments * kPointerSize));
5521   }
5522 }
5523
5524
5525 void MacroAssembler::PrepareCallCFunction(int num_reg_arguments,
5526                                           Register scratch) {
5527   PrepareCallCFunction(num_reg_arguments, 0, scratch);
5528 }
5529
5530
5531 void MacroAssembler::CallCFunction(ExternalReference function,
5532                                    int num_reg_arguments,
5533                                    int num_double_arguments) {
5534   li(t8, Operand(function));
5535   CallCFunctionHelper(t8, num_reg_arguments, num_double_arguments);
5536 }
5537
5538
5539 void MacroAssembler::CallCFunction(Register function,
5540                                    int num_reg_arguments,
5541                                    int num_double_arguments) {
5542   CallCFunctionHelper(function, num_reg_arguments, num_double_arguments);
5543 }
5544
5545
5546 void MacroAssembler::CallCFunction(ExternalReference function,
5547                                    int num_arguments) {
5548   CallCFunction(function, num_arguments, 0);
5549 }
5550
5551
5552 void MacroAssembler::CallCFunction(Register function,
5553                                    int num_arguments) {
5554   CallCFunction(function, num_arguments, 0);
5555 }
5556
5557
5558 void MacroAssembler::CallCFunctionHelper(Register function,
5559                                          int num_reg_arguments,
5560                                          int num_double_arguments) {
5561   DCHECK(has_frame());
5562   // Make sure that the stack is aligned before calling a C function unless
5563   // running in the simulator. The simulator has its own alignment check which
5564   // provides more information.
5565   // The argument stots are presumed to have been set up by
5566   // PrepareCallCFunction. The C function must be called via t9, for mips ABI.
5567
5568 #if V8_HOST_ARCH_MIPS
5569   if (emit_debug_code()) {
5570     int frame_alignment = base::OS::ActivationFrameAlignment();
5571     int frame_alignment_mask = frame_alignment - 1;
5572     if (frame_alignment > kPointerSize) {
5573       DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
5574       Label alignment_as_expected;
5575       And(at, sp, Operand(frame_alignment_mask));
5576       Branch(&alignment_as_expected, eq, at, Operand(zero_reg));
5577       // Don't use Check here, as it will call Runtime_Abort possibly
5578       // re-entering here.
5579       stop("Unexpected alignment in CallCFunction");
5580       bind(&alignment_as_expected);
5581     }
5582   }
5583 #endif  // V8_HOST_ARCH_MIPS
5584
5585   // Just call directly. The function called cannot cause a GC, or
5586   // allow preemption, so the return address in the link register
5587   // stays correct.
5588
5589   if (!function.is(t9)) {
5590     mov(t9, function);
5591     function = t9;
5592   }
5593
5594   Call(function);
5595
5596   int stack_passed_arguments = CalculateStackPassedWords(
5597       num_reg_arguments, num_double_arguments);
5598
5599   if (base::OS::ActivationFrameAlignment() > kPointerSize) {
5600     lw(sp, MemOperand(sp, stack_passed_arguments * kPointerSize));
5601   } else {
5602     Addu(sp, sp, Operand(stack_passed_arguments * sizeof(kPointerSize)));
5603   }
5604 }
5605
5606
5607 #undef BRANCH_ARGS_CHECK
5608
5609
5610 void MacroAssembler::PatchRelocatedValue(Register li_location,
5611                                          Register scratch,
5612                                          Register new_value) {
5613   lw(scratch, MemOperand(li_location));
5614   // At this point scratch is a lui(at, ...) instruction.
5615   if (emit_debug_code()) {
5616     And(scratch, scratch, kOpcodeMask);
5617     Check(eq, kTheInstructionToPatchShouldBeALui,
5618         scratch, Operand(LUI));
5619     lw(scratch, MemOperand(li_location));
5620   }
5621   srl(t9, new_value, kImm16Bits);
5622   Ins(scratch, t9, 0, kImm16Bits);
5623   sw(scratch, MemOperand(li_location));
5624
5625   lw(scratch, MemOperand(li_location, kInstrSize));
5626   // scratch is now ori(at, ...).
5627   if (emit_debug_code()) {
5628     And(scratch, scratch, kOpcodeMask);
5629     Check(eq, kTheInstructionToPatchShouldBeAnOri,
5630         scratch, Operand(ORI));
5631     lw(scratch, MemOperand(li_location, kInstrSize));
5632   }
5633   Ins(scratch, new_value, 0, kImm16Bits);
5634   sw(scratch, MemOperand(li_location, kInstrSize));
5635
5636   // Update the I-cache so the new lui and ori can be executed.
5637   FlushICache(li_location, 2);
5638 }
5639
5640 void MacroAssembler::GetRelocatedValue(Register li_location,
5641                                        Register value,
5642                                        Register scratch) {
5643   lw(value, MemOperand(li_location));
5644   if (emit_debug_code()) {
5645     And(value, value, kOpcodeMask);
5646     Check(eq, kTheInstructionShouldBeALui,
5647         value, Operand(LUI));
5648     lw(value, MemOperand(li_location));
5649   }
5650
5651   // value now holds a lui instruction. Extract the immediate.
5652   sll(value, value, kImm16Bits);
5653
5654   lw(scratch, MemOperand(li_location, kInstrSize));
5655   if (emit_debug_code()) {
5656     And(scratch, scratch, kOpcodeMask);
5657     Check(eq, kTheInstructionShouldBeAnOri,
5658         scratch, Operand(ORI));
5659     lw(scratch, MemOperand(li_location, kInstrSize));
5660   }
5661   // "scratch" now holds an ori instruction. Extract the immediate.
5662   andi(scratch, scratch, kImm16Mask);
5663
5664   // Merge the results.
5665   or_(value, value, scratch);
5666 }
5667
5668
5669 void MacroAssembler::CheckPageFlag(
5670     Register object,
5671     Register scratch,
5672     int mask,
5673     Condition cc,
5674     Label* condition_met) {
5675   And(scratch, object, Operand(~Page::kPageAlignmentMask));
5676   lw(scratch, MemOperand(scratch, MemoryChunk::kFlagsOffset));
5677   And(scratch, scratch, Operand(mask));
5678   Branch(condition_met, cc, scratch, Operand(zero_reg));
5679 }
5680
5681
5682 void MacroAssembler::JumpIfBlack(Register object,
5683                                  Register scratch0,
5684                                  Register scratch1,
5685                                  Label* on_black) {
5686   HasColor(object, scratch0, scratch1, on_black, 1, 0);  // kBlackBitPattern.
5687   DCHECK(strcmp(Marking::kBlackBitPattern, "10") == 0);
5688 }
5689
5690
5691 void MacroAssembler::HasColor(Register object,
5692                               Register bitmap_scratch,
5693                               Register mask_scratch,
5694                               Label* has_color,
5695                               int first_bit,
5696                               int second_bit) {
5697   DCHECK(!AreAliased(object, bitmap_scratch, mask_scratch, t8));
5698   DCHECK(!AreAliased(object, bitmap_scratch, mask_scratch, t9));
5699
5700   GetMarkBits(object, bitmap_scratch, mask_scratch);
5701
5702   Label other_color, word_boundary;
5703   lw(t9, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
5704   And(t8, t9, Operand(mask_scratch));
5705   Branch(&other_color, first_bit == 1 ? eq : ne, t8, Operand(zero_reg));
5706   // Shift left 1 by adding.
5707   Addu(mask_scratch, mask_scratch, Operand(mask_scratch));
5708   Branch(&word_boundary, eq, mask_scratch, Operand(zero_reg));
5709   And(t8, t9, Operand(mask_scratch));
5710   Branch(has_color, second_bit == 1 ? ne : eq, t8, Operand(zero_reg));
5711   jmp(&other_color);
5712
5713   bind(&word_boundary);
5714   lw(t9, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize + kPointerSize));
5715   And(t9, t9, Operand(1));
5716   Branch(has_color, second_bit == 1 ? ne : eq, t9, Operand(zero_reg));
5717   bind(&other_color);
5718 }
5719
5720
5721 // Detect some, but not all, common pointer-free objects.  This is used by the
5722 // incremental write barrier which doesn't care about oddballs (they are always
5723 // marked black immediately so this code is not hit).
5724 void MacroAssembler::JumpIfDataObject(Register value,
5725                                       Register scratch,
5726                                       Label* not_data_object) {
5727   DCHECK(!AreAliased(value, scratch, t8, no_reg));
5728   Label is_data_object;
5729   lw(scratch, FieldMemOperand(value, HeapObject::kMapOffset));
5730   LoadRoot(t8, Heap::kHeapNumberMapRootIndex);
5731   Branch(&is_data_object, eq, t8, Operand(scratch));
5732   DCHECK(kIsIndirectStringTag == 1 && kIsIndirectStringMask == 1);
5733   DCHECK(kNotStringTag == 0x80 && kIsNotStringMask == 0x80);
5734   // If it's a string and it's not a cons string then it's an object containing
5735   // no GC pointers.
5736   lbu(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
5737   And(t8, scratch, Operand(kIsIndirectStringMask | kIsNotStringMask));
5738   Branch(not_data_object, ne, t8, Operand(zero_reg));
5739   bind(&is_data_object);
5740 }
5741
5742
5743 void MacroAssembler::GetMarkBits(Register addr_reg,
5744                                  Register bitmap_reg,
5745                                  Register mask_reg) {
5746   DCHECK(!AreAliased(addr_reg, bitmap_reg, mask_reg, no_reg));
5747   And(bitmap_reg, addr_reg, Operand(~Page::kPageAlignmentMask));
5748   Ext(mask_reg, addr_reg, kPointerSizeLog2, Bitmap::kBitsPerCellLog2);
5749   const int kLowBits = kPointerSizeLog2 + Bitmap::kBitsPerCellLog2;
5750   Ext(t8, addr_reg, kLowBits, kPageSizeBits - kLowBits);
5751   sll(t8, t8, kPointerSizeLog2);
5752   Addu(bitmap_reg, bitmap_reg, t8);
5753   li(t8, Operand(1));
5754   sllv(mask_reg, t8, mask_reg);
5755 }
5756
5757
5758 void MacroAssembler::EnsureNotWhite(
5759     Register value,
5760     Register bitmap_scratch,
5761     Register mask_scratch,
5762     Register load_scratch,
5763     Label* value_is_white_and_not_data) {
5764   DCHECK(!AreAliased(value, bitmap_scratch, mask_scratch, t8));
5765   GetMarkBits(value, bitmap_scratch, mask_scratch);
5766
5767   // If the value is black or grey we don't need to do anything.
5768   DCHECK(strcmp(Marking::kWhiteBitPattern, "00") == 0);
5769   DCHECK(strcmp(Marking::kBlackBitPattern, "10") == 0);
5770   DCHECK(strcmp(Marking::kGreyBitPattern, "11") == 0);
5771   DCHECK(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
5772
5773   Label done;
5774
5775   // Since both black and grey have a 1 in the first position and white does
5776   // not have a 1 there we only need to check one bit.
5777   lw(load_scratch, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
5778   And(t8, mask_scratch, load_scratch);
5779   Branch(&done, ne, t8, Operand(zero_reg));
5780
5781   if (emit_debug_code()) {
5782     // Check for impossible bit pattern.
5783     Label ok;
5784     // sll may overflow, making the check conservative.
5785     sll(t8, mask_scratch, 1);
5786     And(t8, load_scratch, t8);
5787     Branch(&ok, eq, t8, Operand(zero_reg));
5788     stop("Impossible marking bit pattern");
5789     bind(&ok);
5790   }
5791
5792   // Value is white.  We check whether it is data that doesn't need scanning.
5793   // Currently only checks for HeapNumber and non-cons strings.
5794   Register map = load_scratch;  // Holds map while checking type.
5795   Register length = load_scratch;  // Holds length of object after testing type.
5796   Label is_data_object;
5797
5798   // Check for heap-number
5799   lw(map, FieldMemOperand(value, HeapObject::kMapOffset));
5800   LoadRoot(t8, Heap::kHeapNumberMapRootIndex);
5801   {
5802     Label skip;
5803     Branch(&skip, ne, t8, Operand(map));
5804     li(length, HeapNumber::kSize);
5805     Branch(&is_data_object);
5806     bind(&skip);
5807   }
5808
5809   // Check for strings.
5810   DCHECK(kIsIndirectStringTag == 1 && kIsIndirectStringMask == 1);
5811   DCHECK(kNotStringTag == 0x80 && kIsNotStringMask == 0x80);
5812   // If it's a string and it's not a cons string then it's an object containing
5813   // no GC pointers.
5814   Register instance_type = load_scratch;
5815   lbu(instance_type, FieldMemOperand(map, Map::kInstanceTypeOffset));
5816   And(t8, instance_type, Operand(kIsIndirectStringMask | kIsNotStringMask));
5817   Branch(value_is_white_and_not_data, ne, t8, Operand(zero_reg));
5818   // It's a non-indirect (non-cons and non-slice) string.
5819   // If it's external, the length is just ExternalString::kSize.
5820   // Otherwise it's String::kHeaderSize + string->length() * (1 or 2).
5821   // External strings are the only ones with the kExternalStringTag bit
5822   // set.
5823   DCHECK_EQ(0, kSeqStringTag & kExternalStringTag);
5824   DCHECK_EQ(0, kConsStringTag & kExternalStringTag);
5825   And(t8, instance_type, Operand(kExternalStringTag));
5826   {
5827     Label skip;
5828     Branch(&skip, eq, t8, Operand(zero_reg));
5829     li(length, ExternalString::kSize);
5830     Branch(&is_data_object);
5831     bind(&skip);
5832   }
5833
5834   // Sequential string, either Latin1 or UC16.
5835   // For Latin1 (char-size of 1) we shift the smi tag away to get the length.
5836   // For UC16 (char-size of 2) we just leave the smi tag in place, thereby
5837   // getting the length multiplied by 2.
5838   DCHECK(kOneByteStringTag == 4 && kStringEncodingMask == 4);
5839   DCHECK(kSmiTag == 0 && kSmiTagSize == 1);
5840   lw(t9, FieldMemOperand(value, String::kLengthOffset));
5841   And(t8, instance_type, Operand(kStringEncodingMask));
5842   {
5843     Label skip;
5844     Branch(&skip, eq, t8, Operand(zero_reg));
5845     srl(t9, t9, 1);
5846     bind(&skip);
5847   }
5848   Addu(length, t9, Operand(SeqString::kHeaderSize + kObjectAlignmentMask));
5849   And(length, length, Operand(~kObjectAlignmentMask));
5850
5851   bind(&is_data_object);
5852   // Value is a data object, and it is white.  Mark it black.  Since we know
5853   // that the object is white we can make it black by flipping one bit.
5854   lw(t8, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
5855   Or(t8, t8, Operand(mask_scratch));
5856   sw(t8, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
5857
5858   And(bitmap_scratch, bitmap_scratch, Operand(~Page::kPageAlignmentMask));
5859   lw(t8, MemOperand(bitmap_scratch, MemoryChunk::kLiveBytesOffset));
5860   Addu(t8, t8, Operand(length));
5861   sw(t8, MemOperand(bitmap_scratch, MemoryChunk::kLiveBytesOffset));
5862
5863   bind(&done);
5864 }
5865
5866
5867 void MacroAssembler::LoadInstanceDescriptors(Register map,
5868                                              Register descriptors) {
5869   lw(descriptors, FieldMemOperand(map, Map::kDescriptorsOffset));
5870 }
5871
5872
5873 void MacroAssembler::NumberOfOwnDescriptors(Register dst, Register map) {
5874   lw(dst, FieldMemOperand(map, Map::kBitField3Offset));
5875   DecodeField<Map::NumberOfOwnDescriptorsBits>(dst);
5876 }
5877
5878
5879 void MacroAssembler::EnumLength(Register dst, Register map) {
5880   STATIC_ASSERT(Map::EnumLengthBits::kShift == 0);
5881   lw(dst, FieldMemOperand(map, Map::kBitField3Offset));
5882   And(dst, dst, Operand(Map::EnumLengthBits::kMask));
5883   SmiTag(dst);
5884 }
5885
5886
5887 void MacroAssembler::LoadAccessor(Register dst, Register holder,
5888                                   int accessor_index,
5889                                   AccessorComponent accessor) {
5890   lw(dst, FieldMemOperand(holder, HeapObject::kMapOffset));
5891   LoadInstanceDescriptors(dst, dst);
5892   lw(dst,
5893      FieldMemOperand(dst, DescriptorArray::GetValueOffset(accessor_index)));
5894   int offset = accessor == ACCESSOR_GETTER ? AccessorPair::kGetterOffset
5895                                            : AccessorPair::kSetterOffset;
5896   lw(dst, FieldMemOperand(dst, offset));
5897 }
5898
5899
5900 void MacroAssembler::CheckEnumCache(Register null_value, Label* call_runtime) {
5901   Register  empty_fixed_array_value = t2;
5902   LoadRoot(empty_fixed_array_value, Heap::kEmptyFixedArrayRootIndex);
5903   Label next, start;
5904   mov(a2, a0);
5905
5906   // Check if the enum length field is properly initialized, indicating that
5907   // there is an enum cache.
5908   lw(a1, FieldMemOperand(a2, HeapObject::kMapOffset));
5909
5910   EnumLength(a3, a1);
5911   Branch(
5912       call_runtime, eq, a3, Operand(Smi::FromInt(kInvalidEnumCacheSentinel)));
5913
5914   jmp(&start);
5915
5916   bind(&next);
5917   lw(a1, FieldMemOperand(a2, HeapObject::kMapOffset));
5918
5919   // For all objects but the receiver, check that the cache is empty.
5920   EnumLength(a3, a1);
5921   Branch(call_runtime, ne, a3, Operand(Smi::FromInt(0)));
5922
5923   bind(&start);
5924
5925   // Check that there are no elements. Register a2 contains the current JS
5926   // object we've reached through the prototype chain.
5927   Label no_elements;
5928   lw(a2, FieldMemOperand(a2, JSObject::kElementsOffset));
5929   Branch(&no_elements, eq, a2, Operand(empty_fixed_array_value));
5930
5931   // Second chance, the object may be using the empty slow element dictionary.
5932   LoadRoot(at, Heap::kEmptySlowElementDictionaryRootIndex);
5933   Branch(call_runtime, ne, a2, Operand(at));
5934
5935   bind(&no_elements);
5936   lw(a2, FieldMemOperand(a1, Map::kPrototypeOffset));
5937   Branch(&next, ne, a2, Operand(null_value));
5938 }
5939
5940
5941 void MacroAssembler::ClampUint8(Register output_reg, Register input_reg) {
5942   DCHECK(!output_reg.is(input_reg));
5943   Label done;
5944   li(output_reg, Operand(255));
5945   // Normal branch: nop in delay slot.
5946   Branch(&done, gt, input_reg, Operand(output_reg));
5947   // Use delay slot in this branch.
5948   Branch(USE_DELAY_SLOT, &done, lt, input_reg, Operand(zero_reg));
5949   mov(output_reg, zero_reg);  // In delay slot.
5950   mov(output_reg, input_reg);  // Value is in range 0..255.
5951   bind(&done);
5952 }
5953
5954
5955 void MacroAssembler::ClampDoubleToUint8(Register result_reg,
5956                                         DoubleRegister input_reg,
5957                                         DoubleRegister temp_double_reg) {
5958   Label above_zero;
5959   Label done;
5960   Label in_bounds;
5961
5962   Move(temp_double_reg, 0.0);
5963   BranchF(&above_zero, NULL, gt, input_reg, temp_double_reg);
5964
5965   // Double value is less than zero, NaN or Inf, return 0.
5966   mov(result_reg, zero_reg);
5967   Branch(&done);
5968
5969   // Double value is >= 255, return 255.
5970   bind(&above_zero);
5971   Move(temp_double_reg, 255.0);
5972   BranchF(&in_bounds, NULL, le, input_reg, temp_double_reg);
5973   li(result_reg, Operand(255));
5974   Branch(&done);
5975
5976   // In 0-255 range, round and truncate.
5977   bind(&in_bounds);
5978   cvt_w_d(temp_double_reg, input_reg);
5979   mfc1(result_reg, temp_double_reg);
5980   bind(&done);
5981 }
5982
5983
5984 void MacroAssembler::TestJSArrayForAllocationMemento(
5985     Register receiver_reg,
5986     Register scratch_reg,
5987     Label* no_memento_found,
5988     Condition cond,
5989     Label* allocation_memento_present) {
5990   ExternalReference new_space_start =
5991       ExternalReference::new_space_start(isolate());
5992   ExternalReference new_space_allocation_top =
5993       ExternalReference::new_space_allocation_top_address(isolate());
5994   Addu(scratch_reg, receiver_reg,
5995        Operand(JSArray::kSize + AllocationMemento::kSize - kHeapObjectTag));
5996   Branch(no_memento_found, lt, scratch_reg, Operand(new_space_start));
5997   li(at, Operand(new_space_allocation_top));
5998   lw(at, MemOperand(at));
5999   Branch(no_memento_found, gt, scratch_reg, Operand(at));
6000   lw(scratch_reg, MemOperand(scratch_reg, -AllocationMemento::kSize));
6001   if (allocation_memento_present) {
6002     Branch(allocation_memento_present, cond, scratch_reg,
6003            Operand(isolate()->factory()->allocation_memento_map()));
6004   }
6005 }
6006
6007
6008 Register GetRegisterThatIsNotOneOf(Register reg1,
6009                                    Register reg2,
6010                                    Register reg3,
6011                                    Register reg4,
6012                                    Register reg5,
6013                                    Register reg6) {
6014   RegList regs = 0;
6015   if (reg1.is_valid()) regs |= reg1.bit();
6016   if (reg2.is_valid()) regs |= reg2.bit();
6017   if (reg3.is_valid()) regs |= reg3.bit();
6018   if (reg4.is_valid()) regs |= reg4.bit();
6019   if (reg5.is_valid()) regs |= reg5.bit();
6020   if (reg6.is_valid()) regs |= reg6.bit();
6021
6022   for (int i = 0; i < Register::NumAllocatableRegisters(); i++) {
6023     Register candidate = Register::FromAllocationIndex(i);
6024     if (regs & candidate.bit()) continue;
6025     return candidate;
6026   }
6027   UNREACHABLE();
6028   return no_reg;
6029 }
6030
6031
6032 void MacroAssembler::JumpIfDictionaryInPrototypeChain(
6033     Register object,
6034     Register scratch0,
6035     Register scratch1,
6036     Label* found) {
6037   DCHECK(!scratch1.is(scratch0));
6038   Factory* factory = isolate()->factory();
6039   Register current = scratch0;
6040   Label loop_again;
6041
6042   // Scratch contained elements pointer.
6043   Move(current, object);
6044
6045   // Loop based on the map going up the prototype chain.
6046   bind(&loop_again);
6047   lw(current, FieldMemOperand(current, HeapObject::kMapOffset));
6048   lb(scratch1, FieldMemOperand(current, Map::kBitField2Offset));
6049   DecodeField<Map::ElementsKindBits>(scratch1);
6050   Branch(found, eq, scratch1, Operand(DICTIONARY_ELEMENTS));
6051   lw(current, FieldMemOperand(current, Map::kPrototypeOffset));
6052   Branch(&loop_again, ne, current, Operand(factory->null_value()));
6053 }
6054
6055
6056 bool AreAliased(Register reg1,
6057                 Register reg2,
6058                 Register reg3,
6059                 Register reg4,
6060                 Register reg5,
6061                 Register reg6,
6062                 Register reg7,
6063                 Register reg8) {
6064   int n_of_valid_regs = reg1.is_valid() + reg2.is_valid() +
6065       reg3.is_valid() + reg4.is_valid() + reg5.is_valid() + reg6.is_valid() +
6066       reg7.is_valid() + reg8.is_valid();
6067
6068   RegList regs = 0;
6069   if (reg1.is_valid()) regs |= reg1.bit();
6070   if (reg2.is_valid()) regs |= reg2.bit();
6071   if (reg3.is_valid()) regs |= reg3.bit();
6072   if (reg4.is_valid()) regs |= reg4.bit();
6073   if (reg5.is_valid()) regs |= reg5.bit();
6074   if (reg6.is_valid()) regs |= reg6.bit();
6075   if (reg7.is_valid()) regs |= reg7.bit();
6076   if (reg8.is_valid()) regs |= reg8.bit();
6077   int n_of_non_aliasing_regs = NumRegs(regs);
6078
6079   return n_of_valid_regs != n_of_non_aliasing_regs;
6080 }
6081
6082
6083 CodePatcher::CodePatcher(byte* address,
6084                          int instructions,
6085                          FlushICache flush_cache)
6086     : address_(address),
6087       size_(instructions * Assembler::kInstrSize),
6088       masm_(NULL, address, size_ + Assembler::kGap),
6089       flush_cache_(flush_cache) {
6090   // Create a new macro assembler pointing to the address of the code to patch.
6091   // The size is adjusted with kGap on order for the assembler to generate size
6092   // bytes of instructions without failing with buffer size constraints.
6093   DCHECK(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
6094 }
6095
6096
6097 CodePatcher::~CodePatcher() {
6098   // Indicate that code has changed.
6099   if (flush_cache_ == FLUSH) {
6100     CpuFeatures::FlushICache(address_, size_);
6101   }
6102
6103   // Check that the code was patched as expected.
6104   DCHECK(masm_.pc_ == address_ + size_);
6105   DCHECK(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
6106 }
6107
6108
6109 void CodePatcher::Emit(Instr instr) {
6110   masm()->emit(instr);
6111 }
6112
6113
6114 void CodePatcher::Emit(Address addr) {
6115   masm()->emit(reinterpret_cast<Instr>(addr));
6116 }
6117
6118
6119 void CodePatcher::ChangeBranchCondition(Condition cond) {
6120   Instr instr = Assembler::instr_at(masm_.pc_);
6121   DCHECK(Assembler::IsBranch(instr));
6122   uint32_t opcode = Assembler::GetOpcodeField(instr);
6123   // Currently only the 'eq' and 'ne' cond values are supported and the simple
6124   // branch instructions (with opcode being the branch type).
6125   // There are some special cases (see Assembler::IsBranch()) so extending this
6126   // would be tricky.
6127   DCHECK(opcode == BEQ ||
6128          opcode == BNE ||
6129         opcode == BLEZ ||
6130         opcode == BGTZ ||
6131         opcode == BEQL ||
6132         opcode == BNEL ||
6133        opcode == BLEZL ||
6134        opcode == BGTZL);
6135   opcode = (cond == eq) ? BEQ : BNE;
6136   instr = (instr & ~kOpcodeMask) | opcode;
6137   masm_.emit(instr);
6138 }
6139
6140
6141 void MacroAssembler::TruncatingDiv(Register result,
6142                                    Register dividend,
6143                                    int32_t divisor) {
6144   DCHECK(!dividend.is(result));
6145   DCHECK(!dividend.is(at));
6146   DCHECK(!result.is(at));
6147   base::MagicNumbersForDivision<uint32_t> mag =
6148       base::SignedDivisionByConstant(static_cast<uint32_t>(divisor));
6149   li(at, Operand(mag.multiplier));
6150   Mulh(result, dividend, Operand(at));
6151   bool neg = (mag.multiplier & (static_cast<uint32_t>(1) << 31)) != 0;
6152   if (divisor > 0 && neg) {
6153     Addu(result, result, Operand(dividend));
6154   }
6155   if (divisor < 0 && !neg && mag.multiplier > 0) {
6156     Subu(result, result, Operand(dividend));
6157   }
6158   if (mag.shift > 0) sra(result, result, mag.shift);
6159   srl(at, dividend, 31);
6160   Addu(result, result, Operand(at));
6161 }
6162
6163
6164 } }  // namespace v8::internal
6165
6166 #endif  // V8_TARGET_ARCH_MIPS