Upstream version 9.38.207.0
[platform/framework/web/crosswalk.git] / src / v8 / src / x64 / macro-assembler-x64.h
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_X64_MACRO_ASSEMBLER_X64_H_
6 #define V8_X64_MACRO_ASSEMBLER_X64_H_
7
8 #include "src/assembler.h"
9 #include "src/frames.h"
10 #include "src/globals.h"
11
12 namespace v8 {
13 namespace internal {
14
15 // Default scratch register used by MacroAssembler (and other code that needs
16 // a spare register). The register isn't callee save, and not used by the
17 // function calling convention.
18 const Register kScratchRegister = { 10 };      // r10.
19 const Register kSmiConstantRegister = { 12 };  // r12 (callee save).
20 const Register kRootRegister = { 13 };         // r13 (callee save).
21 // Value of smi in kSmiConstantRegister.
22 const int kSmiConstantRegisterValue = 1;
23 // Actual value of root register is offset from the root array's start
24 // to take advantage of negitive 8-bit displacement values.
25 const int kRootRegisterBias = 128;
26
27 // Convenience for platform-independent signatures.
28 typedef Operand MemOperand;
29
30 enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET };
31 enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK };
32 enum PointersToHereCheck {
33   kPointersToHereMaybeInteresting,
34   kPointersToHereAreAlwaysInteresting
35 };
36
37 enum SmiOperationConstraint {
38   PRESERVE_SOURCE_REGISTER,
39   BAILOUT_ON_NO_OVERFLOW,
40   BAILOUT_ON_OVERFLOW,
41   NUMBER_OF_CONSTRAINTS
42 };
43
44 STATIC_ASSERT(NUMBER_OF_CONSTRAINTS <= 8);
45
46 class SmiOperationExecutionMode : public EnumSet<SmiOperationConstraint, byte> {
47  public:
48   SmiOperationExecutionMode() : EnumSet<SmiOperationConstraint, byte>(0) { }
49   explicit SmiOperationExecutionMode(byte bits)
50       : EnumSet<SmiOperationConstraint, byte>(bits) { }
51 };
52
53 #ifdef DEBUG
54 bool AreAliased(Register reg1,
55                 Register reg2,
56                 Register reg3 = no_reg,
57                 Register reg4 = no_reg,
58                 Register reg5 = no_reg,
59                 Register reg6 = no_reg,
60                 Register reg7 = no_reg,
61                 Register reg8 = no_reg);
62 #endif
63
64 // Forward declaration.
65 class JumpTarget;
66
67 struct SmiIndex {
68   SmiIndex(Register index_register, ScaleFactor scale)
69       : reg(index_register),
70         scale(scale) {}
71   Register reg;
72   ScaleFactor scale;
73 };
74
75
76 // MacroAssembler implements a collection of frequently used macros.
77 class MacroAssembler: public Assembler {
78  public:
79   // The isolate parameter can be NULL if the macro assembler should
80   // not use isolate-dependent functionality. In this case, it's the
81   // responsibility of the caller to never invoke such function on the
82   // macro assembler.
83   MacroAssembler(Isolate* isolate, void* buffer, int size);
84
85   // Prevent the use of the RootArray during the lifetime of this
86   // scope object.
87   class NoRootArrayScope BASE_EMBEDDED {
88    public:
89     explicit NoRootArrayScope(MacroAssembler* assembler)
90         : variable_(&assembler->root_array_available_),
91           old_value_(assembler->root_array_available_) {
92       assembler->root_array_available_ = false;
93     }
94     ~NoRootArrayScope() {
95       *variable_ = old_value_;
96     }
97    private:
98     bool* variable_;
99     bool old_value_;
100   };
101
102   // Operand pointing to an external reference.
103   // May emit code to set up the scratch register. The operand is
104   // only guaranteed to be correct as long as the scratch register
105   // isn't changed.
106   // If the operand is used more than once, use a scratch register
107   // that is guaranteed not to be clobbered.
108   Operand ExternalOperand(ExternalReference reference,
109                           Register scratch = kScratchRegister);
110   // Loads and stores the value of an external reference.
111   // Special case code for load and store to take advantage of
112   // load_rax/store_rax if possible/necessary.
113   // For other operations, just use:
114   //   Operand operand = ExternalOperand(extref);
115   //   operation(operand, ..);
116   void Load(Register destination, ExternalReference source);
117   void Store(ExternalReference destination, Register source);
118   // Loads the address of the external reference into the destination
119   // register.
120   void LoadAddress(Register destination, ExternalReference source);
121   // Returns the size of the code generated by LoadAddress.
122   // Used by CallSize(ExternalReference) to find the size of a call.
123   int LoadAddressSize(ExternalReference source);
124   // Pushes the address of the external reference onto the stack.
125   void PushAddress(ExternalReference source);
126
127   // Operations on roots in the root-array.
128   void LoadRoot(Register destination, Heap::RootListIndex index);
129   void StoreRoot(Register source, Heap::RootListIndex index);
130   // Load a root value where the index (or part of it) is variable.
131   // The variable_offset register is added to the fixed_offset value
132   // to get the index into the root-array.
133   void LoadRootIndexed(Register destination,
134                        Register variable_offset,
135                        int fixed_offset);
136   void CompareRoot(Register with, Heap::RootListIndex index);
137   void CompareRoot(const Operand& with, Heap::RootListIndex index);
138   void PushRoot(Heap::RootListIndex index);
139
140   // These functions do not arrange the registers in any particular order so
141   // they are not useful for calls that can cause a GC.  The caller can
142   // exclude up to 3 registers that do not need to be saved and restored.
143   void PushCallerSaved(SaveFPRegsMode fp_mode,
144                        Register exclusion1 = no_reg,
145                        Register exclusion2 = no_reg,
146                        Register exclusion3 = no_reg);
147   void PopCallerSaved(SaveFPRegsMode fp_mode,
148                       Register exclusion1 = no_reg,
149                       Register exclusion2 = no_reg,
150                       Register exclusion3 = no_reg);
151
152 // ---------------------------------------------------------------------------
153 // GC Support
154
155
156   enum RememberedSetFinalAction {
157     kReturnAtEnd,
158     kFallThroughAtEnd
159   };
160
161   // Record in the remembered set the fact that we have a pointer to new space
162   // at the address pointed to by the addr register.  Only works if addr is not
163   // in new space.
164   void RememberedSetHelper(Register object,  // Used for debug code.
165                            Register addr,
166                            Register scratch,
167                            SaveFPRegsMode save_fp,
168                            RememberedSetFinalAction and_then);
169
170   void CheckPageFlag(Register object,
171                      Register scratch,
172                      int mask,
173                      Condition cc,
174                      Label* condition_met,
175                      Label::Distance condition_met_distance = Label::kFar);
176
177   void CheckMapDeprecated(Handle<Map> map,
178                           Register scratch,
179                           Label* if_deprecated);
180
181   // Check if object is in new space.  Jumps if the object is not in new space.
182   // The register scratch can be object itself, but scratch will be clobbered.
183   void JumpIfNotInNewSpace(Register object,
184                            Register scratch,
185                            Label* branch,
186                            Label::Distance distance = Label::kFar) {
187     InNewSpace(object, scratch, not_equal, branch, distance);
188   }
189
190   // Check if object is in new space.  Jumps if the object is in new space.
191   // The register scratch can be object itself, but it will be clobbered.
192   void JumpIfInNewSpace(Register object,
193                         Register scratch,
194                         Label* branch,
195                         Label::Distance distance = Label::kFar) {
196     InNewSpace(object, scratch, equal, branch, distance);
197   }
198
199   // Check if an object has the black incremental marking color.  Also uses rcx!
200   void JumpIfBlack(Register object,
201                    Register scratch0,
202                    Register scratch1,
203                    Label* on_black,
204                    Label::Distance on_black_distance = Label::kFar);
205
206   // Detects conservatively whether an object is data-only, i.e. it does need to
207   // be scanned by the garbage collector.
208   void JumpIfDataObject(Register value,
209                         Register scratch,
210                         Label* not_data_object,
211                         Label::Distance not_data_object_distance);
212
213   // Checks the color of an object.  If the object is already grey or black
214   // then we just fall through, since it is already live.  If it is white and
215   // we can determine that it doesn't need to be scanned, then we just mark it
216   // black and fall through.  For the rest we jump to the label so the
217   // incremental marker can fix its assumptions.
218   void EnsureNotWhite(Register object,
219                       Register scratch1,
220                       Register scratch2,
221                       Label* object_is_white_and_not_data,
222                       Label::Distance distance);
223
224   // Notify the garbage collector that we wrote a pointer into an object.
225   // |object| is the object being stored into, |value| is the object being
226   // stored.  value and scratch registers are clobbered by the operation.
227   // The offset is the offset from the start of the object, not the offset from
228   // the tagged HeapObject pointer.  For use with FieldOperand(reg, off).
229   void RecordWriteField(
230       Register object,
231       int offset,
232       Register value,
233       Register scratch,
234       SaveFPRegsMode save_fp,
235       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
236       SmiCheck smi_check = INLINE_SMI_CHECK,
237       PointersToHereCheck pointers_to_here_check_for_value =
238           kPointersToHereMaybeInteresting);
239
240   // As above, but the offset has the tag presubtracted.  For use with
241   // Operand(reg, off).
242   void RecordWriteContextSlot(
243       Register context,
244       int offset,
245       Register value,
246       Register scratch,
247       SaveFPRegsMode save_fp,
248       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
249       SmiCheck smi_check = INLINE_SMI_CHECK,
250       PointersToHereCheck pointers_to_here_check_for_value =
251           kPointersToHereMaybeInteresting) {
252     RecordWriteField(context,
253                      offset + kHeapObjectTag,
254                      value,
255                      scratch,
256                      save_fp,
257                      remembered_set_action,
258                      smi_check,
259                      pointers_to_here_check_for_value);
260   }
261
262   // Notify the garbage collector that we wrote a pointer into a fixed array.
263   // |array| is the array being stored into, |value| is the
264   // object being stored.  |index| is the array index represented as a non-smi.
265   // All registers are clobbered by the operation RecordWriteArray
266   // filters out smis so it does not update the write barrier if the
267   // value is a smi.
268   void RecordWriteArray(
269       Register array,
270       Register value,
271       Register index,
272       SaveFPRegsMode save_fp,
273       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
274       SmiCheck smi_check = INLINE_SMI_CHECK,
275       PointersToHereCheck pointers_to_here_check_for_value =
276           kPointersToHereMaybeInteresting);
277
278   void RecordWriteForMap(
279       Register object,
280       Register map,
281       Register dst,
282       SaveFPRegsMode save_fp);
283
284   // For page containing |object| mark region covering |address|
285   // dirty. |object| is the object being stored into, |value| is the
286   // object being stored. The address and value registers are clobbered by the
287   // operation.  RecordWrite filters out smis so it does not update
288   // the write barrier if the value is a smi.
289   void RecordWrite(
290       Register object,
291       Register address,
292       Register value,
293       SaveFPRegsMode save_fp,
294       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
295       SmiCheck smi_check = INLINE_SMI_CHECK,
296       PointersToHereCheck pointers_to_here_check_for_value =
297           kPointersToHereMaybeInteresting);
298
299   // ---------------------------------------------------------------------------
300   // Debugger Support
301
302   void DebugBreak();
303
304   // Generates function and stub prologue code.
305   void StubPrologue();
306   void Prologue(bool code_pre_aging);
307
308   // Enter specific kind of exit frame; either in normal or
309   // debug mode. Expects the number of arguments in register rax and
310   // sets up the number of arguments in register rdi and the pointer
311   // to the first argument in register rsi.
312   //
313   // Allocates arg_stack_space * kPointerSize memory (not GCed) on the stack
314   // accessible via StackSpaceOperand.
315   void EnterExitFrame(int arg_stack_space = 0, bool save_doubles = false);
316
317   // Enter specific kind of exit frame. Allocates arg_stack_space * kPointerSize
318   // memory (not GCed) on the stack accessible via StackSpaceOperand.
319   void EnterApiExitFrame(int arg_stack_space);
320
321   // Leave the current exit frame. Expects/provides the return value in
322   // register rax:rdx (untouched) and the pointer to the first
323   // argument in register rsi.
324   void LeaveExitFrame(bool save_doubles = false);
325
326   // Leave the current exit frame. Expects/provides the return value in
327   // register rax (untouched).
328   void LeaveApiExitFrame(bool restore_context);
329
330   // Push and pop the registers that can hold pointers.
331   void PushSafepointRegisters() { Pushad(); }
332   void PopSafepointRegisters() { Popad(); }
333   // Store the value in register src in the safepoint register stack
334   // slot for register dst.
335   void StoreToSafepointRegisterSlot(Register dst, const Immediate& imm);
336   void StoreToSafepointRegisterSlot(Register dst, Register src);
337   void LoadFromSafepointRegisterSlot(Register dst, Register src);
338
339   void InitializeRootRegister() {
340     ExternalReference roots_array_start =
341         ExternalReference::roots_array_start(isolate());
342     Move(kRootRegister, roots_array_start);
343     addp(kRootRegister, Immediate(kRootRegisterBias));
344   }
345
346   // ---------------------------------------------------------------------------
347   // JavaScript invokes
348
349   // Invoke the JavaScript function code by either calling or jumping.
350   void InvokeCode(Register code,
351                   const ParameterCount& expected,
352                   const ParameterCount& actual,
353                   InvokeFlag flag,
354                   const CallWrapper& call_wrapper);
355
356   // Invoke the JavaScript function in the given register. Changes the
357   // current context to the context in the function before invoking.
358   void InvokeFunction(Register function,
359                       const ParameterCount& actual,
360                       InvokeFlag flag,
361                       const CallWrapper& call_wrapper);
362
363   void InvokeFunction(Register function,
364                       const ParameterCount& expected,
365                       const ParameterCount& actual,
366                       InvokeFlag flag,
367                       const CallWrapper& call_wrapper);
368
369   void InvokeFunction(Handle<JSFunction> function,
370                       const ParameterCount& expected,
371                       const ParameterCount& actual,
372                       InvokeFlag flag,
373                       const CallWrapper& call_wrapper);
374
375   // Invoke specified builtin JavaScript function. Adds an entry to
376   // the unresolved list if the name does not resolve.
377   void InvokeBuiltin(Builtins::JavaScript id,
378                      InvokeFlag flag,
379                      const CallWrapper& call_wrapper = NullCallWrapper());
380
381   // Store the function for the given builtin in the target register.
382   void GetBuiltinFunction(Register target, Builtins::JavaScript id);
383
384   // Store the code object for the given builtin in the target register.
385   void GetBuiltinEntry(Register target, Builtins::JavaScript id);
386
387
388   // ---------------------------------------------------------------------------
389   // Smi tagging, untagging and operations on tagged smis.
390
391   // Support for constant splitting.
392   bool IsUnsafeInt(const int32_t x);
393   void SafeMove(Register dst, Smi* src);
394   void SafePush(Smi* src);
395
396   void InitializeSmiConstantRegister() {
397     Move(kSmiConstantRegister, Smi::FromInt(kSmiConstantRegisterValue),
398          Assembler::RelocInfoNone());
399   }
400
401   // Conversions between tagged smi values and non-tagged integer values.
402
403   // Tag an integer value. The result must be known to be a valid smi value.
404   // Only uses the low 32 bits of the src register. Sets the N and Z flags
405   // based on the value of the resulting smi.
406   void Integer32ToSmi(Register dst, Register src);
407
408   // Stores an integer32 value into a memory field that already holds a smi.
409   void Integer32ToSmiField(const Operand& dst, Register src);
410
411   // Adds constant to src and tags the result as a smi.
412   // Result must be a valid smi.
413   void Integer64PlusConstantToSmi(Register dst, Register src, int constant);
414
415   // Convert smi to 32-bit integer. I.e., not sign extended into
416   // high 32 bits of destination.
417   void SmiToInteger32(Register dst, Register src);
418   void SmiToInteger32(Register dst, const Operand& src);
419
420   // Convert smi to 64-bit integer (sign extended if necessary).
421   void SmiToInteger64(Register dst, Register src);
422   void SmiToInteger64(Register dst, const Operand& src);
423
424   // Multiply a positive smi's integer value by a power of two.
425   // Provides result as 64-bit integer value.
426   void PositiveSmiTimesPowerOfTwoToInteger64(Register dst,
427                                              Register src,
428                                              int power);
429
430   // Divide a positive smi's integer value by a power of two.
431   // Provides result as 32-bit integer value.
432   void PositiveSmiDivPowerOfTwoToInteger32(Register dst,
433                                            Register src,
434                                            int power);
435
436   // Perform the logical or of two smi values and return a smi value.
437   // If either argument is not a smi, jump to on_not_smis and retain
438   // the original values of source registers. The destination register
439   // may be changed if it's not one of the source registers.
440   void SmiOrIfSmis(Register dst,
441                    Register src1,
442                    Register src2,
443                    Label* on_not_smis,
444                    Label::Distance near_jump = Label::kFar);
445
446
447   // Simple comparison of smis.  Both sides must be known smis to use these,
448   // otherwise use Cmp.
449   void SmiCompare(Register smi1, Register smi2);
450   void SmiCompare(Register dst, Smi* src);
451   void SmiCompare(Register dst, const Operand& src);
452   void SmiCompare(const Operand& dst, Register src);
453   void SmiCompare(const Operand& dst, Smi* src);
454   // Compare the int32 in src register to the value of the smi stored at dst.
455   void SmiCompareInteger32(const Operand& dst, Register src);
456   // Sets sign and zero flags depending on value of smi in register.
457   void SmiTest(Register src);
458
459   // Functions performing a check on a known or potential smi. Returns
460   // a condition that is satisfied if the check is successful.
461
462   // Is the value a tagged smi.
463   Condition CheckSmi(Register src);
464   Condition CheckSmi(const Operand& src);
465
466   // Is the value a non-negative tagged smi.
467   Condition CheckNonNegativeSmi(Register src);
468
469   // Are both values tagged smis.
470   Condition CheckBothSmi(Register first, Register second);
471
472   // Are both values non-negative tagged smis.
473   Condition CheckBothNonNegativeSmi(Register first, Register second);
474
475   // Are either value a tagged smi.
476   Condition CheckEitherSmi(Register first,
477                            Register second,
478                            Register scratch = kScratchRegister);
479
480   // Is the value the minimum smi value (since we are using
481   // two's complement numbers, negating the value is known to yield
482   // a non-smi value).
483   Condition CheckIsMinSmi(Register src);
484
485   // Checks whether an 32-bit integer value is a valid for conversion
486   // to a smi.
487   Condition CheckInteger32ValidSmiValue(Register src);
488
489   // Checks whether an 32-bit unsigned integer value is a valid for
490   // conversion to a smi.
491   Condition CheckUInteger32ValidSmiValue(Register src);
492
493   // Check whether src is a Smi, and set dst to zero if it is a smi,
494   // and to one if it isn't.
495   void CheckSmiToIndicator(Register dst, Register src);
496   void CheckSmiToIndicator(Register dst, const Operand& src);
497
498   // Test-and-jump functions. Typically combines a check function
499   // above with a conditional jump.
500
501   // Jump if the value can be represented by a smi.
502   void JumpIfValidSmiValue(Register src, Label* on_valid,
503                            Label::Distance near_jump = Label::kFar);
504
505   // Jump if the value cannot be represented by a smi.
506   void JumpIfNotValidSmiValue(Register src, Label* on_invalid,
507                               Label::Distance near_jump = Label::kFar);
508
509   // Jump if the unsigned integer value can be represented by a smi.
510   void JumpIfUIntValidSmiValue(Register src, Label* on_valid,
511                                Label::Distance near_jump = Label::kFar);
512
513   // Jump if the unsigned integer value cannot be represented by a smi.
514   void JumpIfUIntNotValidSmiValue(Register src, Label* on_invalid,
515                                   Label::Distance near_jump = Label::kFar);
516
517   // Jump to label if the value is a tagged smi.
518   void JumpIfSmi(Register src,
519                  Label* on_smi,
520                  Label::Distance near_jump = Label::kFar);
521
522   // Jump to label if the value is not a tagged smi.
523   void JumpIfNotSmi(Register src,
524                     Label* on_not_smi,
525                     Label::Distance near_jump = Label::kFar);
526
527   // Jump to label if the value is not a non-negative tagged smi.
528   void JumpUnlessNonNegativeSmi(Register src,
529                                 Label* on_not_smi,
530                                 Label::Distance near_jump = Label::kFar);
531
532   // Jump to label if the value, which must be a tagged smi, has value equal
533   // to the constant.
534   void JumpIfSmiEqualsConstant(Register src,
535                                Smi* constant,
536                                Label* on_equals,
537                                Label::Distance near_jump = Label::kFar);
538
539   // Jump if either or both register are not smi values.
540   void JumpIfNotBothSmi(Register src1,
541                         Register src2,
542                         Label* on_not_both_smi,
543                         Label::Distance near_jump = Label::kFar);
544
545   // Jump if either or both register are not non-negative smi values.
546   void JumpUnlessBothNonNegativeSmi(Register src1, Register src2,
547                                     Label* on_not_both_smi,
548                                     Label::Distance near_jump = Label::kFar);
549
550   // Operations on tagged smi values.
551
552   // Smis represent a subset of integers. The subset is always equivalent to
553   // a two's complement interpretation of a fixed number of bits.
554
555   // Add an integer constant to a tagged smi, giving a tagged smi as result.
556   // No overflow testing on the result is done.
557   void SmiAddConstant(Register dst, Register src, Smi* constant);
558
559   // Add an integer constant to a tagged smi, giving a tagged smi as result.
560   // No overflow testing on the result is done.
561   void SmiAddConstant(const Operand& dst, Smi* constant);
562
563   // Add an integer constant to a tagged smi, giving a tagged smi as result,
564   // or jumping to a label if the result cannot be represented by a smi.
565   void SmiAddConstant(Register dst,
566                       Register src,
567                       Smi* constant,
568                       SmiOperationExecutionMode mode,
569                       Label* bailout_label,
570                       Label::Distance near_jump = Label::kFar);
571
572   // Subtract an integer constant from a tagged smi, giving a tagged smi as
573   // result. No testing on the result is done. Sets the N and Z flags
574   // based on the value of the resulting integer.
575   void SmiSubConstant(Register dst, Register src, Smi* constant);
576
577   // Subtract an integer constant from a tagged smi, giving a tagged smi as
578   // result, or jumping to a label if the result cannot be represented by a smi.
579   void SmiSubConstant(Register dst,
580                       Register src,
581                       Smi* constant,
582                       SmiOperationExecutionMode mode,
583                       Label* bailout_label,
584                       Label::Distance near_jump = Label::kFar);
585
586   // Negating a smi can give a negative zero or too large positive value.
587   // NOTICE: This operation jumps on success, not failure!
588   void SmiNeg(Register dst,
589               Register src,
590               Label* on_smi_result,
591               Label::Distance near_jump = Label::kFar);
592
593   // Adds smi values and return the result as a smi.
594   // If dst is src1, then src1 will be destroyed if the operation is
595   // successful, otherwise kept intact.
596   void SmiAdd(Register dst,
597               Register src1,
598               Register src2,
599               Label* on_not_smi_result,
600               Label::Distance near_jump = Label::kFar);
601   void SmiAdd(Register dst,
602               Register src1,
603               const Operand& src2,
604               Label* on_not_smi_result,
605               Label::Distance near_jump = Label::kFar);
606
607   void SmiAdd(Register dst,
608               Register src1,
609               Register src2);
610
611   // Subtracts smi values and return the result as a smi.
612   // If dst is src1, then src1 will be destroyed if the operation is
613   // successful, otherwise kept intact.
614   void SmiSub(Register dst,
615               Register src1,
616               Register src2,
617               Label* on_not_smi_result,
618               Label::Distance near_jump = Label::kFar);
619   void SmiSub(Register dst,
620               Register src1,
621               const Operand& src2,
622               Label* on_not_smi_result,
623               Label::Distance near_jump = Label::kFar);
624
625   void SmiSub(Register dst,
626               Register src1,
627               Register src2);
628
629   void SmiSub(Register dst,
630               Register src1,
631               const Operand& src2);
632
633   // Multiplies smi values and return the result as a smi,
634   // if possible.
635   // If dst is src1, then src1 will be destroyed, even if
636   // the operation is unsuccessful.
637   void SmiMul(Register dst,
638               Register src1,
639               Register src2,
640               Label* on_not_smi_result,
641               Label::Distance near_jump = Label::kFar);
642
643   // Divides one smi by another and returns the quotient.
644   // Clobbers rax and rdx registers.
645   void SmiDiv(Register dst,
646               Register src1,
647               Register src2,
648               Label* on_not_smi_result,
649               Label::Distance near_jump = Label::kFar);
650
651   // Divides one smi by another and returns the remainder.
652   // Clobbers rax and rdx registers.
653   void SmiMod(Register dst,
654               Register src1,
655               Register src2,
656               Label* on_not_smi_result,
657               Label::Distance near_jump = Label::kFar);
658
659   // Bitwise operations.
660   void SmiNot(Register dst, Register src);
661   void SmiAnd(Register dst, Register src1, Register src2);
662   void SmiOr(Register dst, Register src1, Register src2);
663   void SmiXor(Register dst, Register src1, Register src2);
664   void SmiAndConstant(Register dst, Register src1, Smi* constant);
665   void SmiOrConstant(Register dst, Register src1, Smi* constant);
666   void SmiXorConstant(Register dst, Register src1, Smi* constant);
667
668   void SmiShiftLeftConstant(Register dst,
669                             Register src,
670                             int shift_value,
671                             Label* on_not_smi_result = NULL,
672                             Label::Distance near_jump = Label::kFar);
673   void SmiShiftLogicalRightConstant(Register dst,
674                                     Register src,
675                                     int shift_value,
676                                     Label* on_not_smi_result,
677                                     Label::Distance near_jump = Label::kFar);
678   void SmiShiftArithmeticRightConstant(Register dst,
679                                        Register src,
680                                        int shift_value);
681
682   // Shifts a smi value to the left, and returns the result if that is a smi.
683   // Uses and clobbers rcx, so dst may not be rcx.
684   void SmiShiftLeft(Register dst,
685                     Register src1,
686                     Register src2,
687                     Label* on_not_smi_result = NULL,
688                     Label::Distance near_jump = Label::kFar);
689   // Shifts a smi value to the right, shifting in zero bits at the top, and
690   // returns the unsigned intepretation of the result if that is a smi.
691   // Uses and clobbers rcx, so dst may not be rcx.
692   void SmiShiftLogicalRight(Register dst,
693                             Register src1,
694                             Register src2,
695                             Label* on_not_smi_result,
696                             Label::Distance near_jump = Label::kFar);
697   // Shifts a smi value to the right, sign extending the top, and
698   // returns the signed intepretation of the result. That will always
699   // be a valid smi value, since it's numerically smaller than the
700   // original.
701   // Uses and clobbers rcx, so dst may not be rcx.
702   void SmiShiftArithmeticRight(Register dst,
703                                Register src1,
704                                Register src2);
705
706   // Specialized operations
707
708   // Select the non-smi register of two registers where exactly one is a
709   // smi. If neither are smis, jump to the failure label.
710   void SelectNonSmi(Register dst,
711                     Register src1,
712                     Register src2,
713                     Label* on_not_smis,
714                     Label::Distance near_jump = Label::kFar);
715
716   // Converts, if necessary, a smi to a combination of number and
717   // multiplier to be used as a scaled index.
718   // The src register contains a *positive* smi value. The shift is the
719   // power of two to multiply the index value by (e.g.
720   // to index by smi-value * kPointerSize, pass the smi and kPointerSizeLog2).
721   // The returned index register may be either src or dst, depending
722   // on what is most efficient. If src and dst are different registers,
723   // src is always unchanged.
724   SmiIndex SmiToIndex(Register dst, Register src, int shift);
725
726   // Converts a positive smi to a negative index.
727   SmiIndex SmiToNegativeIndex(Register dst, Register src, int shift);
728
729   // Add the value of a smi in memory to an int32 register.
730   // Sets flags as a normal add.
731   void AddSmiField(Register dst, const Operand& src);
732
733   // Basic Smi operations.
734   void Move(Register dst, Smi* source) {
735     LoadSmiConstant(dst, source);
736   }
737
738   void Move(const Operand& dst, Smi* source) {
739     Register constant = GetSmiConstant(source);
740     movp(dst, constant);
741   }
742
743   void Push(Smi* smi);
744
745   // Save away a raw integer with pointer size on the stack as two integers
746   // masquerading as smis so that the garbage collector skips visiting them.
747   void PushRegisterAsTwoSmis(Register src, Register scratch = kScratchRegister);
748   // Reconstruct a raw integer with pointer size from two integers masquerading
749   // as smis on the top of stack.
750   void PopRegisterAsTwoSmis(Register dst, Register scratch = kScratchRegister);
751
752   void Test(const Operand& dst, Smi* source);
753
754
755   // ---------------------------------------------------------------------------
756   // SIMD macros.
757   void absps(XMMRegister dst);
758   void abspd(XMMRegister dst);
759   void negateps(XMMRegister dst);
760   void negatepd(XMMRegister dst);
761   void notps(XMMRegister dst);
762   void pnegd(XMMRegister dst);
763
764
765   // ---------------------------------------------------------------------------
766   // String macros.
767
768   // Generate code to do a lookup in the number string cache. If the number in
769   // the register object is found in the cache the generated code falls through
770   // with the result in the result register. The object and the result register
771   // can be the same. If the number is not found in the cache the code jumps to
772   // the label not_found with only the content of register object unchanged.
773   void LookupNumberStringCache(Register object,
774                                Register result,
775                                Register scratch1,
776                                Register scratch2,
777                                Label* not_found);
778
779   // If object is a string, its map is loaded into object_map.
780   void JumpIfNotString(Register object,
781                        Register object_map,
782                        Label* not_string,
783                        Label::Distance near_jump = Label::kFar);
784
785
786   void JumpIfNotBothSequentialAsciiStrings(
787       Register first_object,
788       Register second_object,
789       Register scratch1,
790       Register scratch2,
791       Label* on_not_both_flat_ascii,
792       Label::Distance near_jump = Label::kFar);
793
794   // Check whether the instance type represents a flat ASCII string. Jump to the
795   // label if not. If the instance type can be scratched specify same register
796   // for both instance type and scratch.
797   void JumpIfInstanceTypeIsNotSequentialAscii(
798       Register instance_type,
799       Register scratch,
800       Label*on_not_flat_ascii_string,
801       Label::Distance near_jump = Label::kFar);
802
803   void JumpIfBothInstanceTypesAreNotSequentialAscii(
804       Register first_object_instance_type,
805       Register second_object_instance_type,
806       Register scratch1,
807       Register scratch2,
808       Label* on_fail,
809       Label::Distance near_jump = Label::kFar);
810
811   void EmitSeqStringSetCharCheck(Register string,
812                                  Register index,
813                                  Register value,
814                                  uint32_t encoding_mask);
815
816   // Checks if the given register or operand is a unique name
817   void JumpIfNotUniqueName(Register reg, Label* not_unique_name,
818                            Label::Distance distance = Label::kFar);
819   void JumpIfNotUniqueName(Operand operand, Label* not_unique_name,
820                            Label::Distance distance = Label::kFar);
821
822   // ---------------------------------------------------------------------------
823   // Macro instructions.
824
825   // Load/store with specific representation.
826   void Load(Register dst, const Operand& src, Representation r);
827   void Store(const Operand& dst, Register src, Representation r);
828
829   // Load a register with a long value as efficiently as possible.
830   void Set(Register dst, int64_t x);
831   void Set(const Operand& dst, intptr_t x);
832
833   // cvtsi2sd instruction only writes to the low 64-bit of dst register, which
834   // hinders register renaming and makes dependence chains longer. So we use
835   // xorps to clear the dst register before cvtsi2sd to solve this issue.
836   void Cvtlsi2sd(XMMRegister dst, Register src);
837   void Cvtlsi2sd(XMMRegister dst, const Operand& src);
838
839   // Move if the registers are not identical.
840   void Move(Register target, Register source);
841
842   // TestBit and Load SharedFunctionInfo special field.
843   void TestBitSharedFunctionInfoSpecialField(Register base,
844                                              int offset,
845                                              int bit_index);
846   void LoadSharedFunctionInfoSpecialField(Register dst,
847                                           Register base,
848                                           int offset);
849
850   // Handle support
851   void Move(Register dst, Handle<Object> source);
852   void Move(const Operand& dst, Handle<Object> source);
853   void Cmp(Register dst, Handle<Object> source);
854   void Cmp(const Operand& dst, Handle<Object> source);
855   void Cmp(Register dst, Smi* src);
856   void Cmp(const Operand& dst, Smi* src);
857   void Push(Handle<Object> source);
858
859   // Load a heap object and handle the case of new-space objects by
860   // indirecting via a global cell.
861   void MoveHeapObject(Register result, Handle<Object> object);
862
863   // Load a global cell into a register.
864   void LoadGlobalCell(Register dst, Handle<Cell> cell);
865
866   // Emit code to discard a non-negative number of pointer-sized elements
867   // from the stack, clobbering only the rsp register.
868   void Drop(int stack_elements);
869   // Emit code to discard a positive number of pointer-sized elements
870   // from the stack under the return address which remains on the top,
871   // clobbering the rsp register.
872   void DropUnderReturnAddress(int stack_elements,
873                               Register scratch = kScratchRegister);
874
875   void Call(Label* target) { call(target); }
876   void Push(Register src);
877   void Push(const Operand& src);
878   void PushQuad(const Operand& src);
879   void Push(Immediate value);
880   void PushImm32(int32_t imm32);
881   void Pop(Register dst);
882   void Pop(const Operand& dst);
883   void PopQuad(const Operand& dst);
884   void PushReturnAddressFrom(Register src) { pushq(src); }
885   void PopReturnAddressTo(Register dst) { popq(dst); }
886   void Move(Register dst, ExternalReference ext) {
887     movp(dst, reinterpret_cast<void*>(ext.address()),
888          RelocInfo::EXTERNAL_REFERENCE);
889   }
890
891   // Loads a pointer into a register with a relocation mode.
892   void Move(Register dst, void* ptr, RelocInfo::Mode rmode) {
893     // This method must not be used with heap object references. The stored
894     // address is not GC safe. Use the handle version instead.
895     DCHECK(rmode > RelocInfo::LAST_GCED_ENUM);
896     movp(dst, ptr, rmode);
897   }
898
899   void Move(Register dst, Handle<Object> value, RelocInfo::Mode rmode) {
900     AllowDeferredHandleDereference using_raw_address;
901     DCHECK(!RelocInfo::IsNone(rmode));
902     DCHECK(value->IsHeapObject());
903     DCHECK(!isolate()->heap()->InNewSpace(*value));
904     movp(dst, reinterpret_cast<void*>(value.location()), rmode);
905   }
906
907   // Control Flow
908   void Jump(Address destination, RelocInfo::Mode rmode);
909   void Jump(ExternalReference ext);
910   void Jump(const Operand& op);
911   void Jump(Handle<Code> code_object, RelocInfo::Mode rmode);
912
913   void Call(Address destination, RelocInfo::Mode rmode);
914   void Call(ExternalReference ext);
915   void Call(const Operand& op);
916   void Call(Handle<Code> code_object,
917             RelocInfo::Mode rmode,
918             TypeFeedbackId ast_id = TypeFeedbackId::None());
919
920   // The size of the code generated for different call instructions.
921   int CallSize(Address destination) {
922     return kCallSequenceLength;
923   }
924   int CallSize(ExternalReference ext);
925   int CallSize(Handle<Code> code_object) {
926     // Code calls use 32-bit relative addressing.
927     return kShortCallInstructionLength;
928   }
929   int CallSize(Register target) {
930     // Opcode: REX_opt FF /2 m64
931     return (target.high_bit() != 0) ? 3 : 2;
932   }
933   int CallSize(const Operand& target) {
934     // Opcode: REX_opt FF /2 m64
935     return (target.requires_rex() ? 2 : 1) + target.operand_size();
936   }
937
938   // Emit call to the code we are currently generating.
939   void CallSelf() {
940     Handle<Code> self(reinterpret_cast<Code**>(CodeObject().location()));
941     Call(self, RelocInfo::CODE_TARGET);
942   }
943
944   // Non-x64 instructions.
945   // Push/pop all general purpose registers.
946   // Does not push rsp/rbp nor any of the assembler's special purpose registers
947   // (kScratchRegister, kSmiConstantRegister, kRootRegister).
948   void Pushad();
949   void Popad();
950   // Sets the stack as after performing Popad, without actually loading the
951   // registers.
952   void Dropad();
953
954   // Compare object type for heap object.
955   // Always use unsigned comparisons: above and below, not less and greater.
956   // Incoming register is heap_object and outgoing register is map.
957   // They may be the same register, and may be kScratchRegister.
958   void CmpObjectType(Register heap_object, InstanceType type, Register map);
959
960   // Compare instance type for map.
961   // Always use unsigned comparisons: above and below, not less and greater.
962   void CmpInstanceType(Register map, InstanceType type);
963
964   // Check if a map for a JSObject indicates that the object has fast elements.
965   // Jump to the specified label if it does not.
966   void CheckFastElements(Register map,
967                          Label* fail,
968                          Label::Distance distance = Label::kFar);
969
970   // Check if a map for a JSObject indicates that the object can have both smi
971   // and HeapObject elements.  Jump to the specified label if it does not.
972   void CheckFastObjectElements(Register map,
973                                Label* fail,
974                                Label::Distance distance = Label::kFar);
975
976   // Check if a map for a JSObject indicates that the object has fast smi only
977   // elements.  Jump to the specified label if it does not.
978   void CheckFastSmiElements(Register map,
979                             Label* fail,
980                             Label::Distance distance = Label::kFar);
981
982   // Check to see if maybe_number can be stored as a double in
983   // FastDoubleElements. If it can, store it at the index specified by index in
984   // the FastDoubleElements array elements, otherwise jump to fail.  Note that
985   // index must not be smi-tagged.
986   void StoreNumberToDoubleElements(Register maybe_number,
987                                    Register elements,
988                                    Register index,
989                                    XMMRegister xmm_scratch,
990                                    Label* fail,
991                                    int elements_offset = 0);
992
993   // Compare an object's map with the specified map.
994   void CompareMap(Register obj, Handle<Map> map);
995
996   // Check if the map of an object is equal to a specified map and branch to
997   // label if not. Skip the smi check if not required (object is known to be a
998   // heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match
999   // against maps that are ElementsKind transition maps of the specified map.
1000   void CheckMap(Register obj,
1001                 Handle<Map> map,
1002                 Label* fail,
1003                 SmiCheckType smi_check_type);
1004
1005   // Check if the map of an object is equal to a specified map and branch to a
1006   // specified target if equal. Skip the smi check if not required (object is
1007   // known to be a heap object)
1008   void DispatchMap(Register obj,
1009                    Register unused,
1010                    Handle<Map> map,
1011                    Handle<Code> success,
1012                    SmiCheckType smi_check_type);
1013
1014   // Check if the object in register heap_object is a string. Afterwards the
1015   // register map contains the object map and the register instance_type
1016   // contains the instance_type. The registers map and instance_type can be the
1017   // same in which case it contains the instance type afterwards. Either of the
1018   // registers map and instance_type can be the same as heap_object.
1019   Condition IsObjectStringType(Register heap_object,
1020                                Register map,
1021                                Register instance_type);
1022
1023   // Check if the object in register heap_object is a name. Afterwards the
1024   // register map contains the object map and the register instance_type
1025   // contains the instance_type. The registers map and instance_type can be the
1026   // same in which case it contains the instance type afterwards. Either of the
1027   // registers map and instance_type can be the same as heap_object.
1028   Condition IsObjectNameType(Register heap_object,
1029                              Register map,
1030                              Register instance_type);
1031
1032   // FCmp compares and pops the two values on top of the FPU stack.
1033   // The flag results are similar to integer cmp, but requires unsigned
1034   // jcc instructions (je, ja, jae, jb, jbe, je, and jz).
1035   void FCmp();
1036
1037   void ClampUint8(Register reg);
1038
1039   void ClampDoubleToUint8(XMMRegister input_reg,
1040                           XMMRegister temp_xmm_reg,
1041                           Register result_reg);
1042
1043   void SlowTruncateToI(Register result_reg, Register input_reg,
1044       int offset = HeapNumber::kValueOffset - kHeapObjectTag);
1045
1046   void TruncateHeapNumberToI(Register result_reg, Register input_reg);
1047   void TruncateDoubleToI(Register result_reg, XMMRegister input_reg);
1048
1049   void DoubleToI(Register result_reg, XMMRegister input_reg,
1050       XMMRegister scratch, MinusZeroMode minus_zero_mode,
1051       Label* conversion_failed, Label::Distance dst = Label::kFar);
1052
1053   void TaggedToI(Register result_reg, Register input_reg, XMMRegister temp,
1054       MinusZeroMode minus_zero_mode, Label* lost_precision,
1055       Label::Distance dst = Label::kFar);
1056
1057   void LoadUint32(XMMRegister dst, Register src);
1058
1059   void LoadInstanceDescriptors(Register map, Register descriptors);
1060   void EnumLength(Register dst, Register map);
1061   void NumberOfOwnDescriptors(Register dst, Register map);
1062
1063   template<typename Field>
1064   void DecodeField(Register reg) {
1065     static const int shift = Field::kShift;
1066     static const int mask = Field::kMask >> Field::kShift;
1067     if (shift != 0) {
1068       shrp(reg, Immediate(shift));
1069     }
1070     andp(reg, Immediate(mask));
1071   }
1072
1073   template<typename Field>
1074   void DecodeFieldToSmi(Register reg) {
1075     if (SmiValuesAre32Bits()) {
1076       andp(reg, Immediate(Field::kMask));
1077       shlp(reg, Immediate(kSmiShift - Field::kShift));
1078     } else {
1079       static const int shift = Field::kShift;
1080       static const int mask = (Field::kMask >> Field::kShift) << kSmiTagSize;
1081       DCHECK(SmiValuesAre31Bits());
1082       DCHECK(kSmiShift == kSmiTagSize);
1083       DCHECK((mask & 0x80000000u) == 0);
1084       if (shift < kSmiShift) {
1085         shlp(reg, Immediate(kSmiShift - shift));
1086       } else if (shift > kSmiShift) {
1087         sarp(reg, Immediate(shift - kSmiShift));
1088       }
1089       andp(reg, Immediate(mask));
1090     }
1091   }
1092
1093   // Abort execution if argument is not a number, enabled via --debug-code.
1094   void AssertNumber(Register object);
1095
1096   // Abort execution if argument is a smi, enabled via --debug-code.
1097   void AssertNotSmi(Register object);
1098
1099   // Abort execution if argument is not a smi, enabled via --debug-code.
1100   void AssertSmi(Register object);
1101   void AssertSmi(const Operand& object);
1102
1103   // Abort execution if a 64 bit register containing a 32 bit payload does not
1104   // have zeros in the top 32 bits, enabled via --debug-code.
1105   void AssertZeroExtended(Register reg);
1106
1107   // Abort execution if argument is not a string, enabled via --debug-code.
1108   void AssertString(Register object);
1109
1110   // Abort execution if argument is not a name, enabled via --debug-code.
1111   void AssertName(Register object);
1112
1113   // Abort execution if argument is not undefined or an AllocationSite, enabled
1114   // via --debug-code.
1115   void AssertUndefinedOrAllocationSite(Register object);
1116
1117   // Abort execution if argument is not the root value with the given index,
1118   // enabled via --debug-code.
1119   void AssertRootValue(Register src,
1120                        Heap::RootListIndex root_value_index,
1121                        BailoutReason reason);
1122
1123   // ---------------------------------------------------------------------------
1124   // Exception handling
1125
1126   // Push a new try handler and link it into try handler chain.
1127   void PushTryHandler(StackHandler::Kind kind, int handler_index);
1128
1129   // Unlink the stack handler on top of the stack from the try handler chain.
1130   void PopTryHandler();
1131
1132   // Activate the top handler in the try hander chain and pass the
1133   // thrown value.
1134   void Throw(Register value);
1135
1136   // Propagate an uncatchable exception out of the current JS stack.
1137   void ThrowUncatchable(Register value);
1138
1139   // ---------------------------------------------------------------------------
1140   // Inline caching support
1141
1142   // Generate code for checking access rights - used for security checks
1143   // on access to global objects across environments. The holder register
1144   // is left untouched, but the scratch register and kScratchRegister,
1145   // which must be different, are clobbered.
1146   void CheckAccessGlobalProxy(Register holder_reg,
1147                               Register scratch,
1148                               Label* miss);
1149
1150   void GetNumberHash(Register r0, Register scratch);
1151
1152   void LoadFromNumberDictionary(Label* miss,
1153                                 Register elements,
1154                                 Register key,
1155                                 Register r0,
1156                                 Register r1,
1157                                 Register r2,
1158                                 Register result);
1159
1160
1161   // ---------------------------------------------------------------------------
1162   // Allocation support
1163
1164   // Allocate an object in new space or old pointer space. If the given space
1165   // is exhausted control continues at the gc_required label. The allocated
1166   // object is returned in result and end of the new object is returned in
1167   // result_end. The register scratch can be passed as no_reg in which case
1168   // an additional object reference will be added to the reloc info. The
1169   // returned pointers in result and result_end have not yet been tagged as
1170   // heap objects. If result_contains_top_on_entry is true the content of
1171   // result is known to be the allocation top on entry (could be result_end
1172   // from a previous call). If result_contains_top_on_entry is true scratch
1173   // should be no_reg as it is never used.
1174   void Allocate(int object_size,
1175                 Register result,
1176                 Register result_end,
1177                 Register scratch,
1178                 Label* gc_required,
1179                 AllocationFlags flags);
1180
1181   void Allocate(int header_size,
1182                 ScaleFactor element_size,
1183                 Register element_count,
1184                 Register result,
1185                 Register result_end,
1186                 Register scratch,
1187                 Label* gc_required,
1188                 AllocationFlags flags);
1189
1190   void Allocate(Register object_size,
1191                 Register result,
1192                 Register result_end,
1193                 Register scratch,
1194                 Label* gc_required,
1195                 AllocationFlags flags);
1196
1197   // Undo allocation in new space. The object passed and objects allocated after
1198   // it will no longer be allocated. Make sure that no pointers are left to the
1199   // object(s) no longer allocated as they would be invalid when allocation is
1200   // un-done.
1201   void UndoAllocationInNewSpace(Register object);
1202
1203   // Allocate a heap number in new space with undefined value. Returns
1204   // tagged pointer in result register, or jumps to gc_required if new
1205   // space is full.
1206   void AllocateHeapNumber(Register result,
1207                           Register scratch,
1208                           Label* gc_required,
1209                           MutableMode mode = IMMUTABLE);
1210
1211
1212   // Allocate a float32x4, float64x2 and int32x4 object in new space with
1213   // undefined value.
1214   // Returns tagged pointer in result register, or jumps to gc_required if new
1215   // space is full.
1216   void AllocateFloat32x4(Register result,
1217                          Register scratch1,
1218                          Register scratch2,
1219                          Register scratch3,
1220                          Label* gc_required);
1221
1222   void AllocateFloat64x2(Register result,
1223                          Register scratch1,
1224                          Register scratch2,
1225                          Register scratch3,
1226                          Label* gc_required);
1227
1228   void AllocateInt32x4(Register result,
1229                        Register scratch1,
1230                        Register scratch2,
1231                        Register scratch3,
1232                        Label* gc_required);
1233
1234   // Allocate a sequential string. All the header fields of the string object
1235   // are initialized.
1236   void AllocateTwoByteString(Register result,
1237                              Register length,
1238                              Register scratch1,
1239                              Register scratch2,
1240                              Register scratch3,
1241                              Label* gc_required);
1242   void AllocateAsciiString(Register result,
1243                            Register length,
1244                            Register scratch1,
1245                            Register scratch2,
1246                            Register scratch3,
1247                            Label* gc_required);
1248
1249   // Allocate a raw cons string object. Only the map field of the result is
1250   // initialized.
1251   void AllocateTwoByteConsString(Register result,
1252                           Register scratch1,
1253                           Register scratch2,
1254                           Label* gc_required);
1255   void AllocateAsciiConsString(Register result,
1256                                Register scratch1,
1257                                Register scratch2,
1258                                Label* gc_required);
1259
1260   // Allocate a raw sliced string object. Only the map field of the result is
1261   // initialized.
1262   void AllocateTwoByteSlicedString(Register result,
1263                             Register scratch1,
1264                             Register scratch2,
1265                             Label* gc_required);
1266   void AllocateAsciiSlicedString(Register result,
1267                                  Register scratch1,
1268                                  Register scratch2,
1269                                  Label* gc_required);
1270
1271   // ---------------------------------------------------------------------------
1272   // Support functions.
1273
1274   // Check if result is zero and op is negative.
1275   void NegativeZeroTest(Register result, Register op, Label* then_label);
1276
1277   // Check if result is zero and op is negative in code using jump targets.
1278   void NegativeZeroTest(CodeGenerator* cgen,
1279                         Register result,
1280                         Register op,
1281                         JumpTarget* then_target);
1282
1283   // Check if result is zero and any of op1 and op2 are negative.
1284   // Register scratch is destroyed, and it must be different from op2.
1285   void NegativeZeroTest(Register result, Register op1, Register op2,
1286                         Register scratch, Label* then_label);
1287
1288   // Try to get function prototype of a function and puts the value in
1289   // the result register. Checks that the function really is a
1290   // function and jumps to the miss label if the fast checks fail. The
1291   // function register will be untouched; the other register may be
1292   // clobbered.
1293   void TryGetFunctionPrototype(Register function,
1294                                Register result,
1295                                Label* miss,
1296                                bool miss_on_bound_function = false);
1297
1298   // Picks out an array index from the hash field.
1299   // Register use:
1300   //   hash - holds the index's hash. Clobbered.
1301   //   index - holds the overwritten index on exit.
1302   void IndexFromHash(Register hash, Register index);
1303
1304   // Find the function context up the context chain.
1305   void LoadContext(Register dst, int context_chain_length);
1306
1307   // Conditionally load the cached Array transitioned map of type
1308   // transitioned_kind from the native context if the map in register
1309   // map_in_out is the cached Array map in the native context of
1310   // expected_kind.
1311   void LoadTransitionedArrayMapConditional(
1312       ElementsKind expected_kind,
1313       ElementsKind transitioned_kind,
1314       Register map_in_out,
1315       Register scratch,
1316       Label* no_map_match);
1317
1318   // Load the global function with the given index.
1319   void LoadGlobalFunction(int index, Register function);
1320
1321   // Load the initial map from the global function. The registers
1322   // function and map can be the same.
1323   void LoadGlobalFunctionInitialMap(Register function, Register map);
1324
1325   // ---------------------------------------------------------------------------
1326   // Runtime calls
1327
1328   // Call a code stub.
1329   void CallStub(CodeStub* stub, TypeFeedbackId ast_id = TypeFeedbackId::None());
1330
1331   // Tail call a code stub (jump).
1332   void TailCallStub(CodeStub* stub);
1333
1334   // Return from a code stub after popping its arguments.
1335   void StubReturn(int argc);
1336
1337   // Call a runtime routine.
1338   void CallRuntime(const Runtime::Function* f,
1339                    int num_arguments,
1340                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
1341
1342   // Call a runtime function and save the value of XMM registers.
1343   void CallRuntimeSaveDoubles(Runtime::FunctionId id) {
1344     const Runtime::Function* function = Runtime::FunctionForId(id);
1345     CallRuntime(function, function->nargs, kSaveFPRegs);
1346   }
1347
1348   // Convenience function: Same as above, but takes the fid instead.
1349   void CallRuntime(Runtime::FunctionId id,
1350                    int num_arguments,
1351                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
1352     CallRuntime(Runtime::FunctionForId(id), num_arguments, save_doubles);
1353   }
1354
1355   // Convenience function: call an external reference.
1356   void CallExternalReference(const ExternalReference& ext,
1357                              int num_arguments);
1358
1359   // Tail call of a runtime routine (jump).
1360   // Like JumpToExternalReference, but also takes care of passing the number
1361   // of parameters.
1362   void TailCallExternalReference(const ExternalReference& ext,
1363                                  int num_arguments,
1364                                  int result_size);
1365
1366   // Convenience function: tail call a runtime routine (jump).
1367   void TailCallRuntime(Runtime::FunctionId fid,
1368                        int num_arguments,
1369                        int result_size);
1370
1371   // Jump to a runtime routine.
1372   void JumpToExternalReference(const ExternalReference& ext, int result_size);
1373
1374   // Prepares stack to put arguments (aligns and so on).  WIN64 calling
1375   // convention requires to put the pointer to the return value slot into
1376   // rcx (rcx must be preserverd until CallApiFunctionAndReturn).  Saves
1377   // context (rsi).  Clobbers rax.  Allocates arg_stack_space * kPointerSize
1378   // inside the exit frame (not GCed) accessible via StackSpaceOperand.
1379   void PrepareCallApiFunction(int arg_stack_space);
1380
1381   // Calls an API function.  Allocates HandleScope, extracts returned value
1382   // from handle and propagates exceptions.  Clobbers r14, r15, rbx and
1383   // caller-save registers.  Restores context.  On return removes
1384   // stack_space * kPointerSize (GCed).
1385   void CallApiFunctionAndReturn(Register function_address,
1386                                 ExternalReference thunk_ref,
1387                                 Register thunk_last_arg,
1388                                 int stack_space,
1389                                 Operand return_value_operand,
1390                                 Operand* context_restore_operand);
1391
1392   // Before calling a C-function from generated code, align arguments on stack.
1393   // After aligning the frame, arguments must be stored in rsp[0], rsp[8],
1394   // etc., not pushed. The argument count assumes all arguments are word sized.
1395   // The number of slots reserved for arguments depends on platform. On Windows
1396   // stack slots are reserved for the arguments passed in registers. On other
1397   // platforms stack slots are only reserved for the arguments actually passed
1398   // on the stack.
1399   void PrepareCallCFunction(int num_arguments);
1400
1401   // Calls a C function and cleans up the space for arguments allocated
1402   // by PrepareCallCFunction. The called function is not allowed to trigger a
1403   // garbage collection, since that might move the code and invalidate the
1404   // return address (unless this is somehow accounted for by the called
1405   // function).
1406   void CallCFunction(ExternalReference function, int num_arguments);
1407   void CallCFunction(Register function, int num_arguments);
1408
1409   // Calculate the number of stack slots to reserve for arguments when calling a
1410   // C function.
1411   int ArgumentStackSlotsForCFunctionCall(int num_arguments);
1412
1413   // ---------------------------------------------------------------------------
1414   // Utilities
1415
1416   void Ret();
1417
1418   // Return and drop arguments from stack, where the number of arguments
1419   // may be bigger than 2^16 - 1.  Requires a scratch register.
1420   void Ret(int bytes_dropped, Register scratch);
1421
1422   Handle<Object> CodeObject() {
1423     DCHECK(!code_object_.is_null());
1424     return code_object_;
1425   }
1426
1427   // Copy length bytes from source to destination.
1428   // Uses scratch register internally (if you have a low-eight register
1429   // free, do use it, otherwise kScratchRegister will be used).
1430   // The min_length is a minimum limit on the value that length will have.
1431   // The algorithm has some special cases that might be omitted if the string
1432   // is known to always be long.
1433   void CopyBytes(Register destination,
1434                  Register source,
1435                  Register length,
1436                  int min_length = 0,
1437                  Register scratch = kScratchRegister);
1438
1439   // Initialize fields with filler values.  Fields starting at |start_offset|
1440   // not including end_offset are overwritten with the value in |filler|.  At
1441   // the end the loop, |start_offset| takes the value of |end_offset|.
1442   void InitializeFieldsWithFiller(Register start_offset,
1443                                   Register end_offset,
1444                                   Register filler);
1445
1446
1447   // Emit code for a truncating division by a constant. The dividend register is
1448   // unchanged, the result is in rdx, and rax gets clobbered.
1449   void TruncatingDiv(Register dividend, int32_t divisor);
1450
1451   // ---------------------------------------------------------------------------
1452   // StatsCounter support
1453
1454   void SetCounter(StatsCounter* counter, int value);
1455   void IncrementCounter(StatsCounter* counter, int value);
1456   void DecrementCounter(StatsCounter* counter, int value);
1457
1458
1459   // ---------------------------------------------------------------------------
1460   // Debugging
1461
1462   // Calls Abort(msg) if the condition cc is not satisfied.
1463   // Use --debug_code to enable.
1464   void Assert(Condition cc, BailoutReason reason);
1465
1466   void AssertFastElements(Register elements);
1467
1468   // Like Assert(), but always enabled.
1469   void Check(Condition cc, BailoutReason reason);
1470
1471   // Print a message to stdout and abort execution.
1472   void Abort(BailoutReason msg);
1473
1474   // Check that the stack is aligned.
1475   void CheckStackAlignment();
1476
1477   // Verify restrictions about code generated in stubs.
1478   void set_generating_stub(bool value) { generating_stub_ = value; }
1479   bool generating_stub() { return generating_stub_; }
1480   void set_has_frame(bool value) { has_frame_ = value; }
1481   bool has_frame() { return has_frame_; }
1482   inline bool AllowThisStubCall(CodeStub* stub);
1483
1484   static int SafepointRegisterStackIndex(Register reg) {
1485     return SafepointRegisterStackIndex(reg.code());
1486   }
1487
1488   // Activation support.
1489   void EnterFrame(StackFrame::Type type);
1490   void LeaveFrame(StackFrame::Type type);
1491
1492   // Expects object in rax and returns map with validated enum cache
1493   // in rax.  Assumes that any other register can be used as a scratch.
1494   void CheckEnumCache(Register null_value,
1495                       Label* call_runtime);
1496
1497   // AllocationMemento support. Arrays may have an associated
1498   // AllocationMemento object that can be checked for in order to pretransition
1499   // to another type.
1500   // On entry, receiver_reg should point to the array object.
1501   // scratch_reg gets clobbered.
1502   // If allocation info is present, condition flags are set to equal.
1503   void TestJSArrayForAllocationMemento(Register receiver_reg,
1504                                        Register scratch_reg,
1505                                        Label* no_memento_found);
1506
1507   void JumpIfJSArrayHasAllocationMemento(Register receiver_reg,
1508                                          Register scratch_reg,
1509                                          Label* memento_found) {
1510     Label no_memento_found;
1511     TestJSArrayForAllocationMemento(receiver_reg, scratch_reg,
1512                                     &no_memento_found);
1513     j(equal, memento_found);
1514     bind(&no_memento_found);
1515   }
1516
1517   // Jumps to found label if a prototype map has dictionary elements.
1518   void JumpIfDictionaryInPrototypeChain(Register object, Register scratch0,
1519                                         Register scratch1, Label* found);
1520
1521  private:
1522   // Order general registers are pushed by Pushad.
1523   // rax, rcx, rdx, rbx, rsi, rdi, r8, r9, r11, r14, r15.
1524   static const int kSafepointPushRegisterIndices[Register::kNumRegisters];
1525   static const int kNumSafepointSavedRegisters = 11;
1526   static const int kSmiShift = kSmiTagSize + kSmiShiftSize;
1527
1528   bool generating_stub_;
1529   bool has_frame_;
1530   bool root_array_available_;
1531
1532   // Returns a register holding the smi value. The register MUST NOT be
1533   // modified. It may be the "smi 1 constant" register.
1534   Register GetSmiConstant(Smi* value);
1535
1536   int64_t RootRegisterDelta(ExternalReference other);
1537
1538   // Moves the smi value to the destination register.
1539   void LoadSmiConstant(Register dst, Smi* value);
1540
1541   // This handle will be patched with the code object on installation.
1542   Handle<Object> code_object_;
1543
1544   // Helper functions for generating invokes.
1545   void InvokePrologue(const ParameterCount& expected,
1546                       const ParameterCount& actual,
1547                       Handle<Code> code_constant,
1548                       Register code_register,
1549                       Label* done,
1550                       bool* definitely_mismatches,
1551                       InvokeFlag flag,
1552                       Label::Distance near_jump = Label::kFar,
1553                       const CallWrapper& call_wrapper = NullCallWrapper());
1554
1555   void EnterExitFramePrologue(bool save_rax);
1556
1557   // Allocates arg_stack_space * kPointerSize memory (not GCed) on the stack
1558   // accessible via StackSpaceOperand.
1559   void EnterExitFrameEpilogue(int arg_stack_space, bool save_doubles);
1560
1561   void LeaveExitFrameEpilogue(bool restore_context);
1562
1563   // Allocation support helpers.
1564   // Loads the top of new-space into the result register.
1565   // Otherwise the address of the new-space top is loaded into scratch (if
1566   // scratch is valid), and the new-space top is loaded into result.
1567   void LoadAllocationTopHelper(Register result,
1568                                Register scratch,
1569                                AllocationFlags flags);
1570
1571   void MakeSureDoubleAlignedHelper(Register result,
1572                                    Register scratch,
1573                                    Label* gc_required,
1574                                    AllocationFlags flags);
1575
1576   // Update allocation top with value in result_end register.
1577   // If scratch is valid, it contains the address of the allocation top.
1578   void UpdateAllocationTopHelper(Register result_end,
1579                                  Register scratch,
1580                                  AllocationFlags flags);
1581
1582   // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
1583   void InNewSpace(Register object,
1584                   Register scratch,
1585                   Condition cc,
1586                   Label* branch,
1587                   Label::Distance distance = Label::kFar);
1588
1589   // Helper for finding the mark bits for an address.  Afterwards, the
1590   // bitmap register points at the word with the mark bits and the mask
1591   // the position of the first bit.  Uses rcx as scratch and leaves addr_reg
1592   // unchanged.
1593   inline void GetMarkBits(Register addr_reg,
1594                           Register bitmap_reg,
1595                           Register mask_reg);
1596
1597   // Helper for throwing exceptions.  Compute a handler address and jump to
1598   // it.  See the implementation for register usage.
1599   void JumpToHandlerEntry();
1600
1601   // Compute memory operands for safepoint stack slots.
1602   Operand SafepointRegisterSlot(Register reg);
1603   static int SafepointRegisterStackIndex(int reg_code) {
1604     return kNumSafepointRegisters - kSafepointPushRegisterIndices[reg_code] - 1;
1605   }
1606
1607   // Needs access to SafepointRegisterStackIndex for compiled frame
1608   // traversal.
1609   friend class StandardFrame;
1610 };
1611
1612
1613 // The code patcher is used to patch (typically) small parts of code e.g. for
1614 // debugging and other types of instrumentation. When using the code patcher
1615 // the exact number of bytes specified must be emitted. Is not legal to emit
1616 // relocation information. If any of these constraints are violated it causes
1617 // an assertion.
1618 class CodePatcher {
1619  public:
1620   CodePatcher(byte* address, int size);
1621   virtual ~CodePatcher();
1622
1623   // Macro assembler to emit code.
1624   MacroAssembler* masm() { return &masm_; }
1625
1626  private:
1627   byte* address_;  // The address of the code being patched.
1628   int size_;  // Number of bytes of the expected patch size.
1629   MacroAssembler masm_;  // Macro assembler used to generate the code.
1630 };
1631
1632
1633 // -----------------------------------------------------------------------------
1634 // Static helper functions.
1635
1636 // Generate an Operand for loading a field from an object.
1637 inline Operand FieldOperand(Register object, int offset) {
1638   return Operand(object, offset - kHeapObjectTag);
1639 }
1640
1641
1642 // Generate an Operand for loading an indexed field from an object.
1643 inline Operand FieldOperand(Register object,
1644                             Register index,
1645                             ScaleFactor scale,
1646                             int offset) {
1647   return Operand(object, index, scale, offset - kHeapObjectTag);
1648 }
1649
1650
1651 inline Operand ContextOperand(Register context, int index) {
1652   return Operand(context, Context::SlotOffset(index));
1653 }
1654
1655
1656 inline Operand GlobalObjectOperand() {
1657   return ContextOperand(rsi, Context::GLOBAL_OBJECT_INDEX);
1658 }
1659
1660
1661 // Provides access to exit frame stack space (not GCed).
1662 inline Operand StackSpaceOperand(int index) {
1663 #ifdef _WIN64
1664   const int kShaddowSpace = 4;
1665   return Operand(rsp, (index + kShaddowSpace) * kPointerSize);
1666 #else
1667   return Operand(rsp, index * kPointerSize);
1668 #endif
1669 }
1670
1671
1672 inline Operand StackOperandForReturnAddress(int32_t disp) {
1673   return Operand(rsp, disp);
1674 }
1675
1676
1677 #ifdef GENERATED_CODE_COVERAGE
1678 extern void LogGeneratedCodeCoverage(const char* file_line);
1679 #define CODE_COVERAGE_STRINGIFY(x) #x
1680 #define CODE_COVERAGE_TOSTRING(x) CODE_COVERAGE_STRINGIFY(x)
1681 #define __FILE_LINE__ __FILE__ ":" CODE_COVERAGE_TOSTRING(__LINE__)
1682 #define ACCESS_MASM(masm) {                                                  \
1683     Address x64_coverage_function = FUNCTION_ADDR(LogGeneratedCodeCoverage); \
1684     masm->pushfq();                                                          \
1685     masm->Pushad();                                                          \
1686     masm->Push(Immediate(reinterpret_cast<int>(&__FILE_LINE__)));            \
1687     masm->Call(x64_coverage_function, RelocInfo::EXTERNAL_REFERENCE);        \
1688     masm->Pop(rax);                                                          \
1689     masm->Popad();                                                           \
1690     masm->popfq();                                                           \
1691   }                                                                          \
1692   masm->
1693 #else
1694 #define ACCESS_MASM(masm) masm->
1695 #endif
1696
1697 } }  // namespace v8::internal
1698
1699 #endif  // V8_X64_MACRO_ASSEMBLER_X64_H_