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