1 /*
2  * Copyright (c) 2010-2014,2017 Wind River Systems, Inc.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #ifndef ZEPHYR_INCLUDE_TOOLCHAIN_GCC_H_
8 #define ZEPHYR_INCLUDE_TOOLCHAIN_GCC_H_
9 
10 /**
11  * @file
12  * @brief GCC toolchain abstraction
13  *
14  * Macros to abstract compiler capabilities for GCC toolchain.
15  */
16 
17 /*
18  * Older versions of GCC do not define __BYTE_ORDER__, so it must be manually
19  * detected and defined using arch-specific definitions.
20  */
21 
22 #ifndef _LINKER
23 
24 #ifndef __ORDER_BIG_ENDIAN__
25 #define __ORDER_BIG_ENDIAN__            (1)
26 #endif
27 
28 #ifndef __ORDER_LITTLE_ENDIAN__
29 #define __ORDER_LITTLE_ENDIAN__         (2)
30 #endif
31 
32 #ifndef __BYTE_ORDER__
33 #if defined(__BIG_ENDIAN__) || defined(__ARMEB__) || \
34     defined(__THUMBEB__) || defined(__AARCH64EB__) || \
35     defined(__MIPSEB__) || defined(__TC32EB__)
36 
37 #define __BYTE_ORDER__                  __ORDER_BIG_ENDIAN__
38 
39 #elif defined(__LITTLE_ENDIAN__) || defined(__ARMEL__) || \
40       defined(__THUMBEL__) || defined(__AARCH64EL__) || \
41       defined(__MIPSEL__) || defined(__TC32EL__)
42 
43 #define __BYTE_ORDER__                  __ORDER_LITTLE_ENDIAN__
44 
45 #else
46 #error "__BYTE_ORDER__ is not defined and cannot be automatically resolved"
47 #endif
48 #endif
49 
50 
51 #undef BUILD_ASSERT /* clear out common version */
52 /* C++11 has static_assert built in */
53 #if defined(__cplusplus) && (__cplusplus >= 201103L)
54 #define BUILD_ASSERT(EXPR, MSG...) static_assert(EXPR, "" MSG)
55 
56 /*
57  * GCC 4.6 and higher have the C11 _Static_assert built in, and its
58  * output is easier to understand than the common BUILD_ASSERT macros.
59  */
60 #elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) || \
61 	(__STDC_VERSION__) >= 201100
62 #define BUILD_ASSERT(EXPR, MSG...) _Static_assert(EXPR, "" MSG)
63 #else
64 #define BUILD_ASSERT(EXPR, MSG...)
65 #endif
66 
67 #include <toolchain/common.h>
68 #include <stdbool.h>
69 
70 #define ALIAS_OF(of) __attribute__((alias(#of)))
71 
72 #define FUNC_ALIAS(real_func, new_alias, return_type) \
73 	return_type new_alias() ALIAS_OF(real_func)
74 
75 #if defined(CONFIG_ARCH_POSIX)
76 #include <arch/posix/posix_trace.h>
77 
78 /*let's not segfault if this were to happen for some reason*/
79 #define CODE_UNREACHABLE \
80 {\
81 	posix_print_error_and_exit("CODE_UNREACHABLE reached from %s:%d\n",\
82 		__FILE__, __LINE__);\
83 	__builtin_unreachable(); \
84 }
85 #else
86 #define CODE_UNREACHABLE __builtin_unreachable()
87 #endif
88 #define FUNC_NORETURN    __attribute__((__noreturn__))
89 
90 /* The GNU assembler for Cortex-M3 uses # for immediate values, not
91  * comments, so the @nobits# trick does not work.
92  */
93 #if defined(CONFIG_ARM) || defined(CONFIG_ARM64)
94 #define _NODATA_SECTION(segment)  __attribute__((section(#segment)))
95 #else
96 #define _NODATA_SECTION(segment)				\
97 	__attribute__((section(#segment ",\"wa\",@nobits#")))
98 #endif
99 
100 /* Unaligned access */
101 #define UNALIGNED_GET(p)						\
102 __extension__ ({							\
103 	struct  __attribute__((__packed__)) {				\
104 		__typeof__(*(p)) __v;					\
105 	} *__p = (__typeof__(__p)) (p);					\
106 	__p->__v;							\
107 })
108 
109 
110 #if __GNUC__ >= 7 && (defined(CONFIG_ARM) || defined(CONFIG_ARM64))
111 
112 /* Version of UNALIGNED_PUT() which issues a compiler_barrier() after
113  * the store. It is required to workaround an apparent optimization
114  * bug in GCC for ARM Cortex-M3 and higher targets, when multiple
115  * byte, half-word and word stores (strb, strh, str instructions),
116  * which support unaligned access, can be coalesced into store double
117  * (strd) instruction, which doesn't support unaligned access (the
118  * compilers in question do this optimization ignoring __packed__
119  * attribute).
120  */
121 #define UNALIGNED_PUT(v, p)                                             \
122 do {                                                                    \
123 	struct __attribute__((__packed__)) {                            \
124 		__typeof__(*p) __v;                                     \
125 	} *__p = (__typeof__(__p)) (p);                                 \
126 	__p->__v = (v);                                                 \
127 	compiler_barrier();                                             \
128 } while (false)
129 
130 #else
131 
132 #define UNALIGNED_PUT(v, p)                                             \
133 do {                                                                    \
134 	struct __attribute__((__packed__)) {                            \
135 		__typeof__(*p) __v;                                     \
136 	} *__p = (__typeof__(__p)) (p);                                 \
137 	__p->__v = (v);                                               \
138 } while (false)
139 
140 #endif
141 
142 /* Double indirection to ensure section names are expanded before
143  * stringification
144  */
145 #define __GENERIC_SECTION(segment) __attribute__((section(STRINGIFY(segment))))
146 #define Z_GENERIC_SECTION(segment) __GENERIC_SECTION(segment)
147 
148 #define __GENERIC_DOT_SECTION(segment) \
149 	__attribute__((section("." STRINGIFY(segment))))
150 #define Z_GENERIC_DOT_SECTION(segment) __GENERIC_DOT_SECTION(segment)
151 
152 #define ___in_section(a, b, c) \
153 	__attribute__((section("." Z_STRINGIFY(a)			\
154 				"." Z_STRINGIFY(b)			\
155 				"." Z_STRINGIFY(c))))
156 #define __in_section(a, b, c) ___in_section(a, b, c)
157 
158 #define __in_section_unique(seg) ___in_section(seg, __FILE__, __COUNTER__)
159 
160 #define __in_section_unique_named(seg, name) \
161 	___in_section(seg, __FILE__, name)
162 
163 /* When using XIP, using '__ramfunc' places a function into RAM instead
164  * of FLASH. Make sure '__ramfunc' is defined only when
165  * CONFIG_ARCH_HAS_RAMFUNC_SUPPORT is defined, so that the compiler can
166  * report an error if '__ramfunc' is used but the architecture does not
167  * support it.
168  */
169 #if !defined(CONFIG_XIP)
170 #define __ramfunc
171 #elif defined(CONFIG_ARCH_HAS_RAMFUNC_SUPPORT)
172 #define __ramfunc	__attribute__((noinline))			\
173 			__attribute__((long_call, section(".ramfunc")))
174 #endif /* !CONFIG_XIP */
175 
176 #ifndef __fallthrough
177 #if __GNUC__ >= 7
178 #define __fallthrough        __attribute__((fallthrough))
179 #else
180 #define __fallthrough
181 #endif	/* __GNUC__ >= 7 */
182 #endif
183 
184 #ifndef __packed
185 #define __packed        __attribute__((__packed__))
186 #endif
187 #ifndef __aligned
188 #define __aligned(x)	__attribute__((__aligned__(x)))
189 #endif
190 #define __may_alias     __attribute__((__may_alias__))
191 #ifndef __printf_like
192 #define __printf_like(f, a)   __attribute__((format (printf, f, a)))
193 #endif
194 #define __used		__attribute__((__used__))
195 #ifndef __deprecated
196 #define __deprecated	__attribute__((deprecated))
197 #endif
198 #ifndef __attribute_const__
199 #define __attribute_const__ __attribute__((__const__))
200 #endif
201 #ifndef __must_check
202 #define __must_check __attribute__((warn_unused_result))
203 #endif
204 #define ARG_UNUSED(x) (void)(x)
205 
206 #define likely(x)   __builtin_expect((bool)!!(x), true)
207 #define unlikely(x) __builtin_expect((bool)!!(x), false)
208 
209 #define popcount(x) __builtin_popcount(x)
210 
211 #ifndef __no_optimization
212 #define __no_optimization __attribute__((optimize("-O0")))
213 #endif
214 
215 #ifndef __weak
216 #define __weak __attribute__((__weak__))
217 #endif
218 #define __unused __attribute__((__unused__))
219 
220 /* Builtins with availability that depend on the compiler version. */
221 #if __GNUC__ >= 5
222 #define HAS_BUILTIN___builtin_add_overflow 1
223 #define HAS_BUILTIN___builtin_sub_overflow 1
224 #define HAS_BUILTIN___builtin_mul_overflow 1
225 #define HAS_BUILTIN___builtin_div_overflow 1
226 #endif
227 #if __GNUC__ >= 4
228 #define HAS_BUILTIN___builtin_clz 1
229 #define HAS_BUILTIN___builtin_clzl 1
230 #define HAS_BUILTIN___builtin_clzll 1
231 #define HAS_BUILTIN___builtin_ctz 1
232 #define HAS_BUILTIN___builtin_ctzl 1
233 #define HAS_BUILTIN___builtin_ctzll 1
234 #endif
235 
236 /*
237  * Be *very* careful with these. You cannot filter out __DEPRECATED_MACRO with
238  * -wno-deprecated, which has implications for -Werror.
239  */
240 
241 /*
242  * Expands to nothing and generates a warning. Used like
243  *
244  *   #define FOO __WARN("Please use BAR instead") ...
245  *
246  * The warning points to the location where the macro is expanded.
247  */
248 #define __WARN(msg) __WARN1(GCC warning msg)
249 #define __WARN1(s) _Pragma(#s)
250 
251 /* Generic message */
252 #ifndef __DEPRECATED_MACRO
253 #define __DEPRECATED_MACRO __WARN("Macro is deprecated")
254 #endif
255 
256 /* These macros allow having ARM asm functions callable from thumb */
257 
258 #if defined(_ASMLANGUAGE)
259 
260 #if defined(CONFIG_ARM)
261 
262 #if defined(CONFIG_ASSEMBLER_ISA_THUMB2)
263 
264 #define FUNC_CODE() .thumb;
265 #define FUNC_INSTR(a)
266 
267 #else
268 
269 #define FUNC_CODE() .code 32
270 #define FUNC_INSTR(a)
271 
272 #endif /* CONFIG_ASSEMBLER_ISA_THUMB2 */
273 
274 #else
275 
276 #define FUNC_CODE()
277 #define FUNC_INSTR(a)
278 
279 #endif /* CONFIG_ARM */
280 
281 #endif /* _ASMLANGUAGE */
282 
283 /*
284  * These macros are used to declare assembly language symbols that need
285  * to be typed properly(func or data) to be visible to the OMF tool.
286  * So that the build tool could mark them as an entry point to be linked
287  * correctly.  This is an elfism. Use #if 0 for a.out.
288  */
289 
290 #if defined(_ASMLANGUAGE)
291 
292 #if defined(CONFIG_ARM) || defined(CONFIG_NIOS2) || defined(CONFIG_RISCV) \
293 	|| defined(CONFIG_XTENSA) || defined(CONFIG_ARM64)
294 #define GTEXT(sym) .global sym; .type sym, %function
295 #define GDATA(sym) .global sym; .type sym, %object
296 #define WTEXT(sym) .weak sym; .type sym, %function
297 #define WDATA(sym) .weak sym; .type sym, %object
298 #elif defined(CONFIG_ARC)
299 /*
300  * Need to use assembly macros because ';' is interpreted as the start of
301  * a single line comment in the ARC assembler.
302  */
303 
304 .macro glbl_text symbol
305 	.globl \symbol
306 	.type \symbol, %function
307 .endm
308 
309 .macro glbl_data symbol
310 	.globl \symbol
311 	.type \symbol, %object
312 .endm
313 
314 .macro weak_data symbol
315 	.weak \symbol
316 	.type \symbol, %object
317 .endm
318 
319 #define GTEXT(sym) glbl_text sym
320 #define GDATA(sym) glbl_data sym
321 #define WDATA(sym) weak_data sym
322 
323 #else  /* !CONFIG_ARM && !CONFIG_ARC */
324 #define GTEXT(sym) .globl sym; .type sym, @function
325 #define GDATA(sym) .globl sym; .type sym, @object
326 #endif
327 
328 /*
329  * These macros specify the section in which a given function or variable
330  * resides.
331  *
332  * - SECTION_FUNC	allows only one function to reside in a sub-section
333  * - SECTION_SUBSEC_FUNC allows multiple functions to reside in a sub-section
334  *   This ensures that garbage collection only discards the section
335  *   if all functions in the sub-section are not referenced.
336  */
337 
338 #if defined(CONFIG_ARC)
339 /*
340  * Need to use assembly macros because ';' is interpreted as the start of
341  * a single line comment in the ARC assembler.
342  *
343  * Also, '\()' is needed in the .section directive of these macros for
344  * correct substitution of the 'section' variable.
345  */
346 
347 .macro section_var section, symbol
348 	.section .\section\().\symbol
349 	\symbol :
350 .endm
351 
352 .macro section_func section, symbol
353 	.section .\section\().\symbol, "ax"
354 	FUNC_CODE()
355 	PERFOPT_ALIGN
356 	\symbol :
357 	FUNC_INSTR(\symbol)
358 .endm
359 
360 .macro section_subsec_func section, subsection, symbol
361 	.section .\section\().\subsection, "ax"
362 	PERFOPT_ALIGN
363 	\symbol :
364 .endm
365 
366 #define SECTION_VAR(sect, sym) section_var sect, sym
367 #define SECTION_FUNC(sect, sym) section_func sect, sym
368 #define SECTION_SUBSEC_FUNC(sect, subsec, sym) \
369 	section_subsec_func sect, subsec, sym
370 #else /* !CONFIG_ARC */
371 
372 #define SECTION_VAR(sect, sym)  .section .sect.sym; sym:
373 #define SECTION_FUNC(sect, sym)						\
374 	.section .sect.sym, "ax";					\
375 				FUNC_CODE()				\
376 				PERFOPT_ALIGN; sym :		\
377 							FUNC_INSTR(sym)
378 #define SECTION_SUBSEC_FUNC(sect, subsec, sym)				\
379 		.section .sect.subsec, "ax"; PERFOPT_ALIGN; sym :
380 
381 #endif /* CONFIG_ARC */
382 
383 #endif /* _ASMLANGUAGE */
384 
385 #if defined(_ASMLANGUAGE)
386 #if defined(CONFIG_ARM)
387 #if defined(CONFIG_ASSEMBLER_ISA_THUMB2)
388 /* '.syntax unified' is a gcc-ism used in thumb-2 asm files */
389 #define _ASM_FILE_PROLOGUE .text; .syntax unified; .thumb
390 #else
391 #define _ASM_FILE_PROLOGUE .text; .code 32
392 #endif /* CONFIG_ASSEMBLER_ISA_THUMB2 */
393 #elif defined(CONFIG_ARM64)
394 #define _ASM_FILE_PROLOGUE .text
395 #endif /* CONFIG_ARM64 || CONFIG_ARM */
396 #endif /* _ASMLANGUAGE */
397 
398 /*
399  * These macros generate absolute symbols for GCC
400  */
401 
402 /* create an extern reference to the absolute symbol */
403 
404 #define GEN_OFFSET_EXTERN(name) extern const char name[]
405 
406 #define GEN_ABS_SYM_BEGIN(name) \
407 	EXTERN_C void name(void); \
408 	void name(void)         \
409 	{
410 
411 #define GEN_ABS_SYM_END }
412 
413 /*
414  * Note that GEN_ABSOLUTE_SYM(), depending on the architecture
415  * and toolchain, may restrict the range of values permitted
416  * for assignment to the named symbol.
417  *
418  * For example, on x86, "value" is interpreated as signed
419  * 32-bit integer. Passing in an unsigned 32-bit integer
420  * with MSB set would result in a negative integer.
421  * Moreover, GCC would error out if an integer larger
422  * than 2^32-1 is passed as "value".
423  */
424 
425 /*
426  * GEN_ABSOLUTE_SYM_KCONFIG() is outputted by the build system
427  * to generate named symbol/value pairs for kconfigs.
428  */
429 
430 #if defined(CONFIG_ARM)
431 
432 /*
433  * GNU/ARM backend does not have a proper operand modifier which does not
434  * produces prefix # followed by value, such as %0 for PowerPC, Intel, and
435  * MIPS. The workaround performed here is using %B0 which converts
436  * the value to ~(value). Thus "n"(~(value)) is set in operand constraint
437  * to output (value) in the ARM specific GEN_OFFSET macro.
438  */
439 
440 #define GEN_ABSOLUTE_SYM(name, value)               \
441 	__asm__(".globl\t" #name "\n\t.equ\t" #name \
442 		",%B0"                              \
443 		"\n\t.type\t" #name ",%%object" :  : "n"(~(value)))
444 
445 #define GEN_ABSOLUTE_SYM_KCONFIG(name, value)       \
446 	__asm__(".globl\t" #name                    \
447 		"\n\t.equ\t" #name "," #value       \
448 		"\n\t.type\t" #name ",%object")
449 
450 #elif defined(CONFIG_X86)
451 
452 #define GEN_ABSOLUTE_SYM(name, value)               \
453 	__asm__(".globl\t" #name "\n\t.equ\t" #name \
454 		",%c0"                              \
455 		"\n\t.type\t" #name ",@object" :  : "n"(value))
456 
457 #define GEN_ABSOLUTE_SYM_KCONFIG(name, value)       \
458 	__asm__(".globl\t" #name                    \
459 		"\n\t.equ\t" #name "," #value       \
460 		"\n\t.type\t" #name ",@object")
461 
462 #elif defined(CONFIG_ARC) || defined(CONFIG_ARM64)
463 
464 #define GEN_ABSOLUTE_SYM(name, value)               \
465 	__asm__(".globl\t" #name "\n\t.equ\t" #name \
466 		",%c0"                              \
467 		"\n\t.type\t" #name ",@object" :  : "n"(value))
468 
469 #define GEN_ABSOLUTE_SYM_KCONFIG(name, value)       \
470 	__asm__(".globl\t" #name                    \
471 		"\n\t.equ\t" #name "," #value       \
472 		"\n\t.type\t" #name ",@object")
473 
474 #elif defined(CONFIG_NIOS2) || defined(CONFIG_RISCV) || defined(CONFIG_XTENSA)
475 
476 /* No special prefixes necessary for constants in this arch AFAICT */
477 #define GEN_ABSOLUTE_SYM(name, value)		\
478 	__asm__(".globl\t" #name "\n\t.equ\t" #name \
479 		",%0"                              \
480 		"\n\t.type\t" #name ",%%object" :  : "n"(value))
481 
482 #define GEN_ABSOLUTE_SYM_KCONFIG(name, value)       \
483 	__asm__(".globl\t" #name                    \
484 		"\n\t.equ\t" #name "," #value       \
485 		"\n\t.type\t" #name ",%object")
486 
487 #elif defined(CONFIG_ARCH_POSIX)
488 #define GEN_ABSOLUTE_SYM(name, value)               \
489 	__asm__(".globl\t" #name "\n\t.equ\t" #name \
490 		",%c0"                              \
491 		"\n\t.type\t" #name ",@object" :  : "n"(value))
492 
493 #define GEN_ABSOLUTE_SYM_KCONFIG(name, value)       \
494 	__asm__(".globl\t" #name                    \
495 		"\n\t.equ\t" #name "," #value       \
496 		"\n\t.type\t" #name ",@object")
497 
498 #elif defined(CONFIG_SPARC)
499 #define GEN_ABSOLUTE_SYM(name, value)			\
500 	__asm__(".global\t" #name "\n\t.equ\t" #name	\
501 		",%0"					\
502 		"\n\t.type\t" #name ",#object" : : "n"(value))
503 
504 #define GEN_ABSOLUTE_SYM_KCONFIG(name, value)       \
505 	__asm__(".globl\t" #name                    \
506 		"\n\t.equ\t" #name "," #value       \
507 		"\n\t.type\t" #name ",#object")
508 
509 #else
510 #error processor architecture not supported
511 #endif
512 
513 #define compiler_barrier() do { \
514 	__asm__ __volatile__ ("" ::: "memory"); \
515 } while (false)
516 
517 /** @brief Return larger value of two provided expressions.
518  *
519  * Macro ensures that expressions are evaluated only once.
520  *
521  * @note Macro has limited usage compared to the standard macro as it cannot be
522  *	 used:
523  *	 - to generate constant integer, e.g. __aligned(Z_MAX(4,5))
524  *	 - static variable, e.g. array like static uint8_t array[Z_MAX(...)];
525  */
526 #define Z_MAX(a, b) ({ \
527 		/* random suffix to avoid naming conflict */ \
528 		__typeof__(a) _value_a_ = (a); \
529 		__typeof__(b) _value_b_ = (b); \
530 		_value_a_ > _value_b_ ? _value_a_ : _value_b_; \
531 	})
532 
533 /** @brief Return smaller value of two provided expressions.
534  *
535  * Macro ensures that expressions are evaluated only once. See @ref Z_MAX for
536  * macro limitations.
537  */
538 #define Z_MIN(a, b) ({ \
539 		/* random suffix to avoid naming conflict */ \
540 		__typeof__(a) _value_a_ = (a); \
541 		__typeof__(b) _value_b_ = (b); \
542 		_value_a_ < _value_b_ ? _value_a_ : _value_b_; \
543 	})
544 
545 /** @brief Return a value clamped to a given range.
546  *
547  * Macro ensures that expressions are evaluated only once. See @ref Z_MAX for
548  * macro limitations.
549  */
550 #define Z_CLAMP(val, low, high) ({                                             \
551 		/* random suffix to avoid naming conflict */                   \
552 		__typeof__(val) _value_val_ = (val);                           \
553 		__typeof__(low) _value_low_ = (low);                           \
554 		__typeof__(high) _value_high_ = (high);                        \
555 		(_value_val_ < _value_low_)  ? _value_low_ :                   \
556 		(_value_val_ > _value_high_) ? _value_high_ :                  \
557 					       _value_val_;                    \
558 	})
559 
560 /**
561  * @brief Calculate power of two ceiling for some nonzero value
562  *
563  * @param x Nonzero unsigned long value
564  * @return X rounded up to the next power of two
565  */
566 #ifdef CONFIG_64BIT
567 #define Z_POW2_CEIL(x) ((1UL << (63U - __builtin_clzl(x))) < x ?  \
568 		1UL << (63U - __builtin_clzl(x) + 1U) : \
569 		1UL << (63U - __builtin_clzl(x)))
570 #else
571 #define Z_POW2_CEIL(x) ((1UL << (31U - __builtin_clzl(x))) < x ?  \
572 		1UL << (31U - __builtin_clzl(x) + 1U) : \
573 		1UL << (31U - __builtin_clzl(x)))
574 #endif
575 
576 #endif /* !_LINKER */
577 #endif /* ZEPHYR_INCLUDE_TOOLCHAIN_GCC_H_ */
578