• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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   // Conditionally load the cached Array transitioned map of type
267   // transitioned_kind from the native context if the map in register
268   // map_in_out is the cached Array map in the native context of
269   // expected_kind.
270   void LoadTransitionedArrayMapConditional(ElementsKind expected_kind,
271                                            ElementsKind transitioned_kind,
272                                            Register map_in_out,
273                                            Register scratch,
274                                            Label* no_map_match);
275 
276   // Load the global function with the given index.
277   void LoadGlobalFunction(int index, Register function);
278 
279   // Load the initial map from the global function. The registers
280   // function and map can be the same.
281   void LoadGlobalFunctionInitialMap(Register function, Register map);
282 
283   // Push and pop the registers that can hold pointers.
PushSafepointRegisters()284   void PushSafepointRegisters() { pushad(); }
PopSafepointRegisters()285   void PopSafepointRegisters() { popad(); }
286   // Store the value in register/immediate src in the safepoint
287   // register stack slot for register dst.
288   void StoreToSafepointRegisterSlot(Register dst, Register src);
289   void StoreToSafepointRegisterSlot(Register dst, Immediate src);
290   void LoadFromSafepointRegisterSlot(Register dst, Register src);
291 
292   // Nop, because x87 does not have a root register.
InitializeRootRegister()293   void InitializeRootRegister() {}
294 
295   void LoadHeapObject(Register result, Handle<HeapObject> object);
296   void CmpHeapObject(Register reg, Handle<HeapObject> object);
297   void PushHeapObject(Handle<HeapObject> object);
298 
LoadObject(Register result,Handle<Object> object)299   void LoadObject(Register result, Handle<Object> object) {
300     AllowDeferredHandleDereference heap_object_check;
301     if (object->IsHeapObject()) {
302       LoadHeapObject(result, Handle<HeapObject>::cast(object));
303     } else {
304       Move(result, Immediate(object));
305     }
306   }
307 
CmpObject(Register reg,Handle<Object> object)308   void CmpObject(Register reg, Handle<Object> object) {
309     AllowDeferredHandleDereference heap_object_check;
310     if (object->IsHeapObject()) {
311       CmpHeapObject(reg, Handle<HeapObject>::cast(object));
312     } else {
313       cmp(reg, Immediate(object));
314     }
315   }
316 
317   void CmpWeakValue(Register value, Handle<WeakCell> cell, Register scratch);
318   void GetWeakValue(Register value, Handle<WeakCell> cell);
319   void LoadWeakValue(Register value, Handle<WeakCell> cell, Label* miss);
320 
321   // ---------------------------------------------------------------------------
322   // JavaScript invokes
323 
324   // Removes current frame and its arguments from the stack preserving
325   // the arguments and a return address pushed to the stack for the next call.
326   // |ra_state| defines whether return address is already pushed to stack or
327   // not. Both |callee_args_count| and |caller_args_count_reg| do not include
328   // receiver. |callee_args_count| is not modified, |caller_args_count_reg|
329   // is trashed. |number_of_temp_values_after_return_address| specifies
330   // the number of words pushed to the stack after the return address. This is
331   // to allow "allocation" of scratch registers that this function requires
332   // by saving their values on the stack.
333   void PrepareForTailCall(const ParameterCount& callee_args_count,
334                           Register caller_args_count_reg, Register scratch0,
335                           Register scratch1, ReturnAddressState ra_state,
336                           int number_of_temp_values_after_return_address);
337 
338   // Invoke the JavaScript function code by either calling or jumping.
339 
340   void InvokeFunctionCode(Register function, Register new_target,
341                           const ParameterCount& expected,
342                           const ParameterCount& actual, InvokeFlag flag,
343                           const CallWrapper& call_wrapper);
344 
345   void FloodFunctionIfStepping(Register fun, Register new_target,
346                                const ParameterCount& expected,
347                                const ParameterCount& actual);
348 
349   // Invoke the JavaScript function in the given register. Changes the
350   // current context to the context in the function before invoking.
351   void InvokeFunction(Register function, Register new_target,
352                       const ParameterCount& actual, InvokeFlag flag,
353                       const CallWrapper& call_wrapper);
354 
355   void InvokeFunction(Register function, const ParameterCount& expected,
356                       const ParameterCount& actual, InvokeFlag flag,
357                       const CallWrapper& call_wrapper);
358 
359   void InvokeFunction(Handle<JSFunction> function,
360                       const ParameterCount& expected,
361                       const ParameterCount& actual, InvokeFlag flag,
362                       const CallWrapper& call_wrapper);
363 
364   void ShlPair(Register high, Register low, uint8_t imm8);
365   void ShlPair_cl(Register high, Register low);
366   void ShrPair(Register high, Register low, uint8_t imm8);
367   void ShrPair_cl(Register high, Register src);
368   void SarPair(Register high, Register low, uint8_t imm8);
369   void SarPair_cl(Register high, Register low);
370 
371   // Expression support
372   // Support for constant splitting.
373   bool IsUnsafeImmediate(const Immediate& x);
374   void SafeMove(Register dst, const Immediate& x);
375   void SafePush(const Immediate& x);
376 
377   // Compare object type for heap object.
378   // Incoming register is heap_object and outgoing register is map.
379   void CmpObjectType(Register heap_object, InstanceType type, Register map);
380 
381   // Compare instance type for map.
382   void CmpInstanceType(Register map, InstanceType type);
383 
384   // Check if a map for a JSObject indicates that the object can have both smi
385   // and HeapObject elements.  Jump to the specified label if it does not.
386   void CheckFastObjectElements(Register map, Label* fail,
387                                Label::Distance distance = Label::kFar);
388 
389   // Check if a map for a JSObject indicates that the object has fast smi only
390   // elements.  Jump to the specified label if it does not.
391   void CheckFastSmiElements(Register map, Label* fail,
392                             Label::Distance distance = Label::kFar);
393 
394   // Check to see if maybe_number can be stored as a double in
395   // FastDoubleElements. If it can, store it at the index specified by key in
396   // the FastDoubleElements array elements, otherwise jump to fail.
397   void StoreNumberToDoubleElements(Register maybe_number, Register elements,
398                                    Register key, Register scratch, Label* fail,
399                                    int offset = 0);
400 
401   // Compare an object's map with the specified map.
402   void CompareMap(Register obj, Handle<Map> map);
403 
404   // Check if the map of an object is equal to a specified map and branch to
405   // label if not. Skip the smi check if not required (object is known to be a
406   // heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match
407   // against maps that are ElementsKind transition maps of the specified map.
408   void CheckMap(Register obj, Handle<Map> map, Label* fail,
409                 SmiCheckType smi_check_type);
410 
411   // Check if the map of an object is equal to a specified weak map and branch
412   // to a specified target if equal. Skip the smi check if not required
413   // (object is known to be a heap object)
414   void DispatchWeakMap(Register obj, Register scratch1, Register scratch2,
415                        Handle<WeakCell> cell, Handle<Code> success,
416                        SmiCheckType smi_check_type);
417 
418   // Check if the object in register heap_object is a string. Afterwards the
419   // register map contains the object map and the register instance_type
420   // contains the instance_type. The registers map and instance_type can be the
421   // same in which case it contains the instance type afterwards. Either of the
422   // registers map and instance_type can be the same as heap_object.
423   Condition IsObjectStringType(Register heap_object, Register map,
424                                Register instance_type);
425 
426   // Check if the object in register heap_object is a name. Afterwards the
427   // register map contains the object map and the register instance_type
428   // contains the instance_type. The registers map and instance_type can be the
429   // same in which case it contains the instance type afterwards. Either of the
430   // registers map and instance_type can be the same as heap_object.
431   Condition IsObjectNameType(Register heap_object, Register map,
432                              Register instance_type);
433 
434   // FCmp is similar to integer cmp, but requires unsigned
435   // jcc instructions (je, ja, jae, jb, jbe, je, and jz).
436   void FCmp();
437   void FXamMinusZero();
438   void FXamSign();
439   void X87CheckIA();
440   void X87SetRC(int rc);
441   void X87SetFPUCW(int cw);
442 
443   void ClampUint8(Register reg);
444   void ClampTOSToUint8(Register result_reg);
445 
446   void SlowTruncateToI(Register result_reg, Register input_reg,
447       int offset = HeapNumber::kValueOffset - kHeapObjectTag);
448 
449   void TruncateHeapNumberToI(Register result_reg, Register input_reg);
450   void TruncateX87TOSToI(Register result_reg);
451 
452   void X87TOSToI(Register result_reg, MinusZeroMode minus_zero_mode,
453       Label* lost_precision, Label* is_nan, Label* minus_zero,
454       Label::Distance dst = Label::kFar);
455 
456   // Smi tagging support.
SmiTag(Register reg)457   void SmiTag(Register reg) {
458     STATIC_ASSERT(kSmiTag == 0);
459     STATIC_ASSERT(kSmiTagSize == 1);
460     add(reg, reg);
461   }
SmiUntag(Register reg)462   void SmiUntag(Register reg) {
463     sar(reg, kSmiTagSize);
464   }
465 
466   // Modifies the register even if it does not contain a Smi!
SmiUntag(Register reg,Label * is_smi)467   void SmiUntag(Register reg, Label* is_smi) {
468     STATIC_ASSERT(kSmiTagSize == 1);
469     sar(reg, kSmiTagSize);
470     STATIC_ASSERT(kSmiTag == 0);
471     j(not_carry, is_smi);
472   }
473 
LoadUint32NoSSE2(Register src)474   void LoadUint32NoSSE2(Register src) {
475     LoadUint32NoSSE2(Operand(src));
476   }
477   void LoadUint32NoSSE2(const Operand& src);
478 
479   // Jump the register contains a smi.
480   inline void JumpIfSmi(Register value, Label* smi_label,
481                         Label::Distance distance = Label::kFar) {
482     test(value, Immediate(kSmiTagMask));
483     j(zero, smi_label, distance);
484   }
485   // Jump if the operand is a smi.
486   inline void JumpIfSmi(Operand value, Label* smi_label,
487                         Label::Distance distance = Label::kFar) {
488     test(value, Immediate(kSmiTagMask));
489     j(zero, smi_label, distance);
490   }
491   // Jump if register contain a non-smi.
492   inline void JumpIfNotSmi(Register value, Label* not_smi_label,
493                            Label::Distance distance = Label::kFar) {
494     test(value, Immediate(kSmiTagMask));
495     j(not_zero, not_smi_label, distance);
496   }
497 
498   // Jump if the value cannot be represented by a smi.
499   inline void JumpIfNotValidSmiValue(Register value, Register scratch,
500                                      Label* on_invalid,
501                                      Label::Distance distance = Label::kFar) {
502     mov(scratch, value);
503     add(scratch, Immediate(0x40000000U));
504     j(sign, on_invalid, distance);
505   }
506 
507   // Jump if the unsigned integer value cannot be represented by a smi.
508   inline void JumpIfUIntNotValidSmiValue(
509       Register value, Label* on_invalid,
510       Label::Distance distance = Label::kFar) {
511     cmp(value, Immediate(0x40000000U));
512     j(above_equal, on_invalid, distance);
513   }
514 
515   void LoadInstanceDescriptors(Register map, Register descriptors);
516   void EnumLength(Register dst, Register map);
517   void NumberOfOwnDescriptors(Register dst, Register map);
518   void LoadAccessor(Register dst, Register holder, int accessor_index,
519                     AccessorComponent accessor);
520 
521   template<typename Field>
DecodeField(Register reg)522   void DecodeField(Register reg) {
523     static const int shift = Field::kShift;
524     static const int mask = Field::kMask >> Field::kShift;
525     if (shift != 0) {
526       sar(reg, shift);
527     }
528     and_(reg, Immediate(mask));
529   }
530 
531   template<typename Field>
DecodeFieldToSmi(Register reg)532   void DecodeFieldToSmi(Register reg) {
533     static const int shift = Field::kShift;
534     static const int mask = (Field::kMask >> Field::kShift) << kSmiTagSize;
535     STATIC_ASSERT((mask & (0x80000000u >> (kSmiTagSize - 1))) == 0);
536     STATIC_ASSERT(kSmiTag == 0);
537     if (shift < kSmiTagSize) {
538       shl(reg, kSmiTagSize - shift);
539     } else if (shift > kSmiTagSize) {
540       sar(reg, shift - kSmiTagSize);
541     }
542     and_(reg, Immediate(mask));
543   }
544 
545   // Abort execution if argument is not a number, enabled via --debug-code.
546   void AssertNumber(Register object);
547   void AssertNotNumber(Register object);
548 
549   // Abort execution if argument is not a smi, enabled via --debug-code.
550   void AssertSmi(Register object);
551 
552   // Abort execution if argument is a smi, enabled via --debug-code.
553   void AssertNotSmi(Register object);
554 
555   // Abort execution if argument is not a string, enabled via --debug-code.
556   void AssertString(Register object);
557 
558   // Abort execution if argument is not a name, enabled via --debug-code.
559   void AssertName(Register object);
560 
561   // Abort execution if argument is not a JSFunction, enabled via --debug-code.
562   void AssertFunction(Register object);
563 
564   // Abort execution if argument is not a JSBoundFunction,
565   // enabled via --debug-code.
566   void AssertBoundFunction(Register object);
567 
568   // Abort execution if argument is not a JSGeneratorObject,
569   // enabled via --debug-code.
570   void AssertGeneratorObject(Register object);
571 
572   // Abort execution if argument is not a JSReceiver, enabled via --debug-code.
573   void AssertReceiver(Register object);
574 
575   // Abort execution if argument is not undefined or an AllocationSite, enabled
576   // via --debug-code.
577   void AssertUndefinedOrAllocationSite(Register object);
578 
579   // ---------------------------------------------------------------------------
580   // Exception handling
581 
582   // Push a new stack handler and link it into stack handler chain.
583   void PushStackHandler();
584 
585   // Unlink the stack handler on top of the stack from the stack handler chain.
586   void PopStackHandler();
587 
588   // ---------------------------------------------------------------------------
589   // Inline caching support
590 
591   void GetNumberHash(Register r0, Register scratch);
592 
593   // ---------------------------------------------------------------------------
594   // Allocation support
595 
596   // Allocate an object in new space or old space. If the given space
597   // is exhausted control continues at the gc_required label. The allocated
598   // object is returned in result and end of the new object is returned in
599   // result_end. The register scratch can be passed as no_reg in which case
600   // an additional object reference will be added to the reloc info. The
601   // returned pointers in result and result_end have not yet been tagged as
602   // heap objects. If result_contains_top_on_entry is true the content of
603   // result is known to be the allocation top on entry (could be result_end
604   // from a previous call). If result_contains_top_on_entry is true scratch
605   // should be no_reg as it is never used.
606   void Allocate(int object_size, Register result, Register result_end,
607                 Register scratch, Label* gc_required, AllocationFlags flags);
608 
609   void Allocate(int header_size, ScaleFactor element_size,
610                 Register element_count, RegisterValueType element_count_type,
611                 Register result, Register result_end, Register scratch,
612                 Label* gc_required, AllocationFlags flags);
613 
614   void Allocate(Register object_size, Register result, Register result_end,
615                 Register scratch, Label* gc_required, AllocationFlags flags);
616 
617   // FastAllocate is right now only used for folded allocations. It just
618   // increments the top pointer without checking against limit. This can only
619   // be done if it was proved earlier that the allocation will succeed.
620   void FastAllocate(int object_size, Register result, Register result_end,
621                     AllocationFlags flags);
622   void FastAllocate(Register object_size, Register result, Register result_end,
623                     AllocationFlags flags);
624 
625   // Allocate a heap number in new space with undefined value. The
626   // register scratch2 can be passed as no_reg; the others must be
627   // valid registers. Returns tagged pointer in result register, or
628   // jumps to gc_required if new space is full.
629   void AllocateHeapNumber(Register result, Register scratch1, Register scratch2,
630                           Label* gc_required, MutableMode mode = IMMUTABLE);
631 
632   // Allocate a sequential string. All the header fields of the string object
633   // are initialized.
634   void AllocateTwoByteString(Register result, Register length,
635                              Register scratch1, Register scratch2,
636                              Register scratch3, Label* gc_required);
637   void AllocateOneByteString(Register result, Register length,
638                              Register scratch1, Register scratch2,
639                              Register scratch3, Label* gc_required);
640   void AllocateOneByteString(Register result, int length, Register scratch1,
641                              Register scratch2, Label* gc_required);
642 
643   // Allocate a raw cons string object. Only the map field of the result is
644   // initialized.
645   void AllocateTwoByteConsString(Register result, Register scratch1,
646                                  Register scratch2, Label* gc_required);
647   void AllocateOneByteConsString(Register result, Register scratch1,
648                                  Register scratch2, Label* gc_required);
649 
650   // Allocate a raw sliced string object. Only the map field of the result is
651   // initialized.
652   void AllocateTwoByteSlicedString(Register result, Register scratch1,
653                                    Register scratch2, Label* gc_required);
654   void AllocateOneByteSlicedString(Register result, Register scratch1,
655                                    Register scratch2, Label* gc_required);
656 
657   // Allocate and initialize a JSValue wrapper with the specified {constructor}
658   // and {value}.
659   void AllocateJSValue(Register result, Register constructor, Register value,
660                        Register scratch, Label* gc_required);
661 
662   // Initialize fields with filler values.  Fields starting at |current_address|
663   // not including |end_address| are overwritten with the value in |filler|.  At
664   // the end the loop, |current_address| takes the value of |end_address|.
665   void InitializeFieldsWithFiller(Register current_address,
666                                   Register end_address, Register filler);
667 
668   // ---------------------------------------------------------------------------
669   // Support functions.
670 
671   // Check a boolean-bit of a Smi field.
672   void BooleanBitTest(Register object, int field_offset, int bit_index);
673 
674   // Check if result is zero and op is negative.
675   void NegativeZeroTest(Register result, Register op, Label* then_label);
676 
677   // Check if result is zero and any of op1 and op2 are negative.
678   // Register scratch is destroyed, and it must be different from op2.
679   void NegativeZeroTest(Register result, Register op1, Register op2,
680                         Register scratch, Label* then_label);
681 
682   // Machine code version of Map::GetConstructor().
683   // |temp| holds |result|'s map when done.
684   void GetMapConstructor(Register result, Register map, Register temp);
685 
686   // Try to get function prototype of a function and puts the value in
687   // the result register. Checks that the function really is a
688   // function and jumps to the miss label if the fast checks fail. The
689   // function register will be untouched; the other registers may be
690   // clobbered.
691   void TryGetFunctionPrototype(Register function, Register result,
692                                Register scratch, Label* miss);
693 
694   // ---------------------------------------------------------------------------
695   // Runtime calls
696 
697   // Call a code stub.  Generate the code if necessary.
698   void CallStub(CodeStub* stub, TypeFeedbackId ast_id = TypeFeedbackId::None());
699 
700   // Tail call a code stub (jump).  Generate the code if necessary.
701   void TailCallStub(CodeStub* stub);
702 
703   // Return from a code stub after popping its arguments.
704   void StubReturn(int argc);
705 
706   // Call a runtime routine.
707   void CallRuntime(const Runtime::Function* f, int num_arguments,
708                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
CallRuntimeSaveDoubles(Runtime::FunctionId fid)709   void CallRuntimeSaveDoubles(Runtime::FunctionId fid) {
710     const Runtime::Function* function = Runtime::FunctionForId(fid);
711     CallRuntime(function, function->nargs, kSaveFPRegs);
712   }
713 
714   // Convenience function: Same as above, but takes the fid instead.
715   void CallRuntime(Runtime::FunctionId fid,
716                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
717     const Runtime::Function* function = Runtime::FunctionForId(fid);
718     CallRuntime(function, function->nargs, save_doubles);
719   }
720 
721   // Convenience function: Same as above, but takes the fid instead.
722   void CallRuntime(Runtime::FunctionId fid, int num_arguments,
723                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
724     CallRuntime(Runtime::FunctionForId(fid), num_arguments, save_doubles);
725   }
726 
727   // Convenience function: call an external reference.
728   void CallExternalReference(ExternalReference ref, int num_arguments);
729 
730   // Convenience function: tail call a runtime routine (jump).
731   void TailCallRuntime(Runtime::FunctionId fid);
732 
733   // Before calling a C-function from generated code, align arguments on stack.
734   // After aligning the frame, arguments must be stored in esp[0], esp[4],
735   // etc., not pushed. The argument count assumes all arguments are word sized.
736   // Some compilers/platforms require the stack to be aligned when calling
737   // C++ code.
738   // Needs a scratch register to do some arithmetic. This register will be
739   // trashed.
740   void PrepareCallCFunction(int num_arguments, Register scratch);
741 
742   // Calls a C function and cleans up the space for arguments allocated
743   // by PrepareCallCFunction. The called function is not allowed to trigger a
744   // garbage collection, since that might move the code and invalidate the
745   // return address (unless this is somehow accounted for by the called
746   // function).
747   void CallCFunction(ExternalReference function, int num_arguments);
748   void CallCFunction(Register function, int num_arguments);
749 
750   // Jump to a runtime routine.
751   void JumpToExternalReference(const ExternalReference& ext,
752                                bool builtin_exit_frame = false);
753 
754   // ---------------------------------------------------------------------------
755   // Utilities
756 
757   void Ret();
758 
759   // Return and drop arguments from stack, where the number of arguments
760   // may be bigger than 2^16 - 1.  Requires a scratch register.
761   void Ret(int bytes_dropped, Register scratch);
762 
763   // Emit code that loads |parameter_index|'th parameter from the stack to
764   // the register according to the CallInterfaceDescriptor definition.
765   // |sp_to_caller_sp_offset_in_words| specifies the number of words pushed
766   // below the caller's sp (on x87 it's at least return address).
767   template <class Descriptor>
768   void LoadParameterFromStack(
769       Register reg, typename Descriptor::ParameterIndices parameter_index,
770       int sp_to_ra_offset_in_words = 1) {
771     DCHECK(Descriptor::kPassLastArgsOnStack);
772     DCHECK_LT(parameter_index, Descriptor::kParameterCount);
773     DCHECK_LE(Descriptor::kParameterCount - Descriptor::kStackArgumentsCount,
774               parameter_index);
775     int offset = (Descriptor::kParameterCount - parameter_index - 1 +
776                   sp_to_ra_offset_in_words) *
777                  kPointerSize;
778     mov(reg, Operand(esp, offset));
779   }
780 
781   // Emit code to discard a non-negative number of pointer-sized elements
782   // from the stack, clobbering only the esp register.
783   void Drop(int element_count);
784 
Call(Label * target)785   void Call(Label* target) { call(target); }
786   void Call(Handle<Code> target, RelocInfo::Mode rmode,
787             TypeFeedbackId id = TypeFeedbackId::None()) {
788     call(target, rmode, id);
789   }
Jump(Handle<Code> target,RelocInfo::Mode rmode)790   void Jump(Handle<Code> target, RelocInfo::Mode rmode) { jmp(target, rmode); }
Push(Register src)791   void Push(Register src) { push(src); }
Push(const Operand & src)792   void Push(const Operand& src) { push(src); }
Push(Immediate value)793   void Push(Immediate value) { push(value); }
Pop(Register dst)794   void Pop(Register dst) { pop(dst); }
Pop(const Operand & dst)795   void Pop(const Operand& dst) { pop(dst); }
PushReturnAddressFrom(Register src)796   void PushReturnAddressFrom(Register src) { push(src); }
PopReturnAddressTo(Register dst)797   void PopReturnAddressTo(Register dst) { pop(dst); }
798 
Lzcnt(Register dst,Register src)799   void Lzcnt(Register dst, Register src) { Lzcnt(dst, Operand(src)); }
800   void Lzcnt(Register dst, const Operand& src);
801 
Tzcnt(Register dst,Register src)802   void Tzcnt(Register dst, Register src) { Tzcnt(dst, Operand(src)); }
803   void Tzcnt(Register dst, const Operand& src);
804 
Popcnt(Register dst,Register src)805   void Popcnt(Register dst, Register src) { Popcnt(dst, Operand(src)); }
806   void Popcnt(Register dst, const Operand& src);
807 
808   // Move if the registers are not identical.
809   void Move(Register target, Register source);
810 
811   // Move a constant into a destination using the most efficient encoding.
812   void Move(Register dst, const Immediate& x);
813   void Move(const Operand& dst, const Immediate& x);
814 
Move(Register dst,Handle<Object> handle)815   void Move(Register dst, Handle<Object> handle) { LoadObject(dst, handle); }
Move(Register dst,Smi * source)816   void Move(Register dst, Smi* source) { Move(dst, Immediate(source)); }
817 
818   // Push a handle value.
Push(Handle<Object> handle)819   void Push(Handle<Object> handle) { push(Immediate(handle)); }
Push(Smi * smi)820   void Push(Smi* smi) { Push(Immediate(smi)); }
821 
CodeObject()822   Handle<Object> CodeObject() {
823     DCHECK(!code_object_.is_null());
824     return code_object_;
825   }
826 
827   // Insert code to verify that the x87 stack has the specified depth (0-7)
828   void VerifyX87StackDepth(uint32_t depth);
829 
830   // Emit code for a truncating division by a constant. The dividend register is
831   // unchanged, the result is in edx, and eax gets clobbered.
832   void TruncatingDiv(Register dividend, int32_t divisor);
833 
834   // ---------------------------------------------------------------------------
835   // StatsCounter support
836 
837   void SetCounter(StatsCounter* counter, int value);
838   void IncrementCounter(StatsCounter* counter, int value);
839   void DecrementCounter(StatsCounter* counter, int value);
840   void IncrementCounter(Condition cc, StatsCounter* counter, int value);
841   void DecrementCounter(Condition cc, StatsCounter* counter, int value);
842 
843   // ---------------------------------------------------------------------------
844   // Debugging
845 
846   // Calls Abort(msg) if the condition cc is not satisfied.
847   // Use --debug_code to enable.
848   void Assert(Condition cc, BailoutReason reason);
849 
850   void AssertFastElements(Register elements);
851 
852   // Like Assert(), but always enabled.
853   void Check(Condition cc, BailoutReason reason);
854 
855   // Print a message to stdout and abort execution.
856   void Abort(BailoutReason reason);
857 
858   // Check that the stack is aligned.
859   void CheckStackAlignment();
860 
861   // Verify restrictions about code generated in stubs.
set_generating_stub(bool value)862   void set_generating_stub(bool value) { generating_stub_ = value; }
generating_stub()863   bool generating_stub() { return generating_stub_; }
set_has_frame(bool value)864   void set_has_frame(bool value) { has_frame_ = value; }
has_frame()865   bool has_frame() { return has_frame_; }
866   inline bool AllowThisStubCall(CodeStub* stub);
867 
868   // ---------------------------------------------------------------------------
869   // String utilities.
870 
871   // Check whether the instance type represents a flat one-byte string. Jump to
872   // the label if not. If the instance type can be scratched specify same
873   // register for both instance type and scratch.
874   void JumpIfInstanceTypeIsNotSequentialOneByte(
875       Register instance_type, Register scratch,
876       Label* on_not_flat_one_byte_string);
877 
878   // Checks if both objects are sequential one-byte strings, and jumps to label
879   // if either is not.
880   void JumpIfNotBothSequentialOneByteStrings(
881       Register object1, Register object2, Register scratch1, Register scratch2,
882       Label* on_not_flat_one_byte_strings);
883 
884   // Checks if the given register or operand is a unique name
885   void JumpIfNotUniqueNameInstanceType(Register reg, Label* not_unique_name,
886                                        Label::Distance distance = Label::kFar) {
887     JumpIfNotUniqueNameInstanceType(Operand(reg), not_unique_name, distance);
888   }
889 
890   void JumpIfNotUniqueNameInstanceType(Operand operand, Label* not_unique_name,
891                                        Label::Distance distance = Label::kFar);
892 
893   void EmitSeqStringSetCharCheck(Register string, Register index,
894                                  Register value, uint32_t encoding_mask);
895 
SafepointRegisterStackIndex(Register reg)896   static int SafepointRegisterStackIndex(Register reg) {
897     return SafepointRegisterStackIndex(reg.code());
898   }
899 
900   // Load the type feedback vector from a JavaScript frame.
901   void EmitLoadTypeFeedbackVector(Register vector);
902 
903   // Activation support.
904   void EnterFrame(StackFrame::Type type);
905   void EnterFrame(StackFrame::Type type, bool load_constant_pool_pointer_reg);
906   void LeaveFrame(StackFrame::Type type);
907 
908   void EnterBuiltinFrame(Register context, Register target, Register argc);
909   void LeaveBuiltinFrame(Register context, Register target, Register argc);
910 
911   // Expects object in eax and returns map with validated enum cache
912   // in eax.  Assumes that any other register can be used as a scratch.
913   void CheckEnumCache(Label* call_runtime);
914 
915   // AllocationMemento support. Arrays may have an associated
916   // AllocationMemento object that can be checked for in order to pretransition
917   // to another type.
918   // On entry, receiver_reg should point to the array object.
919   // scratch_reg gets clobbered.
920   // If allocation info is present, conditional code is set to equal.
921   void TestJSArrayForAllocationMemento(Register receiver_reg,
922                                        Register scratch_reg,
923                                        Label* no_memento_found);
924 
JumpIfJSArrayHasAllocationMemento(Register receiver_reg,Register scratch_reg,Label * memento_found)925   void JumpIfJSArrayHasAllocationMemento(Register receiver_reg,
926                                          Register scratch_reg,
927                                          Label* memento_found) {
928     Label no_memento_found;
929     TestJSArrayForAllocationMemento(receiver_reg, scratch_reg,
930                                     &no_memento_found);
931     j(equal, memento_found);
932     bind(&no_memento_found);
933   }
934 
935   // Jumps to found label if a prototype map has dictionary elements.
936   void JumpIfDictionaryInPrototypeChain(Register object, Register scratch0,
937                                         Register scratch1, Label* found);
938 
939  private:
940   bool generating_stub_;
941   bool has_frame_;
942   // This handle will be patched with the code object on installation.
943   Handle<Object> code_object_;
944 
945   // Helper functions for generating invokes.
946   void InvokePrologue(const ParameterCount& expected,
947                       const ParameterCount& actual, Label* done,
948                       bool* definitely_mismatches, InvokeFlag flag,
949                       Label::Distance done_distance,
950                       const CallWrapper& call_wrapper);
951 
952   void EnterExitFramePrologue(StackFrame::Type frame_type);
953   void EnterExitFrameEpilogue(int argc, bool save_doubles);
954 
955   void LeaveExitFrameEpilogue(bool restore_context);
956 
957   // Allocation support helpers.
958   void LoadAllocationTopHelper(Register result, Register scratch,
959                                AllocationFlags flags);
960 
961   void UpdateAllocationTopHelper(Register result_end, Register scratch,
962                                  AllocationFlags flags);
963 
964   // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
965   void InNewSpace(Register object, Register scratch, Condition cc,
966                   Label* condition_met,
967                   Label::Distance condition_met_distance = Label::kFar);
968 
969   // Helper for finding the mark bits for an address.  Afterwards, the
970   // bitmap register points at the word with the mark bits and the mask
971   // the position of the first bit.  Uses ecx as scratch and leaves addr_reg
972   // unchanged.
973   inline void GetMarkBits(Register addr_reg, Register bitmap_reg,
974                           Register mask_reg);
975 
976   // Compute memory operands for safepoint stack slots.
977   Operand SafepointRegisterSlot(Register reg);
978   static int SafepointRegisterStackIndex(int reg_code);
979 
980   // Needs access to SafepointRegisterStackIndex for compiled frame
981   // traversal.
982   friend class StandardFrame;
983 };
984 
985 // The code patcher is used to patch (typically) small parts of code e.g. for
986 // debugging and other types of instrumentation. When using the code patcher
987 // the exact number of bytes specified must be emitted. Is not legal to emit
988 // relocation information. If any of these constraints are violated it causes
989 // an assertion.
990 class CodePatcher {
991  public:
992   CodePatcher(Isolate* isolate, byte* address, int size);
993   ~CodePatcher();
994 
995   // Macro assembler to emit code.
masm()996   MacroAssembler* masm() { return &masm_; }
997 
998  private:
999   byte* address_;        // The address of the code being patched.
1000   int size_;             // Number of bytes of the expected patch size.
1001   MacroAssembler masm_;  // Macro assembler used to generate the code.
1002 };
1003 
1004 // -----------------------------------------------------------------------------
1005 // Static helper functions.
1006 
1007 // Generate an Operand for loading a field from an object.
FieldOperand(Register object,int offset)1008 inline Operand FieldOperand(Register object, int offset) {
1009   return Operand(object, offset - kHeapObjectTag);
1010 }
1011 
1012 // Generate an Operand for loading an indexed field from an object.
FieldOperand(Register object,Register index,ScaleFactor scale,int offset)1013 inline Operand FieldOperand(Register object, Register index, ScaleFactor scale,
1014                             int offset) {
1015   return Operand(object, index, scale, offset - kHeapObjectTag);
1016 }
1017 
1018 inline Operand FixedArrayElementOperand(Register array, Register index_as_smi,
1019                                         int additional_offset = 0) {
1020   int offset = FixedArray::kHeaderSize + additional_offset * kPointerSize;
1021   return FieldOperand(array, index_as_smi, times_half_pointer_size, offset);
1022 }
1023 
ContextOperand(Register context,int index)1024 inline Operand ContextOperand(Register context, int index) {
1025   return Operand(context, Context::SlotOffset(index));
1026 }
1027 
ContextOperand(Register context,Register index)1028 inline Operand ContextOperand(Register context, Register index) {
1029   return Operand(context, index, times_pointer_size, Context::SlotOffset(0));
1030 }
1031 
NativeContextOperand()1032 inline Operand NativeContextOperand() {
1033   return ContextOperand(esi, Context::NATIVE_CONTEXT_INDEX);
1034 }
1035 
1036 #define ACCESS_MASM(masm) masm->
1037 
1038 }  // namespace internal
1039 }  // namespace v8
1040 
1041 #endif  // V8_X87_MACRO_ASSEMBLER_X87_H_
1042