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