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