Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / v8 / src / mips / macro-assembler-mips.h
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 #ifndef V8_MIPS_MACRO_ASSEMBLER_MIPS_H_
6 #define V8_MIPS_MACRO_ASSEMBLER_MIPS_H_
7
8 #include "src/assembler.h"
9 #include "src/globals.h"
10 #include "src/mips/assembler-mips.h"
11
12 namespace v8 {
13 namespace internal {
14
15 // Forward declaration.
16 class JumpTarget;
17
18 // Reserved Register Usage Summary.
19 //
20 // Registers t8, t9, and at are reserved for use by the MacroAssembler.
21 //
22 // The programmer should know that the MacroAssembler may clobber these three,
23 // but won't touch other registers except in special cases.
24 //
25 // Per the MIPS ABI, register t9 must be used for indirect function call
26 // via 'jalr t9' or 'jr t9' instructions. This is relied upon by gcc when
27 // trying to update gp register for position-independent-code. Whenever
28 // MIPS generated code calls C code, it must be via t9 register.
29
30
31 // Flags used for LeaveExitFrame function.
32 enum LeaveExitFrameMode {
33   EMIT_RETURN = true,
34   NO_EMIT_RETURN = false
35 };
36
37 // Flags used for AllocateHeapNumber
38 enum TaggingMode {
39   // Tag the result.
40   TAG_RESULT,
41   // Don't tag
42   DONT_TAG_RESULT
43 };
44
45 // Flags used for the ObjectToDoubleFPURegister function.
46 enum ObjectToDoubleFlags {
47   // No special flags.
48   NO_OBJECT_TO_DOUBLE_FLAGS = 0,
49   // Object is known to be a non smi.
50   OBJECT_NOT_SMI = 1 << 0,
51   // Don't load NaNs or infinities, branch to the non number case instead.
52   AVOID_NANS_AND_INFINITIES = 1 << 1
53 };
54
55 // Allow programmer to use Branch Delay Slot of Branches, Jumps, Calls.
56 enum BranchDelaySlot {
57   USE_DELAY_SLOT,
58   PROTECT
59 };
60
61 // Flags used for the li macro-assembler function.
62 enum LiFlags {
63   // If the constant value can be represented in just 16 bits, then
64   // optimize the li to use a single instruction, rather than lui/ori pair.
65   OPTIMIZE_SIZE = 0,
66   // Always use 2 instructions (lui/ori pair), even if the constant could
67   // be loaded with just one, so that this value is patchable later.
68   CONSTANT_SIZE = 1
69 };
70
71
72 enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET };
73 enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK };
74 enum PointersToHereCheck {
75   kPointersToHereMaybeInteresting,
76   kPointersToHereAreAlwaysInteresting
77 };
78 enum RAStatus { kRAHasNotBeenSaved, kRAHasBeenSaved };
79
80 Register GetRegisterThatIsNotOneOf(Register reg1,
81                                    Register reg2 = no_reg,
82                                    Register reg3 = no_reg,
83                                    Register reg4 = no_reg,
84                                    Register reg5 = no_reg,
85                                    Register reg6 = no_reg);
86
87 bool AreAliased(Register reg1,
88                 Register reg2,
89                 Register reg3 = no_reg,
90                 Register reg4 = no_reg,
91                 Register reg5 = no_reg,
92                 Register reg6 = no_reg,
93                 Register reg7 = no_reg,
94                 Register reg8 = no_reg);
95
96
97 // -----------------------------------------------------------------------------
98 // Static helper functions.
99
100 inline MemOperand ContextOperand(Register context, int index) {
101   return MemOperand(context, Context::SlotOffset(index));
102 }
103
104
105 inline MemOperand GlobalObjectOperand()  {
106   return ContextOperand(cp, Context::GLOBAL_OBJECT_INDEX);
107 }
108
109
110 // Generate a MemOperand for loading a field from an object.
111 inline MemOperand FieldMemOperand(Register object, int offset) {
112   return MemOperand(object, offset - kHeapObjectTag);
113 }
114
115
116 // Generate a MemOperand for storing arguments 5..N on the stack
117 // when calling CallCFunction().
118 inline MemOperand CFunctionArgumentOperand(int index) {
119   DCHECK(index > kCArgSlotCount);
120   // Argument 5 takes the slot just past the four Arg-slots.
121   int offset = (index - 5) * kPointerSize + kCArgsSlotsSize;
122   return MemOperand(sp, offset);
123 }
124
125
126 // MacroAssembler implements a collection of frequently used macros.
127 class MacroAssembler: public Assembler {
128  public:
129   // The isolate parameter can be NULL if the macro assembler should
130   // not use isolate-dependent functionality. In this case, it's the
131   // responsibility of the caller to never invoke such function on the
132   // macro assembler.
133   MacroAssembler(Isolate* isolate, void* buffer, int size);
134
135   // Arguments macros.
136 #define COND_TYPED_ARGS Condition cond, Register r1, const Operand& r2
137 #define COND_ARGS cond, r1, r2
138
139   // Cases when relocation is not needed.
140 #define DECLARE_NORELOC_PROTOTYPE(Name, target_type) \
141   void Name(target_type target, BranchDelaySlot bd = PROTECT); \
142   inline void Name(BranchDelaySlot bd, target_type target) { \
143     Name(target, bd); \
144   } \
145   void Name(target_type target, \
146             COND_TYPED_ARGS, \
147             BranchDelaySlot bd = PROTECT); \
148   inline void Name(BranchDelaySlot bd, \
149                    target_type target, \
150                    COND_TYPED_ARGS) { \
151     Name(target, COND_ARGS, bd); \
152   }
153
154 #define DECLARE_BRANCH_PROTOTYPES(Name) \
155   DECLARE_NORELOC_PROTOTYPE(Name, Label*) \
156   DECLARE_NORELOC_PROTOTYPE(Name, int16_t)
157
158   DECLARE_BRANCH_PROTOTYPES(Branch)
159   DECLARE_BRANCH_PROTOTYPES(BranchAndLink)
160   DECLARE_BRANCH_PROTOTYPES(BranchShort)
161
162 #undef DECLARE_BRANCH_PROTOTYPES
163 #undef COND_TYPED_ARGS
164 #undef COND_ARGS
165
166
167   // Jump, Call, and Ret pseudo instructions implementing inter-working.
168 #define COND_ARGS Condition cond = al, Register rs = zero_reg, \
169   const Operand& rt = Operand(zero_reg), BranchDelaySlot bd = PROTECT
170
171   void Jump(Register target, COND_ARGS);
172   void Jump(intptr_t target, RelocInfo::Mode rmode, COND_ARGS);
173   void Jump(Address target, RelocInfo::Mode rmode, COND_ARGS);
174   void Jump(Handle<Code> code, RelocInfo::Mode rmode, COND_ARGS);
175   static int CallSize(Register target, COND_ARGS);
176   void Call(Register target, COND_ARGS);
177   static int CallSize(Address target, RelocInfo::Mode rmode, COND_ARGS);
178   void Call(Address target, RelocInfo::Mode rmode, COND_ARGS);
179   int CallSize(Handle<Code> code,
180                RelocInfo::Mode rmode = RelocInfo::CODE_TARGET,
181                TypeFeedbackId ast_id = TypeFeedbackId::None(),
182                COND_ARGS);
183   void Call(Handle<Code> code,
184             RelocInfo::Mode rmode = RelocInfo::CODE_TARGET,
185             TypeFeedbackId ast_id = TypeFeedbackId::None(),
186             COND_ARGS);
187   void Ret(COND_ARGS);
188   inline void Ret(BranchDelaySlot bd, Condition cond = al,
189     Register rs = zero_reg, const Operand& rt = Operand(zero_reg)) {
190     Ret(cond, rs, rt, bd);
191   }
192
193   void Branch(Label* L,
194               Condition cond,
195               Register rs,
196               Heap::RootListIndex index,
197               BranchDelaySlot bdslot = PROTECT);
198
199 #undef COND_ARGS
200
201   // Emit code to discard a non-negative number of pointer-sized elements
202   // from the stack, clobbering only the sp register.
203   void Drop(int count,
204             Condition cond = cc_always,
205             Register reg = no_reg,
206             const Operand& op = Operand(no_reg));
207
208   // Trivial case of DropAndRet that utilizes the delay slot and only emits
209   // 2 instructions.
210   void DropAndRet(int drop);
211
212   void DropAndRet(int drop,
213                   Condition cond,
214                   Register reg,
215                   const Operand& op);
216
217   // Swap two registers.  If the scratch register is omitted then a slightly
218   // less efficient form using xor instead of mov is emitted.
219   void Swap(Register reg1, Register reg2, Register scratch = no_reg);
220
221   void Call(Label* target);
222
223   inline void Move(Register dst, Register src) {
224     if (!dst.is(src)) {
225       mov(dst, src);
226     }
227   }
228
229   inline void Move(FPURegister dst, FPURegister src) {
230     if (!dst.is(src)) {
231       mov_d(dst, src);
232     }
233   }
234
235   inline void Move(Register dst_low, Register dst_high, FPURegister src) {
236     mfc1(dst_low, src);
237     mfc1(dst_high, FPURegister::from_code(src.code() + 1));
238   }
239
240   inline void FmoveHigh(Register dst_high, FPURegister src) {
241     mfc1(dst_high, FPURegister::from_code(src.code() + 1));
242   }
243
244   inline void FmoveLow(Register dst_low, FPURegister src) {
245     mfc1(dst_low, src);
246   }
247
248   inline void Move(FPURegister dst, Register src_low, Register src_high) {
249     mtc1(src_low, dst);
250     mtc1(src_high, FPURegister::from_code(dst.code() + 1));
251   }
252
253   // Conditional move.
254   void Move(FPURegister dst, double imm);
255   void Movz(Register rd, Register rs, Register rt);
256   void Movn(Register rd, Register rs, Register rt);
257   void Movt(Register rd, Register rs, uint16_t cc = 0);
258   void Movf(Register rd, Register rs, uint16_t cc = 0);
259
260   void Clz(Register rd, Register rs);
261
262   // Jump unconditionally to given label.
263   // We NEED a nop in the branch delay slot, as it used by v8, for example in
264   // CodeGenerator::ProcessDeferred().
265   // Currently the branch delay slot is filled by the MacroAssembler.
266   // Use rather b(Label) for code generation.
267   void jmp(Label* L) {
268     Branch(L);
269   }
270
271   void Load(Register dst, const MemOperand& src, Representation r);
272   void Store(Register src, const MemOperand& dst, Representation r);
273
274   // Load an object from the root table.
275   void LoadRoot(Register destination,
276                 Heap::RootListIndex index);
277   void LoadRoot(Register destination,
278                 Heap::RootListIndex index,
279                 Condition cond, Register src1, const Operand& src2);
280
281   // Store an object to the root table.
282   void StoreRoot(Register source,
283                  Heap::RootListIndex index);
284   void StoreRoot(Register source,
285                  Heap::RootListIndex index,
286                  Condition cond, Register src1, const Operand& src2);
287
288   // ---------------------------------------------------------------------------
289   // GC Support
290
291   void IncrementalMarkingRecordWriteHelper(Register object,
292                                            Register value,
293                                            Register address);
294
295   enum RememberedSetFinalAction {
296     kReturnAtEnd,
297     kFallThroughAtEnd
298   };
299
300
301   // Record in the remembered set the fact that we have a pointer to new space
302   // at the address pointed to by the addr register.  Only works if addr is not
303   // in new space.
304   void RememberedSetHelper(Register object,  // Used for debug code.
305                            Register addr,
306                            Register scratch,
307                            SaveFPRegsMode save_fp,
308                            RememberedSetFinalAction and_then);
309
310   void CheckPageFlag(Register object,
311                      Register scratch,
312                      int mask,
313                      Condition cc,
314                      Label* condition_met);
315
316   void CheckMapDeprecated(Handle<Map> map,
317                           Register scratch,
318                           Label* if_deprecated);
319
320   // Check if object is in new space.  Jumps if the object is not in new space.
321   // The register scratch can be object itself, but it will be clobbered.
322   void JumpIfNotInNewSpace(Register object,
323                            Register scratch,
324                            Label* branch) {
325     InNewSpace(object, scratch, ne, branch);
326   }
327
328   // Check if object is in new space.  Jumps if the object is in new space.
329   // The register scratch can be object itself, but scratch will be clobbered.
330   void JumpIfInNewSpace(Register object,
331                         Register scratch,
332                         Label* branch) {
333     InNewSpace(object, scratch, eq, branch);
334   }
335
336   // Check if an object has a given incremental marking color.
337   void HasColor(Register object,
338                 Register scratch0,
339                 Register scratch1,
340                 Label* has_color,
341                 int first_bit,
342                 int second_bit);
343
344   void JumpIfBlack(Register object,
345                    Register scratch0,
346                    Register scratch1,
347                    Label* on_black);
348
349   // Checks the color of an object.  If the object is already grey or black
350   // then we just fall through, since it is already live.  If it is white and
351   // we can determine that it doesn't need to be scanned, then we just mark it
352   // black and fall through.  For the rest we jump to the label so the
353   // incremental marker can fix its assumptions.
354   void EnsureNotWhite(Register object,
355                       Register scratch1,
356                       Register scratch2,
357                       Register scratch3,
358                       Label* object_is_white_and_not_data);
359
360   // Detects conservatively whether an object is data-only, i.e. it does need to
361   // be scanned by the garbage collector.
362   void JumpIfDataObject(Register value,
363                         Register scratch,
364                         Label* not_data_object);
365
366   // Notify the garbage collector that we wrote a pointer into an object.
367   // |object| is the object being stored into, |value| is the object being
368   // stored.  value and scratch registers are clobbered by the operation.
369   // The offset is the offset from the start of the object, not the offset from
370   // the tagged HeapObject pointer.  For use with FieldOperand(reg, off).
371   void RecordWriteField(
372       Register object,
373       int offset,
374       Register value,
375       Register scratch,
376       RAStatus ra_status,
377       SaveFPRegsMode save_fp,
378       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
379       SmiCheck smi_check = INLINE_SMI_CHECK,
380       PointersToHereCheck pointers_to_here_check_for_value =
381           kPointersToHereMaybeInteresting);
382
383   // As above, but the offset has the tag presubtracted.  For use with
384   // MemOperand(reg, off).
385   inline void RecordWriteContextSlot(
386       Register context,
387       int offset,
388       Register value,
389       Register scratch,
390       RAStatus ra_status,
391       SaveFPRegsMode save_fp,
392       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
393       SmiCheck smi_check = INLINE_SMI_CHECK,
394       PointersToHereCheck pointers_to_here_check_for_value =
395           kPointersToHereMaybeInteresting) {
396     RecordWriteField(context,
397                      offset + kHeapObjectTag,
398                      value,
399                      scratch,
400                      ra_status,
401                      save_fp,
402                      remembered_set_action,
403                      smi_check,
404                      pointers_to_here_check_for_value);
405   }
406
407   void RecordWriteForMap(
408       Register object,
409       Register map,
410       Register dst,
411       RAStatus ra_status,
412       SaveFPRegsMode save_fp);
413
414   // For a given |object| notify the garbage collector that the slot |address|
415   // has been written.  |value| is the object being stored. The value and
416   // address registers are clobbered by the operation.
417   void RecordWrite(
418       Register object,
419       Register address,
420       Register value,
421       RAStatus ra_status,
422       SaveFPRegsMode save_fp,
423       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
424       SmiCheck smi_check = INLINE_SMI_CHECK,
425       PointersToHereCheck pointers_to_here_check_for_value =
426           kPointersToHereMaybeInteresting);
427
428
429   // ---------------------------------------------------------------------------
430   // Inline caching support.
431
432   // Generate code for checking access rights - used for security checks
433   // on access to global objects across environments. The holder register
434   // is left untouched, whereas both scratch registers are clobbered.
435   void CheckAccessGlobalProxy(Register holder_reg,
436                               Register scratch,
437                               Label* miss);
438
439   void GetNumberHash(Register reg0, Register scratch);
440
441   void LoadFromNumberDictionary(Label* miss,
442                                 Register elements,
443                                 Register key,
444                                 Register result,
445                                 Register reg0,
446                                 Register reg1,
447                                 Register reg2);
448
449
450   inline void MarkCode(NopMarkerTypes type) {
451     nop(type);
452   }
453
454   // Check if the given instruction is a 'type' marker.
455   // i.e. check if it is a sll zero_reg, zero_reg, <type> (referenced as
456   // nop(type)). These instructions are generated to mark special location in
457   // the code, like some special IC code.
458   static inline bool IsMarkedCode(Instr instr, int type) {
459     DCHECK((FIRST_IC_MARKER <= type) && (type < LAST_CODE_MARKER));
460     return IsNop(instr, type);
461   }
462
463
464   static inline int GetCodeMarker(Instr instr) {
465     uint32_t opcode = ((instr & kOpcodeMask));
466     uint32_t rt = ((instr & kRtFieldMask) >> kRtShift);
467     uint32_t rs = ((instr & kRsFieldMask) >> kRsShift);
468     uint32_t sa = ((instr & kSaFieldMask) >> kSaShift);
469
470     // Return <n> if we have a sll zero_reg, zero_reg, n
471     // else return -1.
472     bool sllzz = (opcode == SLL &&
473                   rt == static_cast<uint32_t>(ToNumber(zero_reg)) &&
474                   rs == static_cast<uint32_t>(ToNumber(zero_reg)));
475     int type =
476         (sllzz && FIRST_IC_MARKER <= sa && sa < LAST_CODE_MARKER) ? sa : -1;
477     DCHECK((type == -1) ||
478            ((FIRST_IC_MARKER <= type) && (type < LAST_CODE_MARKER)));
479     return type;
480   }
481
482
483
484   // ---------------------------------------------------------------------------
485   // Allocation support.
486
487   // Allocate an object in new space or old pointer space. The object_size is
488   // specified either in bytes or in words if the allocation flag SIZE_IN_WORDS
489   // is passed. If the space is exhausted control continues at the gc_required
490   // label. The allocated object is returned in result. If the flag
491   // tag_allocated_object is true the result is tagged as as a heap object.
492   // All registers are clobbered also when control continues at the gc_required
493   // label.
494   void Allocate(int object_size,
495                 Register result,
496                 Register scratch1,
497                 Register scratch2,
498                 Label* gc_required,
499                 AllocationFlags flags);
500
501   void Allocate(Register object_size,
502                 Register result,
503                 Register scratch1,
504                 Register scratch2,
505                 Label* gc_required,
506                 AllocationFlags flags);
507
508   // Undo allocation in new space. The object passed and objects allocated after
509   // it will no longer be allocated. The caller must make sure that no pointers
510   // are left to the object(s) no longer allocated as they would be invalid when
511   // allocation is undone.
512   void UndoAllocationInNewSpace(Register object, Register scratch);
513
514
515   void AllocateTwoByteString(Register result,
516                              Register length,
517                              Register scratch1,
518                              Register scratch2,
519                              Register scratch3,
520                              Label* gc_required);
521   void AllocateAsciiString(Register result,
522                            Register length,
523                            Register scratch1,
524                            Register scratch2,
525                            Register scratch3,
526                            Label* gc_required);
527   void AllocateTwoByteConsString(Register result,
528                                  Register length,
529                                  Register scratch1,
530                                  Register scratch2,
531                                  Label* gc_required);
532   void AllocateAsciiConsString(Register result,
533                                Register length,
534                                Register scratch1,
535                                Register scratch2,
536                                Label* gc_required);
537   void AllocateTwoByteSlicedString(Register result,
538                                    Register length,
539                                    Register scratch1,
540                                    Register scratch2,
541                                    Label* gc_required);
542   void AllocateAsciiSlicedString(Register result,
543                                  Register length,
544                                  Register scratch1,
545                                  Register scratch2,
546                                  Label* gc_required);
547
548   // Allocates a heap number or jumps to the gc_required label if the young
549   // space is full and a scavenge is needed. All registers are clobbered also
550   // when control continues at the gc_required label.
551   void AllocateHeapNumber(Register result,
552                           Register scratch1,
553                           Register scratch2,
554                           Register heap_number_map,
555                           Label* gc_required,
556                           TaggingMode tagging_mode = TAG_RESULT,
557                           MutableMode mode = IMMUTABLE);
558   void AllocateHeapNumberWithValue(Register result,
559                                    FPURegister value,
560                                    Register scratch1,
561                                    Register scratch2,
562                                    Label* gc_required);
563
564   // ---------------------------------------------------------------------------
565   // Instruction macros.
566
567 #define DEFINE_INSTRUCTION(instr)                                              \
568   void instr(Register rd, Register rs, const Operand& rt);                     \
569   void instr(Register rd, Register rs, Register rt) {                          \
570     instr(rd, rs, Operand(rt));                                                \
571   }                                                                            \
572   void instr(Register rs, Register rt, int32_t j) {                            \
573     instr(rs, rt, Operand(j));                                                 \
574   }
575
576 #define DEFINE_INSTRUCTION2(instr)                                             \
577   void instr(Register rs, const Operand& rt);                                  \
578   void instr(Register rs, Register rt) {                                       \
579     instr(rs, Operand(rt));                                                    \
580   }                                                                            \
581   void instr(Register rs, int32_t j) {                                         \
582     instr(rs, Operand(j));                                                     \
583   }
584
585   DEFINE_INSTRUCTION(Addu);
586   DEFINE_INSTRUCTION(Subu);
587   DEFINE_INSTRUCTION(Mul);
588   DEFINE_INSTRUCTION2(Mult);
589   DEFINE_INSTRUCTION2(Multu);
590   DEFINE_INSTRUCTION2(Div);
591   DEFINE_INSTRUCTION2(Divu);
592
593   DEFINE_INSTRUCTION(And);
594   DEFINE_INSTRUCTION(Or);
595   DEFINE_INSTRUCTION(Xor);
596   DEFINE_INSTRUCTION(Nor);
597   DEFINE_INSTRUCTION2(Neg);
598
599   DEFINE_INSTRUCTION(Slt);
600   DEFINE_INSTRUCTION(Sltu);
601
602   // MIPS32 R2 instruction macro.
603   DEFINE_INSTRUCTION(Ror);
604
605 #undef DEFINE_INSTRUCTION
606 #undef DEFINE_INSTRUCTION2
607
608   void Pref(int32_t hint, const MemOperand& rs);
609
610
611   // ---------------------------------------------------------------------------
612   // Pseudo-instructions.
613
614   void mov(Register rd, Register rt) { or_(rd, rt, zero_reg); }
615
616   void Ulw(Register rd, const MemOperand& rs);
617   void Usw(Register rd, const MemOperand& rs);
618
619   // Load int32 in the rd register.
620   void li(Register rd, Operand j, LiFlags mode = OPTIMIZE_SIZE);
621   inline void li(Register rd, int32_t j, LiFlags mode = OPTIMIZE_SIZE) {
622     li(rd, Operand(j), mode);
623   }
624   void li(Register dst, Handle<Object> value, LiFlags mode = OPTIMIZE_SIZE);
625
626   // Push multiple registers on the stack.
627   // Registers are saved in numerical order, with higher numbered registers
628   // saved in higher memory addresses.
629   void MultiPush(RegList regs);
630   void MultiPushReversed(RegList regs);
631
632   void MultiPushFPU(RegList regs);
633   void MultiPushReversedFPU(RegList regs);
634
635   void push(Register src) {
636     Addu(sp, sp, Operand(-kPointerSize));
637     sw(src, MemOperand(sp, 0));
638   }
639   void Push(Register src) { push(src); }
640
641   // Push a handle.
642   void Push(Handle<Object> handle);
643   void Push(Smi* smi) { Push(Handle<Smi>(smi, isolate())); }
644
645   // Push two registers. Pushes leftmost register first (to highest address).
646   void Push(Register src1, Register src2) {
647     Subu(sp, sp, Operand(2 * kPointerSize));
648     sw(src1, MemOperand(sp, 1 * kPointerSize));
649     sw(src2, MemOperand(sp, 0 * kPointerSize));
650   }
651
652   // Push three registers. Pushes leftmost register first (to highest address).
653   void Push(Register src1, Register src2, Register src3) {
654     Subu(sp, sp, Operand(3 * kPointerSize));
655     sw(src1, MemOperand(sp, 2 * kPointerSize));
656     sw(src2, MemOperand(sp, 1 * kPointerSize));
657     sw(src3, MemOperand(sp, 0 * kPointerSize));
658   }
659
660   // Push four registers. Pushes leftmost register first (to highest address).
661   void Push(Register src1, Register src2, Register src3, Register src4) {
662     Subu(sp, sp, Operand(4 * kPointerSize));
663     sw(src1, MemOperand(sp, 3 * kPointerSize));
664     sw(src2, MemOperand(sp, 2 * kPointerSize));
665     sw(src3, MemOperand(sp, 1 * kPointerSize));
666     sw(src4, MemOperand(sp, 0 * kPointerSize));
667   }
668
669   void Push(Register src, Condition cond, Register tst1, Register tst2) {
670     // Since we don't have conditional execution we use a Branch.
671     Branch(3, cond, tst1, Operand(tst2));
672     Subu(sp, sp, Operand(kPointerSize));
673     sw(src, MemOperand(sp, 0));
674   }
675
676   // Pops multiple values from the stack and load them in the
677   // registers specified in regs. Pop order is the opposite as in MultiPush.
678   void MultiPop(RegList regs);
679   void MultiPopReversed(RegList regs);
680
681   void MultiPopFPU(RegList regs);
682   void MultiPopReversedFPU(RegList regs);
683
684   void pop(Register dst) {
685     lw(dst, MemOperand(sp, 0));
686     Addu(sp, sp, Operand(kPointerSize));
687   }
688   void Pop(Register dst) { pop(dst); }
689
690   // Pop two registers. Pops rightmost register first (from lower address).
691   void Pop(Register src1, Register src2) {
692     DCHECK(!src1.is(src2));
693     lw(src2, MemOperand(sp, 0 * kPointerSize));
694     lw(src1, MemOperand(sp, 1 * kPointerSize));
695     Addu(sp, sp, 2 * kPointerSize);
696   }
697
698   // Pop three registers. Pops rightmost register first (from lower address).
699   void Pop(Register src1, Register src2, Register src3) {
700     lw(src3, MemOperand(sp, 0 * kPointerSize));
701     lw(src2, MemOperand(sp, 1 * kPointerSize));
702     lw(src1, MemOperand(sp, 2 * kPointerSize));
703     Addu(sp, sp, 3 * kPointerSize);
704   }
705
706   void Pop(uint32_t count = 1) {
707     Addu(sp, sp, Operand(count * kPointerSize));
708   }
709
710   // Push and pop the registers that can hold pointers, as defined by the
711   // RegList constant kSafepointSavedRegisters.
712   void PushSafepointRegisters();
713   void PopSafepointRegisters();
714   // Store value in register src in the safepoint stack slot for
715   // register dst.
716   void StoreToSafepointRegisterSlot(Register src, Register dst);
717   // Load the value of the src register from its safepoint stack slot
718   // into register dst.
719   void LoadFromSafepointRegisterSlot(Register dst, Register src);
720
721   // Flush the I-cache from asm code. You should use CpuFeatures::FlushICache
722   // from C.
723   // Does not handle errors.
724   void FlushICache(Register address, unsigned instructions);
725
726   // MIPS32 R2 instruction macro.
727   void Ins(Register rt, Register rs, uint16_t pos, uint16_t size);
728   void Ext(Register rt, Register rs, uint16_t pos, uint16_t size);
729
730   // ---------------------------------------------------------------------------
731   // FPU macros. These do not handle special cases like NaN or +- inf.
732
733   // Convert unsigned word to double.
734   void Cvt_d_uw(FPURegister fd, FPURegister fs, FPURegister scratch);
735   void Cvt_d_uw(FPURegister fd, Register rs, FPURegister scratch);
736
737   // Convert double to unsigned word.
738   void Trunc_uw_d(FPURegister fd, FPURegister fs, FPURegister scratch);
739   void Trunc_uw_d(FPURegister fd, Register rs, FPURegister scratch);
740
741   void Trunc_w_d(FPURegister fd, FPURegister fs);
742   void Round_w_d(FPURegister fd, FPURegister fs);
743   void Floor_w_d(FPURegister fd, FPURegister fs);
744   void Ceil_w_d(FPURegister fd, FPURegister fs);
745   // Wrapper function for the different cmp/branch types.
746   void BranchF(Label* target,
747                Label* nan,
748                Condition cc,
749                FPURegister cmp1,
750                FPURegister cmp2,
751                BranchDelaySlot bd = PROTECT);
752
753   // Alternate (inline) version for better readability with USE_DELAY_SLOT.
754   inline void BranchF(BranchDelaySlot bd,
755                       Label* target,
756                       Label* nan,
757                       Condition cc,
758                       FPURegister cmp1,
759                       FPURegister cmp2) {
760     BranchF(target, nan, cc, cmp1, cmp2, bd);
761   }
762
763   // Truncates a double using a specific rounding mode, and writes the value
764   // to the result register.
765   // The except_flag will contain any exceptions caused by the instruction.
766   // If check_inexact is kDontCheckForInexactConversion, then the inexact
767   // exception is masked.
768   void EmitFPUTruncate(FPURoundingMode rounding_mode,
769                        Register result,
770                        DoubleRegister double_input,
771                        Register scratch,
772                        DoubleRegister double_scratch,
773                        Register except_flag,
774                        CheckForInexactConversion check_inexact
775                            = kDontCheckForInexactConversion);
776
777   // Performs a truncating conversion of a floating point number as used by
778   // the JS bitwise operations. See ECMA-262 9.5: ToInt32. Goes to 'done' if it
779   // succeeds, otherwise falls through if result is saturated. On return
780   // 'result' either holds answer, or is clobbered on fall through.
781   //
782   // Only public for the test code in test-code-stubs-arm.cc.
783   void TryInlineTruncateDoubleToI(Register result,
784                                   DoubleRegister input,
785                                   Label* done);
786
787   // Performs a truncating conversion of a floating point number as used by
788   // the JS bitwise operations. See ECMA-262 9.5: ToInt32.
789   // Exits with 'result' holding the answer.
790   void TruncateDoubleToI(Register result, DoubleRegister double_input);
791
792   // Performs a truncating conversion of a heap number as used by
793   // the JS bitwise operations. See ECMA-262 9.5: ToInt32. 'result' and 'input'
794   // must be different registers. Exits with 'result' holding the answer.
795   void TruncateHeapNumberToI(Register result, Register object);
796
797   // Converts the smi or heap number in object to an int32 using the rules
798   // for ToInt32 as described in ECMAScript 9.5.: the value is truncated
799   // and brought into the range -2^31 .. +2^31 - 1. 'result' and 'input' must be
800   // different registers.
801   void TruncateNumberToI(Register object,
802                          Register result,
803                          Register heap_number_map,
804                          Register scratch,
805                          Label* not_int32);
806
807   // Loads the number from object into dst register.
808   // If |object| is neither smi nor heap number, |not_number| is jumped to
809   // with |object| still intact.
810   void LoadNumber(Register object,
811                   FPURegister dst,
812                   Register heap_number_map,
813                   Register scratch,
814                   Label* not_number);
815
816   // Loads the number from object into double_dst in the double format.
817   // Control will jump to not_int32 if the value cannot be exactly represented
818   // by a 32-bit integer.
819   // Floating point value in the 32-bit integer range that are not exact integer
820   // won't be loaded.
821   void LoadNumberAsInt32Double(Register object,
822                                DoubleRegister double_dst,
823                                Register heap_number_map,
824                                Register scratch1,
825                                Register scratch2,
826                                FPURegister double_scratch,
827                                Label* not_int32);
828
829   // Loads the number from object into dst as a 32-bit integer.
830   // Control will jump to not_int32 if the object cannot be exactly represented
831   // by a 32-bit integer.
832   // Floating point value in the 32-bit integer range that are not exact integer
833   // won't be converted.
834   void LoadNumberAsInt32(Register object,
835                          Register dst,
836                          Register heap_number_map,
837                          Register scratch1,
838                          Register scratch2,
839                          FPURegister double_scratch0,
840                          FPURegister double_scratch1,
841                          Label* not_int32);
842
843   // Enter exit frame.
844   // argc - argument count to be dropped by LeaveExitFrame.
845   // save_doubles - saves FPU registers on stack, currently disabled.
846   // stack_space - extra stack space.
847   void EnterExitFrame(bool save_doubles,
848                       int stack_space = 0);
849
850   // Leave the current exit frame.
851   void LeaveExitFrame(bool save_doubles,
852                       Register arg_count,
853                       bool restore_context,
854                       bool do_return = NO_EMIT_RETURN);
855
856   // Get the actual activation frame alignment for target environment.
857   static int ActivationFrameAlignment();
858
859   // Make sure the stack is aligned. Only emits code in debug mode.
860   void AssertStackIsAligned();
861
862   void LoadContext(Register dst, int context_chain_length);
863
864   // Conditionally load the cached Array transitioned map of type
865   // transitioned_kind from the native context if the map in register
866   // map_in_out is the cached Array map in the native context of
867   // expected_kind.
868   void LoadTransitionedArrayMapConditional(
869       ElementsKind expected_kind,
870       ElementsKind transitioned_kind,
871       Register map_in_out,
872       Register scratch,
873       Label* no_map_match);
874
875   void LoadGlobalFunction(int index, Register function);
876
877   // Load the initial map from the global function. The registers
878   // function and map can be the same, function is then overwritten.
879   void LoadGlobalFunctionInitialMap(Register function,
880                                     Register map,
881                                     Register scratch);
882
883   void InitializeRootRegister() {
884     ExternalReference roots_array_start =
885         ExternalReference::roots_array_start(isolate());
886     li(kRootRegister, Operand(roots_array_start));
887   }
888
889   // -------------------------------------------------------------------------
890   // JavaScript invokes.
891
892   // Invoke the JavaScript function code by either calling or jumping.
893   void InvokeCode(Register code,
894                   const ParameterCount& expected,
895                   const ParameterCount& actual,
896                   InvokeFlag flag,
897                   const CallWrapper& call_wrapper);
898
899   // Invoke the JavaScript function in the given register. Changes the
900   // current context to the context in the function before invoking.
901   void InvokeFunction(Register function,
902                       const ParameterCount& actual,
903                       InvokeFlag flag,
904                       const CallWrapper& call_wrapper);
905
906   void InvokeFunction(Register function,
907                       const ParameterCount& expected,
908                       const ParameterCount& actual,
909                       InvokeFlag flag,
910                       const CallWrapper& call_wrapper);
911
912   void InvokeFunction(Handle<JSFunction> function,
913                       const ParameterCount& expected,
914                       const ParameterCount& actual,
915                       InvokeFlag flag,
916                       const CallWrapper& call_wrapper);
917
918
919   void IsObjectJSObjectType(Register heap_object,
920                             Register map,
921                             Register scratch,
922                             Label* fail);
923
924   void IsInstanceJSObjectType(Register map,
925                               Register scratch,
926                               Label* fail);
927
928   void IsObjectJSStringType(Register object,
929                             Register scratch,
930                             Label* fail);
931
932   void IsObjectNameType(Register object,
933                         Register scratch,
934                         Label* fail);
935
936   // -------------------------------------------------------------------------
937   // Debugger Support.
938
939   void DebugBreak();
940
941   // -------------------------------------------------------------------------
942   // Exception handling.
943
944   // Push a new try handler and link into try handler chain.
945   void PushTryHandler(StackHandler::Kind kind, int handler_index);
946
947   // Unlink the stack handler on top of the stack from the try handler chain.
948   // Must preserve the result register.
949   void PopTryHandler();
950
951   // Passes thrown value to the handler of top of the try handler chain.
952   void Throw(Register value);
953
954   // Propagates an uncatchable exception to the top of the current JS stack's
955   // handler chain.
956   void ThrowUncatchable(Register value);
957
958   // Copies a fixed number of fields of heap objects from src to dst.
959   void CopyFields(Register dst, Register src, RegList temps, int field_count);
960
961   // Copies a number of bytes from src to dst. All registers are clobbered. On
962   // exit src and dst will point to the place just after where the last byte was
963   // read or written and length will be zero.
964   void CopyBytes(Register src,
965                  Register dst,
966                  Register length,
967                  Register scratch);
968
969   // Initialize fields with filler values.  Fields starting at |start_offset|
970   // not including end_offset are overwritten with the value in |filler|.  At
971   // the end the loop, |start_offset| takes the value of |end_offset|.
972   void InitializeFieldsWithFiller(Register start_offset,
973                                   Register end_offset,
974                                   Register filler);
975
976   // -------------------------------------------------------------------------
977   // Support functions.
978
979   // Try to get function prototype of a function and puts the value in
980   // the result register. Checks that the function really is a
981   // function and jumps to the miss label if the fast checks fail. The
982   // function register will be untouched; the other registers may be
983   // clobbered.
984   void TryGetFunctionPrototype(Register function,
985                                Register result,
986                                Register scratch,
987                                Label* miss,
988                                bool miss_on_bound_function = false);
989
990   void GetObjectType(Register function,
991                      Register map,
992                      Register type_reg);
993
994   // Check if a map for a JSObject indicates that the object has fast elements.
995   // Jump to the specified label if it does not.
996   void CheckFastElements(Register map,
997                          Register scratch,
998                          Label* fail);
999
1000   // Check if a map for a JSObject indicates that the object can have both smi
1001   // and HeapObject elements.  Jump to the specified label if it does not.
1002   void CheckFastObjectElements(Register map,
1003                                Register scratch,
1004                                Label* fail);
1005
1006   // Check if a map for a JSObject indicates that the object has fast smi only
1007   // elements.  Jump to the specified label if it does not.
1008   void CheckFastSmiElements(Register map,
1009                             Register scratch,
1010                             Label* fail);
1011
1012   // Check to see if maybe_number can be stored as a double in
1013   // FastDoubleElements. If it can, store it at the index specified by key in
1014   // the FastDoubleElements array elements. Otherwise jump to fail.
1015   void StoreNumberToDoubleElements(Register value_reg,
1016                                    Register key_reg,
1017                                    Register elements_reg,
1018                                    Register scratch1,
1019                                    Register scratch2,
1020                                    Register scratch3,
1021                                    Label* fail,
1022                                    int elements_offset = 0);
1023
1024   // Compare an object's map with the specified map and its transitioned
1025   // elements maps if mode is ALLOW_ELEMENT_TRANSITION_MAPS. Jumps to
1026   // "branch_to" if the result of the comparison is "cond". If multiple map
1027   // compares are required, the compare sequences branches to early_success.
1028   void CompareMapAndBranch(Register obj,
1029                            Register scratch,
1030                            Handle<Map> map,
1031                            Label* early_success,
1032                            Condition cond,
1033                            Label* branch_to);
1034
1035   // As above, but the map of the object is already loaded into the register
1036   // which is preserved by the code generated.
1037   void CompareMapAndBranch(Register obj_map,
1038                            Handle<Map> map,
1039                            Label* early_success,
1040                            Condition cond,
1041                            Label* branch_to);
1042
1043   // Check if the map of an object is equal to a specified map and branch to
1044   // label if not. Skip the smi check if not required (object is known to be a
1045   // heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match
1046   // against maps that are ElementsKind transition maps of the specificed map.
1047   void CheckMap(Register obj,
1048                 Register scratch,
1049                 Handle<Map> map,
1050                 Label* fail,
1051                 SmiCheckType smi_check_type);
1052
1053
1054   void CheckMap(Register obj,
1055                 Register scratch,
1056                 Heap::RootListIndex index,
1057                 Label* fail,
1058                 SmiCheckType smi_check_type);
1059
1060   // Check if the map of an object is equal to a specified map and branch to a
1061   // specified target if equal. Skip the smi check if not required (object is
1062   // known to be a heap object)
1063   void DispatchMap(Register obj,
1064                    Register scratch,
1065                    Handle<Map> map,
1066                    Handle<Code> success,
1067                    SmiCheckType smi_check_type);
1068
1069
1070   // Load and check the instance type of an object for being a string.
1071   // Loads the type into the second argument register.
1072   // Returns a condition that will be enabled if the object was a string.
1073   Condition IsObjectStringType(Register obj,
1074                                Register type,
1075                                Register result) {
1076     lw(type, FieldMemOperand(obj, HeapObject::kMapOffset));
1077     lbu(type, FieldMemOperand(type, Map::kInstanceTypeOffset));
1078     And(type, type, Operand(kIsNotStringMask));
1079     DCHECK_EQ(0, kStringTag);
1080     return eq;
1081   }
1082
1083
1084   // Picks out an array index from the hash field.
1085   // Register use:
1086   //   hash - holds the index's hash. Clobbered.
1087   //   index - holds the overwritten index on exit.
1088   void IndexFromHash(Register hash, Register index);
1089
1090   // Get the number of least significant bits from a register.
1091   void GetLeastBitsFromSmi(Register dst, Register src, int num_least_bits);
1092   void GetLeastBitsFromInt32(Register dst, Register src, int mun_least_bits);
1093
1094   // Load the value of a number object into a FPU double register. If the
1095   // object is not a number a jump to the label not_number is performed
1096   // and the FPU double register is unchanged.
1097   void ObjectToDoubleFPURegister(
1098       Register object,
1099       FPURegister value,
1100       Register scratch1,
1101       Register scratch2,
1102       Register heap_number_map,
1103       Label* not_number,
1104       ObjectToDoubleFlags flags = NO_OBJECT_TO_DOUBLE_FLAGS);
1105
1106   // Load the value of a smi object into a FPU double register. The register
1107   // scratch1 can be the same register as smi in which case smi will hold the
1108   // untagged value afterwards.
1109   void SmiToDoubleFPURegister(Register smi,
1110                               FPURegister value,
1111                               Register scratch1);
1112
1113   // -------------------------------------------------------------------------
1114   // Overflow handling functions.
1115   // Usage: first call the appropriate arithmetic function, then call one of the
1116   // jump functions with the overflow_dst register as the second parameter.
1117
1118   void AdduAndCheckForOverflow(Register dst,
1119                                Register left,
1120                                Register right,
1121                                Register overflow_dst,
1122                                Register scratch = at);
1123
1124   void SubuAndCheckForOverflow(Register dst,
1125                                Register left,
1126                                Register right,
1127                                Register overflow_dst,
1128                                Register scratch = at);
1129
1130   void BranchOnOverflow(Label* label,
1131                         Register overflow_check,
1132                         BranchDelaySlot bd = PROTECT) {
1133     Branch(label, lt, overflow_check, Operand(zero_reg), bd);
1134   }
1135
1136   void BranchOnNoOverflow(Label* label,
1137                           Register overflow_check,
1138                           BranchDelaySlot bd = PROTECT) {
1139     Branch(label, ge, overflow_check, Operand(zero_reg), bd);
1140   }
1141
1142   void RetOnOverflow(Register overflow_check, BranchDelaySlot bd = PROTECT) {
1143     Ret(lt, overflow_check, Operand(zero_reg), bd);
1144   }
1145
1146   void RetOnNoOverflow(Register overflow_check, BranchDelaySlot bd = PROTECT) {
1147     Ret(ge, overflow_check, Operand(zero_reg), bd);
1148   }
1149
1150   // -------------------------------------------------------------------------
1151   // Runtime calls.
1152
1153   // See comments at the beginning of CEntryStub::Generate.
1154   inline void PrepareCEntryArgs(int num_args) {
1155     li(s0, num_args);
1156     li(s1, (num_args - 1) * kPointerSize);
1157   }
1158
1159   inline void PrepareCEntryFunction(const ExternalReference& ref) {
1160     li(s2, Operand(ref));
1161   }
1162
1163 #define COND_ARGS Condition cond = al, Register rs = zero_reg, \
1164 const Operand& rt = Operand(zero_reg), BranchDelaySlot bd = PROTECT
1165
1166   // Call a code stub.
1167   void CallStub(CodeStub* stub,
1168                 TypeFeedbackId ast_id = TypeFeedbackId::None(),
1169                 COND_ARGS);
1170
1171   // Tail call a code stub (jump).
1172   void TailCallStub(CodeStub* stub, COND_ARGS);
1173
1174 #undef COND_ARGS
1175
1176   void CallJSExitStub(CodeStub* stub);
1177
1178   // Call a runtime routine.
1179   void CallRuntime(const Runtime::Function* f,
1180                    int num_arguments,
1181                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
1182   void CallRuntimeSaveDoubles(Runtime::FunctionId id) {
1183     const Runtime::Function* function = Runtime::FunctionForId(id);
1184     CallRuntime(function, function->nargs, kSaveFPRegs);
1185   }
1186
1187   // Convenience function: Same as above, but takes the fid instead.
1188   void CallRuntime(Runtime::FunctionId id,
1189                    int num_arguments,
1190                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
1191     CallRuntime(Runtime::FunctionForId(id), num_arguments, save_doubles);
1192   }
1193
1194   // Convenience function: call an external reference.
1195   void CallExternalReference(const ExternalReference& ext,
1196                              int num_arguments,
1197                              BranchDelaySlot bd = PROTECT);
1198
1199   // Tail call of a runtime routine (jump).
1200   // Like JumpToExternalReference, but also takes care of passing the number
1201   // of parameters.
1202   void TailCallExternalReference(const ExternalReference& ext,
1203                                  int num_arguments,
1204                                  int result_size);
1205
1206   // Convenience function: tail call a runtime routine (jump).
1207   void TailCallRuntime(Runtime::FunctionId fid,
1208                        int num_arguments,
1209                        int result_size);
1210
1211   int CalculateStackPassedWords(int num_reg_arguments,
1212                                 int num_double_arguments);
1213
1214   // Before calling a C-function from generated code, align arguments on stack
1215   // and add space for the four mips argument slots.
1216   // After aligning the frame, non-register arguments must be stored on the
1217   // stack, after the argument-slots using helper: CFunctionArgumentOperand().
1218   // The argument count assumes all arguments are word sized.
1219   // Some compilers/platforms require the stack to be aligned when calling
1220   // C++ code.
1221   // Needs a scratch register to do some arithmetic. This register will be
1222   // trashed.
1223   void PrepareCallCFunction(int num_reg_arguments,
1224                             int num_double_registers,
1225                             Register scratch);
1226   void PrepareCallCFunction(int num_reg_arguments,
1227                             Register scratch);
1228
1229   // Arguments 1-4 are placed in registers a0 thru a3 respectively.
1230   // Arguments 5..n are stored to stack using following:
1231   //  sw(t0, CFunctionArgumentOperand(5));
1232
1233   // Calls a C function and cleans up the space for arguments allocated
1234   // by PrepareCallCFunction. The called function is not allowed to trigger a
1235   // garbage collection, since that might move the code and invalidate the
1236   // return address (unless this is somehow accounted for by the called
1237   // function).
1238   void CallCFunction(ExternalReference function, int num_arguments);
1239   void CallCFunction(Register function, int num_arguments);
1240   void CallCFunction(ExternalReference function,
1241                      int num_reg_arguments,
1242                      int num_double_arguments);
1243   void CallCFunction(Register function,
1244                      int num_reg_arguments,
1245                      int num_double_arguments);
1246   void MovFromFloatResult(DoubleRegister dst);
1247   void MovFromFloatParameter(DoubleRegister dst);
1248
1249   // There are two ways of passing double arguments on MIPS, depending on
1250   // whether soft or hard floating point ABI is used. These functions
1251   // abstract parameter passing for the three different ways we call
1252   // C functions from generated code.
1253   void MovToFloatParameter(DoubleRegister src);
1254   void MovToFloatParameters(DoubleRegister src1, DoubleRegister src2);
1255   void MovToFloatResult(DoubleRegister src);
1256
1257   // Calls an API function.  Allocates HandleScope, extracts returned value
1258   // from handle and propagates exceptions.  Restores context.  stack_space
1259   // - space to be unwound on exit (includes the call JS arguments space and
1260   // the additional space allocated for the fast call).
1261   void CallApiFunctionAndReturn(Register function_address,
1262                                 ExternalReference thunk_ref,
1263                                 int stack_space,
1264                                 MemOperand return_value_operand,
1265                                 MemOperand* context_restore_operand);
1266
1267   // Jump to the builtin routine.
1268   void JumpToExternalReference(const ExternalReference& builtin,
1269                                BranchDelaySlot bd = PROTECT);
1270
1271   // Invoke specified builtin JavaScript function. Adds an entry to
1272   // the unresolved list if the name does not resolve.
1273   void InvokeBuiltin(Builtins::JavaScript id,
1274                      InvokeFlag flag,
1275                      const CallWrapper& call_wrapper = NullCallWrapper());
1276
1277   // Store the code object for the given builtin in the target register and
1278   // setup the function in a1.
1279   void GetBuiltinEntry(Register target, Builtins::JavaScript id);
1280
1281   // Store the function for the given builtin in the target register.
1282   void GetBuiltinFunction(Register target, Builtins::JavaScript id);
1283
1284   struct Unresolved {
1285     int pc;
1286     uint32_t flags;  // See Bootstrapper::FixupFlags decoders/encoders.
1287     const char* name;
1288   };
1289
1290   Handle<Object> CodeObject() {
1291     DCHECK(!code_object_.is_null());
1292     return code_object_;
1293   }
1294
1295   // Emit code for a truncating division by a constant. The dividend register is
1296   // unchanged and at gets clobbered. Dividend and result must be different.
1297   void TruncatingDiv(Register result, Register dividend, int32_t divisor);
1298
1299   // -------------------------------------------------------------------------
1300   // StatsCounter support.
1301
1302   void SetCounter(StatsCounter* counter, int value,
1303                   Register scratch1, Register scratch2);
1304   void IncrementCounter(StatsCounter* counter, int value,
1305                         Register scratch1, Register scratch2);
1306   void DecrementCounter(StatsCounter* counter, int value,
1307                         Register scratch1, Register scratch2);
1308
1309
1310   // -------------------------------------------------------------------------
1311   // Debugging.
1312
1313   // Calls Abort(msg) if the condition cc is not satisfied.
1314   // Use --debug_code to enable.
1315   void Assert(Condition cc, BailoutReason reason, Register rs, Operand rt);
1316   void AssertFastElements(Register elements);
1317
1318   // Like Assert(), but always enabled.
1319   void Check(Condition cc, BailoutReason reason, Register rs, Operand rt);
1320
1321   // Print a message to stdout and abort execution.
1322   void Abort(BailoutReason msg);
1323
1324   // Verify restrictions about code generated in stubs.
1325   void set_generating_stub(bool value) { generating_stub_ = value; }
1326   bool generating_stub() { return generating_stub_; }
1327   void set_has_frame(bool value) { has_frame_ = value; }
1328   bool has_frame() { return has_frame_; }
1329   inline bool AllowThisStubCall(CodeStub* stub);
1330
1331   // ---------------------------------------------------------------------------
1332   // Number utilities.
1333
1334   // Check whether the value of reg is a power of two and not zero. If not
1335   // control continues at the label not_power_of_two. If reg is a power of two
1336   // the register scratch contains the value of (reg - 1) when control falls
1337   // through.
1338   void JumpIfNotPowerOfTwoOrZero(Register reg,
1339                                  Register scratch,
1340                                  Label* not_power_of_two_or_zero);
1341
1342   // -------------------------------------------------------------------------
1343   // Smi utilities.
1344
1345   void SmiTag(Register reg) {
1346     Addu(reg, reg, reg);
1347   }
1348
1349   // Test for overflow < 0: use BranchOnOverflow() or BranchOnNoOverflow().
1350   void SmiTagCheckOverflow(Register reg, Register overflow);
1351   void SmiTagCheckOverflow(Register dst, Register src, Register overflow);
1352
1353   void SmiTag(Register dst, Register src) {
1354     Addu(dst, src, src);
1355   }
1356
1357   // Try to convert int32 to smi. If the value is to large, preserve
1358   // the original value and jump to not_a_smi. Destroys scratch and
1359   // sets flags.
1360   void TrySmiTag(Register reg, Register scratch, Label* not_a_smi) {
1361     TrySmiTag(reg, reg, scratch, not_a_smi);
1362   }
1363   void TrySmiTag(Register dst,
1364                  Register src,
1365                  Register scratch,
1366                  Label* not_a_smi) {
1367     SmiTagCheckOverflow(at, src, scratch);
1368     BranchOnOverflow(not_a_smi, scratch);
1369     mov(dst, at);
1370   }
1371
1372   void SmiUntag(Register reg) {
1373     sra(reg, reg, kSmiTagSize);
1374   }
1375
1376   void SmiUntag(Register dst, Register src) {
1377     sra(dst, src, kSmiTagSize);
1378   }
1379
1380   // Test if the register contains a smi.
1381   inline void SmiTst(Register value, Register scratch) {
1382     And(scratch, value, Operand(kSmiTagMask));
1383   }
1384   inline void NonNegativeSmiTst(Register value, Register scratch) {
1385     And(scratch, value, Operand(kSmiTagMask | kSmiSignMask));
1386   }
1387
1388   // Untag the source value into destination and jump if source is a smi.
1389   // Souce and destination can be the same register.
1390   void UntagAndJumpIfSmi(Register dst, Register src, Label* smi_case);
1391
1392   // Untag the source value into destination and jump if source is not a smi.
1393   // Souce and destination can be the same register.
1394   void UntagAndJumpIfNotSmi(Register dst, Register src, Label* non_smi_case);
1395
1396   // Jump the register contains a smi.
1397   void JumpIfSmi(Register value,
1398                  Label* smi_label,
1399                  Register scratch = at,
1400                  BranchDelaySlot bd = PROTECT);
1401
1402   // Jump if the register contains a non-smi.
1403   void JumpIfNotSmi(Register value,
1404                     Label* not_smi_label,
1405                     Register scratch = at,
1406                     BranchDelaySlot bd = PROTECT);
1407
1408   // Jump if either of the registers contain a non-smi.
1409   void JumpIfNotBothSmi(Register reg1, Register reg2, Label* on_not_both_smi);
1410   // Jump if either of the registers contain a smi.
1411   void JumpIfEitherSmi(Register reg1, Register reg2, Label* on_either_smi);
1412
1413   // Abort execution if argument is a smi, enabled via --debug-code.
1414   void AssertNotSmi(Register object);
1415   void AssertSmi(Register object);
1416
1417   // Abort execution if argument is not a string, enabled via --debug-code.
1418   void AssertString(Register object);
1419
1420   // Abort execution if argument is not a name, enabled via --debug-code.
1421   void AssertName(Register object);
1422
1423   // Abort execution if argument is not undefined or an AllocationSite, enabled
1424   // via --debug-code.
1425   void AssertUndefinedOrAllocationSite(Register object, Register scratch);
1426
1427   // Abort execution if reg is not the root value with the given index,
1428   // enabled via --debug-code.
1429   void AssertIsRoot(Register reg, Heap::RootListIndex index);
1430
1431   // ---------------------------------------------------------------------------
1432   // HeapNumber utilities.
1433
1434   void JumpIfNotHeapNumber(Register object,
1435                            Register heap_number_map,
1436                            Register scratch,
1437                            Label* on_not_heap_number);
1438
1439   // -------------------------------------------------------------------------
1440   // String utilities.
1441
1442   // Generate code to do a lookup in the number string cache. If the number in
1443   // the register object is found in the cache the generated code falls through
1444   // with the result in the result register. The object and the result register
1445   // can be the same. If the number is not found in the cache the code jumps to
1446   // the label not_found with only the content of register object unchanged.
1447   void LookupNumberStringCache(Register object,
1448                                Register result,
1449                                Register scratch1,
1450                                Register scratch2,
1451                                Register scratch3,
1452                                Label* not_found);
1453
1454   // Checks if both instance types are sequential ASCII strings and jumps to
1455   // label if either is not.
1456   void JumpIfBothInstanceTypesAreNotSequentialAscii(
1457       Register first_object_instance_type,
1458       Register second_object_instance_type,
1459       Register scratch1,
1460       Register scratch2,
1461       Label* failure);
1462
1463   // Check if instance type is sequential ASCII string and jump to label if
1464   // it is not.
1465   void JumpIfInstanceTypeIsNotSequentialAscii(Register type,
1466                                               Register scratch,
1467                                               Label* failure);
1468
1469   void JumpIfNotUniqueName(Register reg, Label* not_unique_name);
1470
1471   void EmitSeqStringSetCharCheck(Register string,
1472                                  Register index,
1473                                  Register value,
1474                                  Register scratch,
1475                                  uint32_t encoding_mask);
1476
1477   // Test that both first and second are sequential ASCII strings.
1478   // Assume that they are non-smis.
1479   void JumpIfNonSmisNotBothSequentialAsciiStrings(Register first,
1480                                                   Register second,
1481                                                   Register scratch1,
1482                                                   Register scratch2,
1483                                                   Label* failure);
1484
1485   // Test that both first and second are sequential ASCII strings.
1486   // Check that they are non-smis.
1487   void JumpIfNotBothSequentialAsciiStrings(Register first,
1488                                            Register second,
1489                                            Register scratch1,
1490                                            Register scratch2,
1491                                            Label* failure);
1492
1493   void ClampUint8(Register output_reg, Register input_reg);
1494
1495   void ClampDoubleToUint8(Register result_reg,
1496                           DoubleRegister input_reg,
1497                           DoubleRegister temp_double_reg);
1498
1499
1500   void LoadInstanceDescriptors(Register map, Register descriptors);
1501   void EnumLength(Register dst, Register map);
1502   void NumberOfOwnDescriptors(Register dst, Register map);
1503
1504   template<typename Field>
1505   void DecodeField(Register dst, Register src) {
1506     Ext(dst, src, Field::kShift, Field::kSize);
1507   }
1508
1509   template<typename Field>
1510   void DecodeField(Register reg) {
1511     DecodeField<Field>(reg, reg);
1512   }
1513
1514   template<typename Field>
1515   void DecodeFieldToSmi(Register dst, Register src) {
1516     static const int shift = Field::kShift;
1517     static const int mask = Field::kMask >> shift << kSmiTagSize;
1518     STATIC_ASSERT((mask & (0x80000000u >> (kSmiTagSize - 1))) == 0);
1519     STATIC_ASSERT(kSmiTag == 0);
1520     if (shift < kSmiTagSize) {
1521       sll(dst, src, kSmiTagSize - shift);
1522       And(dst, dst, Operand(mask));
1523     } else if (shift > kSmiTagSize) {
1524       srl(dst, src, shift - kSmiTagSize);
1525       And(dst, dst, Operand(mask));
1526     } else {
1527       And(dst, src, Operand(mask));
1528     }
1529   }
1530
1531   template<typename Field>
1532   void DecodeFieldToSmi(Register reg) {
1533     DecodeField<Field>(reg, reg);
1534   }
1535
1536   // Generates function and stub prologue code.
1537   void StubPrologue();
1538   void Prologue(bool code_pre_aging);
1539
1540   // Activation support.
1541   void EnterFrame(StackFrame::Type type);
1542   void LeaveFrame(StackFrame::Type type);
1543
1544   // Patch the relocated value (lui/ori pair).
1545   void PatchRelocatedValue(Register li_location,
1546                            Register scratch,
1547                            Register new_value);
1548   // Get the relocatad value (loaded data) from the lui/ori pair.
1549   void GetRelocatedValue(Register li_location,
1550                          Register value,
1551                          Register scratch);
1552
1553   // Expects object in a0 and returns map with validated enum cache
1554   // in a0.  Assumes that any other register can be used as a scratch.
1555   void CheckEnumCache(Register null_value, Label* call_runtime);
1556
1557   // AllocationMemento support. Arrays may have an associated
1558   // AllocationMemento object that can be checked for in order to pretransition
1559   // to another type.
1560   // On entry, receiver_reg should point to the array object.
1561   // scratch_reg gets clobbered.
1562   // If allocation info is present, jump to allocation_memento_present.
1563   void TestJSArrayForAllocationMemento(
1564       Register receiver_reg,
1565       Register scratch_reg,
1566       Label* no_memento_found,
1567       Condition cond = al,
1568       Label* allocation_memento_present = NULL);
1569
1570   void JumpIfJSArrayHasAllocationMemento(Register receiver_reg,
1571                                          Register scratch_reg,
1572                                          Label* memento_found) {
1573     Label no_memento_found;
1574     TestJSArrayForAllocationMemento(receiver_reg, scratch_reg,
1575                                     &no_memento_found, eq, memento_found);
1576     bind(&no_memento_found);
1577   }
1578
1579   // Jumps to found label if a prototype map has dictionary elements.
1580   void JumpIfDictionaryInPrototypeChain(Register object, Register scratch0,
1581                                         Register scratch1, Label* found);
1582
1583  private:
1584   void CallCFunctionHelper(Register function,
1585                            int num_reg_arguments,
1586                            int num_double_arguments);
1587
1588   void BranchAndLinkShort(int16_t offset, BranchDelaySlot bdslot = PROTECT);
1589   void BranchAndLinkShort(int16_t offset, Condition cond, Register rs,
1590                           const Operand& rt,
1591                           BranchDelaySlot bdslot = PROTECT);
1592   void BranchAndLinkShort(Label* L, BranchDelaySlot bdslot = PROTECT);
1593   void BranchAndLinkShort(Label* L, Condition cond, Register rs,
1594                           const Operand& rt,
1595                           BranchDelaySlot bdslot = PROTECT);
1596   void J(Label* L, BranchDelaySlot bdslot);
1597   void Jr(Label* L, BranchDelaySlot bdslot);
1598   void Jalr(Label* L, BranchDelaySlot bdslot);
1599
1600   // Helper functions for generating invokes.
1601   void InvokePrologue(const ParameterCount& expected,
1602                       const ParameterCount& actual,
1603                       Handle<Code> code_constant,
1604                       Register code_reg,
1605                       Label* done,
1606                       bool* definitely_mismatches,
1607                       InvokeFlag flag,
1608                       const CallWrapper& call_wrapper);
1609
1610   // Get the code for the given builtin. Returns if able to resolve
1611   // the function in the 'resolved' flag.
1612   Handle<Code> ResolveBuiltin(Builtins::JavaScript id, bool* resolved);
1613
1614   void InitializeNewString(Register string,
1615                            Register length,
1616                            Heap::RootListIndex map_index,
1617                            Register scratch1,
1618                            Register scratch2);
1619
1620   // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
1621   void InNewSpace(Register object,
1622                   Register scratch,
1623                   Condition cond,  // eq for new space, ne otherwise.
1624                   Label* branch);
1625
1626   // Helper for finding the mark bits for an address.  Afterwards, the
1627   // bitmap register points at the word with the mark bits and the mask
1628   // the position of the first bit.  Leaves addr_reg unchanged.
1629   inline void GetMarkBits(Register addr_reg,
1630                           Register bitmap_reg,
1631                           Register mask_reg);
1632
1633   // Helper for throwing exceptions.  Compute a handler address and jump to
1634   // it.  See the implementation for register usage.
1635   void JumpToHandlerEntry();
1636
1637   // Compute memory operands for safepoint stack slots.
1638   static int SafepointRegisterStackIndex(int reg_code);
1639   MemOperand SafepointRegisterSlot(Register reg);
1640   MemOperand SafepointRegistersAndDoublesSlot(Register reg);
1641
1642   bool generating_stub_;
1643   bool has_frame_;
1644   // This handle will be patched with the code object on installation.
1645   Handle<Object> code_object_;
1646
1647   // Needs access to SafepointRegisterStackIndex for compiled frame
1648   // traversal.
1649   friend class StandardFrame;
1650 };
1651
1652
1653 // The code patcher is used to patch (typically) small parts of code e.g. for
1654 // debugging and other types of instrumentation. When using the code patcher
1655 // the exact number of bytes specified must be emitted. It is not legal to emit
1656 // relocation information. If any of these constraints are violated it causes
1657 // an assertion to fail.
1658 class CodePatcher {
1659  public:
1660   enum FlushICache {
1661     FLUSH,
1662     DONT_FLUSH
1663   };
1664
1665   CodePatcher(byte* address,
1666               int instructions,
1667               FlushICache flush_cache = FLUSH);
1668   virtual ~CodePatcher();
1669
1670   // Macro assembler to emit code.
1671   MacroAssembler* masm() { return &masm_; }
1672
1673   // Emit an instruction directly.
1674   void Emit(Instr instr);
1675
1676   // Emit an address directly.
1677   void Emit(Address addr);
1678
1679   // Change the condition part of an instruction leaving the rest of the current
1680   // instruction unchanged.
1681   void ChangeBranchCondition(Condition cond);
1682
1683  private:
1684   byte* address_;  // The address of the code being patched.
1685   int size_;  // Number of bytes of the expected patch size.
1686   MacroAssembler masm_;  // Macro assembler used to generate the code.
1687   FlushICache flush_cache_;  // Whether to flush the I cache after patching.
1688 };
1689
1690
1691
1692 #ifdef GENERATED_CODE_COVERAGE
1693 #define CODE_COVERAGE_STRINGIFY(x) #x
1694 #define CODE_COVERAGE_TOSTRING(x) CODE_COVERAGE_STRINGIFY(x)
1695 #define __FILE_LINE__ __FILE__ ":" CODE_COVERAGE_TOSTRING(__LINE__)
1696 #define ACCESS_MASM(masm) masm->stop(__FILE_LINE__); masm->
1697 #else
1698 #define ACCESS_MASM(masm) masm->
1699 #endif
1700
1701 } }  // namespace v8::internal
1702
1703 #endif  // V8_MIPS_MACRO_ASSEMBLER_MIPS_H_