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_X87_MACRO_ASSEMBLER_X87_H_
6 #define V8_X87_MACRO_ASSEMBLER_X87_H_
7 
8 #include "src/assembler.h"
9 #include "src/bailout-reason.h"
10 #include "src/frames.h"
11 #include "src/globals.h"
12 
13 namespace v8 {
14 namespace internal {
15 
16 // Give alias names to registers for calling conventions.
17 const Register kReturnRegister0 = {Register::kCode_eax};
18 const Register kReturnRegister1 = {Register::kCode_edx};
19 const Register kReturnRegister2 = {Register::kCode_edi};
20 const Register kJSFunctionRegister = {Register::kCode_edi};
21 const Register kContextRegister = {Register::kCode_esi};
22 const Register kAllocateSizeRegister = {Register::kCode_edx};
23 const Register kInterpreterAccumulatorRegister = {Register::kCode_eax};
24 const Register kInterpreterBytecodeOffsetRegister = {Register::kCode_ecx};
25 const Register kInterpreterBytecodeArrayRegister = {Register::kCode_edi};
26 const Register kInterpreterDispatchTableRegister = {Register::kCode_esi};
27 const Register kJavaScriptCallArgCountRegister = {Register::kCode_eax};
28 const Register kJavaScriptCallNewTargetRegister = {Register::kCode_edx};
29 const Register kRuntimeCallFunctionRegister = {Register::kCode_ebx};
30 const Register kRuntimeCallArgCountRegister = {Register::kCode_eax};
31 
32 // Spill slots used by interpreter dispatch calling convention.
33 const int kInterpreterDispatchTableSpillSlot = -1;
34 
35 // Convenience for platform-independent signatures.  We do not normally
36 // distinguish memory operands from other operands on ia32.
37 typedef Operand MemOperand;
38 
39 enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET };
40 enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK };
41 enum PointersToHereCheck {
42   kPointersToHereMaybeInteresting,
43   kPointersToHereAreAlwaysInteresting
44 };
45 
46 enum RegisterValueType { REGISTER_VALUE_IS_SMI, REGISTER_VALUE_IS_INT32 };
47 
48 enum class ReturnAddressState { kOnStack, kNotOnStack };
49 
50 #ifdef DEBUG
51 bool AreAliased(Register reg1, Register reg2, Register reg3 = no_reg,
52                 Register reg4 = no_reg, Register reg5 = no_reg,
53                 Register reg6 = no_reg, Register reg7 = no_reg,
54                 Register reg8 = no_reg);
55 #endif
56 
57 // MacroAssembler implements a collection of frequently used macros.
58 class MacroAssembler: public Assembler {
59  public:
60   MacroAssembler(Isolate* isolate, void* buffer, int size,
61                  CodeObjectRequired create_code_object);
62 
63   void Load(Register dst, const Operand& src, Representation r);
64   void Store(Register src, const Operand& dst, Representation r);
65 
66   // Load a register with a long value as efficiently as possible.
Set(Register dst,int32_t x)67   void Set(Register dst, int32_t x) {
68     if (x == 0) {
69       xor_(dst, dst);
70     } else {
71       mov(dst, Immediate(x));
72     }
73   }
Set(const Operand & dst,int32_t x)74   void Set(const Operand& dst, int32_t x) { mov(dst, Immediate(x)); }
75 
76   // Operations on roots in the root-array.
77   void LoadRoot(Register destination, Heap::RootListIndex index);
78   void StoreRoot(Register source, Register scratch, Heap::RootListIndex index);
79   void CompareRoot(Register with, Register scratch, Heap::RootListIndex index);
80   // These methods can only be used with constant roots (i.e. non-writable
81   // and not in new space).
82   void CompareRoot(Register with, Heap::RootListIndex index);
83   void CompareRoot(const Operand& with, Heap::RootListIndex index);
84   void PushRoot(Heap::RootListIndex index);
85 
86   // Compare the object in a register to a value and jump if they are equal.
87   void JumpIfRoot(Register with, Heap::RootListIndex index, Label* if_equal,
88                   Label::Distance if_equal_distance = Label::kFar) {
89     CompareRoot(with, index);
90     j(equal, if_equal, if_equal_distance);
91   }
92   void JumpIfRoot(const Operand& with, Heap::RootListIndex index,
93                   Label* if_equal,
94                   Label::Distance if_equal_distance = Label::kFar) {
95     CompareRoot(with, index);
96     j(equal, if_equal, if_equal_distance);
97   }
98 
99   // Compare the object in a register to a value and jump if they are not equal.
100   void JumpIfNotRoot(Register with, Heap::RootListIndex index,
101                      Label* if_not_equal,
102                      Label::Distance if_not_equal_distance = Label::kFar) {
103     CompareRoot(with, index);
104     j(not_equal, if_not_equal, if_not_equal_distance);
105   }
106   void JumpIfNotRoot(const Operand& with, Heap::RootListIndex index,
107                      Label* if_not_equal,
108                      Label::Distance if_not_equal_distance = Label::kFar) {
109     CompareRoot(with, index);
110     j(not_equal, if_not_equal, if_not_equal_distance);
111   }
112 
113   // These functions do not arrange the registers in any particular order so
114   // they are not useful for calls that can cause a GC.  The caller can
115   // exclude up to 3 registers that do not need to be saved and restored.
116   void PushCallerSaved(SaveFPRegsMode fp_mode, Register exclusion1 = no_reg,
117                        Register exclusion2 = no_reg,
118                        Register exclusion3 = no_reg);
119   void PopCallerSaved(SaveFPRegsMode fp_mode, Register exclusion1 = no_reg,
120                       Register exclusion2 = no_reg,
121                       Register exclusion3 = no_reg);
122 
123   // ---------------------------------------------------------------------------
124   // GC Support
125   enum RememberedSetFinalAction { kReturnAtEnd, kFallThroughAtEnd };
126 
127   // Record in the remembered set the fact that we have a pointer to new space
128   // at the address pointed to by the addr register.  Only works if addr is not
129   // in new space.
130   void RememberedSetHelper(Register object,  // Used for debug code.
131                            Register addr, Register scratch,
132                            SaveFPRegsMode save_fp,
133                            RememberedSetFinalAction and_then);
134 
135   void CheckPageFlag(Register object, Register scratch, int mask, Condition cc,
136                      Label* condition_met,
137                      Label::Distance condition_met_distance = Label::kFar);
138 
139   void CheckPageFlagForMap(
140       Handle<Map> map, int mask, Condition cc, Label* condition_met,
141       Label::Distance condition_met_distance = Label::kFar);
142 
143   // Check if object is in new space.  Jumps if the object is not in new space.
144   // The register scratch can be object itself, but scratch will be clobbered.
145   void JumpIfNotInNewSpace(Register object, Register scratch, Label* branch,
146                            Label::Distance distance = Label::kFar) {
147     InNewSpace(object, scratch, zero, branch, distance);
148   }
149 
150   // Check if object is in new space.  Jumps if the object is in new space.
151   // The register scratch can be object itself, but it will be clobbered.
152   void JumpIfInNewSpace(Register object, Register scratch, Label* branch,
153                         Label::Distance distance = Label::kFar) {
154     InNewSpace(object, scratch, not_zero, branch, distance);
155   }
156 
157   // Check if an object has a given incremental marking color.  Also uses ecx!
158   void HasColor(Register object, Register scratch0, Register scratch1,
159                 Label* has_color, Label::Distance has_color_distance,
160                 int first_bit, int second_bit);
161 
162   void JumpIfBlack(Register object, Register scratch0, Register scratch1,
163                    Label* on_black,
164                    Label::Distance on_black_distance = Label::kFar);
165 
166   // Checks the color of an object.  If the object is white we jump to the
167   // incremental marker.
168   void JumpIfWhite(Register value, Register scratch1, Register scratch2,
169                    Label* value_is_white, Label::Distance distance);
170 
171   // Notify the garbage collector that we wrote a pointer into an object.
172   // |object| is the object being stored into, |value| is the object being
173   // stored.  value and scratch registers are clobbered by the operation.
174   // The offset is the offset from the start of the object, not the offset from
175   // the tagged HeapObject pointer.  For use with FieldOperand(reg, off).
176   void RecordWriteField(
177       Register object, int offset, Register value, Register scratch,
178       SaveFPRegsMode save_fp,
179       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
180       SmiCheck smi_check = INLINE_SMI_CHECK,
181       PointersToHereCheck pointers_to_here_check_for_value =
182           kPointersToHereMaybeInteresting);
183 
184   // As above, but the offset has the tag presubtracted.  For use with
185   // Operand(reg, off).
186   void RecordWriteContextSlot(
187       Register context, int offset, Register value, Register scratch,
188       SaveFPRegsMode save_fp,
189       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
190       SmiCheck smi_check = INLINE_SMI_CHECK,
191       PointersToHereCheck pointers_to_here_check_for_value =
192           kPointersToHereMaybeInteresting) {
193     RecordWriteField(context, offset + kHeapObjectTag, value, scratch, save_fp,
194                      remembered_set_action, smi_check,
195                      pointers_to_here_check_for_value);
196   }
197 
198   // Notify the garbage collector that we wrote a pointer into a fixed array.
199   // |array| is the array being stored into, |value| is the
200   // object being stored.  |index| is the array index represented as a
201   // Smi. All registers are clobbered by the operation RecordWriteArray
202   // filters out smis so it does not update the write barrier if the
203   // value is a smi.
204   void RecordWriteArray(
205       Register array, Register value, Register index, SaveFPRegsMode save_fp,
206       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
207       SmiCheck smi_check = INLINE_SMI_CHECK,
208       PointersToHereCheck pointers_to_here_check_for_value =
209           kPointersToHereMaybeInteresting);
210 
211   // For page containing |object| mark region covering |address|
212   // dirty. |object| is the object being stored into, |value| is the
213   // object being stored. The address and value registers are clobbered by the
214   // operation. RecordWrite filters out smis so it does not update the
215   // write barrier if the value is a smi.
216   void RecordWrite(
217       Register object, Register address, Register value, SaveFPRegsMode save_fp,
218       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
219       SmiCheck smi_check = INLINE_SMI_CHECK,
220       PointersToHereCheck pointers_to_here_check_for_value =
221           kPointersToHereMaybeInteresting);
222 
223   // Notify the garbage collector that we wrote a code entry into a
224   // JSFunction. Only scratch is clobbered by the operation.
225   void RecordWriteCodeEntryField(Register js_function, Register code_entry,
226                                  Register scratch);
227 
228   // For page containing |object| mark the region covering the object's map
229   // dirty. |object| is the object being stored into, |map| is the Map object
230   // that was stored.
231   void RecordWriteForMap(Register object, Handle<Map> map, Register scratch1,
232                          Register scratch2, SaveFPRegsMode save_fp);
233 
234   // ---------------------------------------------------------------------------
235   // Debugger Support
236 
237   void DebugBreak();
238 
239   // Generates function and stub prologue code.
240   void StubPrologue(StackFrame::Type type);
241   void Prologue(bool code_pre_aging);
242 
243   // Enter specific kind of exit frame. Expects the number of
244   // arguments in register eax and sets up the number of arguments in
245   // register edi and the pointer to the first argument in register
246   // esi.
247   void EnterExitFrame(int argc, bool save_doubles, StackFrame::Type frame_type);
248 
249   void EnterApiExitFrame(int argc);
250 
251   // Leave the current exit frame. Expects the return value in
252   // register eax:edx (untouched) and the pointer to the first
253   // argument in register esi (if pop_arguments == true).
254   void LeaveExitFrame(bool save_doubles, bool pop_arguments = true);
255 
256   // Leave the current exit frame. Expects the return value in
257   // register eax (untouched).
258   void LeaveApiExitFrame(bool restore_context);
259 
260   // Find the function context up the context chain.
261   void LoadContext(Register dst, int context_chain_length);
262 
263   // Load the global proxy from the current context.
264   void LoadGlobalProxy(Register dst);
265 
266   // Load the global function with the given index.
267   void LoadGlobalFunction(int index, Register function);
268 
269   // Load the initial map from the global function. The registers
270   // function and map can be the same.
271   void LoadGlobalFunctionInitialMap(Register function, Register map);
272 
273   // Push and pop the registers that can hold pointers.
PushSafepointRegisters()274   void PushSafepointRegisters() { pushad(); }
PopSafepointRegisters()275   void PopSafepointRegisters() { popad(); }
276   // Store the value in register/immediate src in the safepoint
277   // register stack slot for register dst.
278   void StoreToSafepointRegisterSlot(Register dst, Register src);
279   void StoreToSafepointRegisterSlot(Register dst, Immediate src);
280   void LoadFromSafepointRegisterSlot(Register dst, Register src);
281 
282   // Nop, because x87 does not have a root register.
InitializeRootRegister()283   void InitializeRootRegister() {}
284 
285   void LoadHeapObject(Register result, Handle<HeapObject> object);
286   void CmpHeapObject(Register reg, Handle<HeapObject> object);
287   void PushHeapObject(Handle<HeapObject> object);
288 
LoadObject(Register result,Handle<Object> object)289   void LoadObject(Register result, Handle<Object> object) {
290     AllowDeferredHandleDereference heap_object_check;
291     if (object->IsHeapObject()) {
292       LoadHeapObject(result, Handle<HeapObject>::cast(object));
293     } else {
294       Move(result, Immediate(object));
295     }
296   }
297 
CmpObject(Register reg,Handle<Object> object)298   void CmpObject(Register reg, Handle<Object> object) {
299     AllowDeferredHandleDereference heap_object_check;
300     if (object->IsHeapObject()) {
301       CmpHeapObject(reg, Handle<HeapObject>::cast(object));
302     } else {
303       cmp(reg, Immediate(object));
304     }
305   }
306 
307   void CmpWeakValue(Register value, Handle<WeakCell> cell, Register scratch);
308   void GetWeakValue(Register value, Handle<WeakCell> cell);
309   void LoadWeakValue(Register value, Handle<WeakCell> cell, Label* miss);
310 
311   // ---------------------------------------------------------------------------
312   // JavaScript invokes
313 
314   // Removes current frame and its arguments from the stack preserving
315   // the arguments and a return address pushed to the stack for the next call.
316   // |ra_state| defines whether return address is already pushed to stack or
317   // not. Both |callee_args_count| and |caller_args_count_reg| do not include
318   // receiver. |callee_args_count| is not modified, |caller_args_count_reg|
319   // is trashed. |number_of_temp_values_after_return_address| specifies
320   // the number of words pushed to the stack after the return address. This is
321   // to allow "allocation" of scratch registers that this function requires
322   // by saving their values on the stack.
323   void PrepareForTailCall(const ParameterCount& callee_args_count,
324                           Register caller_args_count_reg, Register scratch0,
325                           Register scratch1, ReturnAddressState ra_state,
326                           int number_of_temp_values_after_return_address);
327 
328   // Invoke the JavaScript function code by either calling or jumping.
329 
330   void InvokeFunctionCode(Register function, Register new_target,
331                           const ParameterCount& expected,
332                           const ParameterCount& actual, InvokeFlag flag,
333                           const CallWrapper& call_wrapper);
334 
335   // On function call, call into the debugger if necessary.
336   void CheckDebugHook(Register fun, Register new_target,
337                       const ParameterCount& expected,
338                       const ParameterCount& actual);
339 
340   // Invoke the JavaScript function in the given register. Changes the
341   // current context to the context in the function before invoking.
342   void InvokeFunction(Register function, Register new_target,
343                       const ParameterCount& actual, InvokeFlag flag,
344                       const CallWrapper& call_wrapper);
345 
346   void InvokeFunction(Register function, const ParameterCount& expected,
347                       const ParameterCount& actual, InvokeFlag flag,
348                       const CallWrapper& call_wrapper);
349 
350   void InvokeFunction(Handle<JSFunction> function,
351                       const ParameterCount& expected,
352                       const ParameterCount& actual, InvokeFlag flag,
353                       const CallWrapper& call_wrapper);
354 
355   void ShlPair(Register high, Register low, uint8_t imm8);
356   void ShlPair_cl(Register high, Register low);
357   void ShrPair(Register high, Register low, uint8_t imm8);
358   void ShrPair_cl(Register high, Register src);
359   void SarPair(Register high, Register low, uint8_t imm8);
360   void SarPair_cl(Register high, Register low);
361 
362   // Expression support
363   // Support for constant splitting.
364   bool IsUnsafeImmediate(const Immediate& x);
365   void SafeMove(Register dst, const Immediate& x);
366   void SafePush(const Immediate& x);
367 
368   // Compare object type for heap object.
369   // Incoming register is heap_object and outgoing register is map.
370   void CmpObjectType(Register heap_object, InstanceType type, Register map);
371 
372   // Compare instance type for map.
373   void CmpInstanceType(Register map, InstanceType type);
374 
375   // Compare an object's map with the specified map.
376   void CompareMap(Register obj, Handle<Map> map);
377 
378   // Check if the map of an object is equal to a specified map and branch to
379   // label if not. Skip the smi check if not required (object is known to be a
380   // heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match
381   // against maps that are ElementsKind transition maps of the specified map.
382   void CheckMap(Register obj, Handle<Map> map, Label* fail,
383                 SmiCheckType smi_check_type);
384 
385   // Check if the map of an object is equal to a specified weak map and branch
386   // to a specified target if equal. Skip the smi check if not required
387   // (object is known to be a heap object)
388   void DispatchWeakMap(Register obj, Register scratch1, Register scratch2,
389                        Handle<WeakCell> cell, Handle<Code> success,
390                        SmiCheckType smi_check_type);
391 
392   // Check if the object in register heap_object is a string. Afterwards the
393   // register map contains the object map and the register instance_type
394   // contains the instance_type. The registers map and instance_type can be the
395   // same in which case it contains the instance type afterwards. Either of the
396   // registers map and instance_type can be the same as heap_object.
397   Condition IsObjectStringType(Register heap_object, Register map,
398                                Register instance_type);
399 
400   // Check if the object in register heap_object is a name. Afterwards the
401   // register map contains the object map and the register instance_type
402   // contains the instance_type. The registers map and instance_type can be the
403   // same in which case it contains the instance type afterwards. Either of the
404   // registers map and instance_type can be the same as heap_object.
405   Condition IsObjectNameType(Register heap_object, Register map,
406                              Register instance_type);
407 
408   // FCmp is similar to integer cmp, but requires unsigned
409   // jcc instructions (je, ja, jae, jb, jbe, je, and jz).
410   void FCmp();
411   void FXamMinusZero();
412   void FXamSign();
413   void X87CheckIA();
414   void X87SetRC(int rc);
415   void X87SetFPUCW(int cw);
416 
417   void ClampUint8(Register reg);
418   void ClampTOSToUint8(Register result_reg);
419 
420   void SlowTruncateToI(Register result_reg, Register input_reg,
421       int offset = HeapNumber::kValueOffset - kHeapObjectTag);
422 
423   void TruncateHeapNumberToI(Register result_reg, Register input_reg);
424   void TruncateX87TOSToI(Register result_reg);
425 
426   void X87TOSToI(Register result_reg, MinusZeroMode minus_zero_mode,
427       Label* lost_precision, Label* is_nan, Label* minus_zero,
428       Label::Distance dst = Label::kFar);
429 
430   // Smi tagging support.
SmiTag(Register reg)431   void SmiTag(Register reg) {
432     STATIC_ASSERT(kSmiTag == 0);
433     STATIC_ASSERT(kSmiTagSize == 1);
434     add(reg, reg);
435   }
SmiUntag(Register reg)436   void SmiUntag(Register reg) {
437     sar(reg, kSmiTagSize);
438   }
439 
440   // Modifies the register even if it does not contain a Smi!
SmiUntag(Register reg,Label * is_smi)441   void SmiUntag(Register reg, Label* is_smi) {
442     STATIC_ASSERT(kSmiTagSize == 1);
443     sar(reg, kSmiTagSize);
444     STATIC_ASSERT(kSmiTag == 0);
445     j(not_carry, is_smi);
446   }
447 
LoadUint32NoSSE2(Register src)448   void LoadUint32NoSSE2(Register src) {
449     LoadUint32NoSSE2(Operand(src));
450   }
451   void LoadUint32NoSSE2(const Operand& src);
452 
453   // Jump the register contains a smi.
454   inline void JumpIfSmi(Register value, Label* smi_label,
455                         Label::Distance distance = Label::kFar) {
456     test(value, Immediate(kSmiTagMask));
457     j(zero, smi_label, distance);
458   }
459   // Jump if the operand is a smi.
460   inline void JumpIfSmi(Operand value, Label* smi_label,
461                         Label::Distance distance = Label::kFar) {
462     test(value, Immediate(kSmiTagMask));
463     j(zero, smi_label, distance);
464   }
465   // Jump if register contain a non-smi.
466   inline void JumpIfNotSmi(Register value, Label* not_smi_label,
467                            Label::Distance distance = Label::kFar) {
468     test(value, Immediate(kSmiTagMask));
469     j(not_zero, not_smi_label, distance);
470   }
471   // Jump if the operand is not a smi.
472   inline void JumpIfNotSmi(Operand value, Label* smi_label,
473                            Label::Distance distance = Label::kFar) {
474     test(value, Immediate(kSmiTagMask));
475     j(not_zero, smi_label, distance);
476   }
477   // Jump if the value cannot be represented by a smi.
478   inline void JumpIfNotValidSmiValue(Register value, Register scratch,
479                                      Label* on_invalid,
480                                      Label::Distance distance = Label::kFar) {
481     mov(scratch, value);
482     add(scratch, Immediate(0x40000000U));
483     j(sign, on_invalid, distance);
484   }
485 
486   // Jump if the unsigned integer value cannot be represented by a smi.
487   inline void JumpIfUIntNotValidSmiValue(
488       Register value, Label* on_invalid,
489       Label::Distance distance = Label::kFar) {
490     cmp(value, Immediate(0x40000000U));
491     j(above_equal, on_invalid, distance);
492   }
493 
494   void LoadInstanceDescriptors(Register map, Register descriptors);
495   void EnumLength(Register dst, Register map);
496   void NumberOfOwnDescriptors(Register dst, Register map);
497   void LoadAccessor(Register dst, Register holder, int accessor_index,
498                     AccessorComponent accessor);
499 
500   template<typename Field>
DecodeField(Register reg)501   void DecodeField(Register reg) {
502     static const int shift = Field::kShift;
503     static const int mask = Field::kMask >> Field::kShift;
504     if (shift != 0) {
505       sar(reg, shift);
506     }
507     and_(reg, Immediate(mask));
508   }
509 
510   template<typename Field>
DecodeFieldToSmi(Register reg)511   void DecodeFieldToSmi(Register reg) {
512     static const int shift = Field::kShift;
513     static const int mask = (Field::kMask >> Field::kShift) << kSmiTagSize;
514     STATIC_ASSERT((mask & (0x80000000u >> (kSmiTagSize - 1))) == 0);
515     STATIC_ASSERT(kSmiTag == 0);
516     if (shift < kSmiTagSize) {
517       shl(reg, kSmiTagSize - shift);
518     } else if (shift > kSmiTagSize) {
519       sar(reg, shift - kSmiTagSize);
520     }
521     and_(reg, Immediate(mask));
522   }
523 
524   // Abort execution if argument is not a number, enabled via --debug-code.
525   void AssertNumber(Register object);
526   void AssertNotNumber(Register object);
527 
528   // Abort execution if argument is not a smi, enabled via --debug-code.
529   void AssertSmi(Register object);
530 
531   // Abort execution if argument is a smi, enabled via --debug-code.
532   void AssertNotSmi(Register object);
533 
534   // Abort execution if argument is not a string, enabled via --debug-code.
535   void AssertString(Register object);
536 
537   // Abort execution if argument is not a name, enabled via --debug-code.
538   void AssertName(Register object);
539 
540   // Abort execution if argument is not a JSFunction, enabled via --debug-code.
541   void AssertFunction(Register object);
542 
543   // Abort execution if argument is not a JSBoundFunction,
544   // enabled via --debug-code.
545   void AssertBoundFunction(Register object);
546 
547   // Abort execution if argument is not a JSGeneratorObject,
548   // enabled via --debug-code.
549   void AssertGeneratorObject(Register object);
550 
551   // Abort execution if argument is not a JSReceiver, enabled via --debug-code.
552   void AssertReceiver(Register object);
553 
554   // Abort execution if argument is not undefined or an AllocationSite, enabled
555   // via --debug-code.
556   void AssertUndefinedOrAllocationSite(Register object);
557 
558   // ---------------------------------------------------------------------------
559   // Exception handling
560 
561   // Push a new stack handler and link it into stack handler chain.
562   void PushStackHandler();
563 
564   // Unlink the stack handler on top of the stack from the stack handler chain.
565   void PopStackHandler();
566 
567   // ---------------------------------------------------------------------------
568   // Inline caching support
569 
570   void GetNumberHash(Register r0, Register scratch);
571 
572   // ---------------------------------------------------------------------------
573   // Allocation support
574 
575   // Allocate an object in new space or old space. If the given space
576   // is exhausted control continues at the gc_required label. The allocated
577   // object is returned in result and end of the new object is returned in
578   // result_end. The register scratch can be passed as no_reg in which case
579   // an additional object reference will be added to the reloc info. The
580   // returned pointers in result and result_end have not yet been tagged as
581   // heap objects. If result_contains_top_on_entry is true the content of
582   // result is known to be the allocation top on entry (could be result_end
583   // from a previous call). If result_contains_top_on_entry is true scratch
584   // should be no_reg as it is never used.
585   void Allocate(int object_size, Register result, Register result_end,
586                 Register scratch, Label* gc_required, AllocationFlags flags);
587 
588   void Allocate(int header_size, ScaleFactor element_size,
589                 Register element_count, RegisterValueType element_count_type,
590                 Register result, Register result_end, Register scratch,
591                 Label* gc_required, AllocationFlags flags);
592 
593   void Allocate(Register object_size, Register result, Register result_end,
594                 Register scratch, Label* gc_required, AllocationFlags flags);
595 
596   // FastAllocate is right now only used for folded allocations. It just
597   // increments the top pointer without checking against limit. This can only
598   // be done if it was proved earlier that the allocation will succeed.
599   void FastAllocate(int object_size, Register result, Register result_end,
600                     AllocationFlags flags);
601   void FastAllocate(Register object_size, Register result, Register result_end,
602                     AllocationFlags flags);
603 
604   // Allocate a heap number in new space with undefined value. The
605   // register scratch2 can be passed as no_reg; the others must be
606   // valid registers. Returns tagged pointer in result register, or
607   // jumps to gc_required if new space is full.
608   void AllocateHeapNumber(Register result, Register scratch1, Register scratch2,
609                           Label* gc_required, MutableMode mode = IMMUTABLE);
610 
611   // Allocate and initialize a JSValue wrapper with the specified {constructor}
612   // and {value}.
613   void AllocateJSValue(Register result, Register constructor, Register value,
614                        Register scratch, Label* gc_required);
615 
616   // Initialize fields with filler values.  Fields starting at |current_address|
617   // not including |end_address| are overwritten with the value in |filler|.  At
618   // the end the loop, |current_address| takes the value of |end_address|.
619   void InitializeFieldsWithFiller(Register current_address,
620                                   Register end_address, Register filler);
621 
622   // ---------------------------------------------------------------------------
623   // Support functions.
624 
625   // Check a boolean-bit of a Smi field.
626   void BooleanBitTest(Register object, int field_offset, int bit_index);
627 
628   // Check if result is zero and op is negative.
629   void NegativeZeroTest(Register result, Register op, Label* then_label);
630 
631   // Check if result is zero and any of op1 and op2 are negative.
632   // Register scratch is destroyed, and it must be different from op2.
633   void NegativeZeroTest(Register result, Register op1, Register op2,
634                         Register scratch, Label* then_label);
635 
636   // Machine code version of Map::GetConstructor().
637   // |temp| holds |result|'s map when done.
638   void GetMapConstructor(Register result, Register map, Register temp);
639 
640   // ---------------------------------------------------------------------------
641   // Runtime calls
642 
643   // Call a code stub.  Generate the code if necessary.
644   void CallStub(CodeStub* stub, TypeFeedbackId ast_id = TypeFeedbackId::None());
645 
646   // Tail call a code stub (jump).  Generate the code if necessary.
647   void TailCallStub(CodeStub* stub);
648 
649   // Return from a code stub after popping its arguments.
650   void StubReturn(int argc);
651 
652   // Call a runtime routine.
653   void CallRuntime(const Runtime::Function* f, int num_arguments,
654                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
CallRuntimeSaveDoubles(Runtime::FunctionId fid)655   void CallRuntimeSaveDoubles(Runtime::FunctionId fid) {
656     const Runtime::Function* function = Runtime::FunctionForId(fid);
657     CallRuntime(function, function->nargs, kSaveFPRegs);
658   }
659 
660   // Convenience function: Same as above, but takes the fid instead.
661   void CallRuntime(Runtime::FunctionId fid,
662                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
663     const Runtime::Function* function = Runtime::FunctionForId(fid);
664     CallRuntime(function, function->nargs, save_doubles);
665   }
666 
667   // Convenience function: Same as above, but takes the fid instead.
668   void CallRuntime(Runtime::FunctionId fid, int num_arguments,
669                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
670     CallRuntime(Runtime::FunctionForId(fid), num_arguments, save_doubles);
671   }
672 
673   // Convenience function: call an external reference.
674   void CallExternalReference(ExternalReference ref, int num_arguments);
675 
676   // Convenience function: tail call a runtime routine (jump).
677   void TailCallRuntime(Runtime::FunctionId fid);
678 
679   // Before calling a C-function from generated code, align arguments on stack.
680   // After aligning the frame, arguments must be stored in esp[0], esp[4],
681   // etc., not pushed. The argument count assumes all arguments are word sized.
682   // Some compilers/platforms require the stack to be aligned when calling
683   // C++ code.
684   // Needs a scratch register to do some arithmetic. This register will be
685   // trashed.
686   void PrepareCallCFunction(int num_arguments, Register scratch);
687 
688   // Calls a C function and cleans up the space for arguments allocated
689   // by PrepareCallCFunction. The called function is not allowed to trigger a
690   // garbage collection, since that might move the code and invalidate the
691   // return address (unless this is somehow accounted for by the called
692   // function).
693   void CallCFunction(ExternalReference function, int num_arguments);
694   void CallCFunction(Register function, int num_arguments);
695 
696   // Jump to a runtime routine.
697   void JumpToExternalReference(const ExternalReference& ext,
698                                bool builtin_exit_frame = false);
699 
700   // ---------------------------------------------------------------------------
701   // Utilities
702 
703   void Ret();
704 
705   // Return and drop arguments from stack, where the number of arguments
706   // may be bigger than 2^16 - 1.  Requires a scratch register.
707   void Ret(int bytes_dropped, Register scratch);
708 
709   // Emit code that loads |parameter_index|'th parameter from the stack to
710   // the register according to the CallInterfaceDescriptor definition.
711   // |sp_to_caller_sp_offset_in_words| specifies the number of words pushed
712   // below the caller's sp (on x87 it's at least return address).
713   template <class Descriptor>
714   void LoadParameterFromStack(
715       Register reg, typename Descriptor::ParameterIndices parameter_index,
716       int sp_to_ra_offset_in_words = 1) {
717     DCHECK(Descriptor::kPassLastArgsOnStack);
718     DCHECK_LT(parameter_index, Descriptor::kParameterCount);
719     DCHECK_LE(Descriptor::kParameterCount - Descriptor::kStackArgumentsCount,
720               parameter_index);
721     int offset = (Descriptor::kParameterCount - parameter_index - 1 +
722                   sp_to_ra_offset_in_words) *
723                  kPointerSize;
724     mov(reg, Operand(esp, offset));
725   }
726 
727   // Emit code to discard a non-negative number of pointer-sized elements
728   // from the stack, clobbering only the esp register.
729   void Drop(int element_count);
730 
Call(Label * target)731   void Call(Label* target) { call(target); }
732   void Call(Handle<Code> target, RelocInfo::Mode rmode,
733             TypeFeedbackId id = TypeFeedbackId::None()) {
734     call(target, rmode, id);
735   }
Jump(Handle<Code> target,RelocInfo::Mode rmode)736   void Jump(Handle<Code> target, RelocInfo::Mode rmode) { jmp(target, rmode); }
Push(Register src)737   void Push(Register src) { push(src); }
Push(const Operand & src)738   void Push(const Operand& src) { push(src); }
Push(Immediate value)739   void Push(Immediate value) { push(value); }
Pop(Register dst)740   void Pop(Register dst) { pop(dst); }
Pop(const Operand & dst)741   void Pop(const Operand& dst) { pop(dst); }
PushReturnAddressFrom(Register src)742   void PushReturnAddressFrom(Register src) { push(src); }
PopReturnAddressTo(Register dst)743   void PopReturnAddressTo(Register dst) { pop(dst); }
744 
Lzcnt(Register dst,Register src)745   void Lzcnt(Register dst, Register src) { Lzcnt(dst, Operand(src)); }
746   void Lzcnt(Register dst, const Operand& src);
747 
Tzcnt(Register dst,Register src)748   void Tzcnt(Register dst, Register src) { Tzcnt(dst, Operand(src)); }
749   void Tzcnt(Register dst, const Operand& src);
750 
Popcnt(Register dst,Register src)751   void Popcnt(Register dst, Register src) { Popcnt(dst, Operand(src)); }
752   void Popcnt(Register dst, const Operand& src);
753 
754   // Move if the registers are not identical.
755   void Move(Register target, Register source);
756 
757   // Move a constant into a destination using the most efficient encoding.
758   void Move(Register dst, const Immediate& x);
759   void Move(const Operand& dst, const Immediate& x);
760 
Move(Register dst,Handle<Object> handle)761   void Move(Register dst, Handle<Object> handle) { LoadObject(dst, handle); }
Move(Register dst,Smi * source)762   void Move(Register dst, Smi* source) { Move(dst, Immediate(source)); }
763 
764   // Push a handle value.
Push(Handle<Object> handle)765   void Push(Handle<Object> handle) { push(Immediate(handle)); }
Push(Smi * smi)766   void Push(Smi* smi) { Push(Immediate(smi)); }
767 
CodeObject()768   Handle<Object> CodeObject() {
769     DCHECK(!code_object_.is_null());
770     return code_object_;
771   }
772 
773   // Insert code to verify that the x87 stack has the specified depth (0-7)
774   void VerifyX87StackDepth(uint32_t depth);
775 
776   // Emit code for a truncating division by a constant. The dividend register is
777   // unchanged, the result is in edx, and eax gets clobbered.
778   void TruncatingDiv(Register dividend, int32_t divisor);
779 
780   // ---------------------------------------------------------------------------
781   // StatsCounter support
782 
783   void SetCounter(StatsCounter* counter, int value);
784   void IncrementCounter(StatsCounter* counter, int value);
785   void DecrementCounter(StatsCounter* counter, int value);
786   void IncrementCounter(Condition cc, StatsCounter* counter, int value);
787   void DecrementCounter(Condition cc, StatsCounter* counter, int value);
788 
789   // ---------------------------------------------------------------------------
790   // Debugging
791 
792   // Calls Abort(msg) if the condition cc is not satisfied.
793   // Use --debug_code to enable.
794   void Assert(Condition cc, BailoutReason reason);
795 
796   void AssertFastElements(Register elements);
797 
798   // Like Assert(), but always enabled.
799   void Check(Condition cc, BailoutReason reason);
800 
801   // Print a message to stdout and abort execution.
802   void Abort(BailoutReason reason);
803 
804   // Check that the stack is aligned.
805   void CheckStackAlignment();
806 
807   // Verify restrictions about code generated in stubs.
set_generating_stub(bool value)808   void set_generating_stub(bool value) { generating_stub_ = value; }
generating_stub()809   bool generating_stub() { return generating_stub_; }
set_has_frame(bool value)810   void set_has_frame(bool value) { has_frame_ = value; }
has_frame()811   bool has_frame() { return has_frame_; }
812   inline bool AllowThisStubCall(CodeStub* stub);
813 
814   // ---------------------------------------------------------------------------
815   // String utilities.
816 
817   // Checks if both objects are sequential one-byte strings, and jumps to label
818   // if either is not.
819   void JumpIfNotBothSequentialOneByteStrings(
820       Register object1, Register object2, Register scratch1, Register scratch2,
821       Label* on_not_flat_one_byte_strings);
822 
823   // Checks if the given register or operand is a unique name
824   void JumpIfNotUniqueNameInstanceType(Register reg, Label* not_unique_name,
825                                        Label::Distance distance = Label::kFar) {
826     JumpIfNotUniqueNameInstanceType(Operand(reg), not_unique_name, distance);
827   }
828 
829   void JumpIfNotUniqueNameInstanceType(Operand operand, Label* not_unique_name,
830                                        Label::Distance distance = Label::kFar);
831 
832   void EmitSeqStringSetCharCheck(Register string, Register index,
833                                  Register value, uint32_t encoding_mask);
834 
SafepointRegisterStackIndex(Register reg)835   static int SafepointRegisterStackIndex(Register reg) {
836     return SafepointRegisterStackIndex(reg.code());
837   }
838 
839   // Load the type feedback vector from a JavaScript frame.
840   void EmitLoadFeedbackVector(Register vector);
841 
842   // Activation support.
843   void EnterFrame(StackFrame::Type type);
844   void EnterFrame(StackFrame::Type type, bool load_constant_pool_pointer_reg);
845   void LeaveFrame(StackFrame::Type type);
846 
847   void EnterBuiltinFrame(Register context, Register target, Register argc);
848   void LeaveBuiltinFrame(Register context, Register target, Register argc);
849 
850   // Expects object in eax and returns map with validated enum cache
851   // in eax.  Assumes that any other register can be used as a scratch.
852   void CheckEnumCache(Label* call_runtime);
853 
854   // AllocationMemento support. Arrays may have an associated
855   // AllocationMemento object that can be checked for in order to pretransition
856   // to another type.
857   // On entry, receiver_reg should point to the array object.
858   // scratch_reg gets clobbered.
859   // If allocation info is present, conditional code is set to equal.
860   void TestJSArrayForAllocationMemento(Register receiver_reg,
861                                        Register scratch_reg,
862                                        Label* no_memento_found);
863 
864  private:
865   bool generating_stub_;
866   bool has_frame_;
867   // This handle will be patched with the code object on installation.
868   Handle<Object> code_object_;
869 
870   // Helper functions for generating invokes.
871   void InvokePrologue(const ParameterCount& expected,
872                       const ParameterCount& actual, Label* done,
873                       bool* definitely_mismatches, InvokeFlag flag,
874                       Label::Distance done_distance,
875                       const CallWrapper& call_wrapper);
876 
877   void EnterExitFramePrologue(StackFrame::Type frame_type);
878   void EnterExitFrameEpilogue(int argc, bool save_doubles);
879 
880   void LeaveExitFrameEpilogue(bool restore_context);
881 
882   // Allocation support helpers.
883   void LoadAllocationTopHelper(Register result, Register scratch,
884                                AllocationFlags flags);
885 
886   void UpdateAllocationTopHelper(Register result_end, Register scratch,
887                                  AllocationFlags flags);
888 
889   // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
890   void InNewSpace(Register object, Register scratch, Condition cc,
891                   Label* condition_met,
892                   Label::Distance condition_met_distance = Label::kFar);
893 
894   // Helper for finding the mark bits for an address.  Afterwards, the
895   // bitmap register points at the word with the mark bits and the mask
896   // the position of the first bit.  Uses ecx as scratch and leaves addr_reg
897   // unchanged.
898   inline void GetMarkBits(Register addr_reg, Register bitmap_reg,
899                           Register mask_reg);
900 
901   // Compute memory operands for safepoint stack slots.
902   Operand SafepointRegisterSlot(Register reg);
903   static int SafepointRegisterStackIndex(int reg_code);
904 
905   // Needs access to SafepointRegisterStackIndex for compiled frame
906   // traversal.
907   friend class StandardFrame;
908 };
909 
910 // The code patcher is used to patch (typically) small parts of code e.g. for
911 // debugging and other types of instrumentation. When using the code patcher
912 // the exact number of bytes specified must be emitted. Is not legal to emit
913 // relocation information. If any of these constraints are violated it causes
914 // an assertion.
915 class CodePatcher {
916  public:
917   CodePatcher(Isolate* isolate, byte* address, int size);
918   ~CodePatcher();
919 
920   // Macro assembler to emit code.
masm()921   MacroAssembler* masm() { return &masm_; }
922 
923  private:
924   byte* address_;        // The address of the code being patched.
925   int size_;             // Number of bytes of the expected patch size.
926   MacroAssembler masm_;  // Macro assembler used to generate the code.
927 };
928 
929 // -----------------------------------------------------------------------------
930 // Static helper functions.
931 
932 // Generate an Operand for loading a field from an object.
FieldOperand(Register object,int offset)933 inline Operand FieldOperand(Register object, int offset) {
934   return Operand(object, offset - kHeapObjectTag);
935 }
936 
937 // Generate an Operand for loading an indexed field from an object.
FieldOperand(Register object,Register index,ScaleFactor scale,int offset)938 inline Operand FieldOperand(Register object, Register index, ScaleFactor scale,
939                             int offset) {
940   return Operand(object, index, scale, offset - kHeapObjectTag);
941 }
942 
943 inline Operand FixedArrayElementOperand(Register array, Register index_as_smi,
944                                         int additional_offset = 0) {
945   int offset = FixedArray::kHeaderSize + additional_offset * kPointerSize;
946   return FieldOperand(array, index_as_smi, times_half_pointer_size, offset);
947 }
948 
ContextOperand(Register context,int index)949 inline Operand ContextOperand(Register context, int index) {
950   return Operand(context, Context::SlotOffset(index));
951 }
952 
ContextOperand(Register context,Register index)953 inline Operand ContextOperand(Register context, Register index) {
954   return Operand(context, index, times_pointer_size, Context::SlotOffset(0));
955 }
956 
NativeContextOperand()957 inline Operand NativeContextOperand() {
958   return ContextOperand(esi, Context::NATIVE_CONTEXT_INDEX);
959 }
960 
961 #define ACCESS_MASM(masm) masm->
962 
963 }  // namespace internal
964 }  // namespace v8
965 
966 #endif  // V8_X87_MACRO_ASSEMBLER_X87_H_
967