[presubmit] Enable readability/namespace linter checking.
[platform/upstream/v8.git] / src / arm64 / macro-assembler-arm64.h
1 // Copyright 2013 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_ARM64_MACRO_ASSEMBLER_ARM64_H_
6 #define V8_ARM64_MACRO_ASSEMBLER_ARM64_H_
7
8 #include <vector>
9
10 #include "src/arm64/assembler-arm64.h"
11 #include "src/bailout-reason.h"
12 #include "src/base/bits.h"
13 #include "src/globals.h"
14
15 // Simulator specific helpers.
16 #if USE_SIMULATOR
17   // TODO(all): If possible automatically prepend an indicator like
18   // UNIMPLEMENTED or LOCATION.
19   #define ASM_UNIMPLEMENTED(message)                                         \
20   __ Debug(message, __LINE__, NO_PARAM)
21   #define ASM_UNIMPLEMENTED_BREAK(message)                                   \
22   __ Debug(message, __LINE__,                                                \
23            FLAG_ignore_asm_unimplemented_break ? NO_PARAM : BREAK)
24   #define ASM_LOCATION(message)                                              \
25   __ Debug("LOCATION: " message, __LINE__, NO_PARAM)
26 #else
27   #define ASM_UNIMPLEMENTED(message)
28   #define ASM_UNIMPLEMENTED_BREAK(message)
29   #define ASM_LOCATION(message)
30 #endif
31
32
33 namespace v8 {
34 namespace internal {
35
36 // Give alias names to registers for calling conventions.
37 // TODO(titzer): arm64 is a pain for aliasing; get rid of these macros
38 #define kReturnRegister0 x0
39 #define kReturnRegister1 x1
40 #define kJSFunctionRegister x1
41 #define kContextRegister cp
42 #define kInterpreterAccumulatorRegister x0
43 #define kInterpreterRegisterFileRegister x18
44 #define kInterpreterBytecodeOffsetRegister x19
45 #define kInterpreterBytecodeArrayRegister x20
46 #define kInterpreterDispatchTableRegister x21
47 #define kRuntimeCallFunctionRegister x1
48 #define kRuntimeCallArgCountRegister x0
49
50 #define LS_MACRO_LIST(V)                                      \
51   V(Ldrb, Register&, rt, LDRB_w)                              \
52   V(Strb, Register&, rt, STRB_w)                              \
53   V(Ldrsb, Register&, rt, rt.Is64Bits() ? LDRSB_x : LDRSB_w)  \
54   V(Ldrh, Register&, rt, LDRH_w)                              \
55   V(Strh, Register&, rt, STRH_w)                              \
56   V(Ldrsh, Register&, rt, rt.Is64Bits() ? LDRSH_x : LDRSH_w)  \
57   V(Ldr, CPURegister&, rt, LoadOpFor(rt))                     \
58   V(Str, CPURegister&, rt, StoreOpFor(rt))                    \
59   V(Ldrsw, Register&, rt, LDRSW_x)
60
61 #define LSPAIR_MACRO_LIST(V)                             \
62   V(Ldp, CPURegister&, rt, rt2, LoadPairOpFor(rt, rt2))  \
63   V(Stp, CPURegister&, rt, rt2, StorePairOpFor(rt, rt2)) \
64   V(Ldpsw, CPURegister&, rt, rt2, LDPSW_x)
65
66
67 // ----------------------------------------------------------------------------
68 // Static helper functions
69
70 // Generate a MemOperand for loading a field from an object.
71 inline MemOperand FieldMemOperand(Register object, int offset);
72 inline MemOperand UntagSmiFieldMemOperand(Register object, int offset);
73
74 // Generate a MemOperand for loading a SMI from memory.
75 inline MemOperand UntagSmiMemOperand(Register object, int offset);
76
77
78 // ----------------------------------------------------------------------------
79 // MacroAssembler
80
81 enum BranchType {
82   // Copies of architectural conditions.
83   // The associated conditions can be used in place of those, the code will
84   // take care of reinterpreting them with the correct type.
85   integer_eq = eq,
86   integer_ne = ne,
87   integer_hs = hs,
88   integer_lo = lo,
89   integer_mi = mi,
90   integer_pl = pl,
91   integer_vs = vs,
92   integer_vc = vc,
93   integer_hi = hi,
94   integer_ls = ls,
95   integer_ge = ge,
96   integer_lt = lt,
97   integer_gt = gt,
98   integer_le = le,
99   integer_al = al,
100   integer_nv = nv,
101
102   // These two are *different* from the architectural codes al and nv.
103   // 'always' is used to generate unconditional branches.
104   // 'never' is used to not generate a branch (generally as the inverse
105   // branch type of 'always).
106   always, never,
107   // cbz and cbnz
108   reg_zero, reg_not_zero,
109   // tbz and tbnz
110   reg_bit_clear, reg_bit_set,
111
112   // Aliases.
113   kBranchTypeFirstCondition = eq,
114   kBranchTypeLastCondition = nv,
115   kBranchTypeFirstUsingReg = reg_zero,
116   kBranchTypeFirstUsingBit = reg_bit_clear
117 };
118
119 inline BranchType InvertBranchType(BranchType type) {
120   if (kBranchTypeFirstCondition <= type && type <= kBranchTypeLastCondition) {
121     return static_cast<BranchType>(
122         NegateCondition(static_cast<Condition>(type)));
123   } else {
124     return static_cast<BranchType>(type ^ 1);
125   }
126 }
127
128 enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET };
129 enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK };
130 enum PointersToHereCheck {
131   kPointersToHereMaybeInteresting,
132   kPointersToHereAreAlwaysInteresting
133 };
134 enum LinkRegisterStatus { kLRHasNotBeenSaved, kLRHasBeenSaved };
135 enum TargetAddressStorageMode {
136   CAN_INLINE_TARGET_ADDRESS,
137   NEVER_INLINE_TARGET_ADDRESS
138 };
139 enum UntagMode { kNotSpeculativeUntag, kSpeculativeUntag };
140 enum ArrayHasHoles { kArrayCantHaveHoles, kArrayCanHaveHoles };
141 enum CopyHint { kCopyUnknown, kCopyShort, kCopyLong };
142 enum DiscardMoveMode { kDontDiscardForSameWReg, kDiscardForSameWReg };
143 enum SeqStringSetCharCheckIndexType { kIndexIsSmi, kIndexIsInteger32 };
144
145 class MacroAssembler : public Assembler {
146  public:
147   MacroAssembler(Isolate* isolate, byte * buffer, unsigned buffer_size);
148
149   inline Handle<Object> CodeObject();
150
151   // Instruction set functions ------------------------------------------------
152   // Logical macros.
153   inline void And(const Register& rd,
154                   const Register& rn,
155                   const Operand& operand);
156   inline void Ands(const Register& rd,
157                    const Register& rn,
158                    const Operand& operand);
159   inline void Bic(const Register& rd,
160                   const Register& rn,
161                   const Operand& operand);
162   inline void Bics(const Register& rd,
163                    const Register& rn,
164                    const Operand& operand);
165   inline void Orr(const Register& rd,
166                   const Register& rn,
167                   const Operand& operand);
168   inline void Orn(const Register& rd,
169                   const Register& rn,
170                   const Operand& operand);
171   inline void Eor(const Register& rd,
172                   const Register& rn,
173                   const Operand& operand);
174   inline void Eon(const Register& rd,
175                   const Register& rn,
176                   const Operand& operand);
177   inline void Tst(const Register& rn, const Operand& operand);
178   void LogicalMacro(const Register& rd,
179                     const Register& rn,
180                     const Operand& operand,
181                     LogicalOp op);
182
183   // Add and sub macros.
184   inline void Add(const Register& rd,
185                   const Register& rn,
186                   const Operand& operand);
187   inline void Adds(const Register& rd,
188                    const Register& rn,
189                    const Operand& operand);
190   inline void Sub(const Register& rd,
191                   const Register& rn,
192                   const Operand& operand);
193   inline void Subs(const Register& rd,
194                    const Register& rn,
195                    const Operand& operand);
196   inline void Cmn(const Register& rn, const Operand& operand);
197   inline void Cmp(const Register& rn, const Operand& operand);
198   inline void Neg(const Register& rd,
199                   const Operand& operand);
200   inline void Negs(const Register& rd,
201                    const Operand& operand);
202
203   void AddSubMacro(const Register& rd,
204                    const Register& rn,
205                    const Operand& operand,
206                    FlagsUpdate S,
207                    AddSubOp op);
208
209   // Add/sub with carry macros.
210   inline void Adc(const Register& rd,
211                   const Register& rn,
212                   const Operand& operand);
213   inline void Adcs(const Register& rd,
214                    const Register& rn,
215                    const Operand& operand);
216   inline void Sbc(const Register& rd,
217                   const Register& rn,
218                   const Operand& operand);
219   inline void Sbcs(const Register& rd,
220                    const Register& rn,
221                    const Operand& operand);
222   inline void Ngc(const Register& rd,
223                   const Operand& operand);
224   inline void Ngcs(const Register& rd,
225                    const Operand& operand);
226   void AddSubWithCarryMacro(const Register& rd,
227                             const Register& rn,
228                             const Operand& operand,
229                             FlagsUpdate S,
230                             AddSubWithCarryOp op);
231
232   // Move macros.
233   void Mov(const Register& rd,
234            const Operand& operand,
235            DiscardMoveMode discard_mode = kDontDiscardForSameWReg);
236   void Mov(const Register& rd, uint64_t imm);
237   inline void Mvn(const Register& rd, uint64_t imm);
238   void Mvn(const Register& rd, const Operand& operand);
239   static bool IsImmMovn(uint64_t imm, unsigned reg_size);
240   static bool IsImmMovz(uint64_t imm, unsigned reg_size);
241   static unsigned CountClearHalfWords(uint64_t imm, unsigned reg_size);
242
243   // Try to move an immediate into the destination register in a single
244   // instruction. Returns true for success, and updates the contents of dst.
245   // Returns false, otherwise.
246   bool TryOneInstrMoveImmediate(const Register& dst, int64_t imm);
247
248   // Move an immediate into register dst, and return an Operand object for use
249   // with a subsequent instruction that accepts a shift. The value moved into
250   // dst is not necessarily equal to imm; it may have had a shifting operation
251   // applied to it that will be subsequently undone by the shift applied in the
252   // Operand.
253   Operand MoveImmediateForShiftedOp(const Register& dst, int64_t imm);
254
255   // Conditional macros.
256   inline void Ccmp(const Register& rn,
257                    const Operand& operand,
258                    StatusFlags nzcv,
259                    Condition cond);
260   inline void Ccmn(const Register& rn,
261                    const Operand& operand,
262                    StatusFlags nzcv,
263                    Condition cond);
264   void ConditionalCompareMacro(const Register& rn,
265                                const Operand& operand,
266                                StatusFlags nzcv,
267                                Condition cond,
268                                ConditionalCompareOp op);
269   void Csel(const Register& rd,
270             const Register& rn,
271             const Operand& operand,
272             Condition cond);
273
274   // Load/store macros.
275 #define DECLARE_FUNCTION(FN, REGTYPE, REG, OP) \
276   inline void FN(const REGTYPE REG, const MemOperand& addr);
277   LS_MACRO_LIST(DECLARE_FUNCTION)
278 #undef DECLARE_FUNCTION
279
280   void LoadStoreMacro(const CPURegister& rt,
281                       const MemOperand& addr,
282                       LoadStoreOp op);
283
284 #define DECLARE_FUNCTION(FN, REGTYPE, REG, REG2, OP) \
285   inline void FN(const REGTYPE REG, const REGTYPE REG2, const MemOperand& addr);
286   LSPAIR_MACRO_LIST(DECLARE_FUNCTION)
287 #undef DECLARE_FUNCTION
288
289   void LoadStorePairMacro(const CPURegister& rt, const CPURegister& rt2,
290                           const MemOperand& addr, LoadStorePairOp op);
291
292   // V8-specific load/store helpers.
293   void Load(const Register& rt, const MemOperand& addr, Representation r);
294   void Store(const Register& rt, const MemOperand& addr, Representation r);
295
296   enum AdrHint {
297     // The target must be within the immediate range of adr.
298     kAdrNear,
299     // The target may be outside of the immediate range of adr. Additional
300     // instructions may be emitted.
301     kAdrFar
302   };
303   void Adr(const Register& rd, Label* label, AdrHint = kAdrNear);
304
305   // Remaining instructions are simple pass-through calls to the assembler.
306   inline void Asr(const Register& rd, const Register& rn, unsigned shift);
307   inline void Asr(const Register& rd, const Register& rn, const Register& rm);
308
309   // Branch type inversion relies on these relations.
310   STATIC_ASSERT((reg_zero      == (reg_not_zero ^ 1)) &&
311                 (reg_bit_clear == (reg_bit_set ^ 1)) &&
312                 (always        == (never ^ 1)));
313
314   void B(Label* label, BranchType type, Register reg = NoReg, int bit = -1);
315
316   inline void B(Label* label);
317   inline void B(Condition cond, Label* label);
318   void B(Label* label, Condition cond);
319   inline void Bfi(const Register& rd,
320                   const Register& rn,
321                   unsigned lsb,
322                   unsigned width);
323   inline void Bfxil(const Register& rd,
324                     const Register& rn,
325                     unsigned lsb,
326                     unsigned width);
327   inline void Bind(Label* label);
328   inline void Bl(Label* label);
329   inline void Blr(const Register& xn);
330   inline void Br(const Register& xn);
331   inline void Brk(int code);
332   void Cbnz(const Register& rt, Label* label);
333   void Cbz(const Register& rt, Label* label);
334   inline void Cinc(const Register& rd, const Register& rn, Condition cond);
335   inline void Cinv(const Register& rd, const Register& rn, Condition cond);
336   inline void Cls(const Register& rd, const Register& rn);
337   inline void Clz(const Register& rd, const Register& rn);
338   inline void Cneg(const Register& rd, const Register& rn, Condition cond);
339   inline void CzeroX(const Register& rd, Condition cond);
340   inline void CmovX(const Register& rd, const Register& rn, Condition cond);
341   inline void Cset(const Register& rd, Condition cond);
342   inline void Csetm(const Register& rd, Condition cond);
343   inline void Csinc(const Register& rd,
344                     const Register& rn,
345                     const Register& rm,
346                     Condition cond);
347   inline void Csinv(const Register& rd,
348                     const Register& rn,
349                     const Register& rm,
350                     Condition cond);
351   inline void Csneg(const Register& rd,
352                     const Register& rn,
353                     const Register& rm,
354                     Condition cond);
355   inline void Dmb(BarrierDomain domain, BarrierType type);
356   inline void Dsb(BarrierDomain domain, BarrierType type);
357   inline void Debug(const char* message, uint32_t code, Instr params = BREAK);
358   inline void Extr(const Register& rd,
359                    const Register& rn,
360                    const Register& rm,
361                    unsigned lsb);
362   inline void Fabs(const FPRegister& fd, const FPRegister& fn);
363   inline void Fadd(const FPRegister& fd,
364                    const FPRegister& fn,
365                    const FPRegister& fm);
366   inline void Fccmp(const FPRegister& fn,
367                     const FPRegister& fm,
368                     StatusFlags nzcv,
369                     Condition cond);
370   inline void Fcmp(const FPRegister& fn, const FPRegister& fm);
371   inline void Fcmp(const FPRegister& fn, double value);
372   inline void Fcsel(const FPRegister& fd,
373                     const FPRegister& fn,
374                     const FPRegister& fm,
375                     Condition cond);
376   inline void Fcvt(const FPRegister& fd, const FPRegister& fn);
377   inline void Fcvtas(const Register& rd, const FPRegister& fn);
378   inline void Fcvtau(const Register& rd, const FPRegister& fn);
379   inline void Fcvtms(const Register& rd, const FPRegister& fn);
380   inline void Fcvtmu(const Register& rd, const FPRegister& fn);
381   inline void Fcvtns(const Register& rd, const FPRegister& fn);
382   inline void Fcvtnu(const Register& rd, const FPRegister& fn);
383   inline void Fcvtzs(const Register& rd, const FPRegister& fn);
384   inline void Fcvtzu(const Register& rd, const FPRegister& fn);
385   inline void Fdiv(const FPRegister& fd,
386                    const FPRegister& fn,
387                    const FPRegister& fm);
388   inline void Fmadd(const FPRegister& fd,
389                     const FPRegister& fn,
390                     const FPRegister& fm,
391                     const FPRegister& fa);
392   inline void Fmax(const FPRegister& fd,
393                    const FPRegister& fn,
394                    const FPRegister& fm);
395   inline void Fmaxnm(const FPRegister& fd,
396                      const FPRegister& fn,
397                      const FPRegister& fm);
398   inline void Fmin(const FPRegister& fd,
399                    const FPRegister& fn,
400                    const FPRegister& fm);
401   inline void Fminnm(const FPRegister& fd,
402                      const FPRegister& fn,
403                      const FPRegister& fm);
404   inline void Fmov(FPRegister fd, FPRegister fn);
405   inline void Fmov(FPRegister fd, Register rn);
406   // Provide explicit double and float interfaces for FP immediate moves, rather
407   // than relying on implicit C++ casts. This allows signalling NaNs to be
408   // preserved when the immediate matches the format of fd. Most systems convert
409   // signalling NaNs to quiet NaNs when converting between float and double.
410   inline void Fmov(FPRegister fd, double imm);
411   inline void Fmov(FPRegister fd, float imm);
412   // Provide a template to allow other types to be converted automatically.
413   template<typename T>
414   void Fmov(FPRegister fd, T imm) {
415     DCHECK(allow_macro_instructions_);
416     Fmov(fd, static_cast<double>(imm));
417   }
418   inline void Fmov(Register rd, FPRegister fn);
419   inline void Fmsub(const FPRegister& fd,
420                     const FPRegister& fn,
421                     const FPRegister& fm,
422                     const FPRegister& fa);
423   inline void Fmul(const FPRegister& fd,
424                    const FPRegister& fn,
425                    const FPRegister& fm);
426   inline void Fneg(const FPRegister& fd, const FPRegister& fn);
427   inline void Fnmadd(const FPRegister& fd,
428                      const FPRegister& fn,
429                      const FPRegister& fm,
430                      const FPRegister& fa);
431   inline void Fnmsub(const FPRegister& fd,
432                      const FPRegister& fn,
433                      const FPRegister& fm,
434                      const FPRegister& fa);
435   inline void Frinta(const FPRegister& fd, const FPRegister& fn);
436   inline void Frintm(const FPRegister& fd, const FPRegister& fn);
437   inline void Frintn(const FPRegister& fd, const FPRegister& fn);
438   inline void Frintp(const FPRegister& fd, const FPRegister& fn);
439   inline void Frintz(const FPRegister& fd, const FPRegister& fn);
440   inline void Fsqrt(const FPRegister& fd, const FPRegister& fn);
441   inline void Fsub(const FPRegister& fd,
442                    const FPRegister& fn,
443                    const FPRegister& fm);
444   inline void Hint(SystemHint code);
445   inline void Hlt(int code);
446   inline void Isb();
447   inline void Ldnp(const CPURegister& rt,
448                    const CPURegister& rt2,
449                    const MemOperand& src);
450   // Load a literal from the inline constant pool.
451   inline void Ldr(const CPURegister& rt, const Immediate& imm);
452   // Helper function for double immediate.
453   inline void Ldr(const CPURegister& rt, double imm);
454   inline void Lsl(const Register& rd, const Register& rn, unsigned shift);
455   inline void Lsl(const Register& rd, const Register& rn, const Register& rm);
456   inline void Lsr(const Register& rd, const Register& rn, unsigned shift);
457   inline void Lsr(const Register& rd, const Register& rn, const Register& rm);
458   inline void Madd(const Register& rd,
459                    const Register& rn,
460                    const Register& rm,
461                    const Register& ra);
462   inline void Mneg(const Register& rd, const Register& rn, const Register& rm);
463   inline void Mov(const Register& rd, const Register& rm);
464   inline void Movk(const Register& rd, uint64_t imm, int shift = -1);
465   inline void Mrs(const Register& rt, SystemRegister sysreg);
466   inline void Msr(SystemRegister sysreg, const Register& rt);
467   inline void Msub(const Register& rd,
468                    const Register& rn,
469                    const Register& rm,
470                    const Register& ra);
471   inline void Mul(const Register& rd, const Register& rn, const Register& rm);
472   inline void Nop() { nop(); }
473   inline void Rbit(const Register& rd, const Register& rn);
474   inline void Ret(const Register& xn = lr);
475   inline void Rev(const Register& rd, const Register& rn);
476   inline void Rev16(const Register& rd, const Register& rn);
477   inline void Rev32(const Register& rd, const Register& rn);
478   inline void Ror(const Register& rd, const Register& rs, unsigned shift);
479   inline void Ror(const Register& rd, const Register& rn, const Register& rm);
480   inline void Sbfiz(const Register& rd,
481                     const Register& rn,
482                     unsigned lsb,
483                     unsigned width);
484   inline void Sbfx(const Register& rd,
485                    const Register& rn,
486                    unsigned lsb,
487                    unsigned width);
488   inline void Scvtf(const FPRegister& fd,
489                     const Register& rn,
490                     unsigned fbits = 0);
491   inline void Sdiv(const Register& rd, const Register& rn, const Register& rm);
492   inline void Smaddl(const Register& rd,
493                      const Register& rn,
494                      const Register& rm,
495                      const Register& ra);
496   inline void Smsubl(const Register& rd,
497                      const Register& rn,
498                      const Register& rm,
499                      const Register& ra);
500   inline void Smull(const Register& rd,
501                     const Register& rn,
502                     const Register& rm);
503   inline void Smulh(const Register& rd,
504                     const Register& rn,
505                     const Register& rm);
506   inline void Umull(const Register& rd, const Register& rn, const Register& rm);
507   inline void Stnp(const CPURegister& rt,
508                    const CPURegister& rt2,
509                    const MemOperand& dst);
510   inline void Sxtb(const Register& rd, const Register& rn);
511   inline void Sxth(const Register& rd, const Register& rn);
512   inline void Sxtw(const Register& rd, const Register& rn);
513   void Tbnz(const Register& rt, unsigned bit_pos, Label* label);
514   void Tbz(const Register& rt, unsigned bit_pos, Label* label);
515   inline void Ubfiz(const Register& rd,
516                     const Register& rn,
517                     unsigned lsb,
518                     unsigned width);
519   inline void Ubfx(const Register& rd,
520                    const Register& rn,
521                    unsigned lsb,
522                    unsigned width);
523   inline void Ucvtf(const FPRegister& fd,
524                     const Register& rn,
525                     unsigned fbits = 0);
526   inline void Udiv(const Register& rd, const Register& rn, const Register& rm);
527   inline void Umaddl(const Register& rd,
528                      const Register& rn,
529                      const Register& rm,
530                      const Register& ra);
531   inline void Umsubl(const Register& rd,
532                      const Register& rn,
533                      const Register& rm,
534                      const Register& ra);
535   inline void Uxtb(const Register& rd, const Register& rn);
536   inline void Uxth(const Register& rd, const Register& rn);
537   inline void Uxtw(const Register& rd, const Register& rn);
538
539   // Pseudo-instructions ------------------------------------------------------
540
541   // Compute rd = abs(rm).
542   // This function clobbers the condition flags. On output the overflow flag is
543   // set iff the negation overflowed.
544   //
545   // If rm is the minimum representable value, the result is not representable.
546   // Handlers for each case can be specified using the relevant labels.
547   void Abs(const Register& rd, const Register& rm,
548            Label * is_not_representable = NULL,
549            Label * is_representable = NULL);
550
551   // Push or pop up to 4 registers of the same width to or from the stack,
552   // using the current stack pointer as set by SetStackPointer.
553   //
554   // If an argument register is 'NoReg', all further arguments are also assumed
555   // to be 'NoReg', and are thus not pushed or popped.
556   //
557   // Arguments are ordered such that "Push(a, b);" is functionally equivalent
558   // to "Push(a); Push(b);".
559   //
560   // It is valid to push the same register more than once, and there is no
561   // restriction on the order in which registers are specified.
562   //
563   // It is not valid to pop into the same register more than once in one
564   // operation, not even into the zero register.
565   //
566   // If the current stack pointer (as set by SetStackPointer) is csp, then it
567   // must be aligned to 16 bytes on entry and the total size of the specified
568   // registers must also be a multiple of 16 bytes.
569   //
570   // Even if the current stack pointer is not the system stack pointer (csp),
571   // Push (and derived methods) will still modify the system stack pointer in
572   // order to comply with ABI rules about accessing memory below the system
573   // stack pointer.
574   //
575   // Other than the registers passed into Pop, the stack pointer and (possibly)
576   // the system stack pointer, these methods do not modify any other registers.
577   void Push(const CPURegister& src0, const CPURegister& src1 = NoReg,
578             const CPURegister& src2 = NoReg, const CPURegister& src3 = NoReg);
579   void Push(const CPURegister& src0, const CPURegister& src1,
580             const CPURegister& src2, const CPURegister& src3,
581             const CPURegister& src4, const CPURegister& src5 = NoReg,
582             const CPURegister& src6 = NoReg, const CPURegister& src7 = NoReg);
583   void Pop(const CPURegister& dst0, const CPURegister& dst1 = NoReg,
584            const CPURegister& dst2 = NoReg, const CPURegister& dst3 = NoReg);
585   void Pop(const CPURegister& dst0, const CPURegister& dst1,
586            const CPURegister& dst2, const CPURegister& dst3,
587            const CPURegister& dst4, const CPURegister& dst5 = NoReg,
588            const CPURegister& dst6 = NoReg, const CPURegister& dst7 = NoReg);
589   void Push(const Register& src0, const FPRegister& src1);
590
591   // Alternative forms of Push and Pop, taking a RegList or CPURegList that
592   // specifies the registers that are to be pushed or popped. Higher-numbered
593   // registers are associated with higher memory addresses (as in the A32 push
594   // and pop instructions).
595   //
596   // (Push|Pop)SizeRegList allow you to specify the register size as a
597   // parameter. Only kXRegSizeInBits, kWRegSizeInBits, kDRegSizeInBits and
598   // kSRegSizeInBits are supported.
599   //
600   // Otherwise, (Push|Pop)(CPU|X|W|D|S)RegList is preferred.
601   void PushCPURegList(CPURegList registers);
602   void PopCPURegList(CPURegList registers);
603
604   inline void PushSizeRegList(RegList registers, unsigned reg_size,
605       CPURegister::RegisterType type = CPURegister::kRegister) {
606     PushCPURegList(CPURegList(type, reg_size, registers));
607   }
608   inline void PopSizeRegList(RegList registers, unsigned reg_size,
609       CPURegister::RegisterType type = CPURegister::kRegister) {
610     PopCPURegList(CPURegList(type, reg_size, registers));
611   }
612   inline void PushXRegList(RegList regs) {
613     PushSizeRegList(regs, kXRegSizeInBits);
614   }
615   inline void PopXRegList(RegList regs) {
616     PopSizeRegList(regs, kXRegSizeInBits);
617   }
618   inline void PushWRegList(RegList regs) {
619     PushSizeRegList(regs, kWRegSizeInBits);
620   }
621   inline void PopWRegList(RegList regs) {
622     PopSizeRegList(regs, kWRegSizeInBits);
623   }
624   inline void PushDRegList(RegList regs) {
625     PushSizeRegList(regs, kDRegSizeInBits, CPURegister::kFPRegister);
626   }
627   inline void PopDRegList(RegList regs) {
628     PopSizeRegList(regs, kDRegSizeInBits, CPURegister::kFPRegister);
629   }
630   inline void PushSRegList(RegList regs) {
631     PushSizeRegList(regs, kSRegSizeInBits, CPURegister::kFPRegister);
632   }
633   inline void PopSRegList(RegList regs) {
634     PopSizeRegList(regs, kSRegSizeInBits, CPURegister::kFPRegister);
635   }
636
637   // Push the specified register 'count' times.
638   void PushMultipleTimes(CPURegister src, Register count);
639   void PushMultipleTimes(CPURegister src, int count);
640
641   // This is a convenience method for pushing a single Handle<Object>.
642   inline void Push(Handle<Object> handle);
643   void Push(Smi* smi) { Push(Handle<Smi>(smi, isolate())); }
644
645   // Aliases of Push and Pop, required for V8 compatibility.
646   inline void push(Register src) {
647     Push(src);
648   }
649   inline void pop(Register dst) {
650     Pop(dst);
651   }
652
653   // Sometimes callers need to push or pop multiple registers in a way that is
654   // difficult to structure efficiently for fixed Push or Pop calls. This scope
655   // allows push requests to be queued up, then flushed at once. The
656   // MacroAssembler will try to generate the most efficient sequence required.
657   //
658   // Unlike the other Push and Pop macros, PushPopQueue can handle mixed sets of
659   // register sizes and types.
660   class PushPopQueue {
661    public:
662     explicit PushPopQueue(MacroAssembler* masm) : masm_(masm), size_(0) { }
663
664     ~PushPopQueue() {
665       DCHECK(queued_.empty());
666     }
667
668     void Queue(const CPURegister& rt) {
669       size_ += rt.SizeInBytes();
670       queued_.push_back(rt);
671     }
672
673     enum PreambleDirective {
674       WITH_PREAMBLE,
675       SKIP_PREAMBLE
676     };
677     void PushQueued(PreambleDirective preamble_directive = WITH_PREAMBLE);
678     void PopQueued();
679
680    private:
681     MacroAssembler* masm_;
682     int size_;
683     std::vector<CPURegister> queued_;
684   };
685
686   // Poke 'src' onto the stack. The offset is in bytes.
687   //
688   // If the current stack pointer (according to StackPointer()) is csp, then
689   // csp must be aligned to 16 bytes.
690   void Poke(const CPURegister& src, const Operand& offset);
691
692   // Peek at a value on the stack, and put it in 'dst'. The offset is in bytes.
693   //
694   // If the current stack pointer (according to StackPointer()) is csp, then
695   // csp must be aligned to 16 bytes.
696   void Peek(const CPURegister& dst, const Operand& offset);
697
698   // Poke 'src1' and 'src2' onto the stack. The values written will be adjacent
699   // with 'src2' at a higher address than 'src1'. The offset is in bytes.
700   //
701   // If the current stack pointer (according to StackPointer()) is csp, then
702   // csp must be aligned to 16 bytes.
703   void PokePair(const CPURegister& src1, const CPURegister& src2, int offset);
704
705   // Peek at two values on the stack, and put them in 'dst1' and 'dst2'. The
706   // values peeked will be adjacent, with the value in 'dst2' being from a
707   // higher address than 'dst1'. The offset is in bytes.
708   //
709   // If the current stack pointer (according to StackPointer()) is csp, then
710   // csp must be aligned to 16 bytes.
711   void PeekPair(const CPURegister& dst1, const CPURegister& dst2, int offset);
712
713   // Claim or drop stack space without actually accessing memory.
714   //
715   // In debug mode, both of these will write invalid data into the claimed or
716   // dropped space.
717   //
718   // If the current stack pointer (according to StackPointer()) is csp, then it
719   // must be aligned to 16 bytes and the size claimed or dropped must be a
720   // multiple of 16 bytes.
721   //
722   // Note that unit_size must be specified in bytes. For variants which take a
723   // Register count, the unit size must be a power of two.
724   inline void Claim(uint64_t count, uint64_t unit_size = kXRegSize);
725   inline void Claim(const Register& count,
726                     uint64_t unit_size = kXRegSize);
727   inline void Drop(uint64_t count, uint64_t unit_size = kXRegSize);
728   inline void Drop(const Register& count,
729                    uint64_t unit_size = kXRegSize);
730
731   // Variants of Claim and Drop, where the 'count' parameter is a SMI held in a
732   // register.
733   inline void ClaimBySMI(const Register& count_smi,
734                          uint64_t unit_size = kXRegSize);
735   inline void DropBySMI(const Register& count_smi,
736                         uint64_t unit_size = kXRegSize);
737
738   // Compare a register with an operand, and branch to label depending on the
739   // condition. May corrupt the status flags.
740   inline void CompareAndBranch(const Register& lhs,
741                                const Operand& rhs,
742                                Condition cond,
743                                Label* label);
744
745   // Test the bits of register defined by bit_pattern, and branch if ANY of
746   // those bits are set. May corrupt the status flags.
747   inline void TestAndBranchIfAnySet(const Register& reg,
748                                     const uint64_t bit_pattern,
749                                     Label* label);
750
751   // Test the bits of register defined by bit_pattern, and branch if ALL of
752   // those bits are clear (ie. not set.) May corrupt the status flags.
753   inline void TestAndBranchIfAllClear(const Register& reg,
754                                       const uint64_t bit_pattern,
755                                       Label* label);
756
757   // Insert one or more instructions into the instruction stream that encode
758   // some caller-defined data. The instructions used will be executable with no
759   // side effects.
760   inline void InlineData(uint64_t data);
761
762   // Insert an instrumentation enable marker into the instruction stream.
763   inline void EnableInstrumentation();
764
765   // Insert an instrumentation disable marker into the instruction stream.
766   inline void DisableInstrumentation();
767
768   // Insert an instrumentation event marker into the instruction stream. These
769   // will be picked up by the instrumentation system to annotate an instruction
770   // profile. The argument marker_name must be a printable two character string;
771   // it will be encoded in the event marker.
772   inline void AnnotateInstrumentation(const char* marker_name);
773
774   // If emit_debug_code() is true, emit a run-time check to ensure that
775   // StackPointer() does not point below the system stack pointer.
776   //
777   // Whilst it is architecturally legal for StackPointer() to point below csp,
778   // it can be evidence of a potential bug because the ABI forbids accesses
779   // below csp.
780   //
781   // If StackPointer() is the system stack pointer (csp), then csp will be
782   // dereferenced to cause the processor (or simulator) to abort if it is not
783   // properly aligned.
784   //
785   // If emit_debug_code() is false, this emits no code.
786   void AssertStackConsistency();
787
788   // Preserve the callee-saved registers (as defined by AAPCS64).
789   //
790   // Higher-numbered registers are pushed before lower-numbered registers, and
791   // thus get higher addresses.
792   // Floating-point registers are pushed before general-purpose registers, and
793   // thus get higher addresses.
794   //
795   // Note that registers are not checked for invalid values. Use this method
796   // only if you know that the GC won't try to examine the values on the stack.
797   //
798   // This method must not be called unless the current stack pointer (as set by
799   // SetStackPointer) is the system stack pointer (csp), and is aligned to
800   // ActivationFrameAlignment().
801   void PushCalleeSavedRegisters();
802
803   // Restore the callee-saved registers (as defined by AAPCS64).
804   //
805   // Higher-numbered registers are popped after lower-numbered registers, and
806   // thus come from higher addresses.
807   // Floating-point registers are popped after general-purpose registers, and
808   // thus come from higher addresses.
809   //
810   // This method must not be called unless the current stack pointer (as set by
811   // SetStackPointer) is the system stack pointer (csp), and is aligned to
812   // ActivationFrameAlignment().
813   void PopCalleeSavedRegisters();
814
815   // Set the current stack pointer, but don't generate any code.
816   inline void SetStackPointer(const Register& stack_pointer) {
817     DCHECK(!TmpList()->IncludesAliasOf(stack_pointer));
818     sp_ = stack_pointer;
819   }
820
821   // Return the current stack pointer, as set by SetStackPointer.
822   inline const Register& StackPointer() const {
823     return sp_;
824   }
825
826   // Align csp for a frame, as per ActivationFrameAlignment, and make it the
827   // current stack pointer.
828   inline void AlignAndSetCSPForFrame() {
829     int sp_alignment = ActivationFrameAlignment();
830     // AAPCS64 mandates at least 16-byte alignment.
831     DCHECK(sp_alignment >= 16);
832     DCHECK(base::bits::IsPowerOfTwo32(sp_alignment));
833     Bic(csp, StackPointer(), sp_alignment - 1);
834     SetStackPointer(csp);
835   }
836
837   // Push the system stack pointer (csp) down to allow the same to be done to
838   // the current stack pointer (according to StackPointer()). This must be
839   // called _before_ accessing the memory.
840   //
841   // This is necessary when pushing or otherwise adding things to the stack, to
842   // satisfy the AAPCS64 constraint that the memory below the system stack
843   // pointer is not accessed.  The amount pushed will be increased as necessary
844   // to ensure csp remains aligned to 16 bytes.
845   //
846   // This method asserts that StackPointer() is not csp, since the call does
847   // not make sense in that context.
848   inline void BumpSystemStackPointer(const Operand& space);
849
850   // Re-synchronizes the system stack pointer (csp) with the current stack
851   // pointer (according to StackPointer()).
852   //
853   // This method asserts that StackPointer() is not csp, since the call does
854   // not make sense in that context.
855   inline void SyncSystemStackPointer();
856
857   // Helpers ------------------------------------------------------------------
858   // Root register.
859   inline void InitializeRootRegister();
860
861   void AssertFPCRState(Register fpcr = NoReg);
862   void ConfigureFPCR();
863   void CanonicalizeNaN(const FPRegister& dst, const FPRegister& src);
864   void CanonicalizeNaN(const FPRegister& reg) {
865     CanonicalizeNaN(reg, reg);
866   }
867
868   // Load an object from the root table.
869   void LoadRoot(CPURegister destination,
870                 Heap::RootListIndex index);
871   // Store an object to the root table.
872   void StoreRoot(Register source,
873                  Heap::RootListIndex index);
874
875   // Load both TrueValue and FalseValue roots.
876   void LoadTrueFalseRoots(Register true_root, Register false_root);
877
878   void LoadHeapObject(Register dst, Handle<HeapObject> object);
879
880   void LoadObject(Register result, Handle<Object> object) {
881     AllowDeferredHandleDereference heap_object_check;
882     if (object->IsHeapObject()) {
883       LoadHeapObject(result, Handle<HeapObject>::cast(object));
884     } else {
885       DCHECK(object->IsSmi());
886       Mov(result, Operand(object));
887     }
888   }
889
890   static int SafepointRegisterStackIndex(int reg_code);
891
892   // This is required for compatibility with architecture independant code.
893   // Remove if not needed.
894   inline void Move(Register dst, Register src) { Mov(dst, src); }
895
896   void LoadInstanceDescriptors(Register map,
897                                Register descriptors);
898   void EnumLengthUntagged(Register dst, Register map);
899   void EnumLengthSmi(Register dst, Register map);
900   void NumberOfOwnDescriptors(Register dst, Register map);
901   void LoadAccessor(Register dst, Register holder, int accessor_index,
902                     AccessorComponent accessor);
903
904   template<typename Field>
905   void DecodeField(Register dst, Register src) {
906     static const int shift = Field::kShift;
907     static const int setbits = CountSetBits(Field::kMask, 32);
908     Ubfx(dst, src, shift, setbits);
909   }
910
911   template<typename Field>
912   void DecodeField(Register reg) {
913     DecodeField<Field>(reg, reg);
914   }
915
916   // ---- SMI and Number Utilities ----
917
918   inline void SmiTag(Register dst, Register src);
919   inline void SmiTag(Register smi);
920   inline void SmiUntag(Register dst, Register src);
921   inline void SmiUntag(Register smi);
922   inline void SmiUntagToDouble(FPRegister dst,
923                                Register src,
924                                UntagMode mode = kNotSpeculativeUntag);
925   inline void SmiUntagToFloat(FPRegister dst,
926                               Register src,
927                               UntagMode mode = kNotSpeculativeUntag);
928
929   // Tag and push in one step.
930   inline void SmiTagAndPush(Register src);
931   inline void SmiTagAndPush(Register src1, Register src2);
932
933   inline void JumpIfSmi(Register value,
934                         Label* smi_label,
935                         Label* not_smi_label = NULL);
936   inline void JumpIfNotSmi(Register value, Label* not_smi_label);
937   inline void JumpIfBothSmi(Register value1,
938                             Register value2,
939                             Label* both_smi_label,
940                             Label* not_smi_label = NULL);
941   inline void JumpIfEitherSmi(Register value1,
942                               Register value2,
943                               Label* either_smi_label,
944                               Label* not_smi_label = NULL);
945   inline void JumpIfEitherNotSmi(Register value1,
946                                  Register value2,
947                                  Label* not_smi_label);
948   inline void JumpIfBothNotSmi(Register value1,
949                                Register value2,
950                                Label* not_smi_label);
951
952   // Abort execution if argument is a smi, enabled via --debug-code.
953   void AssertNotSmi(Register object, BailoutReason reason = kOperandIsASmi);
954   void AssertSmi(Register object, BailoutReason reason = kOperandIsNotASmi);
955
956   inline void ObjectTag(Register tagged_obj, Register obj);
957   inline void ObjectUntag(Register untagged_obj, Register obj);
958
959   // Abort execution if argument is not a name, enabled via --debug-code.
960   void AssertName(Register object);
961
962   // Abort execution if argument is not a JSFunction, enabled via --debug-code.
963   void AssertFunction(Register object);
964
965   // Abort execution if argument is not undefined or an AllocationSite, enabled
966   // via --debug-code.
967   void AssertUndefinedOrAllocationSite(Register object, Register scratch);
968
969   // Abort execution if argument is not a string, enabled via --debug-code.
970   void AssertString(Register object);
971
972   void JumpIfHeapNumber(Register object, Label* on_heap_number,
973                         SmiCheckType smi_check_type = DONT_DO_SMI_CHECK);
974   void JumpIfNotHeapNumber(Register object, Label* on_not_heap_number,
975                            SmiCheckType smi_check_type = DONT_DO_SMI_CHECK);
976
977   // Sets the vs flag if the input is -0.0.
978   void TestForMinusZero(DoubleRegister input);
979
980   // Jump to label if the input double register contains -0.0.
981   void JumpIfMinusZero(DoubleRegister input, Label* on_negative_zero);
982
983   // Jump to label if the input integer register contains the double precision
984   // floating point representation of -0.0.
985   void JumpIfMinusZero(Register input, Label* on_negative_zero);
986
987   // Saturate a signed 32-bit integer in input to an unsigned 8-bit integer in
988   // output.
989   void ClampInt32ToUint8(Register in_out);
990   void ClampInt32ToUint8(Register output, Register input);
991
992   // Saturate a double in input to an unsigned 8-bit integer in output.
993   void ClampDoubleToUint8(Register output,
994                           DoubleRegister input,
995                           DoubleRegister dbl_scratch);
996
997   // Try to represent a double as a signed 32-bit int.
998   // This succeeds if the result compares equal to the input, so inputs of -0.0
999   // are represented as 0 and handled as a success.
1000   //
1001   // On output the Z flag is set if the operation was successful.
1002   void TryRepresentDoubleAsInt32(Register as_int,
1003                                  FPRegister value,
1004                                  FPRegister scratch_d,
1005                                  Label* on_successful_conversion = NULL,
1006                                  Label* on_failed_conversion = NULL) {
1007     DCHECK(as_int.Is32Bits());
1008     TryRepresentDoubleAsInt(as_int, value, scratch_d, on_successful_conversion,
1009                             on_failed_conversion);
1010   }
1011
1012   // Try to represent a double as a signed 64-bit int.
1013   // This succeeds if the result compares equal to the input, so inputs of -0.0
1014   // are represented as 0 and handled as a success.
1015   //
1016   // On output the Z flag is set if the operation was successful.
1017   void TryRepresentDoubleAsInt64(Register as_int,
1018                                  FPRegister value,
1019                                  FPRegister scratch_d,
1020                                  Label* on_successful_conversion = NULL,
1021                                  Label* on_failed_conversion = NULL) {
1022     DCHECK(as_int.Is64Bits());
1023     TryRepresentDoubleAsInt(as_int, value, scratch_d, on_successful_conversion,
1024                             on_failed_conversion);
1025   }
1026
1027   // ---- Object Utilities ----
1028
1029   // Copy fields from 'src' to 'dst', where both are tagged objects.
1030   // The 'temps' list is a list of X registers which can be used for scratch
1031   // values. The temps list must include at least one register.
1032   //
1033   // Currently, CopyFields cannot make use of more than three registers from
1034   // the 'temps' list.
1035   //
1036   // CopyFields expects to be able to take at least two registers from
1037   // MacroAssembler::TmpList().
1038   void CopyFields(Register dst, Register src, CPURegList temps, unsigned count);
1039
1040   // Starting at address in dst, initialize field_count 64-bit fields with
1041   // 64-bit value in register filler. Register dst is corrupted.
1042   void FillFields(Register dst,
1043                   Register field_count,
1044                   Register filler);
1045
1046   // Copies a number of bytes from src to dst. All passed registers are
1047   // clobbered. On exit src and dst will point to the place just after where the
1048   // last byte was read or written and length will be zero. Hint may be used to
1049   // determine which is the most efficient algorithm to use for copying.
1050   void CopyBytes(Register dst,
1051                  Register src,
1052                  Register length,
1053                  Register scratch,
1054                  CopyHint hint = kCopyUnknown);
1055
1056   // ---- String Utilities ----
1057
1058
1059   // Jump to label if either object is not a sequential one-byte string.
1060   // Optionally perform a smi check on the objects first.
1061   void JumpIfEitherIsNotSequentialOneByteStrings(
1062       Register first, Register second, Register scratch1, Register scratch2,
1063       Label* failure, SmiCheckType smi_check = DO_SMI_CHECK);
1064
1065   // Check if instance type is sequential one-byte string and jump to label if
1066   // it is not.
1067   void JumpIfInstanceTypeIsNotSequentialOneByte(Register type, Register scratch,
1068                                                 Label* failure);
1069
1070   // Checks if both instance types are sequential one-byte strings and jumps to
1071   // label if either is not.
1072   void JumpIfEitherInstanceTypeIsNotSequentialOneByte(
1073       Register first_object_instance_type, Register second_object_instance_type,
1074       Register scratch1, Register scratch2, Label* failure);
1075
1076   // Checks if both instance types are sequential one-byte strings and jumps to
1077   // label if either is not.
1078   void JumpIfBothInstanceTypesAreNotSequentialOneByte(
1079       Register first_object_instance_type, Register second_object_instance_type,
1080       Register scratch1, Register scratch2, Label* failure);
1081
1082   void JumpIfNotUniqueNameInstanceType(Register type, Label* not_unique_name);
1083
1084   // ---- Calling / Jumping helpers ----
1085
1086   // This is required for compatibility in architecture indepenedant code.
1087   inline void jmp(Label* L) { B(L); }
1088
1089   void CallStub(CodeStub* stub, TypeFeedbackId ast_id = TypeFeedbackId::None());
1090   void TailCallStub(CodeStub* stub);
1091
1092   void CallRuntime(const Runtime::Function* f,
1093                    int num_arguments,
1094                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
1095
1096   void CallRuntime(Runtime::FunctionId id,
1097                    int num_arguments,
1098                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
1099     CallRuntime(Runtime::FunctionForId(id), num_arguments, save_doubles);
1100   }
1101
1102   void CallRuntimeSaveDoubles(Runtime::FunctionId id) {
1103     const Runtime::Function* function = Runtime::FunctionForId(id);
1104     CallRuntime(function, function->nargs, kSaveFPRegs);
1105   }
1106
1107   void TailCallRuntime(Runtime::FunctionId fid,
1108                        int num_arguments,
1109                        int result_size);
1110
1111   int ActivationFrameAlignment();
1112
1113   // Calls a C function.
1114   // The called function is not allowed to trigger a
1115   // garbage collection, since that might move the code and invalidate the
1116   // return address (unless this is somehow accounted for by the called
1117   // function).
1118   void CallCFunction(ExternalReference function,
1119                      int num_reg_arguments);
1120   void CallCFunction(ExternalReference function,
1121                      int num_reg_arguments,
1122                      int num_double_arguments);
1123   void CallCFunction(Register function,
1124                      int num_reg_arguments,
1125                      int num_double_arguments);
1126
1127   // Jump to a runtime routine.
1128   void JumpToExternalReference(const ExternalReference& builtin);
1129   // Tail call of a runtime routine (jump).
1130   // Like JumpToExternalReference, but also takes care of passing the number
1131   // of parameters.
1132   void TailCallExternalReference(const ExternalReference& ext,
1133                                  int num_arguments,
1134                                  int result_size);
1135   void CallExternalReference(const ExternalReference& ext,
1136                              int num_arguments);
1137
1138
1139   // Invoke specified builtin JavaScript function.
1140   void InvokeBuiltin(int native_context_index, InvokeFlag flag,
1141                      const CallWrapper& call_wrapper = NullCallWrapper());
1142
1143   // Store the code object for the given builtin in the target register and
1144   // setup the function in the function register.
1145   void GetBuiltinEntry(Register target, Register function,
1146                        int native_context_index);
1147
1148   // Store the function for the given builtin in the target register.
1149   void GetBuiltinFunction(Register target, int native_context_index);
1150
1151   void Jump(Register target);
1152   void Jump(Address target, RelocInfo::Mode rmode, Condition cond = al);
1153   void Jump(Handle<Code> code, RelocInfo::Mode rmode, Condition cond = al);
1154   void Jump(intptr_t target, RelocInfo::Mode rmode, Condition cond = al);
1155
1156   void Call(Register target);
1157   void Call(Label* target);
1158   void Call(Address target, RelocInfo::Mode rmode);
1159   void Call(Handle<Code> code,
1160             RelocInfo::Mode rmode = RelocInfo::CODE_TARGET,
1161             TypeFeedbackId ast_id = TypeFeedbackId::None());
1162
1163   // For every Call variant, there is a matching CallSize function that returns
1164   // the size (in bytes) of the call sequence.
1165   static int CallSize(Register target);
1166   static int CallSize(Label* target);
1167   static int CallSize(Address target, RelocInfo::Mode rmode);
1168   static int CallSize(Handle<Code> code,
1169                       RelocInfo::Mode rmode = RelocInfo::CODE_TARGET,
1170                       TypeFeedbackId ast_id = TypeFeedbackId::None());
1171
1172   // Registers used through the invocation chain are hard-coded.
1173   // We force passing the parameters to ensure the contracts are correctly
1174   // honoured by the caller.
1175   // 'function' must be x1.
1176   // 'actual' must use an immediate or x0.
1177   // 'expected' must use an immediate or x2.
1178   // 'call_kind' must be x5.
1179   void InvokePrologue(const ParameterCount& expected,
1180                       const ParameterCount& actual,
1181                       Handle<Code> code_constant,
1182                       Register code_reg,
1183                       Label* done,
1184                       InvokeFlag flag,
1185                       bool* definitely_mismatches,
1186                       const CallWrapper& call_wrapper);
1187   void InvokeCode(Register code,
1188                   const ParameterCount& expected,
1189                   const ParameterCount& actual,
1190                   InvokeFlag flag,
1191                   const CallWrapper& call_wrapper);
1192   // Invoke the JavaScript function in the given register.
1193   // Changes the current context to the context in the function before invoking.
1194   void InvokeFunction(Register function,
1195                       const ParameterCount& actual,
1196                       InvokeFlag flag,
1197                       const CallWrapper& call_wrapper);
1198   void InvokeFunction(Register function,
1199                       const ParameterCount& expected,
1200                       const ParameterCount& actual,
1201                       InvokeFlag flag,
1202                       const CallWrapper& call_wrapper);
1203   void InvokeFunction(Handle<JSFunction> function,
1204                       const ParameterCount& expected,
1205                       const ParameterCount& actual,
1206                       InvokeFlag flag,
1207                       const CallWrapper& call_wrapper);
1208
1209
1210   // ---- Floating point helpers ----
1211
1212   // Perform a conversion from a double to a signed int64. If the input fits in
1213   // range of the 64-bit result, execution branches to done. Otherwise,
1214   // execution falls through, and the sign of the result can be used to
1215   // determine if overflow was towards positive or negative infinity.
1216   //
1217   // On successful conversion, the least significant 32 bits of the result are
1218   // equivalent to the ECMA-262 operation "ToInt32".
1219   //
1220   // Only public for the test code in test-code-stubs-arm64.cc.
1221   void TryConvertDoubleToInt64(Register result,
1222                                DoubleRegister input,
1223                                Label* done);
1224
1225   // Performs a truncating conversion of a floating point number as used by
1226   // the JS bitwise operations. See ECMA-262 9.5: ToInt32.
1227   // Exits with 'result' holding the answer.
1228   void TruncateDoubleToI(Register result, DoubleRegister double_input);
1229
1230   // Performs a truncating conversion of a heap number as used by
1231   // the JS bitwise operations. See ECMA-262 9.5: ToInt32. 'result' and 'input'
1232   // must be different registers.  Exits with 'result' holding the answer.
1233   void TruncateHeapNumberToI(Register result, Register object);
1234
1235   // Converts the smi or heap number in object to an int32 using the rules
1236   // for ToInt32 as described in ECMAScript 9.5.: the value is truncated
1237   // and brought into the range -2^31 .. +2^31 - 1. 'result' and 'input' must be
1238   // different registers.
1239   void TruncateNumberToI(Register object,
1240                          Register result,
1241                          Register heap_number_map,
1242                          Label* not_int32);
1243
1244   // ---- Code generation helpers ----
1245
1246   void set_generating_stub(bool value) { generating_stub_ = value; }
1247   bool generating_stub() const { return generating_stub_; }
1248 #if DEBUG
1249   void set_allow_macro_instructions(bool value) {
1250     allow_macro_instructions_ = value;
1251   }
1252   bool allow_macro_instructions() const { return allow_macro_instructions_; }
1253 #endif
1254   bool use_real_aborts() const { return use_real_aborts_; }
1255   void set_has_frame(bool value) { has_frame_ = value; }
1256   bool has_frame() const { return has_frame_; }
1257   bool AllowThisStubCall(CodeStub* stub);
1258
1259   class NoUseRealAbortsScope {
1260    public:
1261     explicit NoUseRealAbortsScope(MacroAssembler* masm) :
1262         saved_(masm->use_real_aborts_), masm_(masm) {
1263       masm_->use_real_aborts_ = false;
1264     }
1265     ~NoUseRealAbortsScope() {
1266       masm_->use_real_aborts_ = saved_;
1267     }
1268    private:
1269     bool saved_;
1270     MacroAssembler* masm_;
1271   };
1272
1273   // ---------------------------------------------------------------------------
1274   // Debugger Support
1275
1276   void DebugBreak();
1277
1278   // ---------------------------------------------------------------------------
1279   // Exception handling
1280
1281   // Push a new stack handler and link into stack handler chain.
1282   void PushStackHandler();
1283
1284   // Unlink the stack handler on top of the stack from the stack handler chain.
1285   // Must preserve the result register.
1286   void PopStackHandler();
1287
1288
1289   // ---------------------------------------------------------------------------
1290   // Allocation support
1291
1292   // Allocate an object in new space or old space. The object_size is
1293   // specified either in bytes or in words if the allocation flag SIZE_IN_WORDS
1294   // is passed. The allocated object is returned in result.
1295   //
1296   // If the new space is exhausted control continues at the gc_required label.
1297   // In this case, the result and scratch registers may still be clobbered.
1298   // If flags includes TAG_OBJECT, the result is tagged as as a heap object.
1299   void Allocate(Register object_size,
1300                 Register result,
1301                 Register scratch1,
1302                 Register scratch2,
1303                 Label* gc_required,
1304                 AllocationFlags flags);
1305
1306   void Allocate(int object_size,
1307                 Register result,
1308                 Register scratch1,
1309                 Register scratch2,
1310                 Label* gc_required,
1311                 AllocationFlags flags);
1312
1313   void AllocateTwoByteString(Register result,
1314                              Register length,
1315                              Register scratch1,
1316                              Register scratch2,
1317                              Register scratch3,
1318                              Label* gc_required);
1319   void AllocateOneByteString(Register result, Register length,
1320                              Register scratch1, Register scratch2,
1321                              Register scratch3, Label* gc_required);
1322   void AllocateTwoByteConsString(Register result,
1323                                  Register length,
1324                                  Register scratch1,
1325                                  Register scratch2,
1326                                  Label* gc_required);
1327   void AllocateOneByteConsString(Register result, Register length,
1328                                  Register scratch1, Register scratch2,
1329                                  Label* gc_required);
1330   void AllocateTwoByteSlicedString(Register result,
1331                                    Register length,
1332                                    Register scratch1,
1333                                    Register scratch2,
1334                                    Label* gc_required);
1335   void AllocateOneByteSlicedString(Register result, Register length,
1336                                    Register scratch1, Register scratch2,
1337                                    Label* gc_required);
1338
1339   // Allocates a heap number or jumps to the gc_required label if the young
1340   // space is full and a scavenge is needed.
1341   // All registers are clobbered.
1342   // If no heap_number_map register is provided, the function will take care of
1343   // loading it.
1344   void AllocateHeapNumber(Register result,
1345                           Label* gc_required,
1346                           Register scratch1,
1347                           Register scratch2,
1348                           CPURegister value = NoFPReg,
1349                           CPURegister heap_number_map = NoReg,
1350                           MutableMode mode = IMMUTABLE);
1351
1352   // ---------------------------------------------------------------------------
1353   // Support functions.
1354
1355   // Machine code version of Map::GetConstructor().
1356   // |temp| holds |result|'s map when done, and |temp2| its instance type.
1357   void GetMapConstructor(Register result, Register map, Register temp,
1358                          Register temp2);
1359
1360   void TryGetFunctionPrototype(Register function, Register result,
1361                                Register scratch, Label* miss);
1362
1363   // Compare object type for heap object.  heap_object contains a non-Smi
1364   // whose object type should be compared with the given type.  This both
1365   // sets the flags and leaves the object type in the type_reg register.
1366   // It leaves the map in the map register (unless the type_reg and map register
1367   // are the same register).  It leaves the heap object in the heap_object
1368   // register unless the heap_object register is the same register as one of the
1369   // other registers.
1370   void CompareObjectType(Register heap_object,
1371                          Register map,
1372                          Register type_reg,
1373                          InstanceType type);
1374
1375
1376   // Compare object type for heap object, and branch if equal (or not.)
1377   // heap_object contains a non-Smi whose object type should be compared with
1378   // the given type.  This both sets the flags and leaves the object type in
1379   // the type_reg register. It leaves the map in the map register (unless the
1380   // type_reg and map register are the same register).  It leaves the heap
1381   // object in the heap_object register unless the heap_object register is the
1382   // same register as one of the other registers.
1383   void JumpIfObjectType(Register object,
1384                         Register map,
1385                         Register type_reg,
1386                         InstanceType type,
1387                         Label* if_cond_pass,
1388                         Condition cond = eq);
1389
1390   void JumpIfNotObjectType(Register object,
1391                            Register map,
1392                            Register type_reg,
1393                            InstanceType type,
1394                            Label* if_not_object);
1395
1396   // Compare instance type in a map.  map contains a valid map object whose
1397   // object type should be compared with the given type.  This both
1398   // sets the flags and leaves the object type in the type_reg register.
1399   void CompareInstanceType(Register map,
1400                            Register type_reg,
1401                            InstanceType type);
1402
1403   // Compare an object's map with the specified map. Condition flags are set
1404   // with result of map compare.
1405   void CompareObjectMap(Register obj, Heap::RootListIndex index);
1406
1407   // Compare an object's map with the specified map. Condition flags are set
1408   // with result of map compare.
1409   void CompareObjectMap(Register obj, Register scratch, Handle<Map> map);
1410
1411   // As above, but the map of the object is already loaded into the register
1412   // which is preserved by the code generated.
1413   void CompareMap(Register obj_map,
1414                   Handle<Map> map);
1415
1416   // Check if the map of an object is equal to a specified map and branch to
1417   // label if not. Skip the smi check if not required (object is known to be a
1418   // heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match
1419   // against maps that are ElementsKind transition maps of the specified map.
1420   void CheckMap(Register obj,
1421                 Register scratch,
1422                 Handle<Map> map,
1423                 Label* fail,
1424                 SmiCheckType smi_check_type);
1425
1426
1427   void CheckMap(Register obj,
1428                 Register scratch,
1429                 Heap::RootListIndex index,
1430                 Label* fail,
1431                 SmiCheckType smi_check_type);
1432
1433   // As above, but the map of the object is already loaded into obj_map, and is
1434   // preserved.
1435   void CheckMap(Register obj_map,
1436                 Handle<Map> map,
1437                 Label* fail,
1438                 SmiCheckType smi_check_type);
1439
1440   // Check if the map of an object is equal to a specified weak map and branch
1441   // to a specified target if equal. Skip the smi check if not required
1442   // (object is known to be a heap object)
1443   void DispatchWeakMap(Register obj, Register scratch1, Register scratch2,
1444                        Handle<WeakCell> cell, Handle<Code> success,
1445                        SmiCheckType smi_check_type);
1446
1447   // Compare the given value and the value of weak cell.
1448   void CmpWeakValue(Register value, Handle<WeakCell> cell, Register scratch);
1449
1450   void GetWeakValue(Register value, Handle<WeakCell> cell);
1451
1452   // Load the value of the weak cell in the value register. Branch to the given
1453   // miss label if the weak cell was cleared.
1454   void LoadWeakValue(Register value, Handle<WeakCell> cell, Label* miss);
1455
1456   // Test the bitfield of the heap object map with mask and set the condition
1457   // flags. The object register is preserved.
1458   void TestMapBitfield(Register object, uint64_t mask);
1459
1460   // Load the elements kind field from a map, and return it in the result
1461   // register.
1462   void LoadElementsKindFromMap(Register result, Register map);
1463
1464   // Compare the object in a register to a value from the root list.
1465   void CompareRoot(const Register& obj, Heap::RootListIndex index);
1466
1467   // Compare the object in a register to a value and jump if they are equal.
1468   void JumpIfRoot(const Register& obj,
1469                   Heap::RootListIndex index,
1470                   Label* if_equal);
1471
1472   // Compare the object in a register to a value and jump if they are not equal.
1473   void JumpIfNotRoot(const Register& obj,
1474                      Heap::RootListIndex index,
1475                      Label* if_not_equal);
1476
1477   // Load and check the instance type of an object for being a unique name.
1478   // Loads the type into the second argument register.
1479   // The object and type arguments can be the same register; in that case it
1480   // will be overwritten with the type.
1481   // Fall-through if the object was a string and jump on fail otherwise.
1482   inline void IsObjectNameType(Register object, Register type, Label* fail);
1483
1484   inline void IsObjectJSObjectType(Register heap_object,
1485                                    Register map,
1486                                    Register scratch,
1487                                    Label* fail);
1488
1489   // Check the instance type in the given map to see if it corresponds to a
1490   // JS object type. Jump to the fail label if this is not the case and fall
1491   // through otherwise. However if fail label is NULL, no branch will be
1492   // performed and the flag will be updated. You can test the flag for "le"
1493   // condition to test if it is a valid JS object type.
1494   inline void IsInstanceJSObjectType(Register map,
1495                                      Register scratch,
1496                                      Label* fail);
1497
1498   // Load and check the instance type of an object for being a string.
1499   // Loads the type into the second argument register.
1500   // The object and type arguments can be the same register; in that case it
1501   // will be overwritten with the type.
1502   // Jumps to not_string or string appropriate. If the appropriate label is
1503   // NULL, fall through.
1504   inline void IsObjectJSStringType(Register object, Register type,
1505                                    Label* not_string, Label* string = NULL);
1506
1507   // Compare the contents of a register with an operand, and branch to true,
1508   // false or fall through, depending on condition.
1509   void CompareAndSplit(const Register& lhs,
1510                        const Operand& rhs,
1511                        Condition cond,
1512                        Label* if_true,
1513                        Label* if_false,
1514                        Label* fall_through);
1515
1516   // Test the bits of register defined by bit_pattern, and branch to
1517   // if_any_set, if_all_clear or fall_through accordingly.
1518   void TestAndSplit(const Register& reg,
1519                     uint64_t bit_pattern,
1520                     Label* if_all_clear,
1521                     Label* if_any_set,
1522                     Label* fall_through);
1523
1524   // Check if a map for a JSObject indicates that the object has fast elements.
1525   // Jump to the specified label if it does not.
1526   void CheckFastElements(Register map, Register scratch, Label* fail);
1527
1528   // Check if a map for a JSObject indicates that the object can have both smi
1529   // and HeapObject elements.  Jump to the specified label if it does not.
1530   void CheckFastObjectElements(Register map, Register scratch, Label* fail);
1531
1532   // Check to see if number can be stored as a double in FastDoubleElements.
1533   // If it can, store it at the index specified by key_reg in the array,
1534   // otherwise jump to fail.
1535   void StoreNumberToDoubleElements(Register value_reg,
1536                                    Register key_reg,
1537                                    Register elements_reg,
1538                                    Register scratch1,
1539                                    FPRegister fpscratch1,
1540                                    Label* fail,
1541                                    int elements_offset = 0);
1542
1543   // Picks out an array index from the hash field.
1544   // Register use:
1545   //   hash - holds the index's hash. Clobbered.
1546   //   index - holds the overwritten index on exit.
1547   void IndexFromHash(Register hash, Register index);
1548
1549   // ---------------------------------------------------------------------------
1550   // Inline caching support.
1551
1552   void EmitSeqStringSetCharCheck(Register string,
1553                                  Register index,
1554                                  SeqStringSetCharCheckIndexType index_type,
1555                                  Register scratch,
1556                                  uint32_t encoding_mask);
1557
1558   // Generate code for checking access rights - used for security checks
1559   // on access to global objects across environments. The holder register
1560   // is left untouched, whereas both scratch registers are clobbered.
1561   void CheckAccessGlobalProxy(Register holder_reg,
1562                               Register scratch1,
1563                               Register scratch2,
1564                               Label* miss);
1565
1566   // Hash the interger value in 'key' register.
1567   // It uses the same algorithm as ComputeIntegerHash in utils.h.
1568   void GetNumberHash(Register key, Register scratch);
1569
1570   // Load value from the dictionary.
1571   //
1572   // elements - holds the slow-case elements of the receiver on entry.
1573   //            Unchanged unless 'result' is the same register.
1574   //
1575   // key      - holds the smi key on entry.
1576   //            Unchanged unless 'result' is the same register.
1577   //
1578   // result   - holds the result on exit if the load succeeded.
1579   //            Allowed to be the same as 'key' or 'result'.
1580   //            Unchanged on bailout so 'key' or 'result' can be used
1581   //            in further computation.
1582   void LoadFromNumberDictionary(Label* miss,
1583                                 Register elements,
1584                                 Register key,
1585                                 Register result,
1586                                 Register scratch0,
1587                                 Register scratch1,
1588                                 Register scratch2,
1589                                 Register scratch3);
1590
1591   // ---------------------------------------------------------------------------
1592   // Frames.
1593
1594   // Load the type feedback vector from a JavaScript frame.
1595   void EmitLoadTypeFeedbackVector(Register vector);
1596
1597   // Activation support.
1598   void EnterFrame(StackFrame::Type type);
1599   void EnterFrame(StackFrame::Type type, bool load_constant_pool_pointer_reg);
1600   void LeaveFrame(StackFrame::Type type);
1601
1602   // Returns map with validated enum cache in object register.
1603   void CheckEnumCache(Register object,
1604                       Register null_value,
1605                       Register scratch0,
1606                       Register scratch1,
1607                       Register scratch2,
1608                       Register scratch3,
1609                       Label* call_runtime);
1610
1611   // AllocationMemento support. Arrays may have an associated
1612   // AllocationMemento object that can be checked for in order to pretransition
1613   // to another type.
1614   // On entry, receiver should point to the array object.
1615   // If allocation info is present, the Z flag is set (so that the eq
1616   // condition will pass).
1617   void TestJSArrayForAllocationMemento(Register receiver,
1618                                        Register scratch1,
1619                                        Register scratch2,
1620                                        Label* no_memento_found);
1621
1622   void JumpIfJSArrayHasAllocationMemento(Register receiver,
1623                                          Register scratch1,
1624                                          Register scratch2,
1625                                          Label* memento_found) {
1626     Label no_memento_found;
1627     TestJSArrayForAllocationMemento(receiver, scratch1, scratch2,
1628                                     &no_memento_found);
1629     B(eq, memento_found);
1630     Bind(&no_memento_found);
1631   }
1632
1633   // The stack pointer has to switch between csp and jssp when setting up and
1634   // destroying the exit frame. Hence preserving/restoring the registers is
1635   // slightly more complicated than simple push/pop operations.
1636   void ExitFramePreserveFPRegs();
1637   void ExitFrameRestoreFPRegs();
1638
1639   // Generates function and stub prologue code.
1640   void StubPrologue();
1641   void Prologue(bool code_pre_aging);
1642
1643   // Enter exit frame. Exit frames are used when calling C code from generated
1644   // (JavaScript) code.
1645   //
1646   // The stack pointer must be jssp on entry, and will be set to csp by this
1647   // function. The frame pointer is also configured, but the only other
1648   // registers modified by this function are the provided scratch register, and
1649   // jssp.
1650   //
1651   // The 'extra_space' argument can be used to allocate some space in the exit
1652   // frame that will be ignored by the GC. This space will be reserved in the
1653   // bottom of the frame immediately above the return address slot.
1654   //
1655   // Set up a stack frame and registers as follows:
1656   //         fp[8]: CallerPC (lr)
1657   //   fp -> fp[0]: CallerFP (old fp)
1658   //         fp[-8]: SPOffset (new csp)
1659   //         fp[-16]: CodeObject()
1660   //         fp[-16 - fp-size]: Saved doubles, if saved_doubles is true.
1661   //         csp[8]: Memory reserved for the caller if extra_space != 0.
1662   //                 Alignment padding, if necessary.
1663   //  csp -> csp[0]: Space reserved for the return address.
1664   //
1665   // This function also stores the new frame information in the top frame, so
1666   // that the new frame becomes the current frame.
1667   void EnterExitFrame(bool save_doubles,
1668                       const Register& scratch,
1669                       int extra_space = 0);
1670
1671   // Leave the current exit frame, after a C function has returned to generated
1672   // (JavaScript) code.
1673   //
1674   // This effectively unwinds the operation of EnterExitFrame:
1675   //  * Preserved doubles are restored (if restore_doubles is true).
1676   //  * The frame information is removed from the top frame.
1677   //  * The exit frame is dropped.
1678   //  * The stack pointer is reset to jssp.
1679   //
1680   // The stack pointer must be csp on entry.
1681   void LeaveExitFrame(bool save_doubles,
1682                       const Register& scratch,
1683                       bool restore_context);
1684
1685   void LoadContext(Register dst, int context_chain_length);
1686
1687   // Load the global proxy from the current context.
1688   void LoadGlobalProxy(Register dst);
1689
1690   // Emit code for a truncating division by a constant. The dividend register is
1691   // unchanged. Dividend and result must be different.
1692   void TruncatingDiv(Register result, Register dividend, int32_t divisor);
1693
1694   // ---------------------------------------------------------------------------
1695   // StatsCounter support
1696
1697   void SetCounter(StatsCounter* counter, int value, Register scratch1,
1698                   Register scratch2);
1699   void IncrementCounter(StatsCounter* counter, int value, Register scratch1,
1700                         Register scratch2);
1701   void DecrementCounter(StatsCounter* counter, int value, Register scratch1,
1702                         Register scratch2);
1703
1704   // ---------------------------------------------------------------------------
1705   // Garbage collector support (GC).
1706
1707   enum RememberedSetFinalAction {
1708     kReturnAtEnd,
1709     kFallThroughAtEnd
1710   };
1711
1712   // Record in the remembered set the fact that we have a pointer to new space
1713   // at the address pointed to by the addr register. Only works if addr is not
1714   // in new space.
1715   void RememberedSetHelper(Register object,  // Used for debug code.
1716                            Register addr,
1717                            Register scratch1,
1718                            SaveFPRegsMode save_fp,
1719                            RememberedSetFinalAction and_then);
1720
1721   // Push and pop the registers that can hold pointers, as defined by the
1722   // RegList constant kSafepointSavedRegisters.
1723   void PushSafepointRegisters();
1724   void PopSafepointRegisters();
1725
1726   void PushSafepointRegistersAndDoubles();
1727   void PopSafepointRegistersAndDoubles();
1728
1729   // Store value in register src in the safepoint stack slot for register dst.
1730   void StoreToSafepointRegisterSlot(Register src, Register dst) {
1731     Poke(src, SafepointRegisterStackIndex(dst.code()) * kPointerSize);
1732   }
1733
1734   // Load the value of the src register from its safepoint stack slot
1735   // into register dst.
1736   void LoadFromSafepointRegisterSlot(Register dst, Register src) {
1737     Peek(src, SafepointRegisterStackIndex(dst.code()) * kPointerSize);
1738   }
1739
1740   void CheckPageFlagSet(const Register& object,
1741                         const Register& scratch,
1742                         int mask,
1743                         Label* if_any_set);
1744
1745   void CheckPageFlagClear(const Register& object,
1746                           const Register& scratch,
1747                           int mask,
1748                           Label* if_all_clear);
1749
1750   // Check if object is in new space and jump accordingly.
1751   // Register 'object' is preserved.
1752   void JumpIfNotInNewSpace(Register object,
1753                            Label* branch) {
1754     InNewSpace(object, ne, branch);
1755   }
1756
1757   void JumpIfInNewSpace(Register object,
1758                         Label* branch) {
1759     InNewSpace(object, eq, branch);
1760   }
1761
1762   // Notify the garbage collector that we wrote a pointer into an object.
1763   // |object| is the object being stored into, |value| is the object being
1764   // stored.  value and scratch registers are clobbered by the operation.
1765   // The offset is the offset from the start of the object, not the offset from
1766   // the tagged HeapObject pointer.  For use with FieldMemOperand(reg, off).
1767   void RecordWriteField(
1768       Register object,
1769       int offset,
1770       Register value,
1771       Register scratch,
1772       LinkRegisterStatus lr_status,
1773       SaveFPRegsMode save_fp,
1774       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
1775       SmiCheck smi_check = INLINE_SMI_CHECK,
1776       PointersToHereCheck pointers_to_here_check_for_value =
1777           kPointersToHereMaybeInteresting);
1778
1779   // As above, but the offset has the tag presubtracted. For use with
1780   // MemOperand(reg, off).
1781   inline void RecordWriteContextSlot(
1782       Register context,
1783       int offset,
1784       Register value,
1785       Register scratch,
1786       LinkRegisterStatus lr_status,
1787       SaveFPRegsMode save_fp,
1788       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
1789       SmiCheck smi_check = INLINE_SMI_CHECK,
1790       PointersToHereCheck pointers_to_here_check_for_value =
1791           kPointersToHereMaybeInteresting) {
1792     RecordWriteField(context,
1793                      offset + kHeapObjectTag,
1794                      value,
1795                      scratch,
1796                      lr_status,
1797                      save_fp,
1798                      remembered_set_action,
1799                      smi_check,
1800                      pointers_to_here_check_for_value);
1801   }
1802
1803   void RecordWriteForMap(
1804       Register object,
1805       Register map,
1806       Register dst,
1807       LinkRegisterStatus lr_status,
1808       SaveFPRegsMode save_fp);
1809
1810   // For a given |object| notify the garbage collector that the slot |address|
1811   // has been written.  |value| is the object being stored. The value and
1812   // address registers are clobbered by the operation.
1813   void RecordWrite(
1814       Register object,
1815       Register address,
1816       Register value,
1817       LinkRegisterStatus lr_status,
1818       SaveFPRegsMode save_fp,
1819       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
1820       SmiCheck smi_check = INLINE_SMI_CHECK,
1821       PointersToHereCheck pointers_to_here_check_for_value =
1822           kPointersToHereMaybeInteresting);
1823
1824   // Checks the color of an object. If the object is already grey or black
1825   // then we just fall through, since it is already live. If it is white and
1826   // we can determine that it doesn't need to be scanned, then we just mark it
1827   // black and fall through. For the rest we jump to the label so the
1828   // incremental marker can fix its assumptions.
1829   void EnsureNotWhite(Register object,
1830                       Register scratch1,
1831                       Register scratch2,
1832                       Register scratch3,
1833                       Register scratch4,
1834                       Label* object_is_white_and_not_data);
1835
1836   // Detects conservatively whether an object is data-only, i.e. it does need to
1837   // be scanned by the garbage collector.
1838   void JumpIfDataObject(Register value,
1839                         Register scratch,
1840                         Label* not_data_object);
1841
1842   // Helper for finding the mark bits for an address.
1843   // Note that the behaviour slightly differs from other architectures.
1844   // On exit:
1845   //  - addr_reg is unchanged.
1846   //  - The bitmap register points at the word with the mark bits.
1847   //  - The shift register contains the index of the first color bit for this
1848   //    object in the bitmap.
1849   inline void GetMarkBits(Register addr_reg,
1850                           Register bitmap_reg,
1851                           Register shift_reg);
1852
1853   // Check if an object has a given incremental marking color.
1854   void HasColor(Register object,
1855                 Register scratch0,
1856                 Register scratch1,
1857                 Label* has_color,
1858                 int first_bit,
1859                 int second_bit);
1860
1861   void JumpIfBlack(Register object,
1862                    Register scratch0,
1863                    Register scratch1,
1864                    Label* on_black);
1865
1866
1867   // ---------------------------------------------------------------------------
1868   // Debugging.
1869
1870   // Calls Abort(msg) if the condition cond is not satisfied.
1871   // Use --debug_code to enable.
1872   void Assert(Condition cond, BailoutReason reason);
1873   void AssertRegisterIsClear(Register reg, BailoutReason reason);
1874   void AssertRegisterIsRoot(
1875       Register reg,
1876       Heap::RootListIndex index,
1877       BailoutReason reason = kRegisterDidNotMatchExpectedRoot);
1878   void AssertFastElements(Register elements);
1879
1880   // Abort if the specified register contains the invalid color bit pattern.
1881   // The pattern must be in bits [1:0] of 'reg' register.
1882   //
1883   // If emit_debug_code() is false, this emits no code.
1884   void AssertHasValidColor(const Register& reg);
1885
1886   // Abort if 'object' register doesn't point to a string object.
1887   //
1888   // If emit_debug_code() is false, this emits no code.
1889   void AssertIsString(const Register& object);
1890
1891   // Like Assert(), but always enabled.
1892   void Check(Condition cond, BailoutReason reason);
1893   void CheckRegisterIsClear(Register reg, BailoutReason reason);
1894
1895   // Print a message to stderr and abort execution.
1896   void Abort(BailoutReason reason);
1897
1898   // Conditionally load the cached Array transitioned map of type
1899   // transitioned_kind from the native context if the map in register
1900   // map_in_out is the cached Array map in the native context of
1901   // expected_kind.
1902   void LoadTransitionedArrayMapConditional(
1903       ElementsKind expected_kind,
1904       ElementsKind transitioned_kind,
1905       Register map_in_out,
1906       Register scratch1,
1907       Register scratch2,
1908       Label* no_map_match);
1909
1910   void LoadGlobalFunction(int index, Register function);
1911
1912   // Load the initial map from the global function. The registers function and
1913   // map can be the same, function is then overwritten.
1914   void LoadGlobalFunctionInitialMap(Register function,
1915                                     Register map,
1916                                     Register scratch);
1917
1918   CPURegList* TmpList() { return &tmp_list_; }
1919   CPURegList* FPTmpList() { return &fptmp_list_; }
1920
1921   static CPURegList DefaultTmpList();
1922   static CPURegList DefaultFPTmpList();
1923
1924   // Like printf, but print at run-time from generated code.
1925   //
1926   // The caller must ensure that arguments for floating-point placeholders
1927   // (such as %e, %f or %g) are FPRegisters, and that arguments for integer
1928   // placeholders are Registers.
1929   //
1930   // At the moment it is only possible to print the value of csp if it is the
1931   // current stack pointer. Otherwise, the MacroAssembler will automatically
1932   // update csp on every push (using BumpSystemStackPointer), so determining its
1933   // value is difficult.
1934   //
1935   // Format placeholders that refer to more than one argument, or to a specific
1936   // argument, are not supported. This includes formats like "%1$d" or "%.*d".
1937   //
1938   // This function automatically preserves caller-saved registers so that
1939   // calling code can use Printf at any point without having to worry about
1940   // corruption. The preservation mechanism generates a lot of code. If this is
1941   // a problem, preserve the important registers manually and then call
1942   // PrintfNoPreserve. Callee-saved registers are not used by Printf, and are
1943   // implicitly preserved.
1944   void Printf(const char * format,
1945               CPURegister arg0 = NoCPUReg,
1946               CPURegister arg1 = NoCPUReg,
1947               CPURegister arg2 = NoCPUReg,
1948               CPURegister arg3 = NoCPUReg);
1949
1950   // Like Printf, but don't preserve any caller-saved registers, not even 'lr'.
1951   //
1952   // The return code from the system printf call will be returned in x0.
1953   void PrintfNoPreserve(const char * format,
1954                         const CPURegister& arg0 = NoCPUReg,
1955                         const CPURegister& arg1 = NoCPUReg,
1956                         const CPURegister& arg2 = NoCPUReg,
1957                         const CPURegister& arg3 = NoCPUReg);
1958
1959   // Code ageing support functions.
1960
1961   // Code ageing on ARM64 works similarly to on ARM. When V8 wants to mark a
1962   // function as old, it replaces some of the function prologue (generated by
1963   // FullCodeGenerator::Generate) with a call to a special stub (ultimately
1964   // generated by GenerateMakeCodeYoungAgainCommon). The stub restores the
1965   // function prologue to its initial young state (indicating that it has been
1966   // recently run) and continues. A young function is therefore one which has a
1967   // normal frame setup sequence, and an old function has a code age sequence
1968   // which calls a code ageing stub.
1969
1970   // Set up a basic stack frame for young code (or code exempt from ageing) with
1971   // type FUNCTION. It may be patched later for code ageing support. This is
1972   // done by to Code::PatchPlatformCodeAge and EmitCodeAgeSequence.
1973   //
1974   // This function takes an Assembler so it can be called from either a
1975   // MacroAssembler or a PatchingAssembler context.
1976   static void EmitFrameSetupForCodeAgePatching(Assembler* assm);
1977
1978   // Call EmitFrameSetupForCodeAgePatching from a MacroAssembler context.
1979   void EmitFrameSetupForCodeAgePatching();
1980
1981   // Emit a code age sequence that calls the relevant code age stub. The code
1982   // generated by this sequence is expected to replace the code generated by
1983   // EmitFrameSetupForCodeAgePatching, and represents an old function.
1984   //
1985   // If stub is NULL, this function generates the code age sequence but omits
1986   // the stub address that is normally embedded in the instruction stream. This
1987   // can be used by debug code to verify code age sequences.
1988   static void EmitCodeAgeSequence(Assembler* assm, Code* stub);
1989
1990   // Call EmitCodeAgeSequence from a MacroAssembler context.
1991   void EmitCodeAgeSequence(Code* stub);
1992
1993   // Return true if the sequence is a young sequence geneated by
1994   // EmitFrameSetupForCodeAgePatching. Otherwise, this method asserts that the
1995   // sequence is a code age sequence (emitted by EmitCodeAgeSequence).
1996   static bool IsYoungSequence(Isolate* isolate, byte* sequence);
1997
1998   // Jumps to found label if a prototype map has dictionary elements.
1999   void JumpIfDictionaryInPrototypeChain(Register object, Register scratch0,
2000                                         Register scratch1, Label* found);
2001
2002   // Perform necessary maintenance operations before a push or after a pop.
2003   //
2004   // Note that size is specified in bytes.
2005   void PushPreamble(Operand total_size);
2006   void PopPostamble(Operand total_size);
2007
2008   void PushPreamble(int count, int size) { PushPreamble(count * size); }
2009   void PopPostamble(int count, int size) { PopPostamble(count * size); }
2010
2011  private:
2012   // Helpers for CopyFields.
2013   // These each implement CopyFields in a different way.
2014   void CopyFieldsLoopPairsHelper(Register dst, Register src, unsigned count,
2015                                  Register scratch1, Register scratch2,
2016                                  Register scratch3, Register scratch4,
2017                                  Register scratch5);
2018   void CopyFieldsUnrolledPairsHelper(Register dst, Register src, unsigned count,
2019                                      Register scratch1, Register scratch2,
2020                                      Register scratch3, Register scratch4);
2021   void CopyFieldsUnrolledHelper(Register dst, Register src, unsigned count,
2022                                 Register scratch1, Register scratch2,
2023                                 Register scratch3);
2024
2025   // The actual Push and Pop implementations. These don't generate any code
2026   // other than that required for the push or pop. This allows
2027   // (Push|Pop)CPURegList to bundle together run-time assertions for a large
2028   // block of registers.
2029   //
2030   // Note that size is per register, and is specified in bytes.
2031   void PushHelper(int count, int size,
2032                   const CPURegister& src0, const CPURegister& src1,
2033                   const CPURegister& src2, const CPURegister& src3);
2034   void PopHelper(int count, int size,
2035                  const CPURegister& dst0, const CPURegister& dst1,
2036                  const CPURegister& dst2, const CPURegister& dst3);
2037
2038   // Call Printf. On a native build, a simple call will be generated, but if the
2039   // simulator is being used then a suitable pseudo-instruction is used. The
2040   // arguments and stack (csp) must be prepared by the caller as for a normal
2041   // AAPCS64 call to 'printf'.
2042   //
2043   // The 'args' argument should point to an array of variable arguments in their
2044   // proper PCS registers (and in calling order). The argument registers can
2045   // have mixed types. The format string (x0) should not be included.
2046   void CallPrintf(int arg_count = 0, const CPURegister * args = NULL);
2047
2048   // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
2049   void InNewSpace(Register object,
2050                   Condition cond,  // eq for new space, ne otherwise.
2051                   Label* branch);
2052
2053   // Try to represent a double as an int so that integer fast-paths may be
2054   // used. Not every valid integer value is guaranteed to be caught.
2055   // It supports both 32-bit and 64-bit integers depending whether 'as_int'
2056   // is a W or X register.
2057   //
2058   // This does not distinguish between +0 and -0, so if this distinction is
2059   // important it must be checked separately.
2060   //
2061   // On output the Z flag is set if the operation was successful.
2062   void TryRepresentDoubleAsInt(Register as_int,
2063                                FPRegister value,
2064                                FPRegister scratch_d,
2065                                Label* on_successful_conversion = NULL,
2066                                Label* on_failed_conversion = NULL);
2067
2068   bool generating_stub_;
2069 #if DEBUG
2070   // Tell whether any of the macro instruction can be used. When false the
2071   // MacroAssembler will assert if a method which can emit a variable number
2072   // of instructions is called.
2073   bool allow_macro_instructions_;
2074 #endif
2075   bool has_frame_;
2076
2077   // The Abort method should call a V8 runtime function, but the CallRuntime
2078   // mechanism depends on CEntryStub. If use_real_aborts is false, Abort will
2079   // use a simpler abort mechanism that doesn't depend on CEntryStub.
2080   //
2081   // The purpose of this is to allow Aborts to be compiled whilst CEntryStub is
2082   // being generated.
2083   bool use_real_aborts_;
2084
2085   // This handle will be patched with the code object on installation.
2086   Handle<Object> code_object_;
2087
2088   // The register to use as a stack pointer for stack operations.
2089   Register sp_;
2090
2091   // Scratch registers available for use by the MacroAssembler.
2092   CPURegList tmp_list_;
2093   CPURegList fptmp_list_;
2094
2095   void InitializeNewString(Register string,
2096                            Register length,
2097                            Heap::RootListIndex map_index,
2098                            Register scratch1,
2099                            Register scratch2);
2100
2101  public:
2102   // Far branches resolving.
2103   //
2104   // The various classes of branch instructions with immediate offsets have
2105   // different ranges. While the Assembler will fail to assemble a branch
2106   // exceeding its range, the MacroAssembler offers a mechanism to resolve
2107   // branches to too distant targets, either by tweaking the generated code to
2108   // use branch instructions with wider ranges or generating veneers.
2109   //
2110   // Currently branches to distant targets are resolved using unconditional
2111   // branch isntructions with a range of +-128MB. If that becomes too little
2112   // (!), the mechanism can be extended to generate special veneers for really
2113   // far targets.
2114
2115   // Helps resolve branching to labels potentially out of range.
2116   // If the label is not bound, it registers the information necessary to later
2117   // be able to emit a veneer for this branch if necessary.
2118   // If the label is bound, it returns true if the label (or the previous link
2119   // in the label chain) is out of range. In that case the caller is responsible
2120   // for generating appropriate code.
2121   // Otherwise it returns false.
2122   // This function also checks wether veneers need to be emitted.
2123   bool NeedExtraInstructionsOrRegisterBranch(Label *label,
2124                                              ImmBranchType branch_type);
2125 };
2126
2127
2128 // Use this scope when you need a one-to-one mapping bewteen methods and
2129 // instructions. This scope prevents the MacroAssembler from being called and
2130 // literal pools from being emitted. It also asserts the number of instructions
2131 // emitted is what you specified when creating the scope.
2132 class InstructionAccurateScope BASE_EMBEDDED {
2133  public:
2134   explicit InstructionAccurateScope(MacroAssembler* masm, size_t count = 0)
2135       : masm_(masm)
2136 #ifdef DEBUG
2137         ,
2138         size_(count * kInstructionSize)
2139 #endif
2140   {
2141     // Before blocking the const pool, see if it needs to be emitted.
2142     masm_->CheckConstPool(false, true);
2143     masm_->CheckVeneerPool(false, true);
2144
2145     masm_->StartBlockPools();
2146 #ifdef DEBUG
2147     if (count != 0) {
2148       masm_->bind(&start_);
2149     }
2150     previous_allow_macro_instructions_ = masm_->allow_macro_instructions();
2151     masm_->set_allow_macro_instructions(false);
2152 #endif
2153   }
2154
2155   ~InstructionAccurateScope() {
2156     masm_->EndBlockPools();
2157 #ifdef DEBUG
2158     if (start_.is_bound()) {
2159       DCHECK(masm_->SizeOfCodeGeneratedSince(&start_) == size_);
2160     }
2161     masm_->set_allow_macro_instructions(previous_allow_macro_instructions_);
2162 #endif
2163   }
2164
2165  private:
2166   MacroAssembler* masm_;
2167 #ifdef DEBUG
2168   size_t size_;
2169   Label start_;
2170   bool previous_allow_macro_instructions_;
2171 #endif
2172 };
2173
2174
2175 // This scope utility allows scratch registers to be managed safely. The
2176 // MacroAssembler's TmpList() (and FPTmpList()) is used as a pool of scratch
2177 // registers. These registers can be allocated on demand, and will be returned
2178 // at the end of the scope.
2179 //
2180 // When the scope ends, the MacroAssembler's lists will be restored to their
2181 // original state, even if the lists were modified by some other means.
2182 class UseScratchRegisterScope {
2183  public:
2184   explicit UseScratchRegisterScope(MacroAssembler* masm)
2185       : available_(masm->TmpList()),
2186         availablefp_(masm->FPTmpList()),
2187         old_available_(available_->list()),
2188         old_availablefp_(availablefp_->list()) {
2189     DCHECK(available_->type() == CPURegister::kRegister);
2190     DCHECK(availablefp_->type() == CPURegister::kFPRegister);
2191   }
2192
2193   ~UseScratchRegisterScope();
2194
2195   // Take a register from the appropriate temps list. It will be returned
2196   // automatically when the scope ends.
2197   Register AcquireW() { return AcquireNextAvailable(available_).W(); }
2198   Register AcquireX() { return AcquireNextAvailable(available_).X(); }
2199   FPRegister AcquireS() { return AcquireNextAvailable(availablefp_).S(); }
2200   FPRegister AcquireD() { return AcquireNextAvailable(availablefp_).D(); }
2201
2202   Register UnsafeAcquire(const Register& reg) {
2203     return Register(UnsafeAcquire(available_, reg));
2204   }
2205
2206   Register AcquireSameSizeAs(const Register& reg);
2207   FPRegister AcquireSameSizeAs(const FPRegister& reg);
2208
2209  private:
2210   static CPURegister AcquireNextAvailable(CPURegList* available);
2211   static CPURegister UnsafeAcquire(CPURegList* available,
2212                                    const CPURegister& reg);
2213
2214   // Available scratch registers.
2215   CPURegList* available_;     // kRegister
2216   CPURegList* availablefp_;   // kFPRegister
2217
2218   // The state of the available lists at the start of this scope.
2219   RegList old_available_;     // kRegister
2220   RegList old_availablefp_;   // kFPRegister
2221 };
2222
2223
2224 inline MemOperand ContextMemOperand(Register context, int index = 0) {
2225   return MemOperand(context, Context::SlotOffset(index));
2226 }
2227
2228 inline MemOperand GlobalObjectMemOperand() {
2229   return ContextMemOperand(cp, Context::GLOBAL_OBJECT_INDEX);
2230 }
2231
2232
2233 // Encode and decode information about patchable inline SMI checks.
2234 class InlineSmiCheckInfo {
2235  public:
2236   explicit InlineSmiCheckInfo(Address info);
2237
2238   bool HasSmiCheck() const {
2239     return smi_check_ != NULL;
2240   }
2241
2242   const Register& SmiRegister() const {
2243     return reg_;
2244   }
2245
2246   Instruction* SmiCheck() const {
2247     return smi_check_;
2248   }
2249
2250   // Use MacroAssembler::InlineData to emit information about patchable inline
2251   // SMI checks. The caller may specify 'reg' as NoReg and an unbound 'site' to
2252   // indicate that there is no inline SMI check. Note that 'reg' cannot be csp.
2253   //
2254   // The generated patch information can be read using the InlineSMICheckInfo
2255   // class.
2256   static void Emit(MacroAssembler* masm, const Register& reg,
2257                    const Label* smi_check);
2258
2259   // Emit information to indicate that there is no inline SMI check.
2260   static void EmitNotInlined(MacroAssembler* masm) {
2261     Label unbound;
2262     Emit(masm, NoReg, &unbound);
2263   }
2264
2265  private:
2266   Register reg_;
2267   Instruction* smi_check_;
2268
2269   // Fields in the data encoded by InlineData.
2270
2271   // A width of 5 (Rd_width) for the SMI register preclues the use of csp,
2272   // since kSPRegInternalCode is 63. However, csp should never hold a SMI or be
2273   // used in a patchable check. The Emit() method checks this.
2274   //
2275   // Note that the total size of the fields is restricted by the underlying
2276   // storage size handled by the BitField class, which is a uint32_t.
2277   class RegisterBits : public BitField<unsigned, 0, 5> {};
2278   class DeltaBits : public BitField<uint32_t, 5, 32-5> {};
2279 };
2280
2281 }  // namespace internal
2282 }  // namespace v8
2283
2284 #ifdef GENERATED_CODE_COVERAGE
2285 #error "Unsupported option"
2286 #define CODE_COVERAGE_STRINGIFY(x) #x
2287 #define CODE_COVERAGE_TOSTRING(x) CODE_COVERAGE_STRINGIFY(x)
2288 #define __FILE_LINE__ __FILE__ ":" CODE_COVERAGE_TOSTRING(__LINE__)
2289 #define ACCESS_MASM(masm) masm->stop(__FILE_LINE__); masm->
2290 #else
2291 #define ACCESS_MASM(masm) masm->
2292 #endif
2293
2294 #endif  // V8_ARM64_MACRO_ASSEMBLER_ARM64_H_