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