Upstream version 8.37.186.0
[platform/framework/web/crosswalk.git] / src / v8 / src / assembler.h
1 // Copyright (c) 1994-2006 Sun Microsystems Inc.
2 // All Rights Reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // - Redistributions of source code must retain the above copyright notice,
9 // this list of conditions and the following disclaimer.
10 //
11 // - Redistribution in binary form must reproduce the above copyright
12 // notice, this list of conditions and the following disclaimer in the
13 // documentation and/or other materials provided with the distribution.
14 //
15 // - Neither the name of Sun Microsystems or the names of contributors may
16 // be used to endorse or promote products derived from this software without
17 // specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
20 // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
21 // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 // The original source code covered by the above license above has been
32 // modified significantly by Google Inc.
33 // Copyright 2012 the V8 project authors. All rights reserved.
34
35 #ifndef V8_ASSEMBLER_H_
36 #define V8_ASSEMBLER_H_
37
38 #include "src/v8.h"
39
40 #include "src/allocation.h"
41 #include "src/builtins.h"
42 #include "src/gdb-jit.h"
43 #include "src/isolate.h"
44 #include "src/runtime.h"
45 #include "src/token.h"
46
47 namespace v8 {
48
49 class ApiFunction;
50
51 namespace internal {
52
53 class StatsCounter;
54 // -----------------------------------------------------------------------------
55 // Platform independent assembler base class.
56
57 class AssemblerBase: public Malloced {
58  public:
59   AssemblerBase(Isolate* isolate, void* buffer, int buffer_size);
60   virtual ~AssemblerBase();
61
62   Isolate* isolate() const { return isolate_; }
63   int jit_cookie() const { return jit_cookie_; }
64
65   bool emit_debug_code() const { return emit_debug_code_; }
66   void set_emit_debug_code(bool value) { emit_debug_code_ = value; }
67
68   bool serializer_enabled() const { return serializer_enabled_; }
69
70   bool predictable_code_size() const { return predictable_code_size_; }
71   void set_predictable_code_size(bool value) { predictable_code_size_ = value; }
72
73   uint64_t enabled_cpu_features() const { return enabled_cpu_features_; }
74   void set_enabled_cpu_features(uint64_t features) {
75     enabled_cpu_features_ = features;
76   }
77   bool IsEnabled(CpuFeature f) {
78     return (enabled_cpu_features_ & (static_cast<uint64_t>(1) << f)) != 0;
79   }
80
81   // Overwrite a host NaN with a quiet target NaN.  Used by mksnapshot for
82   // cross-snapshotting.
83   static void QuietNaN(HeapObject* nan) { }
84
85   int pc_offset() const { return static_cast<int>(pc_ - buffer_); }
86
87   // This function is called when code generation is aborted, so that
88   // the assembler could clean up internal data structures.
89   virtual void AbortedCodeGeneration() { }
90
91   static const int kMinimalBufferSize = 4*KB;
92
93  protected:
94   // The buffer into which code and relocation info are generated. It could
95   // either be owned by the assembler or be provided externally.
96   byte* buffer_;
97   int buffer_size_;
98   bool own_buffer_;
99
100   // The program counter, which points into the buffer above and moves forward.
101   byte* pc_;
102
103  private:
104   Isolate* isolate_;
105   int jit_cookie_;
106   uint64_t enabled_cpu_features_;
107   bool emit_debug_code_;
108   bool predictable_code_size_;
109   bool serializer_enabled_;
110 };
111
112
113 // Avoids emitting debug code during the lifetime of this scope object.
114 class DontEmitDebugCodeScope BASE_EMBEDDED {
115  public:
116   explicit DontEmitDebugCodeScope(AssemblerBase* assembler)
117       : assembler_(assembler), old_value_(assembler->emit_debug_code()) {
118     assembler_->set_emit_debug_code(false);
119   }
120   ~DontEmitDebugCodeScope() {
121     assembler_->set_emit_debug_code(old_value_);
122   }
123  private:
124   AssemblerBase* assembler_;
125   bool old_value_;
126 };
127
128
129 // Avoids using instructions that vary in size in unpredictable ways between the
130 // snapshot and the running VM.
131 class PredictableCodeSizeScope {
132  public:
133   PredictableCodeSizeScope(AssemblerBase* assembler, int expected_size);
134   ~PredictableCodeSizeScope();
135
136  private:
137   AssemblerBase* assembler_;
138   int expected_size_;
139   int start_offset_;
140   bool old_value_;
141 };
142
143
144 // Enable a specified feature within a scope.
145 class CpuFeatureScope BASE_EMBEDDED {
146  public:
147 #ifdef DEBUG
148   CpuFeatureScope(AssemblerBase* assembler, CpuFeature f);
149   ~CpuFeatureScope();
150
151  private:
152   AssemblerBase* assembler_;
153   uint64_t old_enabled_;
154 #else
155   CpuFeatureScope(AssemblerBase* assembler, CpuFeature f) {}
156 #endif
157 };
158
159
160 // CpuFeatures keeps track of which features are supported by the target CPU.
161 // Supported features must be enabled by a CpuFeatureScope before use.
162 // Example:
163 //   if (assembler->IsSupported(SSE3)) {
164 //     CpuFeatureScope fscope(assembler, SSE3);
165 //     // Generate code containing SSE3 instructions.
166 //   } else {
167 //     // Generate alternative code.
168 //   }
169 class CpuFeatures : public AllStatic {
170  public:
171   static void Probe(bool cross_compile) {
172     STATIC_ASSERT(NUMBER_OF_CPU_FEATURES <= kBitsPerInt);
173     if (initialized_) return;
174     initialized_ = true;
175     ProbeImpl(cross_compile);
176   }
177
178   static bool IsSupported(CpuFeature f) {
179     return (supported_ & (1u << f)) != 0;
180   }
181
182   static inline bool SupportsCrankshaft();
183   static inline bool SupportsSIMD128InCrankshaft();
184
185   static inline unsigned cache_line_size() {
186     ASSERT(cache_line_size_ != 0);
187     return cache_line_size_;
188   }
189
190   static void PrintTarget();
191   static void PrintFeatures();
192
193  private:
194   // Platform-dependent implementation.
195   static void ProbeImpl(bool cross_compile);
196
197   static unsigned supported_;
198   static unsigned cache_line_size_;
199   static bool initialized_;
200   friend class ExternalReference;
201   DISALLOW_COPY_AND_ASSIGN(CpuFeatures);
202 };
203
204
205 // -----------------------------------------------------------------------------
206 // Labels represent pc locations; they are typically jump or call targets.
207 // After declaration, a label can be freely used to denote known or (yet)
208 // unknown pc location. Assembler::bind() is used to bind a label to the
209 // current pc. A label can be bound only once.
210
211 class Label BASE_EMBEDDED {
212  public:
213   enum Distance {
214     kNear, kFar
215   };
216
217   INLINE(Label()) {
218     Unuse();
219     UnuseNear();
220   }
221
222   INLINE(~Label()) {
223     ASSERT(!is_linked());
224     ASSERT(!is_near_linked());
225   }
226
227   INLINE(void Unuse()) { pos_ = 0; }
228   INLINE(void UnuseNear()) { near_link_pos_ = 0; }
229
230   INLINE(bool is_bound() const) { return pos_ <  0; }
231   INLINE(bool is_unused() const) { return pos_ == 0 && near_link_pos_ == 0; }
232   INLINE(bool is_linked() const) { return pos_ >  0; }
233   INLINE(bool is_near_linked() const) { return near_link_pos_ > 0; }
234
235   // Returns the position of bound or linked labels. Cannot be used
236   // for unused labels.
237   int pos() const;
238   int near_link_pos() const { return near_link_pos_ - 1; }
239
240  private:
241   // pos_ encodes both the binding state (via its sign)
242   // and the binding position (via its value) of a label.
243   //
244   // pos_ <  0  bound label, pos() returns the jump target position
245   // pos_ == 0  unused label
246   // pos_ >  0  linked label, pos() returns the last reference position
247   int pos_;
248
249   // Behaves like |pos_| in the "> 0" case, but for near jumps to this label.
250   int near_link_pos_;
251
252   void bind_to(int pos)  {
253     pos_ = -pos - 1;
254     ASSERT(is_bound());
255   }
256   void link_to(int pos, Distance distance = kFar) {
257     if (distance == kNear) {
258       near_link_pos_ = pos + 1;
259       ASSERT(is_near_linked());
260     } else {
261       pos_ = pos + 1;
262       ASSERT(is_linked());
263     }
264   }
265
266   friend class Assembler;
267   friend class Displacement;
268   friend class RegExpMacroAssemblerIrregexp;
269
270 #if V8_TARGET_ARCH_ARM64
271   // On ARM64, the Assembler keeps track of pointers to Labels to resolve
272   // branches to distant targets. Copying labels would confuse the Assembler.
273   DISALLOW_COPY_AND_ASSIGN(Label);  // NOLINT
274 #endif
275 };
276
277
278 enum SaveFPRegsMode { kDontSaveFPRegs, kSaveFPRegs };
279
280 // Specifies whether to perform icache flush operations on RelocInfo updates.
281 // If FLUSH_ICACHE_IF_NEEDED, the icache will always be flushed if an
282 // instruction was modified. If SKIP_ICACHE_FLUSH the flush will always be
283 // skipped (only use this if you will flush the icache manually before it is
284 // executed).
285 enum ICacheFlushMode { FLUSH_ICACHE_IF_NEEDED, SKIP_ICACHE_FLUSH };
286
287 // -----------------------------------------------------------------------------
288 // Relocation information
289
290
291 // Relocation information consists of the address (pc) of the datum
292 // to which the relocation information applies, the relocation mode
293 // (rmode), and an optional data field. The relocation mode may be
294 // "descriptive" and not indicate a need for relocation, but simply
295 // describe a property of the datum. Such rmodes are useful for GC
296 // and nice disassembly output.
297
298 class RelocInfo {
299  public:
300   // The constant kNoPosition is used with the collecting of source positions
301   // in the relocation information. Two types of source positions are collected
302   // "position" (RelocMode position) and "statement position" (RelocMode
303   // statement_position). The "position" is collected at places in the source
304   // code which are of interest when making stack traces to pin-point the source
305   // location of a stack frame as close as possible. The "statement position" is
306   // collected at the beginning at each statement, and is used to indicate
307   // possible break locations. kNoPosition is used to indicate an
308   // invalid/uninitialized position value.
309   static const int kNoPosition = -1;
310
311   // This string is used to add padding comments to the reloc info in cases
312   // where we are not sure to have enough space for patching in during
313   // lazy deoptimization. This is the case if we have indirect calls for which
314   // we do not normally record relocation info.
315   static const char* const kFillerCommentString;
316
317   // The minimum size of a comment is equal to three bytes for the extra tagged
318   // pc + the tag for the data, and kPointerSize for the actual pointer to the
319   // comment.
320   static const int kMinRelocCommentSize = 3 + kPointerSize;
321
322   // The maximum size for a call instruction including pc-jump.
323   static const int kMaxCallSize = 6;
324
325   // The maximum pc delta that will use the short encoding.
326   static const int kMaxSmallPCDelta;
327
328   enum Mode {
329     // Please note the order is important (see IsCodeTarget, IsGCRelocMode).
330     CODE_TARGET,  // Code target which is not any of the above.
331     CODE_TARGET_WITH_ID,
332     CONSTRUCT_CALL,  // code target that is a call to a JavaScript constructor.
333     DEBUG_BREAK,  // Code target for the debugger statement.
334     EMBEDDED_OBJECT,
335     CELL,
336
337     // Everything after runtime_entry (inclusive) is not GC'ed.
338     RUNTIME_ENTRY,
339     JS_RETURN,  // Marks start of the ExitJSFrame code.
340     COMMENT,
341     POSITION,  // See comment for kNoPosition above.
342     STATEMENT_POSITION,  // See comment for kNoPosition above.
343     DEBUG_BREAK_SLOT,  // Additional code inserted for debug break slot.
344     EXTERNAL_REFERENCE,  // The address of an external C++ function.
345     INTERNAL_REFERENCE,  // An address inside the same function.
346
347     // Marks constant and veneer pools. Only used on ARM and ARM64.
348     // They use a custom noncompact encoding.
349     CONST_POOL,
350     VENEER_POOL,
351
352     // add more as needed
353     // Pseudo-types
354     NUMBER_OF_MODES,  // There are at most 15 modes with noncompact encoding.
355     NONE32,  // never recorded 32-bit value
356     NONE64,  // never recorded 64-bit value
357     CODE_AGE_SEQUENCE,  // Not stored in RelocInfo array, used explictly by
358                         // code aging.
359     FIRST_REAL_RELOC_MODE = CODE_TARGET,
360     LAST_REAL_RELOC_MODE = VENEER_POOL,
361     FIRST_PSEUDO_RELOC_MODE = CODE_AGE_SEQUENCE,
362     LAST_PSEUDO_RELOC_MODE = CODE_AGE_SEQUENCE,
363     LAST_CODE_ENUM = DEBUG_BREAK,
364     LAST_GCED_ENUM = CELL,
365     // Modes <= LAST_COMPACT_ENUM are guaranteed to have compact encoding.
366     LAST_COMPACT_ENUM = CODE_TARGET_WITH_ID,
367     LAST_STANDARD_NONCOMPACT_ENUM = INTERNAL_REFERENCE
368   };
369
370   RelocInfo() {}
371
372   RelocInfo(byte* pc, Mode rmode, intptr_t data, Code* host)
373       : pc_(pc), rmode_(rmode), data_(data), host_(host) {
374   }
375   RelocInfo(byte* pc, double data64)
376       : pc_(pc), rmode_(NONE64), data64_(data64), host_(NULL) {
377   }
378
379   static inline bool IsRealRelocMode(Mode mode) {
380     return mode >= FIRST_REAL_RELOC_MODE &&
381         mode <= LAST_REAL_RELOC_MODE;
382   }
383   static inline bool IsPseudoRelocMode(Mode mode) {
384     ASSERT(!IsRealRelocMode(mode));
385     return mode >= FIRST_PSEUDO_RELOC_MODE &&
386         mode <= LAST_PSEUDO_RELOC_MODE;
387   }
388   static inline bool IsConstructCall(Mode mode) {
389     return mode == CONSTRUCT_CALL;
390   }
391   static inline bool IsCodeTarget(Mode mode) {
392     return mode <= LAST_CODE_ENUM;
393   }
394   static inline bool IsEmbeddedObject(Mode mode) {
395     return mode == EMBEDDED_OBJECT;
396   }
397   static inline bool IsRuntimeEntry(Mode mode) {
398     return mode == RUNTIME_ENTRY;
399   }
400   // Is the relocation mode affected by GC?
401   static inline bool IsGCRelocMode(Mode mode) {
402     return mode <= LAST_GCED_ENUM;
403   }
404   static inline bool IsJSReturn(Mode mode) {
405     return mode == JS_RETURN;
406   }
407   static inline bool IsComment(Mode mode) {
408     return mode == COMMENT;
409   }
410   static inline bool IsConstPool(Mode mode) {
411     return mode == CONST_POOL;
412   }
413   static inline bool IsVeneerPool(Mode mode) {
414     return mode == VENEER_POOL;
415   }
416   static inline bool IsPosition(Mode mode) {
417     return mode == POSITION || mode == STATEMENT_POSITION;
418   }
419   static inline bool IsStatementPosition(Mode mode) {
420     return mode == STATEMENT_POSITION;
421   }
422   static inline bool IsExternalReference(Mode mode) {
423     return mode == EXTERNAL_REFERENCE;
424   }
425   static inline bool IsInternalReference(Mode mode) {
426     return mode == INTERNAL_REFERENCE;
427   }
428   static inline bool IsDebugBreakSlot(Mode mode) {
429     return mode == DEBUG_BREAK_SLOT;
430   }
431   static inline bool IsNone(Mode mode) {
432     return mode == NONE32 || mode == NONE64;
433   }
434   static inline bool IsCodeAgeSequence(Mode mode) {
435     return mode == CODE_AGE_SEQUENCE;
436   }
437   static inline int ModeMask(Mode mode) { return 1 << mode; }
438
439   // Returns true if the first RelocInfo has the same mode and raw data as the
440   // second one.
441   static inline bool IsEqual(RelocInfo first, RelocInfo second) {
442     return first.rmode() == second.rmode() &&
443            (first.rmode() == RelocInfo::NONE64 ?
444               first.raw_data64() == second.raw_data64() :
445               first.data() == second.data());
446   }
447
448   // Accessors
449   byte* pc() const { return pc_; }
450   void set_pc(byte* pc) { pc_ = pc; }
451   Mode rmode() const {  return rmode_; }
452   intptr_t data() const { return data_; }
453   double data64() const { return data64_; }
454   uint64_t raw_data64() {
455     return BitCast<uint64_t>(data64_);
456   }
457   Code* host() const { return host_; }
458   void set_host(Code* host) { host_ = host; }
459
460   // Apply a relocation by delta bytes
461   INLINE(void apply(intptr_t delta,
462                     ICacheFlushMode icache_flush_mode =
463                         FLUSH_ICACHE_IF_NEEDED));
464
465   // Is the pointer this relocation info refers to coded like a plain pointer
466   // or is it strange in some way (e.g. relative or patched into a series of
467   // instructions).
468   bool IsCodedSpecially();
469
470   // If true, the pointer this relocation info refers to is an entry in the
471   // constant pool, otherwise the pointer is embedded in the instruction stream.
472   bool IsInConstantPool();
473
474   // Read/modify the code target in the branch/call instruction
475   // this relocation applies to;
476   // can only be called if IsCodeTarget(rmode_) || IsRuntimeEntry(rmode_)
477   INLINE(Address target_address());
478   INLINE(void set_target_address(Address target,
479                                  WriteBarrierMode write_barrier_mode =
480                                      UPDATE_WRITE_BARRIER,
481                                  ICacheFlushMode icache_flush_mode =
482                                      FLUSH_ICACHE_IF_NEEDED));
483   INLINE(Object* target_object());
484   INLINE(Handle<Object> target_object_handle(Assembler* origin));
485   INLINE(void set_target_object(Object* target,
486                                 WriteBarrierMode write_barrier_mode =
487                                     UPDATE_WRITE_BARRIER,
488                                 ICacheFlushMode icache_flush_mode =
489                                     FLUSH_ICACHE_IF_NEEDED));
490   INLINE(Address target_runtime_entry(Assembler* origin));
491   INLINE(void set_target_runtime_entry(Address target,
492                                        WriteBarrierMode write_barrier_mode =
493                                            UPDATE_WRITE_BARRIER,
494                                        ICacheFlushMode icache_flush_mode =
495                                            FLUSH_ICACHE_IF_NEEDED));
496   INLINE(Cell* target_cell());
497   INLINE(Handle<Cell> target_cell_handle());
498   INLINE(void set_target_cell(Cell* cell,
499                               WriteBarrierMode write_barrier_mode =
500                                   UPDATE_WRITE_BARRIER,
501                               ICacheFlushMode icache_flush_mode =
502                                   FLUSH_ICACHE_IF_NEEDED));
503   INLINE(Handle<Object> code_age_stub_handle(Assembler* origin));
504   INLINE(Code* code_age_stub());
505   INLINE(void set_code_age_stub(Code* stub,
506                                 ICacheFlushMode icache_flush_mode =
507                                     FLUSH_ICACHE_IF_NEEDED));
508
509   // Returns the address of the constant pool entry where the target address
510   // is held.  This should only be called if IsInConstantPool returns true.
511   INLINE(Address constant_pool_entry_address());
512
513   // Read the address of the word containing the target_address in an
514   // instruction stream.  What this means exactly is architecture-independent.
515   // The only architecture-independent user of this function is the serializer.
516   // The serializer uses it to find out how many raw bytes of instruction to
517   // output before the next target.  Architecture-independent code shouldn't
518   // dereference the pointer it gets back from this.
519   INLINE(Address target_address_address());
520
521   // This indicates how much space a target takes up when deserializing a code
522   // stream.  For most architectures this is just the size of a pointer.  For
523   // an instruction like movw/movt where the target bits are mixed into the
524   // instruction bits the size of the target will be zero, indicating that the
525   // serializer should not step forwards in memory after a target is resolved
526   // and written.  In this case the target_address_address function above
527   // should return the end of the instructions to be patched, allowing the
528   // deserializer to deserialize the instructions as raw bytes and put them in
529   // place, ready to be patched with the target.
530   INLINE(int target_address_size());
531
532   // Read/modify the reference in the instruction this relocation
533   // applies to; can only be called if rmode_ is external_reference
534   INLINE(Address target_reference());
535
536   // Read/modify the address of a call instruction. This is used to relocate
537   // the break points where straight-line code is patched with a call
538   // instruction.
539   INLINE(Address call_address());
540   INLINE(void set_call_address(Address target));
541   INLINE(Object* call_object());
542   INLINE(void set_call_object(Object* target));
543   INLINE(Object** call_object_address());
544
545   // Wipe out a relocation to a fixed value, used for making snapshots
546   // reproducible.
547   INLINE(void WipeOut());
548
549   template<typename StaticVisitor> inline void Visit(Heap* heap);
550   inline void Visit(Isolate* isolate, ObjectVisitor* v);
551
552   // Patch the code with some other code.
553   void PatchCode(byte* instructions, int instruction_count);
554
555   // Patch the code with a call.
556   void PatchCodeWithCall(Address target, int guard_bytes);
557
558   // Check whether this return sequence has been patched
559   // with a call to the debugger.
560   INLINE(bool IsPatchedReturnSequence());
561
562   // Check whether this debug break slot has been patched with a call to the
563   // debugger.
564   INLINE(bool IsPatchedDebugBreakSlotSequence());
565
566 #ifdef DEBUG
567   // Check whether the given code contains relocation information that
568   // either is position-relative or movable by the garbage collector.
569   static bool RequiresRelocation(const CodeDesc& desc);
570 #endif
571
572 #ifdef ENABLE_DISASSEMBLER
573   // Printing
574   static const char* RelocModeName(Mode rmode);
575   void Print(Isolate* isolate, FILE* out);
576 #endif  // ENABLE_DISASSEMBLER
577 #ifdef VERIFY_HEAP
578   void Verify(Isolate* isolate);
579 #endif
580
581   static const int kCodeTargetMask = (1 << (LAST_CODE_ENUM + 1)) - 1;
582   static const int kPositionMask = 1 << POSITION | 1 << STATEMENT_POSITION;
583   static const int kDataMask =
584       (1 << CODE_TARGET_WITH_ID) | kPositionMask | (1 << COMMENT);
585   static const int kApplyMask;  // Modes affected by apply. Depends on arch.
586
587  private:
588   // On ARM, note that pc_ is the address of the constant pool entry
589   // to be relocated and not the address of the instruction
590   // referencing the constant pool entry (except when rmode_ ==
591   // comment).
592   byte* pc_;
593   Mode rmode_;
594   union {
595     intptr_t data_;
596     double data64_;
597   };
598   Code* host_;
599   // External-reference pointers are also split across instruction-pairs
600   // on some platforms, but are accessed via indirect pointers. This location
601   // provides a place for that pointer to exist naturally. Its address
602   // is returned by RelocInfo::target_reference_address().
603   Address reconstructed_adr_ptr_;
604   friend class RelocIterator;
605 };
606
607
608 // RelocInfoWriter serializes a stream of relocation info. It writes towards
609 // lower addresses.
610 class RelocInfoWriter BASE_EMBEDDED {
611  public:
612   RelocInfoWriter() : pos_(NULL),
613                       last_pc_(NULL),
614                       last_id_(0),
615                       last_position_(0) {}
616   RelocInfoWriter(byte* pos, byte* pc) : pos_(pos),
617                                          last_pc_(pc),
618                                          last_id_(0),
619                                          last_position_(0) {}
620
621   byte* pos() const { return pos_; }
622   byte* last_pc() const { return last_pc_; }
623
624   void Write(const RelocInfo* rinfo);
625
626   // Update the state of the stream after reloc info buffer
627   // and/or code is moved while the stream is active.
628   void Reposition(byte* pos, byte* pc) {
629     pos_ = pos;
630     last_pc_ = pc;
631   }
632
633   // Max size (bytes) of a written RelocInfo. Longest encoding is
634   // ExtraTag, VariableLengthPCJump, ExtraTag, pc_delta, ExtraTag, data_delta.
635   // On ia32 and arm this is 1 + 4 + 1 + 1 + 1 + 4 = 12.
636   // On x64 this is 1 + 4 + 1 + 1 + 1 + 8 == 16;
637   // Here we use the maximum of the two.
638   static const int kMaxSize = 16;
639
640  private:
641   inline uint32_t WriteVariableLengthPCJump(uint32_t pc_delta);
642   inline void WriteTaggedPC(uint32_t pc_delta, int tag);
643   inline void WriteExtraTaggedPC(uint32_t pc_delta, int extra_tag);
644   inline void WriteExtraTaggedIntData(int data_delta, int top_tag);
645   inline void WriteExtraTaggedPoolData(int data, int pool_type);
646   inline void WriteExtraTaggedData(intptr_t data_delta, int top_tag);
647   inline void WriteTaggedData(intptr_t data_delta, int tag);
648   inline void WriteExtraTag(int extra_tag, int top_tag);
649
650   byte* pos_;
651   byte* last_pc_;
652   int last_id_;
653   int last_position_;
654   DISALLOW_COPY_AND_ASSIGN(RelocInfoWriter);
655 };
656
657
658 // A RelocIterator iterates over relocation information.
659 // Typical use:
660 //
661 //   for (RelocIterator it(code); !it.done(); it.next()) {
662 //     // do something with it.rinfo() here
663 //   }
664 //
665 // A mask can be specified to skip unwanted modes.
666 class RelocIterator: public Malloced {
667  public:
668   // Create a new iterator positioned at
669   // the beginning of the reloc info.
670   // Relocation information with mode k is included in the
671   // iteration iff bit k of mode_mask is set.
672   explicit RelocIterator(Code* code, int mode_mask = -1);
673   explicit RelocIterator(const CodeDesc& desc, int mode_mask = -1);
674
675   // Iteration
676   bool done() const { return done_; }
677   void next();
678
679   // Return pointer valid until next next().
680   RelocInfo* rinfo() {
681     ASSERT(!done());
682     return &rinfo_;
683   }
684
685  private:
686   // Advance* moves the position before/after reading.
687   // *Read* reads from current byte(s) into rinfo_.
688   // *Get* just reads and returns info on current byte.
689   void Advance(int bytes = 1) { pos_ -= bytes; }
690   int AdvanceGetTag();
691   int GetExtraTag();
692   int GetTopTag();
693   void ReadTaggedPC();
694   void AdvanceReadPC();
695   void AdvanceReadId();
696   void AdvanceReadPoolData();
697   void AdvanceReadPosition();
698   void AdvanceReadData();
699   void AdvanceReadVariableLengthPCJump();
700   int GetLocatableTypeTag();
701   void ReadTaggedId();
702   void ReadTaggedPosition();
703
704   // If the given mode is wanted, set it in rinfo_ and return true.
705   // Else return false. Used for efficiently skipping unwanted modes.
706   bool SetMode(RelocInfo::Mode mode) {
707     return (mode_mask_ & (1 << mode)) ? (rinfo_.rmode_ = mode, true) : false;
708   }
709
710   byte* pos_;
711   byte* end_;
712   byte* code_age_sequence_;
713   RelocInfo rinfo_;
714   bool done_;
715   int mode_mask_;
716   int last_id_;
717   int last_position_;
718   DISALLOW_COPY_AND_ASSIGN(RelocIterator);
719 };
720
721
722 //------------------------------------------------------------------------------
723 // External function
724
725 //----------------------------------------------------------------------------
726 class IC_Utility;
727 class SCTableReference;
728 class Debug_Address;
729
730
731 // An ExternalReference represents a C++ address used in the generated
732 // code. All references to C++ functions and variables must be encapsulated in
733 // an ExternalReference instance. This is done in order to track the origin of
734 // all external references in the code so that they can be bound to the correct
735 // addresses when deserializing a heap.
736 class ExternalReference BASE_EMBEDDED {
737  public:
738   // Used in the simulator to support different native api calls.
739   enum Type {
740     // Builtin call.
741     // Object* f(v8::internal::Arguments).
742     BUILTIN_CALL,  // default
743
744     // Builtin that takes float arguments and returns an int.
745     // int f(double, double).
746     BUILTIN_COMPARE_CALL,
747
748     // Builtin call that returns floating point.
749     // double f(double, double).
750     BUILTIN_FP_FP_CALL,
751
752     // Builtin call that returns floating point.
753     // double f(double).
754     BUILTIN_FP_CALL,
755
756     // Builtin call that returns floating point.
757     // double f(double, int).
758     BUILTIN_FP_INT_CALL,
759
760     // Direct call to API function callback.
761     // void f(v8::FunctionCallbackInfo&)
762     DIRECT_API_CALL,
763
764     // Call to function callback via InvokeFunctionCallback.
765     // void f(v8::FunctionCallbackInfo&, v8::FunctionCallback)
766     PROFILING_API_CALL,
767
768     // Direct call to accessor getter callback.
769     // void f(Local<String> property, PropertyCallbackInfo& info)
770     DIRECT_GETTER_CALL,
771
772     // Call to accessor getter callback via InvokeAccessorGetterCallback.
773     // void f(Local<String> property, PropertyCallbackInfo& info,
774     //     AccessorGetterCallback callback)
775     PROFILING_GETTER_CALL
776   };
777
778   static void SetUp();
779   static void InitializeMathExpData();
780   static void TearDownMathExpData();
781
782   typedef void* ExternalReferenceRedirector(void* original, Type type);
783
784   ExternalReference() : address_(NULL) {}
785
786   ExternalReference(Builtins::CFunctionId id, Isolate* isolate);
787
788   ExternalReference(ApiFunction* ptr, Type type, Isolate* isolate);
789
790   ExternalReference(Builtins::Name name, Isolate* isolate);
791
792   ExternalReference(Runtime::FunctionId id, Isolate* isolate);
793
794   ExternalReference(const Runtime::Function* f, Isolate* isolate);
795
796   ExternalReference(const IC_Utility& ic_utility, Isolate* isolate);
797
798   explicit ExternalReference(StatsCounter* counter);
799
800   ExternalReference(Isolate::AddressId id, Isolate* isolate);
801
802   explicit ExternalReference(const SCTableReference& table_ref);
803
804   // Isolate as an external reference.
805   static ExternalReference isolate_address(Isolate* isolate);
806
807   // One-of-a-kind references. These references are not part of a general
808   // pattern. This means that they have to be added to the
809   // ExternalReferenceTable in serialize.cc manually.
810
811   static ExternalReference incremental_marking_record_write_function(
812       Isolate* isolate);
813   static ExternalReference store_buffer_overflow_function(
814       Isolate* isolate);
815   static ExternalReference flush_icache_function(Isolate* isolate);
816   static ExternalReference delete_handle_scope_extensions(Isolate* isolate);
817
818   static ExternalReference get_date_field_function(Isolate* isolate);
819   static ExternalReference date_cache_stamp(Isolate* isolate);
820
821   static ExternalReference get_make_code_young_function(Isolate* isolate);
822   static ExternalReference get_mark_code_as_executed_function(Isolate* isolate);
823
824   // Deoptimization support.
825   static ExternalReference new_deoptimizer_function(Isolate* isolate);
826   static ExternalReference compute_output_frames_function(Isolate* isolate);
827
828   // Log support.
829   static ExternalReference log_enter_external_function(Isolate* isolate);
830   static ExternalReference log_leave_external_function(Isolate* isolate);
831
832   // Static data in the keyed lookup cache.
833   static ExternalReference keyed_lookup_cache_keys(Isolate* isolate);
834   static ExternalReference keyed_lookup_cache_field_offsets(Isolate* isolate);
835
836   // Static variable Heap::roots_array_start()
837   static ExternalReference roots_array_start(Isolate* isolate);
838
839   // Static variable Heap::allocation_sites_list_address()
840   static ExternalReference allocation_sites_list_address(Isolate* isolate);
841
842   // Static variable StackGuard::address_of_jslimit()
843   static ExternalReference address_of_stack_limit(Isolate* isolate);
844
845   // Static variable StackGuard::address_of_real_jslimit()
846   static ExternalReference address_of_real_stack_limit(Isolate* isolate);
847
848   // Static variable RegExpStack::limit_address()
849   static ExternalReference address_of_regexp_stack_limit(Isolate* isolate);
850
851   // Static variables for RegExp.
852   static ExternalReference address_of_static_offsets_vector(Isolate* isolate);
853   static ExternalReference address_of_regexp_stack_memory_address(
854       Isolate* isolate);
855   static ExternalReference address_of_regexp_stack_memory_size(
856       Isolate* isolate);
857
858   // Static variable Heap::NewSpaceStart()
859   static ExternalReference new_space_start(Isolate* isolate);
860   static ExternalReference new_space_mask(Isolate* isolate);
861   static ExternalReference heap_always_allocate_scope_depth(Isolate* isolate);
862   static ExternalReference new_space_mark_bits(Isolate* isolate);
863
864   // Write barrier.
865   static ExternalReference store_buffer_top(Isolate* isolate);
866
867   // Used for fast allocation in generated code.
868   static ExternalReference new_space_allocation_top_address(Isolate* isolate);
869   static ExternalReference new_space_allocation_limit_address(Isolate* isolate);
870   static ExternalReference old_pointer_space_allocation_top_address(
871       Isolate* isolate);
872   static ExternalReference old_pointer_space_allocation_limit_address(
873       Isolate* isolate);
874   static ExternalReference old_data_space_allocation_top_address(
875       Isolate* isolate);
876   static ExternalReference old_data_space_allocation_limit_address(
877       Isolate* isolate);
878
879   static ExternalReference mod_two_doubles_operation(Isolate* isolate);
880   static ExternalReference power_double_double_function(Isolate* isolate);
881   static ExternalReference power_double_int_function(Isolate* isolate);
882
883   static ExternalReference handle_scope_next_address(Isolate* isolate);
884   static ExternalReference handle_scope_limit_address(Isolate* isolate);
885   static ExternalReference handle_scope_level_address(Isolate* isolate);
886
887   static ExternalReference scheduled_exception_address(Isolate* isolate);
888   static ExternalReference address_of_pending_message_obj(Isolate* isolate);
889   static ExternalReference address_of_has_pending_message(Isolate* isolate);
890   static ExternalReference address_of_pending_message_script(Isolate* isolate);
891
892   // Static variables containing common double constants.
893   static ExternalReference address_of_min_int();
894   static ExternalReference address_of_one_half();
895   static ExternalReference address_of_minus_one_half();
896   static ExternalReference address_of_minus_zero();
897   static ExternalReference address_of_zero();
898   static ExternalReference address_of_uint8_max_value();
899   static ExternalReference address_of_negative_infinity();
900   static ExternalReference address_of_canonical_non_hole_nan();
901   static ExternalReference address_of_the_hole_nan();
902   static ExternalReference address_of_uint32_bias();
903
904   static ExternalReference math_log_double_function(Isolate* isolate);
905
906   static ExternalReference math_exp_constants(int constant_index);
907   static ExternalReference math_exp_log_table();
908
909   static ExternalReference page_flags(Page* page);
910
911   static ExternalReference ForDeoptEntry(Address entry);
912
913   static ExternalReference cpu_features();
914
915   static ExternalReference debug_after_break_target_address(Isolate* isolate);
916   static ExternalReference debug_restarter_frame_function_pointer_address(
917       Isolate* isolate);
918
919   static ExternalReference is_profiling_address(Isolate* isolate);
920   static ExternalReference invoke_function_callback(Isolate* isolate);
921   static ExternalReference invoke_accessor_getter_callback(Isolate* isolate);
922
923   Address address() const { return reinterpret_cast<Address>(address_); }
924
925   // Function Debug::Break()
926   static ExternalReference debug_break(Isolate* isolate);
927
928   // Used to check if single stepping is enabled in generated code.
929   static ExternalReference debug_step_in_fp_address(Isolate* isolate);
930
931 #ifndef V8_INTERPRETED_REGEXP
932   // C functions called from RegExp generated code.
933
934   // Function NativeRegExpMacroAssembler::CaseInsensitiveCompareUC16()
935   static ExternalReference re_case_insensitive_compare_uc16(Isolate* isolate);
936
937   // Function RegExpMacroAssembler*::CheckStackGuardState()
938   static ExternalReference re_check_stack_guard_state(Isolate* isolate);
939
940   // Function NativeRegExpMacroAssembler::GrowStack()
941   static ExternalReference re_grow_stack(Isolate* isolate);
942
943   // byte NativeRegExpMacroAssembler::word_character_bitmap
944   static ExternalReference re_word_character_map();
945
946 #endif
947
948   // This lets you register a function that rewrites all external references.
949   // Used by the ARM simulator to catch calls to external references.
950   static void set_redirector(Isolate* isolate,
951                              ExternalReferenceRedirector* redirector) {
952     // We can't stack them.
953     ASSERT(isolate->external_reference_redirector() == NULL);
954     isolate->set_external_reference_redirector(
955         reinterpret_cast<ExternalReferenceRedirectorPointer*>(redirector));
956   }
957
958   static ExternalReference stress_deopt_count(Isolate* isolate);
959
960   bool operator==(const ExternalReference& other) const {
961     return address_ == other.address_;
962   }
963
964   bool operator!=(const ExternalReference& other) const {
965     return !(*this == other);
966   }
967
968  private:
969   explicit ExternalReference(void* address)
970       : address_(address) {}
971
972   static void* Redirect(Isolate* isolate,
973                         void* address,
974                         Type type = ExternalReference::BUILTIN_CALL) {
975     ExternalReferenceRedirector* redirector =
976         reinterpret_cast<ExternalReferenceRedirector*>(
977             isolate->external_reference_redirector());
978     if (redirector == NULL) return address;
979     void* answer = (*redirector)(address, type);
980     return answer;
981   }
982
983   static void* Redirect(Isolate* isolate,
984                         Address address_arg,
985                         Type type = ExternalReference::BUILTIN_CALL) {
986     ExternalReferenceRedirector* redirector =
987         reinterpret_cast<ExternalReferenceRedirector*>(
988             isolate->external_reference_redirector());
989     void* address = reinterpret_cast<void*>(address_arg);
990     void* answer = (redirector == NULL) ?
991                    address :
992                    (*redirector)(address, type);
993     return answer;
994   }
995
996   void* address_;
997 };
998
999
1000 // -----------------------------------------------------------------------------
1001 // Position recording support
1002
1003 struct PositionState {
1004   PositionState() : current_position(RelocInfo::kNoPosition),
1005                     written_position(RelocInfo::kNoPosition),
1006                     current_statement_position(RelocInfo::kNoPosition),
1007                     written_statement_position(RelocInfo::kNoPosition) {}
1008
1009   int current_position;
1010   int written_position;
1011
1012   int current_statement_position;
1013   int written_statement_position;
1014 };
1015
1016
1017 class PositionsRecorder BASE_EMBEDDED {
1018  public:
1019   explicit PositionsRecorder(Assembler* assembler)
1020       : assembler_(assembler) {
1021 #ifdef ENABLE_GDB_JIT_INTERFACE
1022     gdbjit_lineinfo_ = NULL;
1023 #endif
1024     jit_handler_data_ = NULL;
1025   }
1026
1027 #ifdef ENABLE_GDB_JIT_INTERFACE
1028   ~PositionsRecorder() {
1029     delete gdbjit_lineinfo_;
1030   }
1031
1032   void StartGDBJITLineInfoRecording() {
1033     if (FLAG_gdbjit) {
1034       gdbjit_lineinfo_ = new GDBJITLineInfo();
1035     }
1036   }
1037
1038   GDBJITLineInfo* DetachGDBJITLineInfo() {
1039     GDBJITLineInfo* lineinfo = gdbjit_lineinfo_;
1040     gdbjit_lineinfo_ = NULL;  // To prevent deallocation in destructor.
1041     return lineinfo;
1042   }
1043 #endif
1044   void AttachJITHandlerData(void* user_data) {
1045     jit_handler_data_ = user_data;
1046   }
1047
1048   void* DetachJITHandlerData() {
1049     void* old_data = jit_handler_data_;
1050     jit_handler_data_ = NULL;
1051     return old_data;
1052   }
1053   // Set current position to pos.
1054   void RecordPosition(int pos);
1055
1056   // Set current statement position to pos.
1057   void RecordStatementPosition(int pos);
1058
1059   // Write recorded positions to relocation information.
1060   bool WriteRecordedPositions();
1061
1062   int current_position() const { return state_.current_position; }
1063
1064   int current_statement_position() const {
1065     return state_.current_statement_position;
1066   }
1067
1068  private:
1069   Assembler* assembler_;
1070   PositionState state_;
1071 #ifdef ENABLE_GDB_JIT_INTERFACE
1072   GDBJITLineInfo* gdbjit_lineinfo_;
1073 #endif
1074
1075   // Currently jit_handler_data_ is used to store JITHandler-specific data
1076   // over the lifetime of a PositionsRecorder
1077   void* jit_handler_data_;
1078   friend class PreservePositionScope;
1079
1080   DISALLOW_COPY_AND_ASSIGN(PositionsRecorder);
1081 };
1082
1083
1084 class PreservePositionScope BASE_EMBEDDED {
1085  public:
1086   explicit PreservePositionScope(PositionsRecorder* positions_recorder)
1087       : positions_recorder_(positions_recorder),
1088         saved_state_(positions_recorder->state_) {}
1089
1090   ~PreservePositionScope() {
1091     positions_recorder_->state_ = saved_state_;
1092   }
1093
1094  private:
1095   PositionsRecorder* positions_recorder_;
1096   const PositionState saved_state_;
1097
1098   DISALLOW_COPY_AND_ASSIGN(PreservePositionScope);
1099 };
1100
1101
1102 // -----------------------------------------------------------------------------
1103 // Utility functions
1104
1105 inline int NumberOfBitsSet(uint32_t x) {
1106   unsigned int num_bits_set;
1107   for (num_bits_set = 0; x; x >>= 1) {
1108     num_bits_set += x & 1;
1109   }
1110   return num_bits_set;
1111 }
1112
1113 bool EvalComparison(Token::Value op, double op1, double op2);
1114
1115 // Computes pow(x, y) with the special cases in the spec for Math.pow.
1116 double power_helper(double x, double y);
1117 double power_double_int(double x, int y);
1118 double power_double_double(double x, double y);
1119
1120 // Helper class for generating code or data associated with the code
1121 // right after a call instruction. As an example this can be used to
1122 // generate safepoint data after calls for crankshaft.
1123 class CallWrapper {
1124  public:
1125   CallWrapper() { }
1126   virtual ~CallWrapper() { }
1127   // Called just before emitting a call. Argument is the size of the generated
1128   // call code.
1129   virtual void BeforeCall(int call_size) const = 0;
1130   // Called just after emitting a call, i.e., at the return site for the call.
1131   virtual void AfterCall() const = 0;
1132 };
1133
1134 class NullCallWrapper : public CallWrapper {
1135  public:
1136   NullCallWrapper() { }
1137   virtual ~NullCallWrapper() { }
1138   virtual void BeforeCall(int call_size) const { }
1139   virtual void AfterCall() const { }
1140 };
1141
1142
1143 // The multiplier and shift for signed division via multiplication, see Warren's
1144 // "Hacker's Delight", chapter 10.
1145 class MultiplierAndShift {
1146  public:
1147   explicit MultiplierAndShift(int32_t d);
1148   int32_t multiplier() const { return multiplier_; }
1149   int32_t shift() const { return shift_; }
1150
1151  private:
1152   int32_t multiplier_;
1153   int32_t shift_;
1154 };
1155
1156
1157 } }  // namespace v8::internal
1158
1159 #endif  // V8_ASSEMBLER_H_