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