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