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_V8GLOBALS_H_
29#define V8_V8GLOBALS_H_
30
31#include "globals.h"
32#include "checks.h"
33
34namespace v8 {
35namespace internal {
36
37// This file contains constants and global declarations related to the
38// V8 system.
39
40// Mask for the sign bit in a smi.
41const intptr_t kSmiSignMask = kIntptrSignBit;
42
43const int kObjectAlignmentBits = kPointerSizeLog2;
44const intptr_t kObjectAlignment = 1 << kObjectAlignmentBits;
45const intptr_t kObjectAlignmentMask = kObjectAlignment - 1;
46
47// Desired alignment for pointers.
48const intptr_t kPointerAlignment = (1 << kPointerSizeLog2);
49const intptr_t kPointerAlignmentMask = kPointerAlignment - 1;
50
51// Desired alignment for double values.
52const intptr_t kDoubleAlignment = 8;
53const intptr_t kDoubleAlignmentMask = kDoubleAlignment - 1;
54
55// Desired alignment for generated code is 32 bytes (to improve cache line
56// utilization).
57const int kCodeAlignmentBits = 5;
58const intptr_t kCodeAlignment = 1 << kCodeAlignmentBits;
59const intptr_t kCodeAlignmentMask = kCodeAlignment - 1;
60
61// Tag information for Failure.
62const int kFailureTag = 3;
63const int kFailureTagSize = 2;
64const intptr_t kFailureTagMask = (1 << kFailureTagSize) - 1;
65
66
67// Zap-value: The value used for zapping dead objects.
68// Should be a recognizable hex value tagged as a failure.
69#ifdef V8_HOST_ARCH_64_BIT
70const Address kZapValue =
71    reinterpret_cast<Address>(V8_UINT64_C(0xdeadbeedbeadbeef));
72const Address kHandleZapValue =
73    reinterpret_cast<Address>(V8_UINT64_C(0x1baddead0baddeaf));
74const Address kGlobalHandleZapValue =
75    reinterpret_cast<Address>(V8_UINT64_C(0x1baffed00baffedf));
76const Address kFromSpaceZapValue =
77    reinterpret_cast<Address>(V8_UINT64_C(0x1beefdad0beefdaf));
78const uint64_t kDebugZapValue = V8_UINT64_C(0xbadbaddbbadbaddb);
79const uint64_t kSlotsZapValue = V8_UINT64_C(0xbeefdeadbeefdeef);
80const uint64_t kFreeListZapValue = 0xfeed1eaffeed1eaf;
81#else
82const Address kZapValue = reinterpret_cast<Address>(0xdeadbeef);
83const Address kHandleZapValue = reinterpret_cast<Address>(0xbaddeaf);
84const Address kGlobalHandleZapValue = reinterpret_cast<Address>(0xbaffedf);
85const Address kFromSpaceZapValue = reinterpret_cast<Address>(0xbeefdaf);
86const uint32_t kSlotsZapValue = 0xbeefdeef;
87const uint32_t kDebugZapValue = 0xbadbaddb;
88const uint32_t kFreeListZapValue = 0xfeed1eaf;
89#endif
90
91const int kCodeZapValue = 0xbadc0de;
92
93// Number of bits to represent the page size for paged spaces. The value of 20
94// gives 1Mb bytes per page.
95const int kPageSizeBits = 20;
96
97// On Intel architecture, cache line size is 64 bytes.
98// On ARM it may be less (32 bytes), but as far this constant is
99// used for aligning data, it doesn't hurt to align on a greater value.
100#define PROCESSOR_CACHE_LINE_SIZE 64
101
102// Constants relevant to double precision floating point numbers.
103// If looking only at the top 32 bits, the QNaN mask is bits 19 to 30.
104const uint32_t kQuietNaNHighBitsMask = 0xfff << (51 - 32);
105
106
107// -----------------------------------------------------------------------------
108// Forward declarations for frequently used classes
109
110class AccessorInfo;
111class Allocation;
112class Arguments;
113class Assembler;
114class Code;
115class CodeGenerator;
116class CodeStub;
117class Context;
118class Debug;
119class Debugger;
120class DebugInfo;
121class Descriptor;
122class DescriptorArray;
123class TransitionArray;
124class ExternalReference;
125class FixedArray;
126class FunctionTemplateInfo;
127class MemoryChunk;
128class SeededNumberDictionary;
129class UnseededNumberDictionary;
130class NameDictionary;
131template <typename T> class Handle;
132class Heap;
133class HeapObject;
134class IC;
135class InterceptorInfo;
136class JSReceiver;
137class JSArray;
138class JSFunction;
139class JSObject;
140class LargeObjectSpace;
141class LookupResult;
142class MacroAssembler;
143class Map;
144class MapSpace;
145class MarkCompactCollector;
146class NewSpace;
147class Object;
148class MaybeObject;
149class OldSpace;
150class Foreign;
151class Scope;
152class ScopeInfo;
153class Script;
154class Smi;
155template <typename Config, class Allocator = FreeStoreAllocationPolicy>
156    class SplayTree;
157class String;
158class Name;
159class Struct;
160class Variable;
161class RelocInfo;
162class Deserializer;
163class MessageLocation;
164class VirtualMemory;
165class Mutex;
166class RecursiveMutex;
167
168typedef bool (*WeakSlotCallback)(Object** pointer);
169
170typedef bool (*WeakSlotCallbackWithHeap)(Heap* heap, Object** pointer);
171
172// -----------------------------------------------------------------------------
173// Miscellaneous
174
175// NOTE: SpaceIterator depends on AllocationSpace enumeration values being
176// consecutive.
177enum AllocationSpace {
178  NEW_SPACE,            // Semispaces collected with copying collector.
179  OLD_POINTER_SPACE,    // May contain pointers to new space.
180  OLD_DATA_SPACE,       // Must not have pointers to new space.
181  CODE_SPACE,           // No pointers to new space, marked executable.
182  MAP_SPACE,            // Only and all map objects.
183  CELL_SPACE,           // Only and all cell objects.
184  PROPERTY_CELL_SPACE,  // Only and all global property cell objects.
185  LO_SPACE,             // Promoted large objects.
186
187  FIRST_SPACE = NEW_SPACE,
188  LAST_SPACE = LO_SPACE,
189  FIRST_PAGED_SPACE = OLD_POINTER_SPACE,
190  LAST_PAGED_SPACE = PROPERTY_CELL_SPACE
191};
192const int kSpaceTagSize = 3;
193const int kSpaceTagMask = (1 << kSpaceTagSize) - 1;
194
195
196// A flag that indicates whether objects should be pretenured when
197// allocated (allocated directly into the old generation) or not
198// (allocated in the young generation if the object size and type
199// allows).
200enum PretenureFlag { NOT_TENURED, TENURED };
201
202enum MinimumCapacity {
203  USE_DEFAULT_MINIMUM_CAPACITY,
204  USE_CUSTOM_MINIMUM_CAPACITY
205};
206
207enum GarbageCollector { SCAVENGER, MARK_COMPACTOR };
208
209enum Executability { NOT_EXECUTABLE, EXECUTABLE };
210
211enum VisitMode {
212  VISIT_ALL,
213  VISIT_ALL_IN_SCAVENGE,
214  VISIT_ALL_IN_SWEEP_NEWSPACE,
215  VISIT_ONLY_STRONG
216};
217
218// Flag indicating whether code is built into the VM (one of the natives files).
219enum NativesFlag { NOT_NATIVES_CODE, NATIVES_CODE };
220
221
222// A CodeDesc describes a buffer holding instructions and relocation
223// information. The instructions start at the beginning of the buffer
224// and grow forward, the relocation information starts at the end of
225// the buffer and grows backward.
226//
227//  |<--------------- buffer_size ---------------->|
228//  |<-- instr_size -->|        |<-- reloc_size -->|
229//  +==================+========+==================+
230//  |   instructions   |  free  |    reloc info    |
231//  +==================+========+==================+
232//  ^
233//  |
234//  buffer
235
236struct CodeDesc {
237  byte* buffer;
238  int buffer_size;
239  int instr_size;
240  int reloc_size;
241  Assembler* origin;
242};
243
244
245// Callback function used for iterating objects in heap spaces,
246// for example, scanning heap objects.
247typedef int (*HeapObjectCallback)(HeapObject* obj);
248
249
250// Callback function used for checking constraints when copying/relocating
251// objects. Returns true if an object can be copied/relocated from its
252// old_addr to a new_addr.
253typedef bool (*ConstraintCallback)(Address new_addr, Address old_addr);
254
255
256// Callback function on inline caches, used for iterating over inline caches
257// in compiled code.
258typedef void (*InlineCacheCallback)(Code* code, Address ic);
259
260
261// State for inline cache call sites. Aliased as IC::State.
262enum InlineCacheState {
263  // Has never been executed.
264  UNINITIALIZED,
265  // Has been executed but monomorhic state has been delayed.
266  PREMONOMORPHIC,
267  // Has been executed and only one receiver type has been seen.
268  MONOMORPHIC,
269  // Like MONOMORPHIC but check failed due to prototype.
270  MONOMORPHIC_PROTOTYPE_FAILURE,
271  // Multiple receiver types have been seen.
272  POLYMORPHIC,
273  // Many receiver types have been seen.
274  MEGAMORPHIC,
275  // A generic handler is installed and no extra typefeedback is recorded.
276  GENERIC,
277  // Special state for debug break or step in prepare stubs.
278  DEBUG_STUB
279};
280
281
282enum CheckType {
283  RECEIVER_MAP_CHECK,
284  STRING_CHECK,
285  SYMBOL_CHECK,
286  NUMBER_CHECK,
287  BOOLEAN_CHECK
288};
289
290
291enum CallFunctionFlags {
292  NO_CALL_FUNCTION_FLAGS = 0,
293  // Receiver might implicitly be the global objects. If it is, the
294  // hole is passed to the call function stub.
295  RECEIVER_MIGHT_BE_IMPLICIT = 1 << 0,
296  // The call target is cached in the instruction stream.
297  RECORD_CALL_TARGET = 1 << 1
298};
299
300
301enum InlineCacheHolderFlag {
302  OWN_MAP,  // For fast properties objects.
303  PROTOTYPE_MAP  // For slow properties objects (except GlobalObjects).
304};
305
306
307// The Store Buffer (GC).
308typedef enum {
309  kStoreBufferFullEvent,
310  kStoreBufferStartScanningPagesEvent,
311  kStoreBufferScanningPageEvent
312} StoreBufferEvent;
313
314
315typedef void (*StoreBufferCallback)(Heap* heap,
316                                    MemoryChunk* page,
317                                    StoreBufferEvent event);
318
319
320// Union used for fast testing of specific double values.
321union DoubleRepresentation {
322  double  value;
323  int64_t bits;
324  DoubleRepresentation(double x) { value = x; }
325};
326
327
328// Union used for customized checking of the IEEE double types
329// inlined within v8 runtime, rather than going to the underlying
330// platform headers and libraries
331union IeeeDoubleLittleEndianArchType {
332  double d;
333  struct {
334    unsigned int man_low  :32;
335    unsigned int man_high :20;
336    unsigned int exp      :11;
337    unsigned int sign     :1;
338  } bits;
339};
340
341
342union IeeeDoubleBigEndianArchType {
343  double d;
344  struct {
345    unsigned int sign     :1;
346    unsigned int exp      :11;
347    unsigned int man_high :20;
348    unsigned int man_low  :32;
349  } bits;
350};
351
352
353// AccessorCallback
354struct AccessorDescriptor {
355  MaybeObject* (*getter)(Isolate* isolate, Object* object, void* data);
356  MaybeObject* (*setter)(
357      Isolate* isolate, JSObject* object, Object* value, void* data);
358  void* data;
359};
360
361
362// Logging and profiling.  A StateTag represents a possible state of
363// the VM. The logger maintains a stack of these. Creating a VMState
364// object enters a state by pushing on the stack, and destroying a
365// VMState object leaves a state by popping the current state from the
366// stack.
367
368enum StateTag {
369  JS,
370  GC,
371  COMPILER,
372  OTHER,
373  EXTERNAL,
374  IDLE
375};
376
377
378// -----------------------------------------------------------------------------
379// Macros
380
381// Testers for test.
382
383#define HAS_SMI_TAG(value) \
384  ((reinterpret_cast<intptr_t>(value) & kSmiTagMask) == kSmiTag)
385
386#define HAS_FAILURE_TAG(value) \
387  ((reinterpret_cast<intptr_t>(value) & kFailureTagMask) == kFailureTag)
388
389// OBJECT_POINTER_ALIGN returns the value aligned as a HeapObject pointer
390#define OBJECT_POINTER_ALIGN(value)                             \
391  (((value) + kObjectAlignmentMask) & ~kObjectAlignmentMask)
392
393// POINTER_SIZE_ALIGN returns the value aligned as a pointer.
394#define POINTER_SIZE_ALIGN(value)                               \
395  (((value) + kPointerAlignmentMask) & ~kPointerAlignmentMask)
396
397// CODE_POINTER_ALIGN returns the value aligned as a generated code segment.
398#define CODE_POINTER_ALIGN(value)                               \
399  (((value) + kCodeAlignmentMask) & ~kCodeAlignmentMask)
400
401// Support for tracking C++ memory allocation.  Insert TRACK_MEMORY("Fisk")
402// inside a C++ class and new and delete will be overloaded so logging is
403// performed.
404// This file (globals.h) is included before log.h, so we use direct calls to
405// the Logger rather than the LOG macro.
406#ifdef DEBUG
407#define TRACK_MEMORY(name) \
408  void* operator new(size_t size) { \
409    void* result = ::operator new(size); \
410    Logger::NewEventStatic(name, result, size); \
411    return result; \
412  } \
413  void operator delete(void* object) { \
414    Logger::DeleteEventStatic(name, object); \
415    ::operator delete(object); \
416  }
417#else
418#define TRACK_MEMORY(name)
419#endif
420
421
422// Feature flags bit positions. They are mostly based on the CPUID spec.
423// On X86/X64, values below 32 are bits in EDX, values above 32 are bits in ECX.
424enum CpuFeature { SSE4_1 = 32 + 19,  // x86
425                  SSE3 = 32 + 0,     // x86
426                  SSE2 = 26,   // x86
427                  CMOV = 15,   // x86
428                  VFP3 = 1,    // ARM
429                  ARMv7 = 2,   // ARM
430                  SUDIV = 3,   // ARM
431                  UNALIGNED_ACCESSES = 4,  // ARM
432                  MOVW_MOVT_IMMEDIATE_LOADS = 5,  // ARM
433                  VFP32DREGS = 6,  // ARM
434                  NEON = 7,    // ARM
435                  SAHF = 0,    // x86
436                  FPU = 1};    // MIPS
437
438
439// Used to specify if a macro instruction must perform a smi check on tagged
440// values.
441enum SmiCheckType {
442  DONT_DO_SMI_CHECK,
443  DO_SMI_CHECK
444};
445
446
447// Used to specify whether a receiver is implicitly or explicitly
448// provided to a call.
449enum CallKind {
450  CALL_AS_METHOD,
451  CALL_AS_FUNCTION
452};
453
454
455enum ScopeType {
456  EVAL_SCOPE,      // The top-level scope for an eval source.
457  FUNCTION_SCOPE,  // The top-level scope for a function.
458  MODULE_SCOPE,    // The scope introduced by a module literal
459  GLOBAL_SCOPE,    // The top-level scope for a program or a top-level eval.
460  CATCH_SCOPE,     // The scope introduced by catch.
461  BLOCK_SCOPE,     // The scope introduced by a new block.
462  WITH_SCOPE       // The scope introduced by with.
463};
464
465
466const uint32_t kHoleNanUpper32 = 0x7FFFFFFF;
467const uint32_t kHoleNanLower32 = 0xFFFFFFFF;
468const uint32_t kNaNOrInfinityLowerBoundUpper32 = 0x7FF00000;
469
470const uint64_t kHoleNanInt64 =
471    (static_cast<uint64_t>(kHoleNanUpper32) << 32) | kHoleNanLower32;
472const uint64_t kLastNonNaNInt64 =
473    (static_cast<uint64_t>(kNaNOrInfinityLowerBoundUpper32) << 32);
474
475
476// The order of this enum has to be kept in sync with the predicates below.
477enum VariableMode {
478  // User declared variables:
479  VAR,             // declared via 'var', and 'function' declarations
480
481  CONST,           // declared via 'const' declarations
482
483  LET,             // declared via 'let' declarations (first lexical)
484
485  CONST_HARMONY,   // declared via 'const' declarations in harmony mode
486
487  MODULE,          // declared via 'module' declaration (last lexical)
488
489  // Variables introduced by the compiler:
490  INTERNAL,        // like VAR, but not user-visible (may or may not
491                   // be in a context)
492
493  TEMPORARY,       // temporary variables (not user-visible), stack-allocated
494                   // unless the scope as a whole has forced context allocation
495
496  DYNAMIC,         // always require dynamic lookup (we don't know
497                   // the declaration)
498
499  DYNAMIC_GLOBAL,  // requires dynamic lookup, but we know that the
500                   // variable is global unless it has been shadowed
501                   // by an eval-introduced variable
502
503  DYNAMIC_LOCAL    // requires dynamic lookup, but we know that the
504                   // variable is local and where it is unless it
505                   // has been shadowed by an eval-introduced
506                   // variable
507};
508
509
510inline bool IsDynamicVariableMode(VariableMode mode) {
511  return mode >= DYNAMIC && mode <= DYNAMIC_LOCAL;
512}
513
514
515inline bool IsDeclaredVariableMode(VariableMode mode) {
516  return mode >= VAR && mode <= MODULE;
517}
518
519
520inline bool IsLexicalVariableMode(VariableMode mode) {
521  return mode >= LET && mode <= MODULE;
522}
523
524
525inline bool IsImmutableVariableMode(VariableMode mode) {
526  return mode == CONST || (mode >= CONST_HARMONY && mode <= MODULE);
527}
528
529
530// ES6 Draft Rev3 10.2 specifies declarative environment records with mutable
531// and immutable bindings that can be in two states: initialized and
532// uninitialized. In ES5 only immutable bindings have these two states. When
533// accessing a binding, it needs to be checked for initialization. However in
534// the following cases the binding is initialized immediately after creation
535// so the initialization check can always be skipped:
536// 1. Var declared local variables.
537//      var foo;
538// 2. A local variable introduced by a function declaration.
539//      function foo() {}
540// 3. Parameters
541//      function x(foo) {}
542// 4. Catch bound variables.
543//      try {} catch (foo) {}
544// 6. Function variables of named function expressions.
545//      var x = function foo() {}
546// 7. Implicit binding of 'this'.
547// 8. Implicit binding of 'arguments' in functions.
548//
549// ES5 specified object environment records which are introduced by ES elements
550// such as Program and WithStatement that associate identifier bindings with the
551// properties of some object. In the specification only mutable bindings exist
552// (which may be non-writable) and have no distinct initialization step. However
553// V8 allows const declarations in global code with distinct creation and
554// initialization steps which are represented by non-writable properties in the
555// global object. As a result also these bindings need to be checked for
556// initialization.
557//
558// The following enum specifies a flag that indicates if the binding needs a
559// distinct initialization step (kNeedsInitialization) or if the binding is
560// immediately initialized upon creation (kCreatedInitialized).
561enum InitializationFlag {
562  kNeedsInitialization,
563  kCreatedInitialized
564};
565
566
567enum ClearExceptionFlag {
568  KEEP_EXCEPTION,
569  CLEAR_EXCEPTION
570};
571
572
573enum MinusZeroMode {
574  TREAT_MINUS_ZERO_AS_ZERO,
575  FAIL_ON_MINUS_ZERO
576};
577
578} }  // namespace v8::internal
579
580#endif  // V8_V8GLOBALS_H_
581