1 // Copyright (c) 2012 The Chromium 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 BASE_COMPILER_SPECIFIC_H_
6 #define BASE_COMPILER_SPECIFIC_H_
8 #include "build/build_config.h"
10 #if defined(COMPILER_MSVC) && !defined(__clang__)
11 #error "Only clang-cl is supported on Windows, see https://crbug.com/988071"
14 // This is a wrapper around `__has_cpp_attribute`, which can be used to test for
15 // the presence of an attribute. In case the compiler does not support this
16 // macro it will simply evaluate to 0.
19 // https://wg21.link/sd6#testing-for-the-presence-of-an-attribute-__has_cpp_attribute
20 // https://wg21.link/cpp.cond#:__has_cpp_attribute
21 #if defined(__has_cpp_attribute)
22 #define HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
24 #define HAS_CPP_ATTRIBUTE(x) 0
27 // A wrapper around `__has_builtin`, similar to HAS_CPP_ATTRIBUTE.
28 #if defined(__has_builtin)
29 #define HAS_BUILTIN(x) __has_builtin(x)
31 #define HAS_BUILTIN(x) 0
34 // Annotate a variable indicating it's ok if the variable is not used.
35 // (Typically used to silence a compiler warning when the assignment
36 // is important for some other reason.)
39 // ALLOW_UNUSED_LOCAL(x);
40 #define ALLOW_UNUSED_LOCAL(x) (void)x
42 // Annotate a typedef or function indicating it's ok if it's not used.
44 // typedef Foo Bar ALLOW_UNUSED_TYPE;
45 #if defined(COMPILER_GCC) || defined(__clang__)
46 #define ALLOW_UNUSED_TYPE __attribute__((unused))
48 #define ALLOW_UNUSED_TYPE
51 // Annotate a function indicating it should not be inlined.
53 // NOINLINE void DoStuff() { ... }
54 #if defined(COMPILER_GCC)
55 #define NOINLINE __attribute__((noinline))
56 #elif defined(COMPILER_MSVC)
57 #define NOINLINE __declspec(noinline)
62 #if defined(COMPILER_GCC) && defined(NDEBUG)
63 #define ALWAYS_INLINE inline __attribute__((__always_inline__))
64 #elif defined(COMPILER_MSVC) && defined(NDEBUG)
65 #define ALWAYS_INLINE __forceinline
67 #define ALWAYS_INLINE inline
70 // Annotate a function indicating it should never be tail called. Useful to make
71 // sure callers of the annotated function are never omitted from call-stacks.
72 // To provide the complementary behavior (prevent the annotated function from
73 // being omitted) look at NOINLINE. Also note that this doesn't prevent code
74 // folding of multiple identical caller functions into a single signature. To
75 // prevent code folding, see NO_CODE_FOLDING() in base/debug/alias.h.
77 // void NOT_TAIL_CALLED FooBar();
78 #if defined(__clang__) && __has_attribute(not_tail_called)
79 #define NOT_TAIL_CALLED __attribute__((not_tail_called))
81 #define NOT_TAIL_CALLED
84 // Specify memory alignment for structs, classes, etc.
86 // class ALIGNAS(16) MyClass { ... }
87 // ALIGNAS(16) int array[4];
89 // In most places you can use the C++11 keyword "alignas", which is preferred.
91 // But compilers have trouble mixing __attribute__((...)) syntax with
92 // alignas(...) syntax.
94 // Doesn't work in clang or gcc:
95 // struct alignas(16) __attribute__((packed)) S { char c; };
96 // Works in clang but not gcc:
97 // struct __attribute__((packed)) alignas(16) S2 { char c; };
98 // Works in clang and gcc:
99 // struct alignas(16) S3 { char c; } __attribute__((packed));
101 // There are also some attributes that must be specified *before* a class
102 // definition: visibility (used for exporting functions/classes) is one of
103 // these attributes. This means that it is not possible to use alignas() with a
104 // class that is marked as exported.
105 #if defined(COMPILER_MSVC)
106 #define ALIGNAS(byte_alignment) __declspec(align(byte_alignment))
107 #elif defined(COMPILER_GCC)
108 #define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
111 // Annotate a function indicating the caller must examine the return value.
113 // int foo() WARN_UNUSED_RESULT;
114 // To explicitly ignore a result, see |ignore_result()| in base/macros.h.
115 #undef WARN_UNUSED_RESULT
116 #if defined(COMPILER_GCC) || defined(__clang__)
117 #define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
119 #define WARN_UNUSED_RESULT
122 // In case the compiler supports it NO_UNIQUE_ADDRESS evaluates to the C++20
123 // attribute [[no_unique_address]]. This allows annotating data members so that
124 // they need not have an address distinct from all other non-static data members
128 // * https://en.cppreference.com/w/cpp/language/attributes/no_unique_address
129 // * https://wg21.link/dcl.attr.nouniqueaddr
130 #if HAS_CPP_ATTRIBUTE(no_unique_address)
131 #define NO_UNIQUE_ADDRESS [[no_unique_address]]
133 #define NO_UNIQUE_ADDRESS
136 // Tell the compiler a function is using a printf-style format string.
137 // |format_param| is the one-based index of the format string parameter;
138 // |dots_param| is the one-based index of the "..." parameter.
139 // For v*printf functions (which take a va_list), pass 0 for dots_param.
140 // (This is undocumented but matches what the system C headers do.)
141 // For member functions, the implicit this parameter counts as index 1.
142 #if defined(COMPILER_GCC) || defined(__clang__)
143 #define PRINTF_FORMAT(format_param, dots_param) \
144 __attribute__((format(printf, format_param, dots_param)))
146 #define PRINTF_FORMAT(format_param, dots_param)
149 // WPRINTF_FORMAT is the same, but for wide format strings.
150 // This doesn't appear to yet be implemented in any compiler.
151 // See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38308 .
152 #define WPRINTF_FORMAT(format_param, dots_param)
153 // If available, it would look like:
154 // __attribute__((format(wprintf, format_param, dots_param)))
156 // Sanitizers annotations.
157 #if defined(__has_attribute)
158 #if __has_attribute(no_sanitize)
159 #define NO_SANITIZE(what) __attribute__((no_sanitize(what)))
162 #if !defined(NO_SANITIZE)
163 #define NO_SANITIZE(what)
166 // MemorySanitizer annotations.
167 #if defined(MEMORY_SANITIZER) && !defined(OS_NACL)
168 #include <sanitizer/msan_interface.h>
170 // Mark a memory region fully initialized.
171 // Use this to annotate code that deliberately reads uninitialized data, for
172 // example a GC scavenging root set pointers from the stack.
173 #define MSAN_UNPOISON(p, size) __msan_unpoison(p, size)
175 // Check a memory region for initializedness, as if it was being used here.
176 // If any bits are uninitialized, crash with an MSan report.
177 // Use this to sanitize data which MSan won't be able to track, e.g. before
178 // passing data to another process via shared memory.
179 #define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) \
180 __msan_check_mem_is_initialized(p, size)
181 #else // MEMORY_SANITIZER
182 #define MSAN_UNPOISON(p, size)
183 #define MSAN_CHECK_MEM_IS_INITIALIZED(p, size)
184 #endif // MEMORY_SANITIZER
186 // DISABLE_CFI_PERF -- Disable Control Flow Integrity for perf reasons.
187 #if !defined(DISABLE_CFI_PERF)
188 #if defined(__clang__) && defined(OFFICIAL_BUILD)
189 #define DISABLE_CFI_PERF __attribute__((no_sanitize("cfi")))
191 #define DISABLE_CFI_PERF
195 // DISABLE_CFI_ICALL -- Disable Control Flow Integrity indirect call checks.
196 #if !defined(DISABLE_CFI_ICALL)
198 // Windows also needs __declspec(guard(nocf)).
199 #define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall") __declspec(guard(nocf))
201 #define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall")
204 #if !defined(DISABLE_CFI_ICALL)
205 #define DISABLE_CFI_ICALL
208 // Macro useful for writing cross-platform function pointers.
211 #define CDECL __cdecl
212 #else // defined(OS_WIN)
214 #endif // defined(OS_WIN)
215 #endif // !defined(CDECL)
217 // Macro for hinting that an expression is likely to be false.
218 #if !defined(UNLIKELY)
219 #if defined(COMPILER_GCC) || defined(__clang__)
220 #define UNLIKELY(x) __builtin_expect(!!(x), 0)
222 #define UNLIKELY(x) (x)
223 #endif // defined(COMPILER_GCC)
224 #endif // !defined(UNLIKELY)
227 #if defined(COMPILER_GCC) || defined(__clang__)
228 #define LIKELY(x) __builtin_expect(!!(x), 1)
230 #define LIKELY(x) (x)
231 #endif // defined(COMPILER_GCC)
232 #endif // !defined(LIKELY)
234 // Compiler feature-detection.
235 // clang.llvm.org/docs/LanguageExtensions.html#has-feature-and-has-extension
236 #if defined(__has_feature)
237 #define HAS_FEATURE(FEATURE) __has_feature(FEATURE)
239 #define HAS_FEATURE(FEATURE) 0
242 // Macro for telling -Wimplicit-fallthrough that a fallthrough is intentional.
243 #if defined(__clang__)
244 #define FALLTHROUGH [[clang::fallthrough]]
249 #if defined(COMPILER_GCC)
250 #define PRETTY_FUNCTION __PRETTY_FUNCTION__
251 #elif defined(COMPILER_MSVC)
252 #define PRETTY_FUNCTION __FUNCSIG__
254 // See https://en.cppreference.com/w/c/language/function_definition#func
255 #define PRETTY_FUNCTION __func__
258 #if !defined(CPU_ARM_NEON)
260 #if !defined(__ARMEB__) && !defined(__ARM_EABI__) && !defined(__EABI__) && \
261 !defined(__VFP_FP__) && !defined(_WIN32_WCE) && !defined(ANDROID)
262 #error Chromium does not support middle endian architecture
264 #if defined(__ARM_NEON__)
265 #define CPU_ARM_NEON 1
267 #endif // defined(__arm__)
268 #endif // !defined(CPU_ARM_NEON)
270 #if !defined(HAVE_MIPS_MSA_INTRINSICS)
271 #if defined(__mips_msa) && defined(__mips_isa_rev) && (__mips_isa_rev >= 5)
272 #define HAVE_MIPS_MSA_INTRINSICS 1
276 #if defined(__clang__) && __has_attribute(uninitialized)
277 // Attribute "uninitialized" disables -ftrivial-auto-var-init=pattern for
278 // the specified variable.
279 // Library-wide alternative is
280 // 'configs -= [ "//build/config/compiler:default_init_stack_vars" ]' in .gn
283 // See "init_stack_vars" in build/config/compiler/BUILD.gn and
284 // http://crbug.com/977230
285 // "init_stack_vars" is enabled for non-official builds and we hope to enable it
286 // in official build in 2020 as well. The flag writes fixed pattern into
287 // uninitialized parts of all local variables. In rare cases such initialization
288 // is undesirable and attribute can be used:
289 // 1. Degraded performance
290 // In most cases compiler is able to remove additional stores. E.g. if memory is
291 // never accessed or properly initialized later. Preserved stores mostly will
292 // not affect program performance. However if compiler failed on some
293 // performance critical code we can get a visible regression in a benchmark.
294 // 2. memset, memcpy calls
295 // Compiler may replaces some memory writes with memset or memcpy calls. This is
296 // not -ftrivial-auto-var-init specific, but it can happen more likely with the
297 // flag. It can be a problem if code is not linked with C run-time library.
299 // Note: The flag is security risk mitigation feature. So in future the
300 // attribute uses should be avoided when possible. However to enable this
301 // mitigation on the most of the code we need to be less strict now and minimize
302 // number of exceptions later. So if in doubt feel free to use attribute, but
303 // please document the problem for someone who is going to cleanup it later.
304 // E.g. platform, bot, benchmark or test name in patch description or next to
306 #define STACK_UNINITIALIZED __attribute__((uninitialized))
308 #define STACK_UNINITIALIZED
311 // Attribute "no_stack_protector" disables -fstack-protector for the specified
314 // "stack_protector" is enabled on most POSIX builds. The flag adds a canary
315 // to each stack frame, which on function return is checked against a reference
316 // canary. If the canaries do not match, it's likely that a stack buffer
317 // overflow has occurred, so immediately crashing will prevent exploitation in
320 // In some cases it's desirable to remove this, e.g. on hot functions, or if
321 // we have purposely changed the reference canary.
322 #if defined(COMPILER_GCC) || defined(__clang__)
323 #if defined(__has_attribute)
324 #if __has_attribute(__no_stack_protector__)
325 #define NO_STACK_PROTECTOR __attribute__((__no_stack_protector__))
326 #else // __has_attribute(__no_stack_protector__)
327 #define NO_STACK_PROTECTOR __attribute__((__optimize__("-fno-stack-protector")))
329 #else // defined(__has_attribute)
330 #define NO_STACK_PROTECTOR __attribute__((__optimize__("-fno-stack-protector")))
333 #define NO_STACK_PROTECTOR
336 // The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints
337 // to Clang which control what code paths are statically analyzed,
338 // and is meant to be used in conjunction with assert & assert-like functions.
339 // The expression is passed straight through if analysis isn't enabled.
341 // ANALYZER_SKIP_THIS_PATH() suppresses static analysis for the current
342 // codepath and any other branching codepaths that might follow.
343 #if defined(__clang_analyzer__)
345 inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
349 inline constexpr bool AnalyzerAssumeTrue(bool arg) {
350 // AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is
352 return arg || AnalyzerNoReturn();
355 #define ANALYZER_ASSUME_TRUE(arg) ::AnalyzerAssumeTrue(!!(arg))
356 #define ANALYZER_SKIP_THIS_PATH() static_cast<void>(::AnalyzerNoReturn())
357 #define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
359 #else // !defined(__clang_analyzer__)
361 #define ANALYZER_ASSUME_TRUE(arg) (arg)
362 #define ANALYZER_SKIP_THIS_PATH()
363 #define ANALYZER_ALLOW_UNUSED(var) static_cast<void>(var);
365 #endif // defined(__clang_analyzer__)
367 // Use nomerge attribute to disable optimization of merging multiple same calls.
368 // FIXME(M94) Need to remove OS_TIZEN macro
369 #if defined(__clang__) && __has_attribute(nomerge) && !defined(OS_TIZEN)
370 #define NOMERGE [[clang::nomerge]]
375 // Marks a type as being eligible for the "trivial" ABI despite having a
376 // non-trivial destructor or copy/move constructor. Such types can be relocated
377 // after construction by simply copying their memory, which makes them eligible
378 // to be passed in registers. The canonical example is std::unique_ptr.
380 // Use with caution; this has some subtle effects on constructor/destructor
381 // ordering and will be very incorrect if the type relies on its address
382 // remaining constant. When used as a function argument (by value), the value
383 // may be constructed in the caller's stack frame, passed in a register, and
384 // then used and destructed in the callee's stack frame. A similar thing can
385 // occur when values are returned.
387 // TRIVIAL_ABI is not needed for types which have a trivial destructor and
388 // copy/move constructors, such as base::TimeTicks and other POD.
390 // It is also not likely to be effective on types too large to be passed in one
391 // or two registers on typical target ABIs.
394 // https://clang.llvm.org/docs/AttributeReference.html#trivial-abi
395 // https://libcxx.llvm.org/docs/DesignDocs/UniquePtrTrivialAbi.html
396 #if defined(__clang__) && __has_attribute(trivial_abi)
397 #define TRIVIAL_ABI [[clang::trivial_abi]]
402 // Marks a member function as reinitializing a moved-from variable.
404 // https://clang.llvm.org/extra/clang-tidy/checks/bugprone-use-after-move.html#reinitialization
405 #if defined(__clang__) && __has_attribute(reinitializes)
406 #define REINITIALIZES_AFTER_MOVE [[clang::reinitializes]]
408 #define REINITIALIZES_AFTER_MOVE
411 // Requires constant initialization. See constinit in C++20. Allows to rely on a
412 // variable being initialized before execution, and not requiring a global
414 #if defined(__has_attribute)
415 #if __has_attribute(require_constant_initialization)
416 #define CONSTINIT __attribute__((require_constant_initialization))
419 #if !defined(CONSTINIT)
423 #endif // BASE_COMPILER_SPECIFIC_H_