[presubmit] Enable readability/namespace linter checking.
[platform/upstream/v8.git] / src / ia32 / macro-assembler-ia32.h
1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_IA32_MACRO_ASSEMBLER_IA32_H_
6 #define V8_IA32_MACRO_ASSEMBLER_IA32_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 = {kRegister_eax_Code};
18 const Register kReturnRegister1 = {kRegister_edx_Code};
19 const Register kJSFunctionRegister = {kRegister_edi_Code};
20 const Register kContextRegister = {kRegister_esi_Code};
21 const Register kInterpreterAccumulatorRegister = {kRegister_eax_Code};
22 const Register kInterpreterRegisterFileRegister = {kRegister_edx_Code};
23 const Register kInterpreterBytecodeOffsetRegister = {kRegister_ecx_Code};
24 const Register kInterpreterBytecodeArrayRegister = {kRegister_edi_Code};
25 const Register kInterpreterDispatchTableRegister = {kRegister_ebx_Code};
26 const Register kRuntimeCallFunctionRegister = {kRegister_ebx_Code};
27 const Register kRuntimeCallArgCountRegister = {kRegister_eax_Code};
28
29 // Spill slots used by interpreter dispatch calling convention.
30 const int kInterpreterContextSpillSlot = -1;
31
32 // Convenience for platform-independent signatures.  We do not normally
33 // distinguish memory operands from other operands on ia32.
34 typedef Operand MemOperand;
35
36 enum RememberedSetAction { EMIT_REMEMBERED_SET, OMIT_REMEMBERED_SET };
37 enum SmiCheck { INLINE_SMI_CHECK, OMIT_SMI_CHECK };
38 enum PointersToHereCheck {
39   kPointersToHereMaybeInteresting,
40   kPointersToHereAreAlwaysInteresting
41 };
42
43
44 enum RegisterValueType {
45   REGISTER_VALUE_IS_SMI,
46   REGISTER_VALUE_IS_INT32
47 };
48
49
50 #ifdef DEBUG
51 bool AreAliased(Register reg1,
52                 Register reg2,
53                 Register reg3 = no_reg,
54                 Register reg4 = no_reg,
55                 Register reg5 = no_reg,
56                 Register reg6 = no_reg,
57                 Register reg7 = no_reg,
58                 Register reg8 = no_reg);
59 #endif
60
61
62 // MacroAssembler implements a collection of frequently used macros.
63 class MacroAssembler: public Assembler {
64  public:
65   // The isolate parameter can be NULL if the macro assembler should
66   // not use isolate-dependent functionality. In this case, it's the
67   // responsibility of the caller to never invoke such function on the
68   // macro assembler.
69   MacroAssembler(Isolate* isolate, void* buffer, int size);
70
71   void Load(Register dst, const Operand& src, Representation r);
72   void Store(Register src, const Operand& dst, Representation r);
73
74   // Load a register with a long value as efficiently as possible.
75   void Set(Register dst, int32_t x) {
76     if (x == 0) {
77       xor_(dst, dst);
78     } else {
79       mov(dst, Immediate(x));
80     }
81   }
82   void Set(const Operand& dst, int32_t x) { mov(dst, Immediate(x)); }
83
84   // Operations on roots in the root-array.
85   void LoadRoot(Register destination, Heap::RootListIndex index);
86   void StoreRoot(Register source, Register scratch, Heap::RootListIndex index);
87   void CompareRoot(Register with, Register scratch, Heap::RootListIndex index);
88   // These methods can only be used with constant roots (i.e. non-writable
89   // and not in new space).
90   void CompareRoot(Register with, Heap::RootListIndex index);
91   void CompareRoot(const Operand& with, Heap::RootListIndex index);
92   void PushRoot(Heap::RootListIndex index);
93
94   // Compare the object in a register to a value and jump if they are equal.
95   void JumpIfRoot(Register with, Heap::RootListIndex index, Label* if_equal,
96                   Label::Distance if_equal_distance = Label::kNear) {
97     CompareRoot(with, index);
98     j(equal, if_equal, if_equal_distance);
99   }
100
101   // Compare the object in a register to a value and jump if they are not equal.
102   void JumpIfNotRoot(Register with, Heap::RootListIndex index,
103                      Label* if_not_equal,
104                      Label::Distance if_not_equal_distance = Label::kNear) {
105     CompareRoot(with, index);
106     j(not_equal, if_not_equal, if_not_equal_distance);
107   }
108
109   // ---------------------------------------------------------------------------
110   // GC Support
111   enum RememberedSetFinalAction {
112     kReturnAtEnd,
113     kFallThroughAtEnd
114   };
115
116   // Record in the remembered set the fact that we have a pointer to new space
117   // at the address pointed to by the addr register.  Only works if addr is not
118   // in new space.
119   void RememberedSetHelper(Register object,  // Used for debug code.
120                            Register addr,
121                            Register scratch,
122                            SaveFPRegsMode save_fp,
123                            RememberedSetFinalAction and_then);
124
125   void CheckPageFlag(Register object,
126                      Register scratch,
127                      int mask,
128                      Condition cc,
129                      Label* condition_met,
130                      Label::Distance condition_met_distance = Label::kFar);
131
132   void CheckPageFlagForMap(
133       Handle<Map> map,
134       int mask,
135       Condition cc,
136       Label* condition_met,
137       Label::Distance condition_met_distance = Label::kFar);
138
139   // Check if object is in new space.  Jumps if the object is not in new space.
140   // The register scratch can be object itself, but scratch will be clobbered.
141   void JumpIfNotInNewSpace(Register object,
142                            Register scratch,
143                            Label* branch,
144                            Label::Distance distance = Label::kFar) {
145     InNewSpace(object, scratch, zero, branch, distance);
146   }
147
148   // Check if object is in new space.  Jumps if the object is in new space.
149   // The register scratch can be object itself, but it will be clobbered.
150   void JumpIfInNewSpace(Register object,
151                         Register scratch,
152                         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,
159                 Register scratch0,
160                 Register scratch1,
161                 Label* has_color,
162                 Label::Distance has_color_distance,
163                 int first_bit,
164                 int second_bit);
165
166   void JumpIfBlack(Register object,
167                    Register scratch0,
168                    Register scratch1,
169                    Label* on_black,
170                    Label::Distance on_black_distance = Label::kFar);
171
172   // Checks the color of an object.  If the object is already grey or black
173   // then we just fall through, since it is already live.  If it is white and
174   // we can determine that it doesn't need to be scanned, then we just mark it
175   // black and fall through.  For the rest we jump to the label so the
176   // incremental marker can fix its assumptions.
177   void EnsureNotWhite(Register object,
178                       Register scratch1,
179                       Register scratch2,
180                       Label* object_is_white_and_not_data,
181                       Label::Distance distance);
182
183   // Notify the garbage collector that we wrote a pointer into an object.
184   // |object| is the object being stored into, |value| is the object being
185   // stored.  value and scratch registers are clobbered by the operation.
186   // The offset is the offset from the start of the object, not the offset from
187   // the tagged HeapObject pointer.  For use with FieldOperand(reg, off).
188   void RecordWriteField(
189       Register object,
190       int offset,
191       Register value,
192       Register scratch,
193       SaveFPRegsMode save_fp,
194       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
195       SmiCheck smi_check = INLINE_SMI_CHECK,
196       PointersToHereCheck pointers_to_here_check_for_value =
197           kPointersToHereMaybeInteresting);
198
199   // As above, but the offset has the tag presubtracted.  For use with
200   // Operand(reg, off).
201   void RecordWriteContextSlot(
202       Register context,
203       int offset,
204       Register value,
205       Register scratch,
206       SaveFPRegsMode save_fp,
207       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
208       SmiCheck smi_check = INLINE_SMI_CHECK,
209       PointersToHereCheck pointers_to_here_check_for_value =
210           kPointersToHereMaybeInteresting) {
211     RecordWriteField(context,
212                      offset + kHeapObjectTag,
213                      value,
214                      scratch,
215                      save_fp,
216                      remembered_set_action,
217                      smi_check,
218                      pointers_to_here_check_for_value);
219   }
220
221   // Notify the garbage collector that we wrote a pointer into a fixed array.
222   // |array| is the array being stored into, |value| is the
223   // object being stored.  |index| is the array index represented as a
224   // Smi. All registers are clobbered by the operation RecordWriteArray
225   // filters out smis so it does not update the write barrier if the
226   // value is a smi.
227   void RecordWriteArray(
228       Register array,
229       Register value,
230       Register index,
231       SaveFPRegsMode save_fp,
232       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
233       SmiCheck smi_check = INLINE_SMI_CHECK,
234       PointersToHereCheck pointers_to_here_check_for_value =
235           kPointersToHereMaybeInteresting);
236
237   // For page containing |object| mark region covering |address|
238   // dirty. |object| is the object being stored into, |value| is the
239   // object being stored. The address and value registers are clobbered by the
240   // operation. RecordWrite filters out smis so it does not update the
241   // write barrier if the value is a smi.
242   void RecordWrite(
243       Register object,
244       Register address,
245       Register value,
246       SaveFPRegsMode save_fp,
247       RememberedSetAction remembered_set_action = EMIT_REMEMBERED_SET,
248       SmiCheck smi_check = INLINE_SMI_CHECK,
249       PointersToHereCheck pointers_to_here_check_for_value =
250           kPointersToHereMaybeInteresting);
251
252   // For page containing |object| mark the region covering the object's map
253   // dirty. |object| is the object being stored into, |map| is the Map object
254   // that was stored.
255   void RecordWriteForMap(
256       Register object,
257       Handle<Map> map,
258       Register scratch1,
259       Register scratch2,
260       SaveFPRegsMode save_fp);
261
262   // ---------------------------------------------------------------------------
263   // Debugger Support
264
265   void DebugBreak();
266
267   // Generates function and stub prologue code.
268   void StubPrologue();
269   void Prologue(bool code_pre_aging);
270
271   // Enter specific kind of exit frame. Expects the number of
272   // arguments in register eax and sets up the number of arguments in
273   // register edi and the pointer to the first argument in register
274   // esi.
275   void EnterExitFrame(bool save_doubles);
276
277   void EnterApiExitFrame(int argc);
278
279   // Leave the current exit frame. Expects the return value in
280   // register eax:edx (untouched) and the pointer to the first
281   // argument in register esi.
282   void LeaveExitFrame(bool save_doubles);
283
284   // Leave the current exit frame. Expects the return value in
285   // register eax (untouched).
286   void LeaveApiExitFrame(bool restore_context);
287
288   // Find the function context up the context chain.
289   void LoadContext(Register dst, int context_chain_length);
290
291   // Load the global proxy from the current context.
292   void LoadGlobalProxy(Register dst);
293
294   // Conditionally load the cached Array transitioned map of type
295   // transitioned_kind from the native context if the map in register
296   // map_in_out is the cached Array map in the native context of
297   // expected_kind.
298   void LoadTransitionedArrayMapConditional(
299       ElementsKind expected_kind,
300       ElementsKind transitioned_kind,
301       Register map_in_out,
302       Register scratch,
303       Label* no_map_match);
304
305   // Load the global function with the given index.
306   void LoadGlobalFunction(int index, Register function);
307
308   // Load the initial map from the global function. The registers
309   // function and map can be the same.
310   void LoadGlobalFunctionInitialMap(Register function, Register map);
311
312   // Push and pop the registers that can hold pointers.
313   void PushSafepointRegisters() { pushad(); }
314   void PopSafepointRegisters() { popad(); }
315   // Store the value in register/immediate src in the safepoint
316   // register stack slot for register dst.
317   void StoreToSafepointRegisterSlot(Register dst, Register src);
318   void StoreToSafepointRegisterSlot(Register dst, Immediate src);
319   void LoadFromSafepointRegisterSlot(Register dst, Register src);
320
321   void LoadHeapObject(Register result, Handle<HeapObject> object);
322   void CmpHeapObject(Register reg, Handle<HeapObject> object);
323   void PushHeapObject(Handle<HeapObject> object);
324
325   void LoadObject(Register result, Handle<Object> object) {
326     AllowDeferredHandleDereference heap_object_check;
327     if (object->IsHeapObject()) {
328       LoadHeapObject(result, Handle<HeapObject>::cast(object));
329     } else {
330       Move(result, Immediate(object));
331     }
332   }
333
334   void CmpObject(Register reg, Handle<Object> object) {
335     AllowDeferredHandleDereference heap_object_check;
336     if (object->IsHeapObject()) {
337       CmpHeapObject(reg, Handle<HeapObject>::cast(object));
338     } else {
339       cmp(reg, Immediate(object));
340     }
341   }
342
343   // Compare the given value and the value of weak cell.
344   void CmpWeakValue(Register value, Handle<WeakCell> cell, Register scratch);
345
346   void GetWeakValue(Register value, Handle<WeakCell> cell);
347
348   // Load the value of the weak cell in the value register. Branch to the given
349   // miss label if the weak cell was cleared.
350   void LoadWeakValue(Register value, Handle<WeakCell> cell, Label* miss);
351
352   // ---------------------------------------------------------------------------
353   // JavaScript invokes
354
355   // Invoke the JavaScript function code by either calling or jumping.
356   void InvokeCode(Register code,
357                   const ParameterCount& expected,
358                   const ParameterCount& actual,
359                   InvokeFlag flag,
360                   const CallWrapper& call_wrapper) {
361     InvokeCode(Operand(code), expected, actual, flag, call_wrapper);
362   }
363
364   void InvokeCode(const Operand& code,
365                   const ParameterCount& expected,
366                   const ParameterCount& actual,
367                   InvokeFlag flag,
368                   const CallWrapper& call_wrapper);
369
370   // Invoke the JavaScript function in the given register. Changes the
371   // current context to the context in the function before invoking.
372   void InvokeFunction(Register function,
373                       const ParameterCount& actual,
374                       InvokeFlag flag,
375                       const CallWrapper& call_wrapper);
376
377   void InvokeFunction(Register function,
378                       const ParameterCount& expected,
379                       const ParameterCount& actual,
380                       InvokeFlag flag,
381                       const CallWrapper& call_wrapper);
382
383   void InvokeFunction(Handle<JSFunction> function,
384                       const ParameterCount& expected,
385                       const ParameterCount& actual,
386                       InvokeFlag flag,
387                       const CallWrapper& call_wrapper);
388
389   // Invoke specified builtin JavaScript function.
390   void InvokeBuiltin(int native_context_index, InvokeFlag flag,
391                      const CallWrapper& call_wrapper = NullCallWrapper());
392
393   // Store the function for the given builtin in the target register.
394   void GetBuiltinFunction(Register target, int native_context_index);
395
396   // Store the code object for the given builtin in the target register.
397   void GetBuiltinEntry(Register target, int native_context_index);
398
399   // Expression support
400   // cvtsi2sd instruction only writes to the low 64-bit of dst register, which
401   // hinders register renaming and makes dependence chains longer. So we use
402   // xorps to clear the dst register before cvtsi2sd to solve this issue.
403   void Cvtsi2sd(XMMRegister dst, Register src) { Cvtsi2sd(dst, Operand(src)); }
404   void Cvtsi2sd(XMMRegister dst, const Operand& src);
405
406   // Support for constant splitting.
407   bool IsUnsafeImmediate(const Immediate& x);
408   void SafeMove(Register dst, const Immediate& x);
409   void SafePush(const Immediate& x);
410
411   // Compare object type for heap object.
412   // Incoming register is heap_object and outgoing register is map.
413   void CmpObjectType(Register heap_object, InstanceType type, Register map);
414
415   // Compare instance type for map.
416   void CmpInstanceType(Register map, InstanceType type);
417
418   // Check if a map for a JSObject indicates that the object has fast elements.
419   // Jump to the specified label if it does not.
420   void CheckFastElements(Register map,
421                          Label* fail,
422                          Label::Distance distance = Label::kFar);
423
424   // Check if a map for a JSObject indicates that the object can have both smi
425   // and HeapObject elements.  Jump to the specified label if it does not.
426   void CheckFastObjectElements(Register map,
427                                Label* fail,
428                                Label::Distance distance = Label::kFar);
429
430   // Check if a map for a JSObject indicates that the object has fast smi only
431   // elements.  Jump to the specified label if it does not.
432   void CheckFastSmiElements(Register map,
433                             Label* fail,
434                             Label::Distance distance = Label::kFar);
435
436   // Check to see if maybe_number can be stored as a double in
437   // FastDoubleElements. If it can, store it at the index specified by key in
438   // the FastDoubleElements array elements, otherwise jump to fail.
439   void StoreNumberToDoubleElements(Register maybe_number,
440                                    Register elements,
441                                    Register key,
442                                    Register scratch1,
443                                    XMMRegister scratch2,
444                                    Label* fail,
445                                    int offset = 0);
446
447   // Compare an object's map with the specified map.
448   void CompareMap(Register obj, Handle<Map> map);
449
450   // Check if the map of an object is equal to a specified map and branch to
451   // label if not. Skip the smi check if not required (object is known to be a
452   // heap object). If mode is ALLOW_ELEMENT_TRANSITION_MAPS, then also match
453   // against maps that are ElementsKind transition maps of the specified map.
454   void CheckMap(Register obj,
455                 Handle<Map> map,
456                 Label* fail,
457                 SmiCheckType smi_check_type);
458
459   // Check if the map of an object is equal to a specified weak map and branch
460   // to a specified target if equal. Skip the smi check if not required
461   // (object is known to be a heap object)
462   void DispatchWeakMap(Register obj, Register scratch1, Register scratch2,
463                        Handle<WeakCell> cell, Handle<Code> success,
464                        SmiCheckType smi_check_type);
465
466   // Check if the object in register heap_object is a string. Afterwards the
467   // register map contains the object map and the register instance_type
468   // contains the instance_type. The registers map and instance_type can be the
469   // same in which case it contains the instance type afterwards. Either of the
470   // registers map and instance_type can be the same as heap_object.
471   Condition IsObjectStringType(Register heap_object,
472                                Register map,
473                                Register instance_type);
474
475   // Check if the object in register heap_object is a name. Afterwards the
476   // register map contains the object map and the register instance_type
477   // contains the instance_type. The registers map and instance_type can be the
478   // same in which case it contains the instance type afterwards. Either of the
479   // registers map and instance_type can be the same as heap_object.
480   Condition IsObjectNameType(Register heap_object,
481                              Register map,
482                              Register instance_type);
483
484   // FCmp is similar to integer cmp, but requires unsigned
485   // jcc instructions (je, ja, jae, jb, jbe, je, and jz).
486   void FCmp();
487
488   void ClampUint8(Register reg);
489
490   void ClampDoubleToUint8(XMMRegister input_reg,
491                           XMMRegister scratch_reg,
492                           Register result_reg);
493
494   void SlowTruncateToI(Register result_reg, Register input_reg,
495       int offset = HeapNumber::kValueOffset - kHeapObjectTag);
496
497   void TruncateHeapNumberToI(Register result_reg, Register input_reg);
498   void TruncateDoubleToI(Register result_reg, XMMRegister input_reg);
499
500   void DoubleToI(Register result_reg, XMMRegister input_reg,
501                  XMMRegister scratch, MinusZeroMode minus_zero_mode,
502                  Label* lost_precision, Label* is_nan, Label* minus_zero,
503                  Label::Distance dst = Label::kFar);
504
505   // Smi tagging support.
506   void SmiTag(Register reg) {
507     STATIC_ASSERT(kSmiTag == 0);
508     STATIC_ASSERT(kSmiTagSize == 1);
509     add(reg, reg);
510   }
511   void SmiUntag(Register reg) {
512     sar(reg, kSmiTagSize);
513   }
514
515   // Modifies the register even if it does not contain a Smi!
516   void SmiUntag(Register reg, Label* is_smi) {
517     STATIC_ASSERT(kSmiTagSize == 1);
518     sar(reg, kSmiTagSize);
519     STATIC_ASSERT(kSmiTag == 0);
520     j(not_carry, is_smi);
521   }
522
523   void LoadUint32(XMMRegister dst, Register src) {
524     LoadUint32(dst, Operand(src));
525   }
526   void LoadUint32(XMMRegister dst, const Operand& src);
527
528   // Jump the register contains a smi.
529   inline void JumpIfSmi(Register value,
530                         Label* smi_label,
531                         Label::Distance distance = Label::kFar) {
532     test(value, Immediate(kSmiTagMask));
533     j(zero, smi_label, distance);
534   }
535   // Jump if the operand is a smi.
536   inline void JumpIfSmi(Operand value,
537                         Label* smi_label,
538                         Label::Distance distance = Label::kFar) {
539     test(value, Immediate(kSmiTagMask));
540     j(zero, smi_label, distance);
541   }
542   // Jump if register contain a non-smi.
543   inline void JumpIfNotSmi(Register value,
544                            Label* not_smi_label,
545                            Label::Distance distance = Label::kFar) {
546     test(value, Immediate(kSmiTagMask));
547     j(not_zero, not_smi_label, distance);
548   }
549
550   void LoadInstanceDescriptors(Register map, Register descriptors);
551   void EnumLength(Register dst, Register map);
552   void NumberOfOwnDescriptors(Register dst, Register map);
553   void LoadAccessor(Register dst, Register holder, int accessor_index,
554                     AccessorComponent accessor);
555
556   template<typename Field>
557   void DecodeField(Register reg) {
558     static const int shift = Field::kShift;
559     static const int mask = Field::kMask >> Field::kShift;
560     if (shift != 0) {
561       sar(reg, shift);
562     }
563     and_(reg, Immediate(mask));
564   }
565
566   template<typename Field>
567   void DecodeFieldToSmi(Register reg) {
568     static const int shift = Field::kShift;
569     static const int mask = (Field::kMask >> Field::kShift) << kSmiTagSize;
570     STATIC_ASSERT((mask & (0x80000000u >> (kSmiTagSize - 1))) == 0);
571     STATIC_ASSERT(kSmiTag == 0);
572     if (shift < kSmiTagSize) {
573       shl(reg, kSmiTagSize - shift);
574     } else if (shift > kSmiTagSize) {
575       sar(reg, shift - kSmiTagSize);
576     }
577     and_(reg, Immediate(mask));
578   }
579
580   void LoadPowerOf2(XMMRegister dst, Register scratch, int power);
581
582   // Abort execution if argument is not a number, enabled via --debug-code.
583   void AssertNumber(Register object);
584
585   // Abort execution if argument is not a smi, enabled via --debug-code.
586   void AssertSmi(Register object);
587
588   // Abort execution if argument is a smi, enabled via --debug-code.
589   void AssertNotSmi(Register object);
590
591   // Abort execution if argument is not a string, enabled via --debug-code.
592   void AssertString(Register object);
593
594   // Abort execution if argument is not a name, enabled via --debug-code.
595   void AssertName(Register object);
596
597   // Abort execution if argument is not a JSFunction, enabled via --debug-code.
598   void AssertFunction(Register object);
599
600   // Abort execution if argument is not undefined or an AllocationSite, enabled
601   // via --debug-code.
602   void AssertUndefinedOrAllocationSite(Register object);
603
604   // ---------------------------------------------------------------------------
605   // Exception handling
606
607   // Push a new stack handler and link it into stack handler chain.
608   void PushStackHandler();
609
610   // Unlink the stack handler on top of the stack from the stack handler chain.
611   void PopStackHandler();
612
613   // ---------------------------------------------------------------------------
614   // Inline caching support
615
616   // Generate code for checking access rights - used for security checks
617   // on access to global objects across environments. The holder register
618   // is left untouched, but the scratch register is clobbered.
619   void CheckAccessGlobalProxy(Register holder_reg,
620                               Register scratch1,
621                               Register scratch2,
622                               Label* miss);
623
624   void GetNumberHash(Register r0, Register scratch);
625
626   void LoadFromNumberDictionary(Label* miss,
627                                 Register elements,
628                                 Register key,
629                                 Register r0,
630                                 Register r1,
631                                 Register r2,
632                                 Register result);
633
634
635   // ---------------------------------------------------------------------------
636   // Allocation support
637
638   // Allocate an object in new space or old space. If the given space
639   // is exhausted control continues at the gc_required label. The allocated
640   // object is returned in result and end of the new object is returned in
641   // result_end. The register scratch can be passed as no_reg in which case
642   // an additional object reference will be added to the reloc info. The
643   // returned pointers in result and result_end have not yet been tagged as
644   // heap objects. If result_contains_top_on_entry is true the content of
645   // result is known to be the allocation top on entry (could be result_end
646   // from a previous call). If result_contains_top_on_entry is true scratch
647   // should be no_reg as it is never used.
648   void Allocate(int object_size,
649                 Register result,
650                 Register result_end,
651                 Register scratch,
652                 Label* gc_required,
653                 AllocationFlags flags);
654
655   void Allocate(int header_size,
656                 ScaleFactor element_size,
657                 Register element_count,
658                 RegisterValueType element_count_type,
659                 Register result,
660                 Register result_end,
661                 Register scratch,
662                 Label* gc_required,
663                 AllocationFlags flags);
664
665   void Allocate(Register object_size,
666                 Register result,
667                 Register result_end,
668                 Register scratch,
669                 Label* gc_required,
670                 AllocationFlags flags);
671
672   // Allocate a heap number in new space with undefined value. The
673   // register scratch2 can be passed as no_reg; the others must be
674   // valid registers. Returns tagged pointer in result register, or
675   // jumps to gc_required if new space is full.
676   void AllocateHeapNumber(Register result,
677                           Register scratch1,
678                           Register scratch2,
679                           Label* gc_required,
680                           MutableMode mode = IMMUTABLE);
681
682   // Allocate a sequential string. All the header fields of the string object
683   // are initialized.
684   void AllocateTwoByteString(Register result,
685                              Register length,
686                              Register scratch1,
687                              Register scratch2,
688                              Register scratch3,
689                              Label* gc_required);
690   void AllocateOneByteString(Register result, Register length,
691                              Register scratch1, Register scratch2,
692                              Register scratch3, Label* gc_required);
693   void AllocateOneByteString(Register result, int length, Register scratch1,
694                              Register scratch2, Label* gc_required);
695
696   // Allocate a raw cons string object. Only the map field of the result is
697   // initialized.
698   void AllocateTwoByteConsString(Register result,
699                           Register scratch1,
700                           Register scratch2,
701                           Label* gc_required);
702   void AllocateOneByteConsString(Register result, Register scratch1,
703                                  Register scratch2, Label* gc_required);
704
705   // Allocate a raw sliced string object. Only the map field of the result is
706   // initialized.
707   void AllocateTwoByteSlicedString(Register result,
708                             Register scratch1,
709                             Register scratch2,
710                             Label* gc_required);
711   void AllocateOneByteSlicedString(Register result, Register scratch1,
712                                    Register scratch2, Label* gc_required);
713
714   // Copy memory, byte-by-byte, from source to destination.  Not optimized for
715   // long or aligned copies.
716   // The contents of index and scratch are destroyed.
717   void CopyBytes(Register source,
718                  Register destination,
719                  Register length,
720                  Register scratch);
721
722   // Initialize fields with filler values.  Fields starting at |start_offset|
723   // not including end_offset are overwritten with the value in |filler|.  At
724   // the end the loop, |start_offset| takes the value of |end_offset|.
725   void InitializeFieldsWithFiller(Register start_offset,
726                                   Register end_offset,
727                                   Register filler);
728
729   // ---------------------------------------------------------------------------
730   // Support functions.
731
732   // Check a boolean-bit of a Smi field.
733   void BooleanBitTest(Register object, int field_offset, int bit_index);
734
735   // Check if result is zero and op is negative.
736   void NegativeZeroTest(Register result, Register op, Label* then_label);
737
738   // Check if result is zero and any of op1 and op2 are negative.
739   // Register scratch is destroyed, and it must be different from op2.
740   void NegativeZeroTest(Register result, Register op1, Register op2,
741                         Register scratch, Label* then_label);
742
743   // Machine code version of Map::GetConstructor().
744   // |temp| holds |result|'s map when done.
745   void GetMapConstructor(Register result, Register map, Register temp);
746
747   // Try to get function prototype of a function and puts the value in
748   // the result register. Checks that the function really is a
749   // function and jumps to the miss label if the fast checks fail. The
750   // function register will be untouched; the other registers may be
751   // clobbered.
752   void TryGetFunctionPrototype(Register function, Register result,
753                                Register scratch, Label* miss);
754
755   // Picks out an array index from the hash field.
756   // Register use:
757   //   hash - holds the index's hash. Clobbered.
758   //   index - holds the overwritten index on exit.
759   void IndexFromHash(Register hash, Register index);
760
761   // ---------------------------------------------------------------------------
762   // Runtime calls
763
764   // Call a code stub.  Generate the code if necessary.
765   void CallStub(CodeStub* stub, TypeFeedbackId ast_id = TypeFeedbackId::None());
766
767   // Tail call a code stub (jump).  Generate the code if necessary.
768   void TailCallStub(CodeStub* stub);
769
770   // Return from a code stub after popping its arguments.
771   void StubReturn(int argc);
772
773   // Call a runtime routine.
774   void CallRuntime(const Runtime::Function* f,
775                    int num_arguments,
776                    SaveFPRegsMode save_doubles = kDontSaveFPRegs);
777   void CallRuntimeSaveDoubles(Runtime::FunctionId id) {
778     const Runtime::Function* function = Runtime::FunctionForId(id);
779     CallRuntime(function, function->nargs, kSaveFPRegs);
780   }
781
782   // Convenience function: Same as above, but takes the fid instead.
783   void CallRuntime(Runtime::FunctionId id,
784                    int num_arguments,
785                    SaveFPRegsMode save_doubles = kDontSaveFPRegs) {
786     CallRuntime(Runtime::FunctionForId(id), num_arguments, save_doubles);
787   }
788
789   // Convenience function: call an external reference.
790   void CallExternalReference(ExternalReference ref, int num_arguments);
791
792   // Tail call of a runtime routine (jump).
793   // Like JumpToExternalReference, but also takes care of passing the number
794   // of parameters.
795   void TailCallExternalReference(const ExternalReference& ext,
796                                  int num_arguments,
797                                  int result_size);
798
799   // Convenience function: tail call a runtime routine (jump).
800   void TailCallRuntime(Runtime::FunctionId fid,
801                        int num_arguments,
802                        int result_size);
803
804   // Before calling a C-function from generated code, align arguments on stack.
805   // After aligning the frame, arguments must be stored in esp[0], esp[4],
806   // etc., not pushed. The argument count assumes all arguments are word sized.
807   // Some compilers/platforms require the stack to be aligned when calling
808   // C++ code.
809   // Needs a scratch register to do some arithmetic. This register will be
810   // trashed.
811   void PrepareCallCFunction(int num_arguments, Register scratch);
812
813   // Calls a C function and cleans up the space for arguments allocated
814   // by PrepareCallCFunction. The called function is not allowed to trigger a
815   // garbage collection, since that might move the code and invalidate the
816   // return address (unless this is somehow accounted for by the called
817   // function).
818   void CallCFunction(ExternalReference function, int num_arguments);
819   void CallCFunction(Register function, int num_arguments);
820
821   // Jump to a runtime routine.
822   void JumpToExternalReference(const ExternalReference& ext);
823
824   // ---------------------------------------------------------------------------
825   // Utilities
826
827   void Ret();
828
829   // Return and drop arguments from stack, where the number of arguments
830   // may be bigger than 2^16 - 1.  Requires a scratch register.
831   void Ret(int bytes_dropped, Register scratch);
832
833   // Emit code to discard a non-negative number of pointer-sized elements
834   // from the stack, clobbering only the esp register.
835   void Drop(int element_count);
836
837   void Call(Label* target) { call(target); }
838   void Call(Handle<Code> target, RelocInfo::Mode rmode) { call(target, rmode); }
839   void Jump(Handle<Code> target, RelocInfo::Mode rmode) { jmp(target, rmode); }
840   void Push(Register src) { push(src); }
841   void Push(const Operand& src) { push(src); }
842   void Push(Immediate value) { push(value); }
843   void Pop(Register dst) { pop(dst); }
844   void PushReturnAddressFrom(Register src) { push(src); }
845   void PopReturnAddressTo(Register dst) { pop(dst); }
846
847   // Non-SSE2 instructions.
848   void Pextrd(Register dst, XMMRegister src, int8_t imm8);
849   void Pinsrd(XMMRegister dst, Register src, int8_t imm8) {
850     Pinsrd(dst, Operand(src), imm8);
851   }
852   void Pinsrd(XMMRegister dst, const Operand& src, int8_t imm8);
853
854   void Lzcnt(Register dst, Register src) { Lzcnt(dst, Operand(src)); }
855   void Lzcnt(Register dst, const Operand& src);
856
857   // Emit call to the code we are currently generating.
858   void CallSelf() {
859     Handle<Code> self(reinterpret_cast<Code**>(CodeObject().location()));
860     call(self, RelocInfo::CODE_TARGET);
861   }
862
863   // Move if the registers are not identical.
864   void Move(Register target, Register source);
865
866   // Move a constant into a destination using the most efficient encoding.
867   void Move(Register dst, const Immediate& x);
868   void Move(const Operand& dst, const Immediate& x);
869
870   // Move an immediate into an XMM register.
871   void Move(XMMRegister dst, uint32_t src);
872   void Move(XMMRegister dst, uint64_t src);
873   void Move(XMMRegister dst, double src) { Move(dst, bit_cast<uint64_t>(src)); }
874
875   // Push a handle value.
876   void Push(Handle<Object> handle) { push(Immediate(handle)); }
877   void Push(Smi* smi) { Push(Handle<Smi>(smi, isolate())); }
878
879   Handle<Object> CodeObject() {
880     DCHECK(!code_object_.is_null());
881     return code_object_;
882   }
883
884   // Emit code for a truncating division by a constant. The dividend register is
885   // unchanged, the result is in edx, and eax gets clobbered.
886   void TruncatingDiv(Register dividend, int32_t divisor);
887
888   // ---------------------------------------------------------------------------
889   // StatsCounter support
890
891   void SetCounter(StatsCounter* counter, int value);
892   void IncrementCounter(StatsCounter* counter, int value);
893   void DecrementCounter(StatsCounter* counter, int value);
894   void IncrementCounter(Condition cc, StatsCounter* counter, int value);
895   void DecrementCounter(Condition cc, StatsCounter* counter, int value);
896
897
898   // ---------------------------------------------------------------------------
899   // Debugging
900
901   // Calls Abort(msg) if the condition cc is not satisfied.
902   // Use --debug_code to enable.
903   void Assert(Condition cc, BailoutReason reason);
904
905   void AssertFastElements(Register elements);
906
907   // Like Assert(), but always enabled.
908   void Check(Condition cc, BailoutReason reason);
909
910   // Print a message to stdout and abort execution.
911   void Abort(BailoutReason reason);
912
913   // Check that the stack is aligned.
914   void CheckStackAlignment();
915
916   // Verify restrictions about code generated in stubs.
917   void set_generating_stub(bool value) { generating_stub_ = value; }
918   bool generating_stub() { return generating_stub_; }
919   void set_has_frame(bool value) { has_frame_ = value; }
920   bool has_frame() { return has_frame_; }
921   inline bool AllowThisStubCall(CodeStub* stub);
922
923   // ---------------------------------------------------------------------------
924   // String utilities.
925
926   // Check whether the instance type represents a flat one-byte string. Jump to
927   // the label if not. If the instance type can be scratched specify same
928   // register for both instance type and scratch.
929   void JumpIfInstanceTypeIsNotSequentialOneByte(
930       Register instance_type, Register scratch,
931       Label* on_not_flat_one_byte_string);
932
933   // Checks if both objects are sequential one-byte strings, and jumps to label
934   // if either is not.
935   void JumpIfNotBothSequentialOneByteStrings(
936       Register object1, Register object2, Register scratch1, Register scratch2,
937       Label* on_not_flat_one_byte_strings);
938
939   // Checks if the given register or operand is a unique name
940   void JumpIfNotUniqueNameInstanceType(Register reg, Label* not_unique_name,
941                                        Label::Distance distance = Label::kFar) {
942     JumpIfNotUniqueNameInstanceType(Operand(reg), not_unique_name, distance);
943   }
944
945   void JumpIfNotUniqueNameInstanceType(Operand operand, Label* not_unique_name,
946                                        Label::Distance distance = Label::kFar);
947
948   void EmitSeqStringSetCharCheck(Register string,
949                                  Register index,
950                                  Register value,
951                                  uint32_t encoding_mask);
952
953   static int SafepointRegisterStackIndex(Register reg) {
954     return SafepointRegisterStackIndex(reg.code());
955   }
956
957   // Load the type feedback vector from a JavaScript frame.
958   void EmitLoadTypeFeedbackVector(Register vector);
959
960   // Activation support.
961   void EnterFrame(StackFrame::Type type);
962   void EnterFrame(StackFrame::Type type, bool load_constant_pool_pointer_reg);
963   void LeaveFrame(StackFrame::Type type);
964
965   // Expects object in eax and returns map with validated enum cache
966   // in eax.  Assumes that any other register can be used as a scratch.
967   void CheckEnumCache(Label* call_runtime);
968
969   // AllocationMemento support. Arrays may have an associated
970   // AllocationMemento object that can be checked for in order to pretransition
971   // to another type.
972   // On entry, receiver_reg should point to the array object.
973   // scratch_reg gets clobbered.
974   // If allocation info is present, conditional code is set to equal.
975   void TestJSArrayForAllocationMemento(Register receiver_reg,
976                                        Register scratch_reg,
977                                        Label* no_memento_found);
978
979   void JumpIfJSArrayHasAllocationMemento(Register receiver_reg,
980                                          Register scratch_reg,
981                                          Label* memento_found) {
982     Label no_memento_found;
983     TestJSArrayForAllocationMemento(receiver_reg, scratch_reg,
984                                     &no_memento_found);
985     j(equal, memento_found);
986     bind(&no_memento_found);
987   }
988
989   // Jumps to found label if a prototype map has dictionary elements.
990   void JumpIfDictionaryInPrototypeChain(Register object, Register scratch0,
991                                         Register scratch1, Label* found);
992
993  private:
994   bool generating_stub_;
995   bool has_frame_;
996   // This handle will be patched with the code object on installation.
997   Handle<Object> code_object_;
998
999   // Helper functions for generating invokes.
1000   void InvokePrologue(const ParameterCount& expected,
1001                       const ParameterCount& actual,
1002                       Handle<Code> code_constant,
1003                       const Operand& code_operand,
1004                       Label* done,
1005                       bool* definitely_mismatches,
1006                       InvokeFlag flag,
1007                       Label::Distance done_distance,
1008                       const CallWrapper& call_wrapper = NullCallWrapper());
1009
1010   void EnterExitFramePrologue();
1011   void EnterExitFrameEpilogue(int argc, bool save_doubles);
1012
1013   void LeaveExitFrameEpilogue(bool restore_context);
1014
1015   // Allocation support helpers.
1016   void LoadAllocationTopHelper(Register result,
1017                                Register scratch,
1018                                AllocationFlags flags);
1019
1020   void UpdateAllocationTopHelper(Register result_end,
1021                                  Register scratch,
1022                                  AllocationFlags flags);
1023
1024   // Helper for implementing JumpIfNotInNewSpace and JumpIfInNewSpace.
1025   void InNewSpace(Register object,
1026                   Register scratch,
1027                   Condition cc,
1028                   Label* condition_met,
1029                   Label::Distance condition_met_distance = Label::kFar);
1030
1031   // Helper for finding the mark bits for an address.  Afterwards, the
1032   // bitmap register points at the word with the mark bits and the mask
1033   // the position of the first bit.  Uses ecx as scratch and leaves addr_reg
1034   // unchanged.
1035   inline void GetMarkBits(Register addr_reg,
1036                           Register bitmap_reg,
1037                           Register mask_reg);
1038
1039   // Compute memory operands for safepoint stack slots.
1040   Operand SafepointRegisterSlot(Register reg);
1041   static int SafepointRegisterStackIndex(int reg_code);
1042
1043   // Needs access to SafepointRegisterStackIndex for compiled frame
1044   // traversal.
1045   friend class StandardFrame;
1046 };
1047
1048
1049 // The code patcher is used to patch (typically) small parts of code e.g. for
1050 // debugging and other types of instrumentation. When using the code patcher
1051 // the exact number of bytes specified must be emitted. Is not legal to emit
1052 // relocation information. If any of these constraints are violated it causes
1053 // an assertion.
1054 class CodePatcher {
1055  public:
1056   CodePatcher(byte* address, int size);
1057   ~CodePatcher();
1058
1059   // Macro assembler to emit code.
1060   MacroAssembler* masm() { return &masm_; }
1061
1062  private:
1063   byte* address_;  // The address of the code being patched.
1064   int size_;  // Number of bytes of the expected patch size.
1065   MacroAssembler masm_;  // Macro assembler used to generate the code.
1066 };
1067
1068
1069 // -----------------------------------------------------------------------------
1070 // Static helper functions.
1071
1072 // Generate an Operand for loading a field from an object.
1073 inline Operand FieldOperand(Register object, int offset) {
1074   return Operand(object, offset - kHeapObjectTag);
1075 }
1076
1077
1078 // Generate an Operand for loading an indexed field from an object.
1079 inline Operand FieldOperand(Register object,
1080                             Register index,
1081                             ScaleFactor scale,
1082                             int offset) {
1083   return Operand(object, index, scale, offset - kHeapObjectTag);
1084 }
1085
1086
1087 inline Operand FixedArrayElementOperand(Register array,
1088                                         Register index_as_smi,
1089                                         int additional_offset = 0) {
1090   int offset = FixedArray::kHeaderSize + additional_offset * kPointerSize;
1091   return FieldOperand(array, index_as_smi, times_half_pointer_size, offset);
1092 }
1093
1094
1095 inline Operand ContextOperand(Register context, int index) {
1096   return Operand(context, Context::SlotOffset(index));
1097 }
1098
1099
1100 inline Operand ContextOperand(Register context, Register index) {
1101   return Operand(context, index, times_pointer_size, Context::SlotOffset(0));
1102 }
1103
1104
1105 inline Operand GlobalObjectOperand() {
1106   return ContextOperand(esi, Context::GLOBAL_OBJECT_INDEX);
1107 }
1108
1109
1110 #ifdef GENERATED_CODE_COVERAGE
1111 extern void LogGeneratedCodeCoverage(const char* file_line);
1112 #define CODE_COVERAGE_STRINGIFY(x) #x
1113 #define CODE_COVERAGE_TOSTRING(x) CODE_COVERAGE_STRINGIFY(x)
1114 #define __FILE_LINE__ __FILE__ ":" CODE_COVERAGE_TOSTRING(__LINE__)
1115 #define ACCESS_MASM(masm) {                                               \
1116     byte* ia32_coverage_function =                                        \
1117         reinterpret_cast<byte*>(FUNCTION_ADDR(LogGeneratedCodeCoverage)); \
1118     masm->pushfd();                                                       \
1119     masm->pushad();                                                       \
1120     masm->push(Immediate(reinterpret_cast<int>(&__FILE_LINE__)));         \
1121     masm->call(ia32_coverage_function, RelocInfo::RUNTIME_ENTRY);         \
1122     masm->pop(eax);                                                       \
1123     masm->popad();                                                        \
1124     masm->popfd();                                                        \
1125   }                                                                       \
1126   masm->
1127 #else
1128 #define ACCESS_MASM(masm) masm->
1129 #endif
1130
1131
1132 }  // namespace internal
1133 }  // namespace v8
1134
1135 #endif  // V8_IA32_MACRO_ASSEMBLER_IA32_H_