1 // Copyright 2014 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef V8_BASE_MACROS_H_
6 #define V8_BASE_MACROS_H_
13 #include "src/base/build_config.h"
14 #include "src/base/compiler-specific.h"
15 #include "src/base/logging.h"
18 // TODO(all) Replace all uses of this macro with C++'s offsetof. To do that, we
19 // have to make sure that only standard-layout types and simple field
20 // designators are used.
21 #define OFFSET_OF(type, field) \
22 (reinterpret_cast<intptr_t>(&(reinterpret_cast<type*>(16)->field)) - 16)
27 // ARRAYSIZE_UNSAFE performs essentially the same calculation as arraysize,
28 // but can be used on anonymous types or types defined inside
29 // functions. It's less safe than arraysize as it accepts some
30 // (although not all) pointers. Therefore, you should use arraysize
33 // The expression ARRAYSIZE_UNSAFE(a) is a compile-time constant of type
36 // ARRAYSIZE_UNSAFE catches a few type errors. If you see a compiler error
38 // "warning: division by zero in ..."
40 // when using ARRAYSIZE_UNSAFE, you are (wrongfully) giving it a pointer.
41 // You should only use ARRAYSIZE_UNSAFE on statically allocated arrays.
43 // The following comments are on the implementation details, and can
44 // be ignored by the users.
46 // ARRAYSIZE_UNSAFE(arr) works by inspecting sizeof(arr) (the # of bytes in
47 // the array) and sizeof(*(arr)) (the # of bytes in one array
48 // element). If the former is divisible by the latter, perhaps arr is
49 // indeed an array, in which case the division result is the # of
50 // elements in the array. Otherwise, arr cannot possibly be an array,
51 // and we generate a compiler error to prevent the code from
54 // Since the size of bool is implementation-defined, we need to cast
55 // !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
56 // result has type size_t.
58 // This macro is not perfect as it wrongfully accepts certain
59 // pointers, namely where the pointer size is divisible by the pointee
60 // size. Since all our code has to go through a 32-bit compiler,
61 // where a pointer is 4 bytes, this means all pointers to a type whose
62 // size is 3 or greater than 4 will be (righteously) rejected.
63 #define ARRAYSIZE_UNSAFE(a) \
64 ((sizeof(a) / sizeof(*(a))) / \
65 static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) // NOLINT
67 // TODO(bmeurer): For some reason, the NaCl toolchain cannot handle the correct
68 // definition of arraysize() below, so we have to use the unsafe version for
70 #define arraysize ARRAYSIZE_UNSAFE
74 // The arraysize(arr) macro returns the # of elements in an array arr.
75 // The expression is a compile-time constant, and therefore can be
76 // used in defining new arrays, for example. If you use arraysize on
77 // a pointer by mistake, you will get a compile-time error.
79 // One caveat is that arraysize() doesn't accept any array of an
80 // anonymous type or a type defined inside a function. In these rare
81 // cases, you have to use the unsafe ARRAYSIZE_UNSAFE() macro below. This is
82 // due to a limitation in C++'s template system. The limitation might
83 // eventually be removed, but it hasn't happened yet.
84 #define arraysize(array) (sizeof(ArraySizeHelper(array)))
87 // This template function declaration is used in defining arraysize.
88 // Note that the function doesn't need an implementation, as we only
90 template <typename T, size_t N>
91 char (&ArraySizeHelper(T (&array)[N]))[N];
95 // That gcc wants both of these prototypes seems mysterious. VC, for
96 // its part, can't decide which to use (another mystery). Matching of
97 // template overloads: the final frontier.
98 template <typename T, size_t N>
99 char (&ArraySizeHelper(const T (&array)[N]))[N];
105 // The COMPILE_ASSERT macro can be used to verify that a compile time
106 // expression is true. For example, you could use it to verify the
107 // size of a static array:
109 // COMPILE_ASSERT(ARRAYSIZE_UNSAFE(content_type_names) == CONTENT_NUM_TYPES,
110 // content_type_names_incorrect_size);
112 // or to make sure a struct is smaller than a certain size:
114 // COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
116 // The second argument to the macro is the name of the variable. If
117 // the expression is false, most compilers will issue a warning/error
118 // containing the name of the variable.
119 #if V8_HAS_CXX11_STATIC_ASSERT
121 // Under C++11, just use static_assert.
122 #define COMPILE_ASSERT(expr, msg) static_assert(expr, #msg)
127 struct CompileAssert {};
129 #define COMPILE_ASSERT(expr, msg) \
130 typedef CompileAssert<static_cast<bool>(expr)> \
131 msg[static_cast<bool>(expr) ? 1 : -1] ALLOW_UNUSED_TYPE
133 // Implementation details of COMPILE_ASSERT:
135 // - COMPILE_ASSERT works by defining an array type that has -1
136 // elements (and thus is invalid) when the expression is false.
138 // - The simpler definition
140 // #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
142 // does not work, as gcc supports variable-length arrays whose sizes
143 // are determined at run-time (this is gcc's extension and not part
144 // of the C++ standard). As a result, gcc fails to reject the
145 // following code with the simple definition:
148 // COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
149 // // not a compile-time constant.
151 // - By using the type CompileAssert<static_cast<bool>(expr)>, we ensure that
152 // expr is a compile-time constant. (Template arguments must be
153 // determined at compile-time.)
155 // - The array size is (static_cast<bool>(expr) ? 1 : -1), instead of simply
157 // ((expr) ? 1 : -1).
159 // This is to avoid running into a bug in MS VC 7.1, which
160 // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
165 // bit_cast<Dest,Source> is a template function that implements the
166 // equivalent of "*reinterpret_cast<Dest*>(&source)". We need this in
167 // very low-level functions like the protobuf library and fast math
170 // float f = 3.14159265358979;
171 // int i = bit_cast<int32>(f);
174 // The classical address-casting method is:
177 // float f = 3.14159265358979; // WRONG
178 // int i = * reinterpret_cast<int*>(&f); // WRONG
180 // The address-casting method actually produces undefined behavior
181 // according to ISO C++ specification section 3.10 -15 -. Roughly, this
182 // section says: if an object in memory has one type, and a program
183 // accesses it with a different type, then the result is undefined
184 // behavior for most values of "different type".
186 // This is true for any cast syntax, either *(int*)&f or
187 // *reinterpret_cast<int*>(&f). And it is particularly true for
188 // conversions between integral lvalues and floating-point lvalues.
190 // The purpose of 3.10 -15- is to allow optimizing compilers to assume
191 // that expressions with different types refer to different memory. gcc
192 // 4.0.1 has an optimizer that takes advantage of this. So a
193 // non-conforming program quietly produces wildly incorrect output.
195 // The problem is not the use of reinterpret_cast. The problem is type
196 // punning: holding an object in memory of one type and reading its bits
197 // back using a different type.
199 // The C++ standard is more subtle and complex than this, but that
200 // is the basic idea.
204 // bit_cast<> calls memcpy() which is blessed by the standard,
205 // especially by the example in section 3.9 . Also, of course,
206 // bit_cast<> wraps up the nasty logic in one place.
208 // Fortunately memcpy() is very fast. In optimized mode, with a
209 // constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline
210 // code with the minimal amount of data movement. On a 32-bit system,
211 // memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8)
212 // compiles to two loads and two stores.
214 // I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1.
216 // WARNING: if Dest or Source is a non-POD type, the result of the memcpy
217 // is likely to surprise you.
218 template <class Dest, class Source>
219 V8_INLINE Dest bit_cast(Source const& source) {
220 COMPILE_ASSERT(sizeof(Dest) == sizeof(Source), VerifySizesAreEqual);
223 memcpy(&dest, &source, sizeof(dest));
228 // Put this in the private: declarations for a class to be unassignable.
229 #define DISALLOW_ASSIGN(TypeName) void operator=(const TypeName&)
232 // A macro to disallow the evil copy constructor and operator= functions
233 // This should be used in the private: declarations for a class
234 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
235 TypeName(const TypeName&) = delete; \
236 void operator=(const TypeName&) = delete
239 // A macro to disallow all the implicit constructors, namely the
240 // default constructor, copy constructor and operator= functions.
242 // This should be used in the private: declarations for a class
243 // that wants to prevent anyone from instantiating it. This is
244 // especially useful for classes containing only static methods.
245 #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
246 TypeName() = delete; \
247 DISALLOW_COPY_AND_ASSIGN(TypeName)
250 // Newly written code should use V8_INLINE and V8_NOINLINE directly.
251 #define INLINE(declarator) V8_INLINE declarator
252 #define NO_INLINE(declarator) V8_NOINLINE declarator
255 // Newly written code should use WARN_UNUSED_RESULT.
256 #define MUST_USE_RESULT WARN_UNUSED_RESULT
259 // Define V8_USE_ADDRESS_SANITIZER macros.
260 #if defined(__has_feature)
261 #if __has_feature(address_sanitizer)
262 #define V8_USE_ADDRESS_SANITIZER 1
266 // Define DISABLE_ASAN macros.
267 #ifdef V8_USE_ADDRESS_SANITIZER
268 #define DISABLE_ASAN __attribute__((no_sanitize_address))
275 #define V8_IMMEDIATE_CRASH() __builtin_trap()
277 #define V8_IMMEDIATE_CRASH() ((void(*)())0)()
281 // Use C++11 static_assert if possible, which gives error
282 // messages that are easier to understand on first sight.
283 #if V8_HAS_CXX11_STATIC_ASSERT
284 #define STATIC_ASSERT(test) static_assert(test, #test)
286 // This is inspired by the static assertion facility in boost. This
287 // is pretty magical. If it causes you trouble on a platform you may
288 // find a fix in the boost code.
289 template <bool> class StaticAssertion;
290 template <> class StaticAssertion<true> { };
291 // This macro joins two tokens. If one of the tokens is a macro the
292 // helper call causes it to be resolved before joining.
293 #define SEMI_STATIC_JOIN(a, b) SEMI_STATIC_JOIN_HELPER(a, b)
294 #define SEMI_STATIC_JOIN_HELPER(a, b) a##b
295 // Causes an error during compilation of the condition is not
296 // statically known to be true. It is formulated as a typedef so that
297 // it can be used wherever a typedef can be used. Beware that this
298 // actually causes each use to introduce a new defined type with a
299 // name depending on the source line.
300 template <int> class StaticAssertionHelper { };
301 #define STATIC_ASSERT(test) \
302 typedef StaticAssertionHelper< \
303 sizeof(StaticAssertion<static_cast<bool>((test))>)> \
304 SEMI_STATIC_JOIN(__StaticAssertTypedef__, __LINE__) ALLOW_UNUSED_TYPE
309 // The USE(x) template is used to silence C++ compiler warnings
310 // issued for (yet) unused variables (typically parameters).
311 template <typename T>
312 inline void USE(T) { }
315 #define IS_POWER_OF_TWO(x) ((x) != 0 && (((x) & ((x) - 1)) == 0))
318 // Define our own macros for writing 64-bit constants. This is less fragile
319 // than defining __STDC_CONSTANT_MACROS before including <stdint.h>, and it
320 // works on compilers that don't have it (like MSVC).
322 # define V8_UINT64_C(x) (x ## UI64)
323 # define V8_INT64_C(x) (x ## I64)
324 # if V8_HOST_ARCH_64_BIT
325 # define V8_INTPTR_C(x) (x ## I64)
326 # define V8_PTR_PREFIX "ll"
328 # define V8_INTPTR_C(x) (x)
329 # define V8_PTR_PREFIX ""
330 # endif // V8_HOST_ARCH_64_BIT
332 # define V8_UINT64_C(x) (x ## ULL)
333 # define V8_INT64_C(x) (x ## LL)
334 # define V8_INTPTR_C(x) (x ## LL)
335 # define V8_PTR_PREFIX "I64"
336 #elif V8_HOST_ARCH_64_BIT
337 # if V8_OS_MACOSX || V8_OS_OPENBSD
338 # define V8_UINT64_C(x) (x ## ULL)
339 # define V8_INT64_C(x) (x ## LL)
341 # define V8_UINT64_C(x) (x ## UL)
342 # define V8_INT64_C(x) (x ## L)
344 # define V8_INTPTR_C(x) (x ## L)
345 # define V8_PTR_PREFIX "l"
347 # define V8_UINT64_C(x) (x ## ULL)
348 # define V8_INT64_C(x) (x ## LL)
349 # define V8_INTPTR_C(x) (x)
351 #define V8_PTR_PREFIX "l"
353 # define V8_PTR_PREFIX ""
357 #define V8PRIxPTR V8_PTR_PREFIX "x"
358 #define V8PRIdPTR V8_PTR_PREFIX "d"
359 #define V8PRIuPTR V8_PTR_PREFIX "u"
361 // Fix for Mac OS X defining uintptr_t as "unsigned long":
364 #define V8PRIxPTR "lx"
367 // The following macro works on both 32 and 64-bit platforms.
368 // Usage: instead of writing 0x1234567890123456
369 // write V8_2PART_UINT64_C(0x12345678,90123456);
370 #define V8_2PART_UINT64_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
373 // Compute the 0-relative offset of some absolute value x of type T.
374 // This allows conversion of Addresses and integral types into
375 // 0-relative int offsets.
376 template <typename T>
377 inline intptr_t OffsetFrom(T x) {
378 return x - static_cast<T>(0);
382 // Compute the absolute value of type T for some 0-relative offset x.
383 // This allows conversion of 0-relative int offsets into Addresses and
385 template <typename T>
386 inline T AddressFrom(intptr_t x) {
387 return static_cast<T>(static_cast<T>(0) + x);
391 // Return the largest multiple of m which is <= x.
392 template <typename T>
393 inline T RoundDown(T x, intptr_t m) {
394 DCHECK(IS_POWER_OF_TWO(m));
395 return AddressFrom<T>(OffsetFrom(x) & -m);
399 // Return the smallest multiple of m which is >= x.
400 template <typename T>
401 inline T RoundUp(T x, intptr_t m) {
402 return RoundDown<T>(static_cast<T>(x + m - 1), m);
409 // TODO(yangguo): This is a poor man's replacement for std::is_fundamental,
410 // which requires C++11. Switch to std::is_fundamental once possible.
411 template <typename T>
412 inline bool is_fundamental() {
417 inline bool is_fundamental<uint8_t>() {
424 #endif // V8_BASE_MACROS_H_