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 // The expression OFFSET_OF(type, field) computes the byte-offset
19 // of the specified field relative to the containing type. This
20 // corresponds to 'offsetof' (in stddef.h), except that it doesn't
21 // use 0 or NULL, which causes a problem with the compiler warnings
22 // we have enabled (which is also why 'offsetof' doesn't seem to work).
23 // Here we simply use the non-zero value 4, which seems to work.
24 #define OFFSET_OF(type, field) \
25 (reinterpret_cast<intptr_t>(&(reinterpret_cast<type*>(4)->field)) - 4)
28 // ARRAYSIZE_UNSAFE performs essentially the same calculation as arraysize,
29 // but can be used on anonymous types or types defined inside
30 // functions. It's less safe than arraysize as it accepts some
31 // (although not all) pointers. Therefore, you should use arraysize
34 // The expression ARRAYSIZE_UNSAFE(a) is a compile-time constant of type
37 // ARRAYSIZE_UNSAFE catches a few type errors. If you see a compiler error
39 // "warning: division by zero in ..."
41 // when using ARRAYSIZE_UNSAFE, you are (wrongfully) giving it a pointer.
42 // You should only use ARRAYSIZE_UNSAFE on statically allocated arrays.
44 // The following comments are on the implementation details, and can
45 // be ignored by the users.
47 // ARRAYSIZE_UNSAFE(arr) works by inspecting sizeof(arr) (the # of bytes in
48 // the array) and sizeof(*(arr)) (the # of bytes in one array
49 // element). If the former is divisible by the latter, perhaps arr is
50 // indeed an array, in which case the division result is the # of
51 // elements in the array. Otherwise, arr cannot possibly be an array,
52 // and we generate a compiler error to prevent the code from
55 // Since the size of bool is implementation-defined, we need to cast
56 // !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
57 // result has type size_t.
59 // This macro is not perfect as it wrongfully accepts certain
60 // pointers, namely where the pointer size is divisible by the pointee
61 // size. Since all our code has to go through a 32-bit compiler,
62 // where a pointer is 4 bytes, this means all pointers to a type whose
63 // size is 3 or greater than 4 will be (righteously) rejected.
64 #define ARRAYSIZE_UNSAFE(a) \
65 ((sizeof(a) / sizeof(*(a))) / \
66 static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))) // NOLINT
71 // TODO(bmeurer): For some reason, the NaCl toolchain cannot handle the correct
72 // definition of arraysize() below, so we have to use the unsafe version for
74 #define arraysize ARRAYSIZE_UNSAFE
78 // The arraysize(arr) macro returns the # of elements in an array arr.
79 // The expression is a compile-time constant, and therefore can be
80 // used in defining new arrays, for example. If you use arraysize on
81 // a pointer by mistake, you will get a compile-time error.
83 // One caveat is that arraysize() doesn't accept any array of an
84 // anonymous type or a type defined inside a function. In these rare
85 // cases, you have to use the unsafe ARRAYSIZE_UNSAFE() macro below. This is
86 // due to a limitation in C++'s template system. The limitation might
87 // eventually be removed, but it hasn't happened yet.
88 #define arraysize(array) (sizeof(ArraySizeHelper(array)))
91 // This template function declaration is used in defining arraysize.
92 // Note that the function doesn't need an implementation, as we only
94 template <typename T, size_t N>
95 char (&ArraySizeHelper(T (&array)[N]))[N];
99 // That gcc wants both of these prototypes seems mysterious. VC, for
100 // its part, can't decide which to use (another mystery). Matching of
101 // template overloads: the final frontier.
102 template <typename T, size_t N>
103 char (&ArraySizeHelper(const T (&array)[N]))[N];
109 // The COMPILE_ASSERT macro can be used to verify that a compile time
110 // expression is true. For example, you could use it to verify the
111 // size of a static array:
113 // COMPILE_ASSERT(ARRAYSIZE_UNSAFE(content_type_names) == CONTENT_NUM_TYPES,
114 // content_type_names_incorrect_size);
116 // or to make sure a struct is smaller than a certain size:
118 // COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
120 // The second argument to the macro is the name of the variable. If
121 // the expression is false, most compilers will issue a warning/error
122 // containing the name of the variable.
123 #if V8_HAS_CXX11_STATIC_ASSERT
125 // Under C++11, just use static_assert.
126 #define COMPILE_ASSERT(expr, msg) static_assert(expr, #msg)
131 struct CompileAssert {};
133 #define COMPILE_ASSERT(expr, msg) \
134 typedef CompileAssert<static_cast<bool>(expr)> \
135 msg[static_cast<bool>(expr) ? 1 : -1] ALLOW_UNUSED_TYPE
137 // Implementation details of COMPILE_ASSERT:
139 // - COMPILE_ASSERT works by defining an array type that has -1
140 // elements (and thus is invalid) when the expression is false.
142 // - The simpler definition
144 // #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
146 // does not work, as gcc supports variable-length arrays whose sizes
147 // are determined at run-time (this is gcc's extension and not part
148 // of the C++ standard). As a result, gcc fails to reject the
149 // following code with the simple definition:
152 // COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
153 // // not a compile-time constant.
155 // - By using the type CompileAssert<static_cast<bool>(expr)>, we ensure that
156 // expr is a compile-time constant. (Template arguments must be
157 // determined at compile-time.)
159 // - The array size is (static_cast<bool>(expr) ? 1 : -1), instead of simply
161 // ((expr) ? 1 : -1).
163 // This is to avoid running into a bug in MS VC 7.1, which
164 // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
169 // bit_cast<Dest,Source> is a template function that implements the
170 // equivalent of "*reinterpret_cast<Dest*>(&source)". We need this in
171 // very low-level functions like the protobuf library and fast math
174 // float f = 3.14159265358979;
175 // int i = bit_cast<int32>(f);
178 // The classical address-casting method is:
181 // float f = 3.14159265358979; // WRONG
182 // int i = * reinterpret_cast<int*>(&f); // WRONG
184 // The address-casting method actually produces undefined behavior
185 // according to ISO C++ specification section 3.10 -15 -. Roughly, this
186 // section says: if an object in memory has one type, and a program
187 // accesses it with a different type, then the result is undefined
188 // behavior for most values of "different type".
190 // This is true for any cast syntax, either *(int*)&f or
191 // *reinterpret_cast<int*>(&f). And it is particularly true for
192 // conversions between integral lvalues and floating-point lvalues.
194 // The purpose of 3.10 -15- is to allow optimizing compilers to assume
195 // that expressions with different types refer to different memory. gcc
196 // 4.0.1 has an optimizer that takes advantage of this. So a
197 // non-conforming program quietly produces wildly incorrect output.
199 // The problem is not the use of reinterpret_cast. The problem is type
200 // punning: holding an object in memory of one type and reading its bits
201 // back using a different type.
203 // The C++ standard is more subtle and complex than this, but that
204 // is the basic idea.
208 // bit_cast<> calls memcpy() which is blessed by the standard,
209 // especially by the example in section 3.9 . Also, of course,
210 // bit_cast<> wraps up the nasty logic in one place.
212 // Fortunately memcpy() is very fast. In optimized mode, with a
213 // constant size, gcc 2.95.3, gcc 4.0.1, and msvc 7.1 produce inline
214 // code with the minimal amount of data movement. On a 32-bit system,
215 // memcpy(d,s,4) compiles to one load and one store, and memcpy(d,s,8)
216 // compiles to two loads and two stores.
218 // I tested this code with gcc 2.95.3, gcc 4.0.1, icc 8.1, and msvc 7.1.
220 // WARNING: if Dest or Source is a non-POD type, the result of the memcpy
221 // is likely to surprise you.
222 template <class Dest, class Source>
223 V8_INLINE Dest bit_cast(Source const& source) {
224 COMPILE_ASSERT(sizeof(Dest) == sizeof(Source), VerifySizesAreEqual);
227 memcpy(&dest, &source, sizeof(dest));
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&) V8_DELETE; \
236 void operator=(const TypeName&) V8_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() V8_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
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)
350 # define V8_PTR_PREFIX ""
353 #define V8PRIxPTR V8_PTR_PREFIX "x"
354 #define V8PRIdPTR V8_PTR_PREFIX "d"
355 #define V8PRIuPTR V8_PTR_PREFIX "u"
357 // Fix for Mac OS X defining uintptr_t as "unsigned long":
360 #define V8PRIxPTR "lx"
363 // The following macro works on both 32 and 64-bit platforms.
364 // Usage: instead of writing 0x1234567890123456
365 // write V8_2PART_UINT64_C(0x12345678,90123456);
366 #define V8_2PART_UINT64_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
369 // Compute the 0-relative offset of some absolute value x of type T.
370 // This allows conversion of Addresses and integral types into
371 // 0-relative int offsets.
372 template <typename T>
373 inline intptr_t OffsetFrom(T x) {
374 return x - static_cast<T>(0);
378 // Compute the absolute value of type T for some 0-relative offset x.
379 // This allows conversion of 0-relative int offsets into Addresses and
381 template <typename T>
382 inline T AddressFrom(intptr_t x) {
383 return static_cast<T>(static_cast<T>(0) + x);
387 // Return the largest multiple of m which is <= x.
388 template <typename T>
389 inline T RoundDown(T x, intptr_t m) {
390 DCHECK(IS_POWER_OF_TWO(m));
391 return AddressFrom<T>(OffsetFrom(x) & -m);
395 // Return the smallest multiple of m which is >= x.
396 template <typename T>
397 inline T RoundUp(T x, intptr_t m) {
398 return RoundDown<T>(static_cast<T>(x + m - 1), m);
401 #endif // V8_BASE_MACROS_H_