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