blob: 55e0278c6dbaf158bae04311553d65e8fe93a637 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
[email protected]f1ea2fa2008-08-21 22:26:064
5#ifndef BASE_COMPILER_SPECIFIC_H_
6#define BASE_COMPILER_SPECIFIC_H_
7
8#include "build/build_config.h"
9
Nico Weberfb053cc2020-03-03 13:33:0510#if defined(COMPILER_MSVC) && !defined(__clang__)
Nico Weber59791812019-07-27 04:02:1111#error "Only clang-cl is supported on Windows, see https://crbug.com/988071"
12#endif
13
Jan Wilken Dörrief8d479d2020-11-23 12:21:1314// 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.
17//
18// References:
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)
23#else
24#define HAS_CPP_ATTRIBUTE(x) 0
25#endif
26
Peter Kasting64c67dd2022-05-12 18:11:5127// A wrapper around `__has_attribute`, similar to HAS_CPP_ATTRIBUTE.
28#if defined(__has_attribute)
29#define HAS_ATTRIBUTE(x) __has_attribute(x)
30#else
31#define HAS_ATTRIBUTE(x) 0
32#endif
33
Jann Horn9e4b48552021-03-04 14:34:2734// A wrapper around `__has_builtin`, similar to HAS_CPP_ATTRIBUTE.
35#if defined(__has_builtin)
36#define HAS_BUILTIN(x) __has_builtin(x)
37#else
38#define HAS_BUILTIN(x) 0
39#endif
40
[email protected]2149cc622012-02-14 01:12:1241// Annotate a function indicating it should not be inlined.
42// Use like:
43// NOINLINE void DoStuff() { ... }
Peter Kastingf541f7782023-03-10 23:44:4644#if defined(__clang__) && HAS_ATTRIBUTE(noinline)
45#define NOINLINE [[clang::noinline]]
46#elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(noinline)
[email protected]2149cc622012-02-14 01:12:1247#define NOINLINE __attribute__((noinline))
48#elif defined(COMPILER_MSVC)
49#define NOINLINE __declspec(noinline)
50#else
[email protected]50795a02011-05-09 20:11:0151#define NOINLINE
[email protected]f50595102010-10-08 16:20:3252#endif
53
Jose Dapena Paz7cc1b1d42023-11-08 18:37:2854// Annotate a function indicating it should not be optimized.
55#if defined(__clang__) && HAS_ATTRIBUTE(optnone)
56#define NOOPT [[clang::optnone]]
57#elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(optimize)
58#define NOOPT __attribute__((optimize(0)))
59#else
60#define NOOPT
61#endif
62
Peter Kastingf541f7782023-03-10 23:44:4663#if defined(__clang__) && defined(NDEBUG) && HAS_ATTRIBUTE(always_inline)
64#define ALWAYS_INLINE [[clang::always_inline]] inline
65#elif defined(COMPILER_GCC) && defined(NDEBUG) && HAS_ATTRIBUTE(always_inline)
palmer58184a8282016-11-08 19:15:3966#define ALWAYS_INLINE inline __attribute__((__always_inline__))
Ivan Krasin9c098a0d2018-08-05 03:57:5767#elif defined(COMPILER_MSVC) && defined(NDEBUG)
palmer58184a8282016-11-08 19:15:3968#define ALWAYS_INLINE __forceinline
69#else
70#define ALWAYS_INLINE inline
71#endif
72
Olivier Li19d89252020-05-13 17:57:5573// Annotate a function indicating it should never be tail called. Useful to make
74// sure callers of the annotated function are never omitted from call-stacks.
75// To provide the complementary behavior (prevent the annotated function from
76// being omitted) look at NOINLINE. Also note that this doesn't prevent code
77// folding of multiple identical caller functions into a single signature. To
Bruce Dawson7915efd2021-01-27 18:07:5878// prevent code folding, see NO_CODE_FOLDING() in base/debug/alias.h.
Olivier Li19d89252020-05-13 17:57:5579// Use like:
Daniel Chengddf1b222023-02-02 02:41:5280// NOT_TAIL_CALLED void FooBar();
Peter Kasting64c67dd2022-05-12 18:11:5181#if defined(__clang__) && HAS_ATTRIBUTE(not_tail_called)
Peter Kastingf541f7782023-03-10 23:44:4682#define NOT_TAIL_CALLED [[clang::not_tail_called]]
Olivier Li19d89252020-05-13 17:57:5583#else
84#define NOT_TAIL_CALLED
85#endif
86
mikt2a4fdf02024-07-09 18:47:5787// Annotate a function indicating it must be tail called.
88// Can be used only on return statements, even for functions returning void.
89// Caller and callee must have the same number of arguments and its types must
90// be "similar".
91#if defined(__clang__) && HAS_ATTRIBUTE(musttail)
92#define MUSTTAIL [[clang::musttail]]
93#else
94#define MUSTTAIL
95#endif
96
[email protected]cd924d62012-02-23 17:52:2097// Specify memory alignment for structs, classes, etc.
98// Use like:
99// class ALIGNAS(16) MyClass { ... }
100// ALIGNAS(16) int array[4];
brettw16289b3e2017-06-13 21:58:40101//
102// In most places you can use the C++11 keyword "alignas", which is preferred.
103//
Peter Kastingf541f7782023-03-10 23:44:46104// Historically, compilers had trouble mixing __attribute__((...)) syntax with
105// alignas(...) syntax. However, at least Clang is very accepting nowadays. It
106// may be that this macro can be removed entirely.
107#if defined(__clang__)
108#define ALIGNAS(byte_alignment) alignas(byte_alignment)
109#elif defined(COMPILER_MSVC)
[email protected]cd924d62012-02-23 17:52:20110#define ALIGNAS(byte_alignment) __declspec(align(byte_alignment))
Peter Kastingf541f7782023-03-10 23:44:46111#elif defined(COMPILER_GCC) && HAS_ATTRIBUTE(aligned)
[email protected]cd924d62012-02-23 17:52:20112#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
113#endif
114
Jan Wilken Dörrief8d479d2020-11-23 12:21:13115// In case the compiler supports it NO_UNIQUE_ADDRESS evaluates to the C++20
116// attribute [[no_unique_address]]. This allows annotating data members so that
117// they need not have an address distinct from all other non-static data members
118// of its class.
119//
120// References:
121// * https://en.cppreference.com/w/cpp/language/attributes/no_unique_address
122// * https://wg21.link/dcl.attr.nouniqueaddr
Peter Kasting8bc046d22023-11-14 00:38:03123#if defined(COMPILER_MSVC) && HAS_CPP_ATTRIBUTE(msvc::no_unique_address)
124// Unfortunately MSVC ignores [[no_unique_address]] (see
125// https://devblogs.microsoft.com/cppblog/msvc-cpp20-and-the-std-cpp20-switch/#msvc-extensions-and-abi),
126// and clang-cl matches it for ABI compatibility reasons. We need to prefer
127// [[msvc::no_unique_address]] when available if we actually want any effect.
Helmut Januschka13cd38b2023-12-22 03:31:47128#define NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
Peter Kasting8bc046d22023-11-14 00:38:03129#elif HAS_CPP_ATTRIBUTE(no_unique_address)
Jan Wilken Dörrief8d479d2020-11-23 12:21:13130#define NO_UNIQUE_ADDRESS [[no_unique_address]]
131#else
132#define NO_UNIQUE_ADDRESS
133#endif
134
Peter Kastingf541f7782023-03-10 23:44:46135// Tells the compiler a function is using a printf-style format string.
[email protected]34b2b002009-11-20 06:53:28136// |format_param| is the one-based index of the format string parameter;
137// |dots_param| is the one-based index of the "..." parameter.
138// For v*printf functions (which take a va_list), pass 0 for dots_param.
139// (This is undocumented but matches what the system C headers do.)
Nico Weberfc7c8dd2019-02-28 21:28:44140// For member functions, the implicit this parameter counts as index 1.
Peter Kastingf541f7782023-03-10 23:44:46141#if (defined(COMPILER_GCC) || defined(__clang__)) && HAS_ATTRIBUTE(format)
[email protected]34b2b002009-11-20 06:53:28142#define PRINTF_FORMAT(format_param, dots_param) \
Vitaly Buka2b790762019-12-20 21:11:48143 __attribute__((format(printf, format_param, dots_param)))
[email protected]f50595102010-10-08 16:20:32144#else
145#define PRINTF_FORMAT(format_param, dots_param)
146#endif
[email protected]34b2b002009-11-20 06:53:28147
148// WPRINTF_FORMAT is the same, but for wide format strings.
[email protected]f50595102010-10-08 16:20:32149// This doesn't appear to yet be implemented in any compiler.
[email protected]34b2b002009-11-20 06:53:28150// See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=38308 .
151#define WPRINTF_FORMAT(format_param, dots_param)
152// If available, it would look like:
153// __attribute__((format(wprintf, format_param, dots_param)))
154
etienneb4e9250a2016-11-18 18:47:53155// Sanitizers annotations.
Peter Kasting64c67dd2022-05-12 18:11:51156#if HAS_ATTRIBUTE(no_sanitize)
etienneb4e9250a2016-11-18 18:47:53157#define NO_SANITIZE(what) __attribute__((no_sanitize(what)))
158#endif
etienneb4e9250a2016-11-18 18:47:53159#if !defined(NO_SANITIZE)
160#define NO_SANITIZE(what)
161#endif
162
[email protected]75086be2013-03-20 21:18:22163// MemorySanitizer annotations.
Xiaohan Wang38e4ebb2022-01-19 06:57:43164#if defined(MEMORY_SANITIZER) && !BUILDFLAG(IS_NACL)
[email protected]eb82dfb2014-02-03 19:51:17165#include <sanitizer/msan_interface.h>
[email protected]75086be2013-03-20 21:18:22166
167// Mark a memory region fully initialized.
168// Use this to annotate code that deliberately reads uninitialized data, for
169// example a GC scavenging root set pointers from the stack.
Vitaly Buka2b790762019-12-20 21:11:48170#define MSAN_UNPOISON(p, size) __msan_unpoison(p, size)
thestig1a42b4072015-03-16 22:36:55171
172// Check a memory region for initializedness, as if it was being used here.
173// If any bits are uninitialized, crash with an MSan report.
174// Use this to sanitize data which MSan won't be able to track, e.g. before
175// passing data to another process via shared memory.
176#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) \
Vitaly Buka2b790762019-12-20 21:11:48177 __msan_check_mem_is_initialized(p, size)
[email protected]75086be2013-03-20 21:18:22178#else // MEMORY_SANITIZER
thestig1a42b4072015-03-16 22:36:55179#define MSAN_UNPOISON(p, size)
180#define MSAN_CHECK_MEM_IS_INITIALIZED(p, size)
[email protected]75086be2013-03-20 21:18:22181#endif // MEMORY_SANITIZER
182
krasin825ce482016-08-27 11:01:11183// DISABLE_CFI_PERF -- Disable Control Flow Integrity for perf reasons.
184#if !defined(DISABLE_CFI_PERF)
krasin40f7c782016-09-22 19:04:27185#if defined(__clang__) && defined(OFFICIAL_BUILD)
Peter Kastingf541f7782023-03-10 23:44:46186#define DISABLE_CFI_PERF NO_SANITIZE("cfi")
krasin825ce482016-08-27 11:01:11187#else
188#define DISABLE_CFI_PERF
189#endif
190#endif
191
Will Harris9a033b02020-07-11 01:26:54192// DISABLE_CFI_ICALL -- Disable Control Flow Integrity indirect call checks.
Alex Gough36579802022-07-25 20:20:46193// Security Note: if you just need to allow calling of dlsym functions use
194// DISABLE_CFI_DLSYM.
Will Harris9a033b02020-07-11 01:26:54195#if !defined(DISABLE_CFI_ICALL)
Xiaohan Wang38e4ebb2022-01-19 06:57:43196#if BUILDFLAG(IS_WIN)
Will Harris9a033b02020-07-11 01:26:54197// Windows also needs __declspec(guard(nocf)).
198#define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall") __declspec(guard(nocf))
199#else
200#define DISABLE_CFI_ICALL NO_SANITIZE("cfi-icall")
201#endif
202#endif
203#if !defined(DISABLE_CFI_ICALL)
204#define DISABLE_CFI_ICALL
205#endif
206
Alex Gough36579802022-07-25 20:20:46207// DISABLE_CFI_DLSYM -- applies DISABLE_CFI_ICALL on platforms where dlsym
208// functions must be called. Retains CFI checks on platforms where loaded
209// modules participate in CFI (e.g. Windows).
210#if !defined(DISABLE_CFI_DLSYM)
211#if BUILDFLAG(IS_WIN)
212// Windows modules register functions when loaded so can be checked by CFG.
213#define DISABLE_CFI_DLSYM
214#else
215#define DISABLE_CFI_DLSYM DISABLE_CFI_ICALL
216#endif
217#endif
218#if !defined(DISABLE_CFI_DLSYM)
219#define DISABLE_CFI_DLSYM
220#endif
221
[email protected]5a8d4ce2013-12-18 17:42:27222// Macro useful for writing cross-platform function pointers.
223#if !defined(CDECL)
Xiaohan Wang38e4ebb2022-01-19 06:57:43224#if BUILDFLAG(IS_WIN)
[email protected]5a8d4ce2013-12-18 17:42:27225#define CDECL __cdecl
Xiaohan Wang38e4ebb2022-01-19 06:57:43226#else // BUILDFLAG(IS_WIN)
[email protected]5a8d4ce2013-12-18 17:42:27227#define CDECL
Xiaohan Wang38e4ebb2022-01-19 06:57:43228#endif // BUILDFLAG(IS_WIN)
[email protected]5a8d4ce2013-12-18 17:42:27229#endif // !defined(CDECL)
230
[email protected]2bc0c6992014-02-13 16:11:04231// Macro for hinting that an expression is likely to be false.
232#if !defined(UNLIKELY)
Vladimir Levin6b777712017-09-09 00:12:05233#if defined(COMPILER_GCC) || defined(__clang__)
[email protected]2bc0c6992014-02-13 16:11:04234#define UNLIKELY(x) __builtin_expect(!!(x), 0)
235#else
236#define UNLIKELY(x) (x)
237#endif // defined(COMPILER_GCC)
238#endif // !defined(UNLIKELY)
239
palmer58184a8282016-11-08 19:15:39240#if !defined(LIKELY)
Vladimir Levin6b777712017-09-09 00:12:05241#if defined(COMPILER_GCC) || defined(__clang__)
Chris Palmerad4cb83f2016-11-18 20:02:25242#define LIKELY(x) __builtin_expect(!!(x), 1)
palmer58184a8282016-11-08 19:15:39243#else
244#define LIKELY(x) (x)
245#endif // defined(COMPILER_GCC)
246#endif // !defined(LIKELY)
247
jfbd81c1ce2016-04-05 20:50:35248// Compiler feature-detection.
jfba8dc9dd82016-04-06 20:20:31249// clang.llvm.org/docs/LanguageExtensions.html#has-feature-and-has-extension
250#if defined(__has_feature)
251#define HAS_FEATURE(FEATURE) __has_feature(FEATURE)
252#else
253#define HAS_FEATURE(FEATURE) 0
jfbd81c1ce2016-04-05 20:50:35254#endif
255
Alex Clarke23c6cf72018-11-21 13:22:27256#if defined(COMPILER_GCC)
257#define PRETTY_FUNCTION __PRETTY_FUNCTION__
258#elif defined(COMPILER_MSVC)
259#define PRETTY_FUNCTION __FUNCSIG__
260#else
261// See https://en.cppreference.com/w/c/language/function_definition#func
262#define PRETTY_FUNCTION __func__
263#endif
264
Henrique Ferreiro6daf71db2019-04-03 13:12:42265#if !defined(CPU_ARM_NEON)
Matt Reynolds96ad2252023-06-05 20:01:48266#if defined(__arm__)
267#if !defined(__ARMEB__) && !defined(__ARM_EABI__) && !defined(__EABI__) && \
268 !defined(__VFP_FP__) && !defined(_WIN32_WCE) && !defined(ANDROID)
269#error Chromium does not support middle endian architecture
270#endif
271#if defined(__ARM_NEON__)
Henrique Ferreiro6daf71db2019-04-03 13:12:42272#define CPU_ARM_NEON 1
273#endif
Matt Reynolds96ad2252023-06-05 20:01:48274#endif // defined(__arm__)
Henrique Ferreiro6daf71db2019-04-03 13:12:42275#endif // !defined(CPU_ARM_NEON)
276
277#if !defined(HAVE_MIPS_MSA_INTRINSICS)
278#if defined(__mips_msa) && defined(__mips_isa_rev) && (__mips_isa_rev >= 5)
279#define HAVE_MIPS_MSA_INTRINSICS 1
280#endif
281#endif
282
Peter Kasting64c67dd2022-05-12 18:11:51283#if defined(__clang__) && HAS_ATTRIBUTE(uninitialized)
Vitaly Buka2b790762019-12-20 21:11:48284// Attribute "uninitialized" disables -ftrivial-auto-var-init=pattern for
285// the specified variable.
286// Library-wide alternative is
287// 'configs -= [ "//build/config/compiler:default_init_stack_vars" ]' in .gn
288// file.
289//
290// See "init_stack_vars" in build/config/compiler/BUILD.gn and
291// http://crbug.com/977230
292// "init_stack_vars" is enabled for non-official builds and we hope to enable it
293// in official build in 2020 as well. The flag writes fixed pattern into
294// uninitialized parts of all local variables. In rare cases such initialization
295// is undesirable and attribute can be used:
296// 1. Degraded performance
297// In most cases compiler is able to remove additional stores. E.g. if memory is
298// never accessed or properly initialized later. Preserved stores mostly will
299// not affect program performance. However if compiler failed on some
300// performance critical code we can get a visible regression in a benchmark.
301// 2. memset, memcpy calls
302// Compiler may replaces some memory writes with memset or memcpy calls. This is
303// not -ftrivial-auto-var-init specific, but it can happen more likely with the
304// flag. It can be a problem if code is not linked with C run-time library.
305//
306// Note: The flag is security risk mitigation feature. So in future the
307// attribute uses should be avoided when possible. However to enable this
308// mitigation on the most of the code we need to be less strict now and minimize
309// number of exceptions later. So if in doubt feel free to use attribute, but
310// please document the problem for someone who is going to cleanup it later.
311// E.g. platform, bot, benchmark or test name in patch description or next to
312// the attribute.
Peter Kastingf541f7782023-03-10 23:44:46313#define STACK_UNINITIALIZED [[clang::uninitialized]]
Vitaly Buka2b790762019-12-20 21:11:48314#else
315#define STACK_UNINITIALIZED
316#endif
317
Matthew Dentonbb0b03e2021-07-22 16:18:13318// Attribute "no_stack_protector" disables -fstack-protector for the specified
319// function.
320//
321// "stack_protector" is enabled on most POSIX builds. The flag adds a canary
322// to each stack frame, which on function return is checked against a reference
323// canary. If the canaries do not match, it's likely that a stack buffer
324// overflow has occurred, so immediately crashing will prevent exploitation in
325// many cases.
326//
327// In some cases it's desirable to remove this, e.g. on hot functions, or if
328// we have purposely changed the reference canary.
329#if defined(COMPILER_GCC) || defined(__clang__)
Peter Kasting64c67dd2022-05-12 18:11:51330#if HAS_ATTRIBUTE(__no_stack_protector__)
Stephan Hartmann4b456e72021-08-10 03:25:02331#define NO_STACK_PROTECTOR __attribute__((__no_stack_protector__))
Peter Kasting64c67dd2022-05-12 18:11:51332#else
Stephan Hartmann4b456e72021-08-10 03:25:02333#define NO_STACK_PROTECTOR __attribute__((__optimize__("-fno-stack-protector")))
334#endif
Matthew Dentonbb0b03e2021-07-22 16:18:13335#else
336#define NO_STACK_PROTECTOR
337#endif
338
Hans Wennborg12aea3e2020-04-14 15:29:00339// The ANALYZER_ASSUME_TRUE(bool arg) macro adds compiler-specific hints
340// to Clang which control what code paths are statically analyzed,
341// and is meant to be used in conjunction with assert & assert-like functions.
342// The expression is passed straight through if analysis isn't enabled.
343//
344// ANALYZER_SKIP_THIS_PATH() suppresses static analysis for the current
345// codepath and any other branching codepaths that might follow.
346#if defined(__clang_analyzer__)
347
348inline constexpr bool AnalyzerNoReturn() __attribute__((analyzer_noreturn)) {
349 return false;
350}
351
352inline constexpr bool AnalyzerAssumeTrue(bool arg) {
353 // AnalyzerNoReturn() is invoked and analysis is terminated if |arg| is
354 // false.
355 return arg || AnalyzerNoReturn();
356}
357
George Burgess IVa09d235d2020-04-17 13:32:50358#define ANALYZER_ASSUME_TRUE(arg) ::AnalyzerAssumeTrue(!!(arg))
359#define ANALYZER_SKIP_THIS_PATH() static_cast<void>(::AnalyzerNoReturn())
Hans Wennborg12aea3e2020-04-14 15:29:00360
361#else // !defined(__clang_analyzer__)
362
363#define ANALYZER_ASSUME_TRUE(arg) (arg)
364#define ANALYZER_SKIP_THIS_PATH()
Hans Wennborg12aea3e2020-04-14 15:29:00365
366#endif // defined(__clang_analyzer__)
367
Zequan Wu9909f142021-02-10 03:26:00368// Use nomerge attribute to disable optimization of merging multiple same calls.
Peter Kasting64c67dd2022-05-12 18:11:51369#if defined(__clang__) && HAS_ATTRIBUTE(nomerge)
Zequan Wu9909f142021-02-10 03:26:00370#define NOMERGE [[clang::nomerge]]
371#else
372#define NOMERGE
373#endif
374
Jeremy Roman810d98d2021-04-06 16:46:07375// 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.
379//
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.
386//
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.
389//
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.
392//
393// See also:
394// https://clang.llvm.org/docs/AttributeReference.html#trivial-abi
395// https://libcxx.llvm.org/docs/DesignDocs/UniquePtrTrivialAbi.html
Peter Kasting64c67dd2022-05-12 18:11:51396#if defined(__clang__) && HAS_ATTRIBUTE(trivial_abi)
Jeremy Roman810d98d2021-04-06 16:46:07397#define TRIVIAL_ABI [[clang::trivial_abi]]
398#else
399#define TRIVIAL_ABI
400#endif
401
Adam Ricefb288d02023-10-13 08:36:21402// Detect whether a type is trivially relocatable, ie. a move-and-destroy
403// sequence can replaced with memmove(). This can be used to optimise the
404// implementation of containers. This is automatically true for types that were
405// defined with TRIVIAL_ABI such as scoped_refptr.
406//
407// See also:
408// https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p1144r8.html
409// https://clang.llvm.org/docs/LanguageExtensions.html#:~:text=__is_trivially_relocatable
410#if defined(__clang__) && HAS_BUILTIN(__is_trivially_relocatable)
411#define IS_TRIVIALLY_RELOCATABLE(t) __is_trivially_relocatable(t)
412#else
413#define IS_TRIVIALLY_RELOCATABLE(t) false
414#endif
415
Lukasz Anforowicz3be38fbb2021-04-14 20:29:29416// Marks a member function as reinitializing a moved-from variable.
417// See also
Lei Zhangdd1e6fe2024-02-01 08:51:35418// https://clang.llvm.org/extra/clang-tidy/checks/bugprone/use-after-move.html#reinitialization
Peter Kasting64c67dd2022-05-12 18:11:51419#if defined(__clang__) && HAS_ATTRIBUTE(reinitializes)
Lukasz Anforowicz3be38fbb2021-04-14 20:29:29420#define REINITIALIZES_AFTER_MOVE [[clang::reinitializes]]
421#else
422#define REINITIALIZES_AFTER_MOVE
423#endif
424
danakjceb17022022-02-11 23:52:01425#if defined(__clang__)
Daniel Cheng8ac305b2022-02-17 00:05:11426#define GSL_OWNER [[gsl::Owner]]
danakjceb17022022-02-11 23:52:01427#define GSL_POINTER [[gsl::Pointer]]
428#else
Jose Dapena Paz1183b142022-02-18 16:28:25429#define GSL_OWNER
danakjceb17022022-02-11 23:52:01430#define GSL_POINTER
431#endif
432
Daniel Chengf2c05382022-09-16 02:51:42433// Adds the "logically_const" tag to a symbol's mangled name. The "Mutable
434// Constants" check [1] detects instances of constants that aren't in .rodata,
435// e.g. due to a missing `const`. Using this tag suppresses the check for this
436// symbol, allowing it to live outside .rodata without a warning.
437//
438// [1]:
439// https://crsrc.org/c/docs/speed/binary_size/android_binary_size_trybot.md#Mutable-Constants
Anthony Vallee-Dubois9dbbbda32022-08-26 01:25:31440#if defined(COMPILER_GCC) || defined(__clang__)
441#define LOGICALLY_CONST [[gnu::abi_tag("logically_const")]]
442#else
443#define LOGICALLY_CONST
444#endif
445
Anton Bikineev4d23e842023-06-14 10:46:19446// preserve_most clang's calling convention. Reduces register pressure for the
447// caller and as such can be used for cold calls. Support for the
448// "preserve_most" attribute is limited:
449// - 32-bit platforms do not implement it,
450// - component builds fail because _dl_runtime_resolve() clobbers registers,
451// - there are crashes on arm64 on Windows (https://crbug.com/v8/14065), which
452// can hopefully be fixed in the future.
453// Additionally, the initial implementation in clang <= 16 overwrote the return
454// register(s) in the epilogue of a preserve_most function, so we only use
455// preserve_most in clang >= 17 (see https://reviews.llvm.org/D143425).
kxxt120045d2024-02-13 04:22:39456// Clang only supports preserve_most on X86-64 and AArch64 for now.
Anton Bikineev4d23e842023-06-14 10:46:19457// See https://clang.llvm.org/docs/AttributeReference.html#preserve-most for
458// more details.
kxxt120045d2024-02-13 04:22:39459#if (defined(ARCH_CPU_ARM64) || defined(ARCH_CPU_X86_64)) && \
460 !(BUILDFLAG(IS_WIN) && defined(ARCH_CPU_ARM64)) && \
461 !defined(COMPONENT_BUILD) && defined(__clang__) && \
Anton Bikineev4d23e842023-06-14 10:46:19462 __clang_major__ >= 17 && HAS_ATTRIBUTE(preserve_most)
463#define PRESERVE_MOST __attribute__((preserve_most))
464#else
465#define PRESERVE_MOST
466#endif
467
danakjc077a30e2024-03-22 19:25:36468// Mark parameters or return types as having a lifetime attached to the class.
469//
470// When used to mark a method's pointer/reference parameter, the compiler is
471// made aware that it will be stored internally in the class and the pointee
472// must outlive the class. Typically used on constructor arguments. It should
473// appear to the right of the parameter's variable name.
474//
475// Example:
476// ```
477// struct S {
478// S(int* p LIFETIME_BOUND) : ptr_(p) {}
479//
480// int* ptr_;
481// };
482// ```
483//
484// When used on a method with a return value, the compiler is made aware that
485// the returned type is/has a pointer to the internals of the class, and must
486// not outlive the class object. It should appear after any method qualifiers.
487//
488// Example:
489// ```
490// struct S {
491// int* GetPtr() const LIFETIME_BOUND { return i_; };
492//
493// int i_;
494// };
495// ```
496//
497// This allows the compiler to warn in (a limited set of) cases where the
498// pointer would otherwise be left dangling, especially in cases where the
499// pointee would be a destroyed temporary.
500//
501// Docs: https://clang.llvm.org/docs/AttributeReference.html#lifetimebound
502#if defined(__clang__)
503#define LIFETIME_BOUND [[clang::lifetimebound]]
504#else
505#define LIFETIME_BOUND
506#endif
507
508// Mark a function as pure, meaning that it does not have side effects, meaning
509// that it does not write anything external to the function's local variables
510// and return value.
511//
512// WARNING: If this attribute is mis-used it will result in UB and
513// miscompilation, as the optimizator may fold multiple calls into one and
514// reorder them inappropriately. This shouldn't appear outside of key vocabulary
515// types. It allows callers to work with the vocab type directly, and call its
516// methods without having to worry about caching things into local variables in
517// hot code.
518//
519// This attribute must not appear on functions that make use of function
520// pointers, virtual methods, or methods of templates (including operators like
521// comparison), as the "pure" function can not know what those functions do and
522// can not guarantee there will never be sideeffects.
523#if defined(COMPILER_GCC) || defined(__clang__)
524#define PURE_FUNCTION [[gnu::pure]]
525#else
526#define PURE_FUNCTION
527#endif
528
danakj59f56d92024-02-01 15:31:35529// Functions should be marked with UNSAFE_BUFFER_USAGE when they lead to
530// out-of-bounds bugs when called with incorrect inputs.
531//
532// Ideally such functions should be paired with a safer version that works with
533// safe primitives like `base::span`. Otherwise, another safer coding pattern
534// should be documented along side the use of `UNSAFE_BUFFER_USAGE`.
535//
536// All functions marked with UNSAFE_BUFFER_USAGE should come with a safety
David Benjamin34f6c2d02024-04-16 17:43:54537// comment that explains the requirements of the function to prevent an
538// out-of-bounds bug. For example:
danakj59f56d92024-02-01 15:31:35539// ```
540// // Function to do things between `input` and `end`.
541// //
542// // # Safety
543// // The `input` must point to an array with size at least 5. The `end` must
544// // point within the same allocation of `input` and not come before `input`.
545// ```
David Benjamin34f6c2d02024-04-16 17:43:54546//
547// The requirements described in the safety comment must be sufficient to
548// guarantee that the function never goes out of bounds. Annotating a function
549// in this way means that all callers will be required to wrap the call in an
550// `UNSAFE_BUFFERS()` macro (see below), with a comment justifying how it meets
551// the requirements.
danakj59f56d92024-02-01 15:31:35552#if defined(__clang__) && HAS_ATTRIBUTE(unsafe_buffer_usage)
553#define UNSAFE_BUFFER_USAGE [[clang::unsafe_buffer_usage]]
554#else
555#define UNSAFE_BUFFER_USAGE
556#endif
557
558// UNSAFE_BUFFERS() wraps code that violates the -Wunsafe-buffer-usage warning,
559// such as:
560// - pointer arithmetic,
561// - pointer subscripting, and
562// - calls to functions annotated with UNSAFE_BUFFER_USAGE.
563//
David Benjamin34f6c2d02024-04-16 17:43:54564// This indicates code whose bounds correctness cannot be ensured
565// systematically, and thus requires manual review.
566//
567// ** USE OF THIS MACRO SHOULD BE VERY RARE.** This should only be used when
568// strictly necessary. Prefer to use `base::span` instead of pointers, or other
569// safer coding patterns (like std containers) that avoid the opportunity for
570// out-of-bounds bugs to creep into the code. Any use of UNSAFE_BUFFERS() can
571// lead to a critical security bug if any assumptions are wrong, or ever become
572// wrong in the future.
danakj59f56d92024-02-01 15:31:35573//
574// The macro should be used to wrap the minimum necessary code, to make it clear
575// what is unsafe, and prevent accidentally opting extra things out of the
576// warning.
577//
578// All usage of UNSAFE_BUFFERS() should come with a `// SAFETY: ...` comment
David Benjamin34f6c2d02024-04-16 17:43:54579// that explains how we have guaranteed that the pointer usage can never go
580// out-of-bounds, or that the requirements of the UNSAFE_BUFFER_USAGE function
581// are met. The safety comment should allow a reader to check that all
582// requirements have been met, using only local invariants. Examples of local
583// invariants include:
584// - Runtime conditions or CHECKs near the UNSAFE_BUFFERS macros
585// - Invariants guaranteed by types in the surrounding code
586// - Invariants guaranteed by function calls in the surrounding code
587// - Caller requirements, if the containing function is itself marked with
588// UNSAFE_BUFFER_USAGE
589//
590// The last case should be an option of last resort. It is less safe and will
591// require the caller also use the UNSAFE_BUFFERS() macro. Prefer directly
592// capturing such invariants in types like `base::span`.
593//
594// Safety explanations may not rely on invariants that are not fully
595// encapsulated close to the UNSAFE_BUFFERS() usage. Instead, use safer coding
596// patterns or stronger invariants.
danakj59f56d92024-02-01 15:31:35597#if defined(__clang__)
598// clang-format off
599// Formatting is off so that we can put each _Pragma on its own line, as
600// recommended by the gcc docs.
601#define UNSAFE_BUFFERS(...) \
602 _Pragma("clang unsafe_buffer_usage begin") \
603 __VA_ARGS__ \
604 _Pragma("clang unsafe_buffer_usage end")
605// clang-format on
606#else
607#define UNSAFE_BUFFERS(...) __VA_ARGS__
608#endif
609
danakjc077a30e2024-03-22 19:25:36610// Defines a condition for a function to be checked at compile time if the
611// parameter's value is known at compile time. If the condition is failed, the
612// function is omitted from the overload set resolution, much like `requires`.
613//
614// If the parameter is a runtime value, then the condition is unable to be
615// checked and the function will be omitted from the overload set resolution.
616// This ensures the function can only be called with values known at compile
617// time. This is a clang extension.
618//
619// Example:
620// ```
621// void f(int a) ENABLE_IF_ATTR(a > 0) {}
622// f(1); // Ok.
623// f(0); // Error: no valid f() found.
624// ```
625//
626// The `ENABLE_IF_ATTR` annotation is preferred over `consteval` with a check
627// that breaks compile because metaprogramming does not observe such checks. So
628// with `consteval`, the function looks callable to concepts/type_traits but is
629// not and will fail to compile even though it reports it's usable. Whereas
630// `ENABLE_IF_ATTR` interacts correctly with metaprogramming. This is especially
631// painful for constructors. See also
632// https://github.com/chromium/subspace/issues/266.
633#if defined(__clang__)
634#define ENABLE_IF_ATTR(cond, msg) __attribute__((enable_if(cond, msg)))
635#else
636#define ENABLE_IF_ATTR(cond, msg)
637#endif
638
[email protected]dd9afc0b2008-11-21 23:58:09639#endif // BASE_COMPILER_SPECIFIC_H_