Pyrogenesis  13997
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
code_annotation.h
Go to the documentation of this file.
1 /* Copyright (c) 2013 Wildfire Games
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining
4  * a copy of this software and associated documentation files (the
5  * "Software"), to deal in the Software without restriction, including
6  * without limitation the rights to use, copy, modify, merge, publish,
7  * distribute, sublicense, and/or sell copies of the Software, and to
8  * permit persons to whom the Software is furnished to do so, subject to
9  * the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included
12  * in all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21  */
22 
23 /*
24  * macros for code annotation.
25  */
26 
27 #ifndef INCLUDED_CODE_ANNOTATION
28 #define INCLUDED_CODE_ANNOTATION
29 
30 #include "lib/sysdep/compiler.h"
31 #include "lib/sysdep/arch.h" // ARCH_AMD64
32 
33 /**
34  * mark a function parameter as unused and avoid
35  * the corresponding compiler warning.
36  * wrap around the parameter name, e.g. void f(int UNUSED(x))
37  **/
38 #define UNUSED(param)
39 
40 /**
41  * mark a function local variable or parameter as unused and avoid
42  * the corresponding compiler warning.
43  * note that UNUSED is not applicable to variable definitions that
44  * involve initialization, nor is it sufficient in cases where
45  * an argument is unused only in certain situations.
46  * example: void f(int x) { ASSERT(x == 0); UNUSED2(x); }
47  * this asserts in debug builds and avoids warnings in release.
48  **/
49 #if HAVE_C99 && GCC_VERSION // _Pragma from C99, unused from GCC
50 # define UNUSED2(param) _Pragma("unused " #param)
51 #elif ICC_VERSION
52 // ICC 12 still doesn't recognize pragma unused, casting to void
53 // isn't sufficient, and self-assignment doesn't work for references.
54 # define UNUSED2(param) do{ if(&param) {} } while(false)
55 #else
56 # define UNUSED2(param) ((void)(param))
57 #endif
58 
59 
60 /**
61  * indicate a function will not throw any synchronous exceptions,
62  * thus hopefully generating smaller and more efficient code.
63  *
64  * must be placed BEFORE return types because "The [VC++] compiler
65  * ignores, without warning, any __declspec keywords placed after *".
66  * such syntax is apparently also legal in GCC, per the example
67  * "__attribute__((noreturn)) void d0 (void)".
68  *
69  * example:
70  * NOTHROW_DECLARE void function();
71  * NOTHROW_DEFINE void function() {}
72  **/
73 #if GCC_VERSION >= 303
74 # define NOTHROW_DECLARE __attribute__((nothrow))
75 # define NOTHROW_DEFINE // not supported for definitions
76 #elif MSC_VERSION
77 // Kevin Frei, 2006-03-23: "I work on the Visual C++ compiler team,
78 // and agree completely with Paul Parks: don't use throw(), because
79 // there's a chance that we'll eventually implement it according to the standard".
80 # define NOTHROW_DECLARE __declspec(nothrow)
81 # define NOTHROW_DEFINE __declspec(nothrow)
82 #else
83 // don't use throw() because it might result in ADDITIONAL checks
84 // (the standard mandates calling unexpected())
85 # define NOTHROW_DECLARE
86 # define NOTHROW_DEFINE
87 #endif
88 
89 
90 /**
91  * "unreachable code" helpers
92  *
93  * unreachable lines of code are often the source or symptom of subtle bugs.
94  * they are flagged by compiler warnings; however, the opposite problem -
95  * erroneously reaching certain spots (e.g. due to missing return statement)
96  * is worse and not detected automatically.
97  *
98  * to defend against this, the programmer can annotate their code to
99  * indicate to humans that a particular spot should never be reached.
100  * however, that isn't much help; better is a sentinel that raises an
101  * error if if it is actually reached. hence, the UNREACHABLE macro.
102  *
103  * ironically, if the code guarded by UNREACHABLE works as it should,
104  * compilers may flag the macro's code as unreachable. this would
105  * distract from genuine warnings, which is unacceptable.
106  *
107  * even worse, compilers differ in their code checking: GCC only complains if
108  * non-void functions end without returning a value (i.e. missing return
109  * statement), while VC checks if lines are unreachable (e.g. if they are
110  * preceded by a return on all paths).
111  *
112  * the implementation below enables optimization and automated checking
113  * without raising warnings.
114  **/
115 #define UNREACHABLE // actually defined below.. this is for
116 # undef UNREACHABLE // CppDoc's benefit only.
117 
118 // this macro should not generate any fallback code; it is merely the
119 // compiler-specific backend for UNREACHABLE.
120 // #define it to nothing if the compiler doesn't support such a hint.
121 #define HAVE_ASSUME_UNREACHABLE 1
122 #if MSC_VERSION && !ICC_VERSION // (ICC ignores this)
123 # define ASSUME_UNREACHABLE __assume(0)
124 #elif GCC_VERSION >= 450
125 # define ASSUME_UNREACHABLE __builtin_unreachable()
126 #else
127 # define ASSUME_UNREACHABLE
128 # undef HAVE_ASSUME_UNREACHABLE
129 # define HAVE_ASSUME_UNREACHABLE 0
130 #endif
131 
132 // compiler supports ASSUME_UNREACHABLE => allow it to assume the code is
133 // never reached (improves optimization at the cost of undefined behavior
134 // if the annotation turns out to be incorrect).
135 #if HAVE_ASSUME_UNREACHABLE && !CONFIG_ENABLE_CHECKS
136 # define UNREACHABLE ASSUME_UNREACHABLE
137 // otherwise (or if CONFIG_ENABLE_CHECKS is set), add a user-visible
138 // warning if the code is reached. note that abort() fails to stop
139 // ICC from warning about the lack of a return statement, so we
140 // use an infinite loop instead.
141 #else
142 # define UNREACHABLE\
143  STMT(\
144  DEBUG_WARN_ERR(ERR::LOGIC); /* hit supposedly unreachable code */\
145  for(;;){};\
146  )
147 #endif
148 
149 /**
150 convenient specialization of UNREACHABLE for switch statements whose
151 default can never be reached. example usage:
152 int x;
153 switch(x % 2)
154 {
155  case 0: break;
156  case 1: break;
157  NODEFAULT;
158 }
159 **/
160 #define NODEFAULT default: UNREACHABLE
161 
162 
163 // generate a symbol containing the line number of the macro invocation.
164 // used to give a unique name (per file) to types made by cassert.
165 // we can't prepend __FILE__ to make it globally unique - the filename
166 // may be enclosed in quotes. PASTE3_HIDDEN__ is needed to make sure
167 // __LINE__ is expanded correctly.
168 #define PASTE3_HIDDEN__(a, b, c) a ## b ## c
169 #define PASTE3__(a, b, c) PASTE3_HIDDEN__(a, b, c)
170 #define UID__ PASTE3__(LINE_, __LINE__, _)
171 #define UID2__ PASTE3__(LINE_, __LINE__, _2)
172 
173 
174 //-----------------------------------------------------------------------------
175 // cassert
176 
177 // Silence warnings about unused local typedefs
178 #if GCC_VERSION >= 408
179 # define UNUSED_ATTRIBUTE __attribute__((unused))
180 #else
181 # define UNUSED_ATTRIBUTE
182 #endif
183 
184 /**
185  * Compile-time assertion. Causes a compile error if the expression
186  * evaluates to zero/false.
187  *
188  * No runtime overhead; may be used anywhere, including file scope.
189  * Especially useful for testing sizeof types.
190  *
191  * @param expr Expression that is expected to evaluate to non-zero at compile-time.
192  **/
193 #define cassert(expr) typedef static_assert_<(expr)>::type UID__ UNUSED_ATTRIBUTE
194 template<bool> struct static_assert_;
195 template<> struct static_assert_<true>
196 {
197  typedef int type;
198 };
199 
200 /**
201  * @copydoc cassert(expr)
202  *
203  * This version must be used if expr uses a dependent type (e.g. depends on
204  * a template parameter).
205  **/
206 #define cassert_dependent(expr) typedef typename static_assert_<(expr)>::type UID__ UNUSED_ATTRIBUTE
207 
208 /**
209  * @copydoc cassert(expr)
210  *
211  * This version has a less helpful error message, but redefinition doesn't
212  * trigger warnings.
213  **/
214 #define cassert2(expr) extern char CASSERT_FAILURE[1][(expr)]
215 
216 
217 // indicate a class is noncopyable (usually due to const or reference members).
218 // example:
219 // class C {
220 // NONCOPYABLE(C);
221 // public: // etc.
222 // };
223 // this is preferable to inheritance from boost::noncopyable because it
224 // avoids ICC 11 W4 warnings about non-virtual dtors and suppression of
225 // the copy assignment operator.
226 #define NONCOPYABLE(className)\
227 private:\
228  className(const className&);\
229  const className& operator=(const className&)
230 
231 #if ICC_VERSION
232 # define ASSUME_ALIGNED(ptr, multiple) __assume_aligned(ptr, multiple)
233 #else
234 # define ASSUME_ALIGNED(ptr, multiple)
235 #endif
236 
237 // annotate printf-style functions for compile-time type checking.
238 // fmtpos is the index of the format argument, counting from 1 or
239 // (if it's a non-static class function) 2; the '...' is assumed
240 // to come directly after it.
241 #if GCC_VERSION
242 # define PRINTF_ARGS(fmtpos) __attribute__ ((format (printf, fmtpos, fmtpos+1)))
243 # define VPRINTF_ARGS(fmtpos) __attribute__ ((format (printf, fmtpos, 0)))
244 # if CONFIG_DEHYDRA
245 # define WPRINTF_ARGS(fmtpos) __attribute__ ((user("format, w, printf, " #fmtpos ", +1")))
246 # else
247 # define WPRINTF_ARGS(fmtpos) /* not currently supported in GCC */
248 # endif
249 # define VWPRINTF_ARGS(fmtpos) /* not currently supported in GCC */
250 #else
251 # define PRINTF_ARGS(fmtpos)
252 # define VPRINTF_ARGS(fmtpos)
253 # define WPRINTF_ARGS(fmtpos)
254 # define VWPRINTF_ARGS(fmtpos)
255 // TODO: support _Printf_format_string_ for VC9+
256 #endif
257 
258 // annotate vararg functions that expect to end with an explicit NULL
259 #if GCC_VERSION
260 # define SENTINEL_ARG __attribute__ ((sentinel))
261 #else
262 # define SENTINEL_ARG
263 #endif
264 
265 /**
266  * prevent the compiler from reordering loads or stores across this point.
267  **/
268 #if ICC_VERSION
269 # define COMPILER_FENCE __memory_barrier()
270 #elif MSC_VERSION
271 # include <intrin.h>
272 # pragma intrinsic(_ReadWriteBarrier)
273 # define COMPILER_FENCE _ReadWriteBarrier()
274 #elif GCC_VERSION
275 # define COMPILER_FENCE asm volatile("" : : : "memory")
276 #else
277 # define COMPILER_FENCE
278 #endif
279 
280 
281 // try to define _W64, if not already done
282 // (this is useful for catching pointer size bugs)
283 #ifndef _W64
284 # if MSC_VERSION
285 # define _W64 __w64
286 # elif GCC_VERSION
287 # define _W64 __attribute__((mode (__pointer__)))
288 # else
289 # define _W64
290 # endif
291 #endif
292 
293 
294 // C99-like restrict (non-standard in C++, but widely supported in various forms).
295 //
296 // May be used on pointers. May also be used on member functions to indicate
297 // that 'this' is unaliased (e.g. "void C::m() RESTRICT { ... }").
298 // Must not be used on references - GCC supports that but VC doesn't.
299 //
300 // We call this "RESTRICT" to avoid conflicts with VC's __declspec(restrict),
301 // and because it's not really the same as C99's restrict.
302 //
303 // To be safe and satisfy the compilers' stated requirements: an object accessed
304 // by a restricted pointer must not be accessed by any other pointer within the
305 // lifetime of the restricted pointer, if the object is modified.
306 // To maximise the chance of optimisation, any pointers that could potentially
307 // alias with the restricted one should be marked as restricted too.
308 //
309 // It would probably be a good idea to write test cases for any code that uses
310 // this in an even very slightly unclear way, in case it causes obscure problems
311 // in a rare compiler due to differing semantics.
312 //
313 // .. GCC
314 #if GCC_VERSION
315 # define RESTRICT __restrict__
316 // .. VC8 provides __restrict
317 #elif MSC_VERSION >= 1400
318 # define RESTRICT __restrict
319 // .. ICC supports the keyword 'restrict' when run with the /Qrestrict option,
320 // but it always also supports __restrict__ or __restrict to be compatible
321 // with GCC/MSVC, so we'll use the underscored version. One of {GCC,MSC}_VERSION
322 // should have been defined in addition to ICC_VERSION, so we should be using
323 // one of the above cases (unless it's an old VS7.1-emulating ICC).
324 #elif ICC_VERSION
325 # error ICC_VERSION defined without either GCC_VERSION or an adequate MSC_VERSION
326 // .. unsupported; remove it from code
327 #else
328 # define RESTRICT
329 #endif
330 
331 
332 //
333 // number of array elements
334 //
335 
336 #if GCC_VERSION
337 
338 // The function trick below does not work in GCC. Instead use the old fashioned
339 // divide-by-sizeof-element. This causes problems when the argument to
340 // ARRAY_SIZE is a pointer and not an array, but we will catch those when we
341 // compile on something other than GCC.
342 
343 #define ARRAY_SIZE(name) (sizeof(name) / (sizeof((name)[0])))
344 
345 #else
346 
347 // (function taking a reference to an array and returning a pointer to
348 // an array of characters. it's only declared and never defined; we just
349 // need it to determine n, the size of the array that was passed.)
350 template<typename T, size_t n> char (*ArraySizeDeducer(T (&)[n]))[n];
351 
352 // (although requiring C++, this method is much better than the standard
353 // sizeof(name) / sizeof(name[0]) because it doesn't compile when a
354 // pointer is passed, which can easily happen under maintenance.)
355 #define ARRAY_SIZE(name) (sizeof(*ArraySizeDeducer(name)))
356 
357 #endif // GCC_VERSION
358 
359 // C99-style __func__
360 // .. newer GCC already have it
361 #if GCC_VERSION >= 300
362 // nothing need be done
363 // .. old GCC and MSVC have __FUNCTION__
364 #elif GCC_VERSION >= 200 || MSC_VERSION
365 # define __func__ __FUNCTION__
366 // .. unsupported
367 #else
368 # define __func__ "(unknown)"
369 #endif
370 
371 
372 // extern "C", but does the right thing in pure-C mode
373 #if defined(__cplusplus)
374 # define EXTERN_C extern "C"
375 #else
376 # define EXTERN_C extern
377 #endif
378 
379 
380 #if MSC_VERSION
381 # define INLINE __forceinline
382 #else
383 # define INLINE inline
384 #endif
385 
386 
387 #if MSC_VERSION
388 # define CALL_CONV __cdecl
389 #else
390 # define CALL_CONV
391 #endif
392 
393 
394 #if MSC_VERSION && !ARCH_AMD64
395 # define DECORATED_NAME(name) _##name
396 #else
397 # define DECORATED_NAME(name) name
398 #endif
399 
400 
401 // workaround for preprocessor limitation: macro args aren't expanded
402 // before being pasted.
403 #define STRINGIZE2(id) # id
404 #define STRINGIZE(id) STRINGIZE2(id)
405 
406 // for widening non-literals (e.g. __FILE__)
407 // note: C99 says __func__ is a magic *variable*, and GCC doesn't allow
408 // widening it via preprocessor.
409 #define WIDEN2(x) L ## x
410 #define WIDEN(x) WIDEN2(x)
411 
412 
413 //-----------------------------------------------------------------------------
414 // C++0x rvalue references (required for UniqueRange)
415 
416 /**
417  * expands to the type `rvalue reference to T'; used in function
418  * parameter declarations. for example, UniqueRange's move ctor is:
419  * UniqueRange(RVALUE_REF(UniqueRange) rvalue) { ... }
420  **/
421 #define RVALUE_REF(T) T&&
422 
423 /**
424  * convert an rvalue to an lvalue
425  **/
426 #define LVALUE(rvalue) rvalue // in C++0x, a named rvalue reference is already an lvalue
427 
428 /**
429  * convert anything (lvalue or rvalue) to an rvalue
430  **/
431 #define RVALUE(lvalue) std::move(lvalue)
432 
433 
434 #if !HAVE_CPP0X // partial emulation
435 
436 // lvalue references are wrapped in this class, which is the
437 // actual argument passed to the "move ctor" etc.
438 template<typename T>
439 class RValue
440 {
441 public:
442  explicit RValue(T& lvalue): lvalue(lvalue) {}
443  T& LValue() const { return lvalue; }
444 
445 private:
446  // (avoid "assignment operator could not be generated" warning)
447  const RValue& operator=(const RValue&);
448 
450 };
451 
452 // (to deduce T automatically, we need function templates)
453 
454 template<class T>
455 static inline RValue<T> ToRValue(T& lvalue)
456 {
457  return RValue<T>(lvalue);
458 }
459 
460 template<class T>
461 static inline RValue<T> ToRValue(const T& lvalue)
462 {
463  return RValue<T>((T&)lvalue);
464 }
465 
466 template<class T>
467 static inline RValue<T> ToRValue(const RValue<T>& rvalue)
468 {
469  return RValue<T>(rvalue.LValue());
470 }
471 
472 #undef RVALUE_REF
473 #undef LVALUE
474 #undef RVALUE
475 
476 #define RVALUE_REF(T) const RValue<T>&
477 #define LVALUE(rvalue) rvalue.LValue()
478 #define RVALUE(lvalue) ToRValue(lvalue)
479 
480 #endif // #if !HAVE_CPP0X
481 
482 #endif // #ifndef INCLUDED_CODE_ANNOTATION
RValue(T &lvalue)
const RValue & operator=(const RValue &)
#define T(string_literal)
Definition: secure_crt.cpp:70
char(* ArraySizeDeducer(T(&)[n]))[n]
static RValue< T > ToRValue(T &lvalue)
T & LValue() const