Debian Codegraph @

gcc/config/bpf/core-builtins.cc

raw
1 /* Subroutines used for code generation for eBPF.
2 Copyright (C) 2019-2025 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
10
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
19
20 #define IN_TARGET_CODE 1
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "target.h"
26 #include "rtl.h"
27 #include "output.h"
28 #include "tree.h"
29 #include "stringpool.h"
30 #include "attribs.h"
31 #include "function.h"
32 #include "memmodel.h"
33 #include "emit-rtl.h"
34 #include "expr.h"
35 #include "diagnostic.h"
36 #include "langhooks.h"
37 #include "basic-block.h"
38 #include "gimple.h"
39 #include "gimple-iterator.h"
40 #include "gimple-walk.h"
41 #include "gimple-fold.h"
42 #include "tree-pass.h"
43 #include "plugin.h"
44 #include "gimplify.h"
45
46 #include "ctfc.h"
47 #include "btf.h"
48 #include "btfext-out.h"
49 #include "core-builtins.h"
50
51 /* BPF CO-RE builtins definition.
52
53 The expansion of CO-RE builtins occur in three steps:
54 1. - bpf_resolve_overloaded_core_builtin (pack step)
55 Right after the front-end, all of the CO-RE builtins are converted to an
56 internal builtin __builtin_core_reloc, which takes a single argument and
57 has polymorphic return value to fit the particular expected return type
58 from the original builtin. The first argument contains an index argument
59 which points to the information stored in a vec<struct cr_builtins> which
60 collects the required information from the original CO-RE builtin in
61 order to use it later on in the __builtin_core_reloc expansion (the next
62 step).
63
64 2. - bpf_expand_core_builtin
65 In this step, the __builtin_core_reloc is expanded to a
66 unspec:UNSPEC_CORE_RELOC with 3 operands, destination, source and the
67 index. The index operand is the index in the vec constructed in the
68 previous step.
69
70 3. - final asm output (process step)
71 This is the output of the unspec:UNSPEC_CORE_RELOC. The index passed in
72 the third operand is read and extracted as a integer from the rtx node.
73 The data is collected from the vec and it is used to create the proper
74 CO-RE relocation as well as do the final assembly output. It also
75 creates a label to mark the location of the move instruction that is used
76 in the CO-RE relocation.
77
78 The initialization of the CO-RE builtins infrastructure occurs in
79 bpf_init_core_builtins function. It creates a struct builtin_helpers_t
80 arrays which defines the kind argument position, the callback helpers,
81 kind, compare, pack and process, for each individual type of builtin
82 argument possible in the original CO-RE builtins.
83
84 More precisely, field expression, type and enum value, used in the
85 following relocations:
86 - __builtin_core_field_info (<field_expr>, <kind>)
87 - __builtin_core_type_id (<type>, <kind>)
88 - __builtin_core_type_info (<type>, <kind>)
89 - __builtin_core_enum_value (<enum_value>, <kind>)
90
91 The kind helper allows to identify the proper relocation for the builtin
92 call based on the value within the kind argument.
93
94 The compare helper is used to identify if a new builtin call has similar
95 arguments to any other builtin call with the compiling unit. This enables
96 the possibility to optimize consecutive similar calls of the builtins.
97
98 The pack helper callbacks are suppose to decode the original CO-RE builtin
99 call arguments, verify that it is a valid tree node for the particular
100 builtin, allocate a struct cr_local in vector and write it with the
101 relevant data for the particular builtin type.
102
103 The process helper should take the data constructed in the pack helper and
104 create a struct cr_final element which contains the essential information
105 to create a CO-RE relocation.
106 This information is further used by the final assembly output step to
107 define the CO-RE relocation and pass-through the default value for the
108 original CO-RE builtin.
109
110 BPF CO-RE preserve access is supported in two forms:
111 - A target builtin, __builtin_preserve_access_index
112
113 This builtin accepts a single argument. Any access to an aggregate data
114 structure (struct, union or array), also referred through the document as
115 an field expression, within the argument will be recorded by the CO-RE
116 machinery, resulting in one or more relocations being inserted in the
117 .BTF.ext section of the output.
118
119 - An attribute, __attribute__((preserve_access_index))
120
121 This attribute can be applied to struct and union types. Any access done
122 through a node typed with this attribute will be recorded by the CO-RE
123 machinery. This conversion is done in an independent gimple pass very
124 early in compilation, making sure that the field expression is
125 originating from a tree node which his type is attributed.
126
127 Both these variants of preserve_access_index rely on a tree walker that
128 identifies and converts any CO-RE valid field expressions. Apart from the
129 gimple specific requirements for the attribute implementation both builtin
130 and attribute implementations rely on the same mechanism. */
131
132 struct GTY(()) cr_builtins
133 {
134 tree type;
135 tree expr;
136 tree default_value;
137 rtx rtx_default_value;
138 enum btf_core_reloc_kind kind;
139 enum bpf_builtins orig_builtin_code;
140 tree orig_arg_expr;
141 tree access_node;
142 };
143 typedef struct cr_builtins *cr_builtins_ref;
144
145 #define CORE_BUILTINS_DATA_EMPTY \
146 { NULL_TREE, NULL_TREE, NULL_TREE, NULL_RTX, BPF_RELO_INVALID, \
147 BPF_BUILTIN_UNUSED, NULL_TREE, NULL_TREE}
148
149 /* Vector definition and its access function. */
150 static GTY(()) vec<cr_builtins_ref, va_gc> *builtins_data = NULL;
151
152 static inline int
153 allocate_builtin_data ()
154 {
155 if (builtins_data == NULL)
156 vec_alloc (builtins_data, 1);
157
158 cr_builtins_ref data = ggc_cleared_alloc<struct cr_builtins> ();
159 int ret = builtins_data->length ();
160 vec_safe_push (builtins_data, data);
161 return ret;
162 }
163
164 static inline struct cr_builtins *
165 get_builtin_data (int index)
166 {
167 return (*builtins_data)[index];
168 }
169
170 typedef bool
171 (*builtin_local_data_compare_fn) (struct cr_builtins *a,
172 struct cr_builtins *b);
173 static inline int
174 search_builtin_data (builtin_local_data_compare_fn callback,
175 struct cr_builtins *elem)
176 {
177 unsigned int i;
178 if (builtins_data != NULL)
179 for (i = 0; i < builtins_data->length (); i++)
180 if ((callback != NULL && (callback) (elem, (*builtins_data)[i]))
181 || (callback == NULL
182 && ((*builtins_data)[i]->orig_arg_expr == elem->orig_arg_expr)))
183 return (int) i;
184
185 return -1;
186 }
187
188 /* Possible relocation decisions. */
189 enum cr_decision
190 {
191 FAILED_VALIDATION = 0,
192 REPLACE_CREATE_RELOCATION,
193 REPLACE_NO_RELOCATION
194 };
195
196 /* Core Relocation Pack local structure. */
197 struct cr_local
198 {
199 struct cr_builtins reloc_data;
200 enum cr_decision reloc_decision;
201 bool fail;
202 };
203 #define CR_LOCAL_EMPTY { CORE_BUILTINS_DATA_EMPTY, FAILED_VALIDATION, false }
204
205 /* Core Relocation Final data */
206 struct cr_final
207 {
208 const char *str;
209 tree type;
210 enum btf_core_reloc_kind kind;
211 };
212
213 /* CO-RE builtin helpers struct. Used and initialized in
214 bpf_init_core_builtins. */
215 struct builtin_helpers
216 {
217 enum btf_core_reloc_kind (*kind) (tree *args, int nargs);
218 bool (*compare) (struct cr_builtins *a, struct cr_builtins *b);
219 struct cr_local (*pack) (tree *args,
220 enum btf_core_reloc_kind kind,
221 enum bpf_builtins code);
222 struct cr_final (*process) (struct cr_builtins *data);
223 bool is_pure;
224 bool is_valid;
225 };
226
227 struct builtin_helpers
228 core_builtin_helpers[(int) BPF_BUILTIN_MAX];
229
230 #define BPF_CORE_HELPER_NOTSET { NULL, NULL, NULL, NULL, false, false }
231 #define BPF_CORE_HELPER_SET(KIND, COMPARE, PACK, PROCESS, IS_PURE) \
232 { KIND, COMPARE, PACK, PROCESS, IS_PURE, true }
233
234 enum bpf_plugin_states
235 {
236 BPF_PLUGIN_DISABLED = 0,
237 BPF_PLUGIN_ENABLED,
238 BPF_PLUGIN_REMOVED
239 };
240 enum bpf_plugin_states plugin_state = BPF_PLUGIN_DISABLED;
241
242 static void
243 remove_parser_plugin ()
244 {
245 /* Restore state of the plugin system. */
246 if (flag_plugin_added == true && plugin_state != BPF_PLUGIN_REMOVED)
247 {
248 unregister_callback ("bpf_collect_enum_info", PLUGIN_FINISH_TYPE);
249 flag_plugin_added = (bool) plugin_state == BPF_PLUGIN_ENABLED;
250 plugin_state = BPF_PLUGIN_REMOVED;
251 }
252 }
253
254 #define bpf_error(MSG) { \
255 remove_parser_plugin (); \
256 error (MSG); \
257 }
258
259 #define bpf_error_at(LOC, MSG) { \
260 remove_parser_plugin (); \
261 error_at (LOC, MSG); \
262 }
263
264
265 /* Helper compare functions used to verify if multiple builtin calls contain
266 the same argument as input. In that case the builtin calls can be optimized
267 out by identifying redundat calls. This happen since the internal
268 __core_reloc builtin is marked as PURE. */
269
270 static inline bool
271 compare_same_kind (struct cr_builtins *a, struct cr_builtins *b)
272 {
273 return a->kind == b->kind;
274 }
275 static inline bool
276 compare_same_ptr_expr (struct cr_builtins *a, struct cr_builtins *b)
277 {
278 return compare_same_kind (a, b) && a->expr == b->expr;
279 }
280 static inline bool
281 compare_same_ptr_type (struct cr_builtins *a, struct cr_builtins *b)
282 {
283 return compare_same_kind (a, b) && a->type == b->type;
284 }
285
286 /* Handling for __attribute__((preserve_access_index)) for BPF CO-RE support.
287
288 This attribute marks a structure/union/array type as "preserve", so that
289 every access to that type should be recorded and replayed by the BPF loader;
290 this is just the same functionality as __builtin_preserve_access_index,
291 but in the form of an attribute for an entire aggregate type.
292
293 Note also that nested structs behave as though they all have the attribute.
294 For example:
295 struct X { int a; };
296 struct Y { struct X bar} __attribute__((preserve_access_index));
297 struct Y foo;
298 foo.bar.a;
299 will record access all the way to 'a', even though struct X does not have
300 the preserve_access_index attribute.
301
302 This is to follow LLVM behavior. */
303
304 /* True if tree T accesses any member of a struct/union/class which is marked
305 with the PRESERVE_ACCESS_INDEX attribute. */
306
307 static bool
308 is_attr_preserve_access (tree t)
309 {
310 if (t == NULL_TREE)
311 return false;
312
313 poly_int64 bitsize, bitpos;
314 tree var_off;
315 machine_mode mode;
316 int sign, reverse, vol;
317
318 tree base = get_inner_reference (t, &bitsize, &bitpos, &var_off, &mode,
319 &sign, &reverse, &vol);
320
321 if (TREE_CODE (t) == SSA_NAME
322 || TREE_CODE (t) == VAR_DECL)
323 return lookup_attribute ("preserve_access_index",
324 TYPE_ATTRIBUTES (TREE_TYPE (base)));
325
326 if (TREE_CODE (base) == MEM_REF)
327 return lookup_attribute ("preserve_access_index",
328 TYPE_ATTRIBUTES (TREE_TYPE (base)));
329
330 if (TREE_CODE (t) == COMPONENT_REF)
331 {
332 /* preserve_access_index propagates into nested structures,
333 so check whether this is a component of another component
334 which in turn is part of such a struct. */
335
336 const tree op = TREE_OPERAND (t, 0);
337
338 if (TREE_CODE (op) == COMPONENT_REF)
339 return is_attr_preserve_access (op);
340
341 const tree container = DECL_CONTEXT (TREE_OPERAND (t, 1));
342
343 return lookup_attribute ("preserve_access_index",
344 TYPE_ATTRIBUTES (container))
345 || is_attr_preserve_access (op);
346 }
347
348 else if (TREE_CODE (t) == ADDR_EXPR)
349 return is_attr_preserve_access (TREE_OPERAND (t, 0));
350
351 return false;
352 }
353
354 static tree
355 root_for_core_field_info (tree node)
356 {
357 bool done = false;
358 while (!done)
359 {
360 switch (TREE_CODE (node))
361 {
362 case ADDR_EXPR:
363 case NOP_EXPR:
364 node = TREE_OPERAND (node, 0);
365 break;
366 default:
367 done = true;
368 break;
369 }
370 }
371 return node;
372 }
373
374 /* Expand a call to __builtin_preserve_field_info by evaluating the requested
375 information about SRC according to KIND, and return a tree holding
376 the result. */
377
378 static tree
379 core_field_info (tree src, enum btf_core_reloc_kind kind)
380 {
381 unsigned int result;
382 poly_int64 bitsize, bitpos;
383 tree var_off = NULL_TREE;
384 machine_mode mode;
385 int unsignedp, reversep, volatilep;
386 location_t loc = EXPR_LOCATION (src);
387 tree type = TREE_TYPE (src);
388
389 src = root_for_core_field_info (src);
390
391 tree root = get_inner_reference (src, &bitsize, &bitpos, &var_off, &mode,
392 &unsignedp, &reversep, &volatilep);
393
394 /* Note: Use DECL_BIT_FIELD_TYPE rather than DECL_BIT_FIELD here, because it
395 remembers whether the field in question was originally declared as a
396 bitfield, regardless of how it has been optimized. */
397 bool bitfieldp = (TREE_CODE (src) == COMPONENT_REF
398 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (src, 1)));
399
400 unsigned int align = TYPE_ALIGN (TREE_TYPE (src));
401 if (TREE_CODE (src) == COMPONENT_REF)
402 {
403 tree field = TREE_OPERAND (src, 1);
404 if (DECL_BIT_FIELD_TYPE (field))
405 align = TYPE_ALIGN (DECL_BIT_FIELD_TYPE (field));
406 else
407 align = TYPE_ALIGN (TREE_TYPE (field));
408 }
409
410 unsigned int start_bitpos = bitpos & ~(align - 1);
411 unsigned int end_bitpos = start_bitpos + align;
412
413 switch (kind)
414 {
415 case BPF_RELO_FIELD_BYTE_OFFSET:
416 {
417 result = 0;
418 if (var_off == NULL_TREE
419 && TREE_CODE (root) == INDIRECT_REF
420 && TREE_CODE (TREE_OPERAND (root, 0)) == POINTER_PLUS_EXPR)
421 {
422 tree node = TREE_OPERAND (root, 0);
423 tree offset = TREE_OPERAND (node, 1);
424 tree type = TREE_TYPE (TREE_OPERAND (node, 0));
425 type = TREE_TYPE (type);
426
427 gcc_assert (TREE_CODE (offset) == INTEGER_CST && tree_fits_shwi_p (offset)
428 && COMPLETE_TYPE_P (type) && tree_fits_shwi_p (TYPE_SIZE (type)));
429
430 HOST_WIDE_INT offset_i = tree_to_shwi (offset);
431 result += offset_i;
432 }
433
434 type = unsigned_type_node;
435 if (var_off != NULL_TREE)
436 {
437 bpf_error_at (loc, "unsupported variable field offset");
438 return error_mark_node;
439 }
440
441 if (bitfieldp)
442 result += start_bitpos / 8;
443 else
444 result += bitpos / 8;
445 }
446 break;
447
448 case BPF_RELO_FIELD_BYTE_SIZE:
449 {
450 type = unsigned_type_node;
451 if (mode == BLKmode && bitsize == -1)
452 {
453 bpf_error_at (loc, "unsupported variable size field access");
454 return error_mark_node;
455 }
456
457 if (bitfieldp)
458 {
459 /* To match LLVM behavior, byte size of bitfields is recorded as
460 the full size of the base type. A 3-bit bitfield of type int is
461 therefore recorded as having a byte size of 4 bytes. */
462 result = end_bitpos - start_bitpos;
463 if (result & (result - 1))
464 {
465 bpf_error_at (loc, "unsupported field expression");
466 return error_mark_node;
467 }
468 result = result / 8;
469 }
470 else
471 result = bitsize / 8;
472 }
473 break;
474
475 case BPF_RELO_FIELD_EXISTS:
476 type = unsigned_type_node;
477 /* The field always exists at compile time. */
478 result = 1;
479 break;
480
481 case BPF_RELO_FIELD_SIGNED:
482 type = unsigned_type_node;
483 result = !unsignedp;
484 break;
485
486 case BPF_RELO_FIELD_LSHIFT_U64:
487 case BPF_RELO_FIELD_RSHIFT_U64:
488 {
489 type = unsigned_type_node;
490 if (mode == BLKmode && bitsize == -1)
491 {
492 bpf_error_at (loc, "unsupported variable size field access");
493 return error_mark_node;
494 }
495 if (var_off != NULL_TREE)
496 {
497 bpf_error_at (loc, "unsupported variable field offset");
498 return error_mark_node;
499 }
500
501 if (!bitfieldp)
502 {
503 if (bitsize > 64)
504 {
505 bpf_error_at (loc, "field size too large");
506 return error_mark_node;
507 }
508 result = 64 - bitsize;
509 break;
510 }
511
512 if (end_bitpos - start_bitpos > 64)
513 {
514 bpf_error_at (loc, "field size too large");
515 return error_mark_node;
516 }
517
518 if (kind == BPF_RELO_FIELD_LSHIFT_U64)
519 {
520 if (TARGET_BIG_ENDIAN)
521 result = bitpos + 64 - start_bitpos - align;
522 else
523 result = start_bitpos + 64 - bitpos - bitsize;
524 }
525 else /* RSHIFT_U64 */
526 result = 64 - bitsize;
527 }
528 break;
529
530 default:
531 bpf_error ("invalid second argument to built-in function");
532 return error_mark_node;
533 break;
534 }
535
536 return build_int_cst (type, result);
537 }
538
539 /* Compute the index of the NODE in its immediate container.
540 NODE should be a FIELD_DECL (i.e. of struct or union), or an ARRAY_REF. */
541
542 static int
543 bpf_core_get_index (const tree node, bool *valid)
544 {
545 enum tree_code code = TREE_CODE (node);
546
547 if (code == FIELD_DECL)
548 {
549 /* Lookup the index from the type fields information. */
550 const tree container = DECL_CONTEXT (node);
551 int i = 0;
552 for (tree l = TYPE_FIELDS (container); l; l = DECL_CHAIN (l))
553 {
554 if (l == node)
555 return i;
556 /* Skip unnamed padding, not represented by BTF. */
557 if (DECL_NAME(l) != NULL_TREE
558 || TREE_CODE (TREE_TYPE (l)) == UNION_TYPE
559 || TREE_CODE (TREE_TYPE (l)) == RECORD_TYPE)
560 i++;
561 }
562 }
563 else if (code == ARRAY_REF || code == ARRAY_RANGE_REF || code == MEM_REF)
564 {
565 /* For array accesses, the index is operand 1. */
566 tree index = TREE_OPERAND (node, 1);
567
568 /* If the indexing operand is a constant, extracting is trivial. */
569 if (TREE_CODE (index) == INTEGER_CST && tree_fits_shwi_p (index))
570 return tree_to_shwi (index);
571 }
572 else if (code == POINTER_PLUS_EXPR)
573 {
574 tree offset = TREE_OPERAND (node, 1);
575 tree type = TREE_TYPE (TREE_OPERAND (node, 0));
576 type = TREE_TYPE (type);
577
578 if (TREE_CODE (offset) == INTEGER_CST && tree_fits_shwi_p (offset)
579 && COMPLETE_TYPE_P (type) && tree_fits_shwi_p (TYPE_SIZE (type)))
580 {
581 HOST_WIDE_INT offset_i = tree_to_shwi (offset);
582 HOST_WIDE_INT type_size_i = tree_to_shwi (TYPE_SIZE_UNIT (type));
583 if ((offset_i % type_size_i) == 0)
584 return offset_i / type_size_i;
585 }
586 }
587
588 if (valid != NULL)
589 *valid = false;
590 return -1;
591 }
592
593 #define PREPARE_FAKE_PTR(P) \
594 _fake_##P; \
595 if (P == NULL) \
596 P = &_fake_##P; \
597 _fake_##P
598
599 #define MAX_NR_ACCESSORS 100
600
601 /* This function validates and extracts information for CO-RE field expression.
602 Any parametric expression is allowed to be passed in argument NODE.
603
604 If NODE is a valid CO-RE expression VALID boolean pointer would be set to
605 true.
606
607 A CO-RE field expression is an expression accessing structures, arrays and
608 unions.
609 An examples of CO-RE valid expression is:
610 A->B[2].UNION_C.D
611
612 This function traverses the tree structure to verify if the expression in
613 NODE is valid and extracts other characteristics of the expression, and
614 returns it by updating the pointer arguments:
615
616 ACCESSORS: is an array with the indexes of the particular fields
617 within the expression. The indexes are related to actual index on the
618 struct/union type, or the array access index. The RETURN of the function
619 is the number of accessors required to represent this expression in CO-RE
620 access string.
621 VALID - boolean pointer that sets if expression is valid or not for CO-RE.
622 ACCESS_NODE - It is the base of the expression. Using the example below is
623 the node that represents the A in the expression.
624
625 ALLOW_ENTRY_CAST is an input arguments and specifies if the function should
626 consider as valid expressions in which NODE entry is a cast expression (or
627 tree code nop_expr).
628
629 EXTRA_FN is a callback function to allow extra functionality with this
630 function traversal. Currently used for marking used type during expand
631 pass. */
632
633 typedef void (*extra_fn) (tree);
634
635 static unsigned char
636 compute_field_expr (tree node, unsigned int *accessors,
637 bool *valid,
638 tree *access_node,
639 bool allow_entry_cast = true,
640 extra_fn callback = NULL)
641 {
642 unsigned char n = 0;
643 unsigned int fake_accessors[MAX_NR_ACCESSORS];
644 if (accessors == NULL)
645 accessors = fake_accessors;
646 bool PREPARE_FAKE_PTR (valid) = true;
647 tree PREPARE_FAKE_PTR (access_node) = NULL_TREE;
648
649 if (node == NULL_TREE)
650 {
651 *valid = false;
652 return 0;
653 }
654
655 *access_node = node;
656
657 if (callback != NULL)
658 callback (node);
659
660 switch (TREE_CODE (node))
661 {
662 case INDIRECT_REF:
663 if (TREE_CODE (node = TREE_OPERAND (node, 0)) == POINTER_PLUS_EXPR)
664 {
665 accessors[0] = bpf_core_get_index (node, valid);
666 *access_node = TREE_OPERAND (node, 0);
667 return 1;
668 }
669 else
670 {
671 accessors[0] = 0;
672 return 1;
673 }
674 case COMPONENT_REF:
675 n = compute_field_expr (TREE_OPERAND (node, 0), accessors,
676 valid,
677 access_node, false, callback);
678 accessors[n] = bpf_core_get_index (TREE_OPERAND (node, 1), valid);
679 return n + 1;
680 case ARRAY_REF:
681 case ARRAY_RANGE_REF:
682 n = compute_field_expr (TREE_OPERAND (node, 0), accessors,
683 valid,
684 access_node, false, callback);
685 accessors[n++] = bpf_core_get_index (node, valid);
686 return n;
687 case MEM_REF:
688 accessors[0] = bpf_core_get_index (node, valid);
689 return 1;
690 case NOP_EXPR:
691 if (allow_entry_cast == true)
692 {
693 *valid = false;
694 return 0;
695 }
696 n = compute_field_expr (TREE_OPERAND (node, 0), accessors,
697 valid,
698 access_node, false, callback);
699 return n;
700
701 case VAR_DECL:
702 accessors[0] = 0;
703 return 1;
704
705 case ADDR_EXPR:
706 case CALL_EXPR:
707 case SSA_NAME:
708 case PARM_DECL:
709 return 0;
710 default:
711 *valid = false;
712 return 0;
713 }
714 }
715 #undef PREPARE_FAKE_PTR
716
717
718 /* Pack helper for the __builtin_preserve_field_info. */
719
720 static struct cr_local
721 pack_field_expr (tree *args,
722 enum btf_core_reloc_kind kind,
723 enum bpf_builtins code ATTRIBUTE_UNUSED)
724 {
725 struct cr_local ret = CR_LOCAL_EMPTY;
726 ret.fail = false;
727
728 tree arg = args[0];
729 tree root = arg;
730 tree access_node = NULL_TREE;
731 tree type = NULL_TREE;
732
733 if (TREE_CODE (root) == ADDR_EXPR)
734 root = TREE_OPERAND (root, 0);
735
736 ret.reloc_decision = REPLACE_CREATE_RELOCATION;
737
738 unsigned int accessors[100];
739 bool valid = true;
740 compute_field_expr (root, accessors, &valid, &access_node, false);
741
742 type = TREE_TYPE (access_node);
743 if (POINTER_TYPE_P (type))
744 type = TREE_TYPE (type);
745
746 if (valid == true)
747 {
748 ret.reloc_data.expr = root;
749
750 /* Note: the type of default_value is used to define the return type of
751 __builtin_core_reloc in bpf_resolve_overloaded_core_builtin. */
752 ret.reloc_data.access_node = access_node;
753 ret.reloc_data.type = type;
754 ret.reloc_data.default_value = core_field_info (root, kind);
755 ret.reloc_data.kind = kind;
756
757 if (TREE_CODE (ret.reloc_data.default_value) == ERROR_MARK)
758 ret.fail = true;
759 }
760 else
761 {
762 bpf_error_at (EXPR_LOC_OR_LOC (arg, UNKNOWN_LOCATION),
763 "argument is not a field access");
764 ret.fail = true;
765 }
766
767 return ret;
768 }
769
770 /* Process helper for the __builtin_preserve_field_info. */
771
772 static struct cr_final
773 process_field_expr (struct cr_builtins *data)
774 {
775 gcc_assert (data->kind == BPF_RELO_FIELD_BYTE_OFFSET
776 || data->kind == BPF_RELO_FIELD_BYTE_SIZE
777 || data->kind == BPF_RELO_FIELD_LSHIFT_U64
778 || data->kind == BPF_RELO_FIELD_RSHIFT_U64
779 || data->kind == BPF_RELO_FIELD_SIGNED
780 || data->kind == BPF_RELO_FIELD_EXISTS);
781
782 unsigned int accessors[MAX_NR_ACCESSORS];
783 unsigned char nr_accessors = 0;
784 tree expr = data->expr;
785 tree type = data->type;
786
787 if (TREE_CODE (expr) == ADDR_EXPR)
788 expr = TREE_OPERAND (expr, 0);
789
790 expr = root_for_core_field_info (expr);
791 nr_accessors = compute_field_expr (expr, accessors, NULL, NULL, false);
792
793 struct cr_final ret = { NULL, type, data->kind };
794
795 char str[100];
796 if (nr_accessors > 0)
797 {
798 int n = 0;
799 for (int i = 0; i < nr_accessors; i++)
800 n += snprintf (str + n, sizeof (str) - n,
801 i == 0 ? "%u" : ":%u", accessors[i]);
802 ret.str = CONST_CAST (char *, ggc_strdup (str));
803 }
804 else
805 gcc_unreachable ();
806
807 return ret;
808 }
809
810 static GTY(()) hash_map<tree, tree> *bpf_enum_mappings;
811 tree enum_value_type = NULL_TREE;
812
813 static int
814 get_index_for_enum_value (tree type, tree expr)
815 {
816 gcc_assert (TREE_CODE (expr) == CONST_DECL
817 && TREE_CODE (type) == ENUMERAL_TYPE);
818
819 unsigned int index = 0;
820 for (tree l = TYPE_VALUES (type); l; l = TREE_CHAIN (l))
821 {
822 gcc_assert (index < (1 << 16));
823 if (TREE_VALUE (l) == expr)
824 return index;
825 index++;
826 }
827 return -1;
828 }
829
830 /* Pack helper for the __builtin_preserve_enum_value. */
831
832 static struct cr_local
833 pack_enum_value (tree *args, enum btf_core_reloc_kind kind,
834 enum bpf_builtins code ATTRIBUTE_UNUSED)
835 {
836 struct cr_local ret = CR_LOCAL_EMPTY;
837 ret.reloc_decision = REPLACE_CREATE_RELOCATION;
838 ret.fail = false;
839
840 tree *result = NULL;
841 tree tmp = args[0];
842 tree enum_value = args[1];
843 tree type = NULL_TREE;
844
845 /* Deconstructing "*(typeof (enum_type) *) enum_value" to collect both the
846 enum_type and enum_value. */
847 if (TREE_CODE (tmp) != TARGET_EXPR
848 || (type = TREE_TYPE (tmp)) == NULL_TREE
849 || (TREE_CODE (type) != POINTER_TYPE)
850 || (type = TREE_TYPE (type)) == NULL_TREE
851 || (TREE_CODE (type) != ENUMERAL_TYPE))
852 {
853 bpf_error ("invalid type argument format for enum value builtin");
854 ret.fail = true;
855 }
856
857 if (TREE_CODE (enum_value) != INTEGER_CST)
858 goto pack_enum_value_fail;
859
860 result = bpf_enum_mappings->get (enum_value);
861 if (result == NULL)
862 goto pack_enum_value_fail;
863
864 tmp = *result;
865
866 if (TREE_CODE (tmp) != CONST_DECL)
867 {
868 pack_enum_value_fail:
869 bpf_error ("invalid enum value argument for enum value builtin");
870 ret.fail = true;
871 }
872 else
873 {
874 ret.reloc_data.expr = tmp;
875 if (kind == BPF_RELO_ENUMVAL_VALUE)
876 ret.reloc_data.default_value = enum_value;
877 else
878 ret.reloc_data.default_value = integer_one_node;
879 }
880
881 if (ret.fail == false )
882 {
883 int index = get_index_for_enum_value (type, tmp);
884 if (index == -1 || index >= (1 << 16))
885 {
886 bpf_error ("enum value in CO-RE builtin cannot be represented");
887 ret.fail = true;
888 }
889 }
890
891 ret.reloc_data.type = type;
892 ret.reloc_data.kind = kind;
893 return ret;
894 }
895
896 /* Process helper for the __builtin_preserve_enum_value. */
897
898 static struct cr_final
899 process_enum_value (struct cr_builtins *data)
900 {
901 gcc_assert (data->kind == BPF_RELO_ENUMVAL_EXISTS
902 || data->kind == BPF_RELO_ENUMVAL_VALUE);
903
904 tree expr = data->expr;
905 tree type = data->type;
906
907 struct cr_final ret = { NULL, type, data->kind };
908
909 gcc_assert (TREE_CODE (expr) == CONST_DECL
910 && TREE_CODE (type) == ENUMERAL_TYPE);
911
912 int index = get_index_for_enum_value (type, expr);
913 gcc_assert (index != -1 && index < (1 << 16));
914
915 /* Index can only be a value up to 2^16. Should always fit
916 in 6 chars. */
917 char tmp[6];
918 sprintf (tmp, "%u", index);
919 ret.str = CONST_CAST (char *, ggc_strdup(tmp));
920
921 return ret;
922 }
923
924 /* Pack helper for the __builtin_preserve_type_info. */
925
926 static struct cr_local
927 pack_type (tree *args, enum btf_core_reloc_kind kind,
928 enum bpf_builtins code ATTRIBUTE_UNUSED)
929 {
930 struct cr_local ret = CR_LOCAL_EMPTY;
931 ret.reloc_decision = FAILED_VALIDATION;
932 ret.reloc_data.default_value = integer_zero_node;
933 ret.fail = false;
934
935 tree root_type = NULL_TREE;
936 tree tmp = args[0];
937 HOST_WIDE_INT type_size_i;
938
939 if (TYPE_P (tmp))
940 goto is_already_type;
941 /* Typical structure to match:
942 *({ extern typeof (TYPE) *<tmp_name>; <tmp_name>; }) */
943
944 /* Extract Pointer dereference from the construct. */
945 while (tmp != NULL_TREE
946 && (TREE_CODE (tmp) == INDIRECT_REF
947 || TREE_CODE (tmp) == NOP_EXPR))
948 tmp = TREE_OPERAND (tmp, 0);
949
950 if (TREE_CODE (tmp) != TARGET_EXPR
951 || TREE_CODE (tmp = TREE_OPERAND (tmp, 1)) != BIND_EXPR)
952 goto pack_type_fail;
953
954 tmp = BIND_EXPR_VARS (tmp);
955
956 if (TREE_CODE (tmp) != TYPE_DECL
957 && TREE_CODE (tmp) != VAR_DECL)
958 goto pack_type_fail;
959
960 tmp = TREE_TYPE (tmp);
961
962 is_already_type:
963 if (TREE_CODE (tmp) == POINTER_TYPE)
964 tmp = TREE_TYPE (tmp);
965
966 root_type = tmp;
967
968 if (TREE_CODE (tmp) != RECORD_TYPE
969 && TREE_CODE (tmp) != UNION_TYPE
970 && TREE_CODE (tmp) != ENUMERAL_TYPE
971 && (TREE_CODE (tmp) != POINTER_TYPE
972 || TREE_CODE (TREE_TYPE (tmp)) == FUNCTION_TYPE)
973 && (TREE_CODE (tmp) != POINTER_TYPE
974 || TREE_CODE (TREE_TYPE (tmp)) == VOID_TYPE)
975 && TREE_CODE (tmp) != ARRAY_TYPE
976 && TREE_CODE (tmp) != INTEGER_TYPE)
977 goto pack_type_fail;
978
979 ret.reloc_data.type = root_type;
980 ret.reloc_decision = REPLACE_CREATE_RELOCATION;
981
982 /* Force this type to be marked as used in dwarf2out. */
983 gcc_assert (cfun);
984 if (cfun->used_types_hash == NULL)
985 cfun->used_types_hash = hash_set<tree>::create_ggc (37);
986 cfun->used_types_hash->add (root_type);
987
988 type_size_i = tree_to_shwi (TYPE_SIZE_UNIT (ret.reloc_data.type));
989
990 switch (kind)
991 {
992 case BPF_RELO_TYPE_SIZE:
993 ret.reloc_data.default_value = build_int_cst (integer_type_node,
994 type_size_i);
995 break;
996 case BPF_RELO_TYPE_EXISTS:
997 case BPF_RELO_TYPE_MATCHES:
998 ret.reloc_data.default_value = integer_one_node;
999 break;
1000 case BPF_RELO_TYPE_ID_LOCAL:
1001 case BPF_RELO_TYPE_ID_TARGET:
1002 ret.reloc_data.default_value = integer_zero_node;
1003 break;
1004 default:
1005 break;
1006 }
1007
1008 ret.reloc_data.kind = kind;
1009 return ret;
1010
1011 pack_type_fail:
1012 bpf_error_at (EXPR_LOC_OR_LOC (args[0], UNKNOWN_LOCATION),
1013 "invalid first argument format for enum value builtin");
1014 ret.fail = true;
1015 return ret;
1016 }
1017
1018 /* Process helper for the __builtin_preserve_type_info. */
1019
1020 static struct cr_final
1021 process_type (struct cr_builtins *data)
1022 {
1023 gcc_assert (data->kind == BPF_RELO_TYPE_ID_LOCAL
1024 || data->kind == BPF_RELO_TYPE_ID_TARGET
1025 || data->kind == BPF_RELO_TYPE_EXISTS
1026 || data->kind == BPF_RELO_TYPE_SIZE
1027 || data->kind == BPF_RELO_TYPE_MATCHES);
1028
1029 struct cr_final ret;
1030 ret.str = ggc_strdup ("0");
1031 ret.type = data->type;
1032 ret.kind = data->kind;
1033
1034 if ((data->kind == BPF_RELO_TYPE_ID_LOCAL
1035 || data->kind == BPF_RELO_TYPE_ID_TARGET)
1036 && data->default_value != NULL)
1037 {
1038 ctf_container_ref ctfc = ctf_get_tu_ctfc ();
1039 ctf_dtdef_ref dtd = ctf_lookup_tree_type (ctfc, ret.type);
1040 unsigned int btf_id = dtd ? dtd->dtd_type : BTF_VOID_TYPEID;
1041 data->rtx_default_value = expand_normal (build_int_cst (integer_type_node,
1042 btf_id));
1043 }
1044
1045 return ret;
1046 }
1047
1048 static bool
1049 bpf_require_core_support ()
1050 {
1051 if (!TARGET_BPF_CORE)
1052 {
1053 bpf_error ("BPF CO-RE is required but not enabled");
1054 return false;
1055 }
1056 return true;
1057 }
1058
1059 /* BPF Compile Once - Run Everywhere (CO-RE) support. Construct a CO-RE
1060 relocation record in DATA to be emitted in the .BTF.ext
1061 section. Does nothing if we are not targetting BPF CO-RE, or if the
1062 constructed relocation would be a no-op. */
1063
1064 static void
1065 make_core_relo (struct cr_final *data, rtx_code_label *label)
1066 {
1067 /* If we are not targetting BPF CO-RE, do not make a relocation. We
1068 might not be generating any debug info at all. */
1069 if (!bpf_require_core_support ())
1070 return;
1071
1072 gcc_assert (data->type);
1073
1074 /* Determine what output section this relocation will apply to.
1075 If this function is associated with a section, use that. Otherwise,
1076 fall back on '.text'. */
1077 const char * section_name;
1078 if (current_function_decl && DECL_SECTION_NAME (current_function_decl))
1079 section_name = DECL_SECTION_NAME (current_function_decl);
1080 else
1081 section_name = ".text";
1082
1083 /* Add the CO-RE relocation information to the BTF container. */
1084 bpf_core_reloc_add (data->type, section_name, data->str, label,
1085 data->kind);
1086 }
1087
1088 /* Support function to extract kind information for CO-RE builtin
1089 calls. */
1090
1091 static inline char
1092 read_kind (tree kind, char max_value, char enum_offset)
1093 {
1094 char kind_val = 0;
1095
1096 if (kind == NULL_TREE)
1097 goto invalid_kind_arg_error;
1098
1099 if (TREE_CODE (kind) != CONST_DECL
1100 && TREE_CODE (kind) == NOP_EXPR)
1101 kind = TREE_OPERAND (kind, 0);
1102
1103 if (TREE_CODE (kind) == CONST_DECL)
1104 kind = DECL_INITIAL (kind);
1105
1106 if (TREE_CODE (kind) == INTEGER_CST
1107 && tree_fits_uhwi_p (kind))
1108 kind_val = tree_to_uhwi (kind);
1109 else
1110 goto invalid_kind_arg_error;
1111
1112 if (kind_val > max_value)
1113 {
1114 invalid_kind_arg_error:
1115 bpf_error ("invalid kind argument to core builtin");
1116 return -1;
1117 }
1118 return kind_val + enum_offset;
1119 }
1120
1121 #define KIND_EXPECT_NARGS(N, MSG) \
1122 { if (nargs != N) { bpf_error (MSG); return BPF_RELO_INVALID; } }
1123
1124 /* Helper functions to extract kind information. */
1125 static inline enum btf_core_reloc_kind
1126 kind_access_index (tree *args ATTRIBUTE_UNUSED, int nargs)
1127 {
1128 KIND_EXPECT_NARGS (1,
1129 "wrong number of arguments for access index core builtin");
1130 return BPF_RELO_FIELD_BYTE_OFFSET;
1131 }
1132 static inline enum btf_core_reloc_kind
1133 kind_preserve_field_info (tree *args, int nargs)
1134 {
1135 KIND_EXPECT_NARGS (2,
1136 "wrong number of arguments for field info core builtin");
1137 return (enum btf_core_reloc_kind) read_kind (args[1], 5,
1138 BPF_RELO_FIELD_BYTE_OFFSET);
1139 }
1140 static inline enum btf_core_reloc_kind
1141 kind_enum_value (tree *args, int nargs)
1142 {
1143 KIND_EXPECT_NARGS (3,
1144 "wrong number of arguments for enum value core builtin");
1145 return (enum btf_core_reloc_kind) read_kind (args[2], 1,
1146 BPF_RELO_ENUMVAL_EXISTS);
1147 }
1148 static inline enum btf_core_reloc_kind
1149 kind_type_id (tree *args, int nargs)
1150 {
1151 KIND_EXPECT_NARGS (2,
1152 "wrong number of arguments for type id core builtin");
1153 return (enum btf_core_reloc_kind) read_kind (args[1], 1,
1154 BPF_RELO_TYPE_ID_LOCAL);
1155 }
1156 static inline enum btf_core_reloc_kind
1157 kind_preserve_type_info (tree *args, int nargs)
1158 {
1159 KIND_EXPECT_NARGS (2,
1160 "wrong number of arguments for type info core builtin");
1161 char val = read_kind (args[1], 2, 0);
1162 switch (val)
1163 {
1164 case 0:
1165 return BPF_RELO_TYPE_EXISTS;
1166 case 1:
1167 return BPF_RELO_TYPE_SIZE;
1168 case 2:
1169 return BPF_RELO_TYPE_MATCHES;
1170 default:
1171 break;
1172 }
1173 return BPF_RELO_INVALID;
1174 }
1175
1176 /* Plugin handler used in the parser that allows to collect enum value
1177 information that other wise would be folded and non recoverable. */
1178
1179 void
1180 bpf_handle_plugin_finish_type (void *event_data,
1181 void *data ATTRIBUTE_UNUSED)
1182 {
1183 tree type = (tree) event_data;
1184
1185 if (bpf_enum_mappings == NULL)
1186 bpf_enum_mappings = hash_map<tree, tree>::create_ggc (10);
1187
1188 if (TREE_CODE (type) == ENUMERAL_TYPE)
1189 for (tree l = TYPE_VALUES (type); l; l = TREE_CHAIN (l))
1190 {
1191 tree value = TREE_VALUE (l);
1192
1193 tree initial = DECL_INITIAL (value);
1194 initial = copy_node (initial);
1195 DECL_INITIAL (value) = initial;
1196
1197 tree *found = bpf_enum_mappings->get (initial);
1198 if (found == NULL)
1199 bpf_enum_mappings->put (initial, value);
1200 }
1201 }
1202
1203 /* Initializes support information to process CO-RE builtins.
1204 Defines information for the builtin processing, such as helper functions to
1205 support the builtin convertion. */
1206
1207 void
1208 bpf_init_core_builtins (void)
1209 {
1210 memset (core_builtin_helpers, 0, sizeof (core_builtin_helpers));
1211
1212 core_builtin_helpers[BPF_BUILTIN_PRESERVE_ACCESS_INDEX] =
1213 BPF_CORE_HELPER_SET (kind_access_index,
1214 NULL,
1215 NULL,
1216 NULL,
1217 true);
1218 core_builtin_helpers[BPF_BUILTIN_PRESERVE_FIELD_INFO] =
1219 BPF_CORE_HELPER_SET (kind_preserve_field_info,
1220 NULL,
1221 pack_field_expr,
1222 process_field_expr,
1223 true);
1224 core_builtin_helpers[BPF_BUILTIN_BTF_TYPE_ID] =
1225 BPF_CORE_HELPER_SET (kind_type_id,
1226 compare_same_ptr_type,
1227 pack_type,
1228 process_type,
1229 true);
1230
1231 core_builtin_helpers[BPF_BUILTIN_PRESERVE_TYPE_INFO] =
1232 BPF_CORE_HELPER_SET (kind_preserve_type_info,
1233 compare_same_ptr_type,
1234 pack_type,
1235 process_type,
1236 true);
1237
1238 core_builtin_helpers[BPF_BUILTIN_PRESERVE_ENUM_VALUE] =
1239 BPF_CORE_HELPER_SET (kind_enum_value,
1240 compare_same_ptr_expr,
1241 pack_enum_value,
1242 process_enum_value,
1243 true);
1244
1245 core_builtin_helpers[BPF_BUILTIN_CORE_RELOC] =
1246 BPF_CORE_HELPER_SET (NULL, NULL, NULL, NULL, true);
1247
1248 /* Initialize plugin handler to record enums value for use in
1249 __builtin_preserve_enum_value. */
1250 plugin_state = (enum bpf_plugin_states) flag_plugin_added;
1251 flag_plugin_added = true;
1252 register_callback ("bpf_collect_enum_info", PLUGIN_FINISH_TYPE,
1253 bpf_handle_plugin_finish_type, NULL);
1254 }
1255
1256 /* This function returns the related __builtin_core_reloc call tree node to a
1257 particular CO-RE builtin definition in FNDECL when called with
1258 arguments ARGS. */
1259
1260 static tree
1261 construct_builtin_core_reloc (location_t loc, tree fndecl, tree *args,
1262 int nargs)
1263 {
1264 int code = DECL_MD_FUNCTION_CODE (fndecl);
1265 builtin_helpers helper = core_builtin_helpers[code];
1266
1267 if (helper.is_valid)
1268 {
1269 gcc_assert (helper.kind);
1270 gcc_assert (helper.pack);
1271 gcc_assert (helper.process);
1272
1273 struct cr_local local_data = CR_LOCAL_EMPTY;
1274 local_data.fail = false;
1275
1276 enum btf_core_reloc_kind kind = helper.kind (args, nargs);
1277 if (kind == BPF_RELO_INVALID)
1278 local_data.fail = true;
1279 else if (helper.pack != NULL)
1280 {
1281 local_data = helper.pack (args, kind, (enum bpf_builtins) code);
1282 local_data.reloc_data.orig_builtin_code = (enum bpf_builtins) code;
1283 local_data.reloc_data.orig_arg_expr = args[0];
1284 }
1285 else
1286 gcc_unreachable ();
1287
1288 if (local_data.fail == true)
1289 return error_mark_node;
1290
1291 if (local_data.reloc_decision == REPLACE_CREATE_RELOCATION)
1292 {
1293 int index = search_builtin_data (helper.compare,
1294 &local_data.reloc_data);
1295 if (index == -1)
1296 index = allocate_builtin_data ();
1297 struct cr_builtins *data = get_builtin_data (index);
1298 memcpy (data, &local_data.reloc_data, sizeof (struct cr_builtins));
1299
1300 tree fndecl = bpf_builtins[BPF_BUILTIN_CORE_RELOC];
1301 return build_call_expr_loc (loc,
1302 fndecl, 1,
1303 build_int_cst (integer_type_node, index));
1304 }
1305 }
1306 return NULL_TREE;
1307 }
1308
1309 /* This function constructs the CO-RE safe code around field expressions.
1310 If the expression is an array access, create an offset by multiplying the
1311 index access by the __builtin_type_info call requesting the size of the
1312 array element and multiplying by the index. The offset is added to the
1313 base pointer.
1314 In a more formal way:
1315 - base + (__blt_preserve_type_info (typeof(expr), SIZEOF) * array_i)
1316
1317 Please notice that __builtin_preserve_type_info is never really created, but
1318 rather a call to __builtin_core_reloc that represents it.
1319
1320 Any other case, it is assumed to be a field access and instead a CO-RE field
1321 expressions offset relocation is created and added to the base node.
1322 More precisely:
1323 - base + __builtin_preserve_field_expr (expr, SIZEOF) */
1324
1325 static tree
1326 core_expr_with_field_expr_plus_base (tree base, tree expr, bool leaf_node)
1327 {
1328 tree type = TREE_TYPE (expr);
1329 tree args[2];
1330
1331 if (base == expr)
1332 return expr;
1333 else if (TREE_CODE (expr) == ARRAY_REF
1334 && leaf_node == false)
1335 {
1336 if (TREE_CODE (base) == MEM_REF)
1337 base = TREE_OPERAND (base, 0);
1338
1339 tree array_index = TREE_OPERAND (expr, 1);
1340 tree fndecl = bpf_builtins[BPF_BUILTIN_PRESERVE_TYPE_INFO];
1341
1342 tree type = TREE_TYPE (base);
1343 gcc_assert (POINTER_TYPE_P (type)
1344 && TREE_CODE (type = TREE_TYPE (type)) == ARRAY_TYPE
1345 && (type = TREE_TYPE (type)) != NULL_TREE);
1346 args[0] = type;
1347 args[1] = build_int_cst (integer_type_node, BPF_TYPE_SIZE);
1348 tree builtin_call = construct_builtin_core_reloc (UNKNOWN_LOCATION,
1349 fndecl,
1350 args, 2);
1351
1352 tree offset = fold_build2 (MULT_EXPR, size_type_node,
1353 fold_build1 (NOP_EXPR, size_type_node, builtin_call),
1354 fold_build1 (NOP_EXPR, size_type_node, array_index));
1355
1356 if (!POINTER_TYPE_P (TREE_TYPE (base)))
1357 base = fold_build1 (ADDR_EXPR,
1358 build_pointer_type (TREE_TYPE (base)), base);
1359
1360 tree tmp = fold_build2 (POINTER_PLUS_EXPR, ptr_type_node,
1361 fold_build1 (NOP_EXPR, ptr_type_node, base),
1362 offset);
1363
1364 tmp = fold_build1 (NOP_EXPR, build_pointer_type (type), tmp);
1365 return tmp;
1366 }
1367 else
1368 {
1369 tree fndecl = bpf_builtins[BPF_BUILTIN_PRESERVE_FIELD_INFO];
1370 args[0] = expr;
1371 args[1] = build_int_cst (integer_type_node, BPF_FIELD_BYTE_OFFSET);
1372 tree builtin_call = construct_builtin_core_reloc (UNKNOWN_LOCATION,
1373 fndecl,
1374 args, 2);
1375
1376 if (!POINTER_TYPE_P (TREE_TYPE (base)))
1377 base = fold_build1 (ADDR_EXPR,
1378 build_pointer_type (TREE_TYPE (base)), base);
1379
1380 tree tmp = fold_build2 (POINTER_PLUS_EXPR, ptr_type_node,
1381 fold_build1 (NOP_EXPR, ptr_type_node, base),
1382 fold_build1 (NOP_EXPR, size_type_node, builtin_call));
1383 tmp = fold_build1 (NOP_EXPR, build_pointer_type (type), tmp);
1384 return tmp;
1385 }
1386 }
1387
1388 /* This function takes arbitrary field expression and returns a CO-RE
1389 compatible version by introducing CO-RE relocations.
1390
1391 In cases where the expression is not supported in CO-RE with a single
1392 relocation, it creates multiple levels of access, i.e. if the expression
1393 contains multiple indirections.
1394 For example:
1395 - A->B->C
1396
1397 It recursively traverses the expression to its leaf nodes and rollbacks
1398 constructing the CO-RE relocations. It calls
1399 core_expr_with_field_expr_plus_base that creates the necessary CO-RE
1400 relocations.
1401
1402 Arguments:
1403 - EXPR: is the expression to be converted. It should be validated by
1404 compute_field_expr function before this function is called.
1405 - CHANGED: is set to true if the returned tree node is different from
1406 the input expr argument.
1407 - ENTRY: internal only. Should not be set in a call. */
1408
1409 static tree
1410 make_core_safe_access_index (tree expr, bool *changed, bool entry = true)
1411 {
1412 poly_int64 bitsize, bitpos;
1413 tree var_off;
1414 machine_mode mode;
1415 int sign, reverse, vol;
1416
1417 tree base = get_inner_reference (expr, &bitsize, &bitpos, &var_off, &mode,
1418 &sign, &reverse, &vol);
1419
1420 if (base == NULL_TREE || base == expr)
1421 return expr;
1422
1423 base = expr;
1424
1425 tree ret = NULL_TREE;
1426 int n;
1427 bool valid = true;
1428 tree access_node = NULL_TREE;
1429
1430 /* In case the base is itself a valid field expression, first convert the
1431 base in a CO-RE safe expression.
1432 This seems to be a requirement since get_inner_reference not always
1433 returns the true base of the expression. */
1434 if ((n = compute_field_expr (base, NULL, &valid, &access_node)) > 0
1435 && valid == true)
1436 {
1437 if (TREE_CODE (access_node) == INDIRECT_REF)
1438 base = TREE_OPERAND (access_node, 0);
1439 else
1440 base = access_node;
1441
1442 bool local_changed = false;
1443 ret = make_core_safe_access_index (base, &local_changed, false);
1444 if (local_changed == true)
1445 {
1446 if (TREE_CODE (access_node) == INDIRECT_REF)
1447 base = fold_build1 (INDIRECT_REF,
1448 TREE_TYPE (base),
1449 ret);
1450 else
1451 base = ret;
1452 }
1453 }
1454
1455 /* The remaining is to traverse the field part of the field expression. */
1456 if (mode != VOIDmode && var_off == NULL_TREE)
1457 {
1458 *changed = true;
1459 return core_expr_with_field_expr_plus_base (base, expr, true);
1460 }
1461 else
1462 {
1463 switch (TREE_CODE (expr))
1464 {
1465 case COMPONENT_REF:
1466 case ARRAY_REF:
1467 case ADDR_EXPR:
1468 {
1469 bool local_changed = false;
1470 tree type = TREE_TYPE (TREE_OPERAND (expr, 0));
1471 ret = make_core_safe_access_index (TREE_OPERAND (expr, 0),
1472 &local_changed, false);
1473
1474 /* This variable is a replaced in the expr for algorithmic purposes.
1475 It reduces the expression just to the remaining sub-expression
1476 that still was not processed. */
1477 if (local_changed == true)
1478 TREE_OPERAND (expr, 0) = create_tmp_var (type, "fake");
1479 }
1480 break;
1481 default:
1482 ret = expr;
1483 break;
1484 }
1485 }
1486
1487 base = get_inner_reference (expr, &bitsize, &bitpos, &var_off, &mode,
1488 &sign, &reverse, &vol);
1489
1490 if ((ret != NULL_TREE
1491 && mode != VOIDmode && var_off != NULL_TREE)
1492 || entry == true)
1493 {
1494 *changed = true;
1495 ret = core_expr_with_field_expr_plus_base (ret, expr, false);
1496 }
1497 return ret;
1498 }
1499
1500 /* This function verifies if the NODE expression is a field expression and
1501 changes and converts it to CO-RE. This is used by a tree walker for any
1502 __builtin_preserve_access_index argument expression from within
1503 bpf_resolve_overloaded_core_builtin. */
1504
1505 static tree
1506 replace_core_access_index_comp_expr (tree *node, int *walk_subtrees,
1507 void *data ATTRIBUTE_UNUSED)
1508 {
1509 bool valid = true;
1510 gcc_assert (*node != NULL_TREE);
1511
1512 tree *expr = node;
1513 bool should_indirect = false;
1514 if (TREE_CODE (*expr) == ADDR_EXPR)
1515 expr = &TREE_OPERAND (*expr, 0);
1516 else
1517 should_indirect = true;
1518
1519 int n = compute_field_expr (*node, NULL, &valid, NULL);
1520 if (valid == true && n > 0)
1521 {
1522 bool changed = false;
1523 tree expr_test = make_core_safe_access_index (*expr, &changed);
1524 *walk_subtrees = 0;
1525
1526 if (changed == true)
1527 {
1528 if (should_indirect == true)
1529 expr_test = fold_build1 (INDIRECT_REF,
1530 TREE_TYPE (TREE_TYPE (expr_test)),
1531 expr_test);
1532
1533 *expr = expr_test;
1534 }
1535 }
1536 return NULL_TREE;
1537 }
1538
1539 /* This function is used by bpf_resolve_overloaded_builtin defined in bpf.cc.
1540 It is executed in a very early stage and processes any CO-RE builtins,
1541 adapting the code and creating the more generic __builtin_core_reloc calls.
1542 */
1543
1544 #define MAX_CORE_BUILTIN_ARGS 3
1545 tree
1546 bpf_resolve_overloaded_core_builtin (location_t loc, tree fndecl,
1547 void *arglist)
1548 {
1549 if (!bpf_require_core_support ())
1550 return error_mark_node;
1551
1552 vec<tree, va_gc> *argsvec = static_cast<vec<tree, va_gc> *> (arglist);
1553 tree args[MAX_CORE_BUILTIN_ARGS];
1554 for (unsigned int i = 0; i < argsvec->length (); i++)
1555 args[i] = (*argsvec)[i];
1556
1557 int code = DECL_MD_FUNCTION_CODE (fndecl);
1558 if (code == BPF_BUILTIN_PRESERVE_ACCESS_INDEX)
1559 {
1560 walk_tree (&args[0], replace_core_access_index_comp_expr, NULL, NULL);
1561 return args[0];
1562 }
1563
1564 return construct_builtin_core_reloc (loc, fndecl, args, argsvec->length ());
1565 }
1566
1567 /* Callback function for bpf_mark_field_expr_types_as_used. */
1568
1569 static void
1570 mark_component_type_as_used (tree node)
1571 {
1572 if (TREE_CODE (node) == COMPONENT_REF)
1573 btf_mark_type_used (TREE_TYPE (TREE_OPERAND (node, 0)));
1574 }
1575
1576 /* Mark types needed for BPF CO-RE relocations as used. Doing so ensures that
1577 these types do not get pruned from the BTF information. */
1578
1579 static void
1580 bpf_mark_types_as_used (struct cr_builtins *data)
1581 {
1582 tree expr = data->expr;
1583 switch (data->kind)
1584 {
1585 case BPF_RELO_FIELD_BYTE_OFFSET:
1586 case BPF_RELO_FIELD_BYTE_SIZE:
1587 case BPF_RELO_FIELD_EXISTS:
1588 case BPF_RELO_FIELD_SIGNED:
1589 case BPF_RELO_FIELD_LSHIFT_U64:
1590 case BPF_RELO_FIELD_RSHIFT_U64:
1591 if (TREE_CODE (expr) == ADDR_EXPR)
1592 expr = TREE_OPERAND (expr, 0);
1593
1594 expr = root_for_core_field_info (expr);
1595 compute_field_expr (data->expr, NULL, NULL, NULL, false,
1596 mark_component_type_as_used);
1597 break;
1598 case BPF_RELO_TYPE_ID_LOCAL:
1599 case BPF_RELO_TYPE_ID_TARGET:
1600 case BPF_RELO_TYPE_EXISTS:
1601 case BPF_RELO_TYPE_SIZE:
1602 case BPF_RELO_ENUMVAL_EXISTS:
1603 case BPF_RELO_ENUMVAL_VALUE:
1604 case BPF_RELO_TYPE_MATCHES:
1605 btf_mark_type_used (data->type);
1606 break;
1607 default:
1608 gcc_unreachable ();
1609 }
1610 }
1611
1612 /* Used in bpf_expand_builtin. This function is called in RTL expand stage to
1613 convert the internal __builtin_core_reloc in unspec:UNSPEC_CORE_RELOC RTL,
1614 which will contain a third argument that is the index in the vec collected
1615 in bpf_resolve_overloaded_core_builtin. */
1616
1617 rtx
1618 bpf_expand_core_builtin (tree exp, enum bpf_builtins code)
1619 {
1620 if (!TARGET_BPF_CORE)
1621 return NULL_RTX;
1622
1623 switch (code)
1624 {
1625 case BPF_BUILTIN_CORE_RELOC:
1626 {
1627 tree index = CALL_EXPR_ARG (exp, 0);
1628 struct cr_builtins *data = get_builtin_data (TREE_INT_CST_LOW (index));
1629
1630 bpf_mark_types_as_used (data);
1631
1632 rtx v = expand_normal (data->default_value);
1633 rtx i = expand_normal (index);
1634 return gen_rtx_UNSPEC (DImode,
1635 gen_rtvec (2, v, i),
1636 UNSPEC_CORE_RELOC);
1637 }
1638 break;
1639 default:
1640 break;
1641 }
1642
1643 return NULL_RTX;
1644 }
1645
1646
1647 /* This function is called in the final assembly output for the
1648 unspec:UNSPEC_CORE_RELOC. It recovers the vec index kept as the third
1649 operand and collects the data from the vec. With that it calls the process
1650 helper in order to construct the data required for the CO-RE relocation.
1651 Also it creates a label pointing to the unspec instruction and uses it in
1652 the CO-RE relocation creation. */
1653
1654 void
1655 bpf_output_core_reloc (rtx *operands, int nr_ops)
1656 {
1657 /* Search for an UNSPEC_CORE_RELOC within the operands of the emitting
1658 intructions. */
1659 rtx unspec_exp = NULL_RTX;
1660 for (int i = 0; i < nr_ops; i++)
1661 {
1662 rtx op = operands[i];
1663
1664 /* An immediate CO-RE reloc. */
1665 if (GET_CODE (op) == UNSPEC
1666 && XINT (op, 1) == UNSPEC_CORE_RELOC)
1667 unspec_exp = op;
1668
1669 /* In case of a MEM operation with an offset resolved in CO-RE. */
1670 if (GET_CODE (op) == MEM
1671 && (op = XEXP (op, 0)) != NULL_RTX
1672 && (GET_CODE (op) == PLUS))
1673 {
1674 rtx x0 = XEXP (op, 0);
1675 rtx x1 = XEXP (op, 1);
1676
1677 if (GET_CODE (x0) == UNSPEC
1678 && XINT (x0, 1) == UNSPEC_CORE_RELOC)
1679 unspec_exp = x0;
1680 if (GET_CODE (x1) == UNSPEC
1681 && XINT (x1, 1) == UNSPEC_CORE_RELOC)
1682 unspec_exp = x1;
1683 }
1684 if (unspec_exp != NULL_RTX)
1685 break;
1686 }
1687
1688 if (unspec_exp != NULL_RTX)
1689 {
1690 int index = INTVAL (XVECEXP (unspec_exp, 0, 1));
1691 struct cr_builtins *data = get_builtin_data (index);
1692 builtin_helpers helper;
1693 helper = core_builtin_helpers[data->orig_builtin_code];
1694
1695 rtx_code_label * tmp_label = gen_label_rtx ();
1696 output_asm_label (tmp_label);
1697 assemble_name (asm_out_file, ":\n");
1698
1699 rtx orig_default_value = data->rtx_default_value;
1700
1701 gcc_assert (helper.process != NULL);
1702 struct cr_final reloc_data = helper.process (data);
1703 make_core_relo (&reloc_data, tmp_label);
1704
1705 /* Replace default value for later processing builtin types.
1706 An example are the type id builtins. */
1707 if (data->rtx_default_value != NULL_RTX
1708 && orig_default_value != data->rtx_default_value)
1709 XVECEXP (unspec_exp, 0, 0) = data->rtx_default_value;
1710 }
1711 }
1712
1713 static tree
1714 maybe_get_base_for_field_expr (tree expr)
1715 {
1716 poly_int64 bitsize, bitpos;
1717 tree var_off;
1718 machine_mode mode;
1719 int sign, reverse, vol;
1720
1721 if (expr == NULL_TREE)
1722 return NULL_TREE;
1723
1724 return get_inner_reference (expr, &bitsize, &bitpos, &var_off, &mode,
1725 &sign, &reverse, &vol);
1726 }
1727
1728 /* Access functions to mark sub expressions as attributed with
1729 __preserve_access_index.
1730 This is required since in gimple format, in order to convert an expression as
1731 CO-RE safe, we must create multiple gimple statements.
1732 Also, only the type of the base of the expression might be attributed with
1733 __preserve_access_index. Nevertheless all the consecutive accesses to this
1734 attributed node should also be converted to CO-RE safe.
1735 Any LHS assigned values with CO-RE converted expressions are marked and
1736 any uses of these values are later checked for further convertion.
1737 The core_access_index_map functions allow to mark this nodes for later
1738 convertion to CO-RE.
1739 This mechanism are used by make_gimple_core_safe_access_index. */
1740
1741 static GTY(()) hash_map<tree, tree> *core_access_index_map = NULL;
1742
1743 static void
1744 core_access_clean (void)
1745 {
1746 if (core_access_index_map == NULL)
1747 core_access_index_map = hash_map<tree, tree>::create_ggc (10);
1748 core_access_index_map->empty ();
1749 }
1750
1751 static bool
1752 core_is_access_index (tree expr)
1753 {
1754 if (TREE_CODE (expr) == MEM_REF
1755 || TREE_CODE (expr) == INDIRECT_REF)
1756 expr = TREE_OPERAND (expr, 0);
1757
1758 tree *def = core_access_index_map->get (expr);
1759 if (def)
1760 return true;
1761 return false;
1762 }
1763
1764 static void
1765 core_mark_as_access_index (tree expr)
1766 {
1767 if (TREE_CODE (expr) == MEM_REF
1768 || TREE_CODE (expr) == INDIRECT_REF)
1769 expr = TREE_OPERAND (expr, 0);
1770
1771 if (core_access_index_map->get (expr) == NULL)
1772 core_access_index_map->put (expr, NULL_TREE);
1773 }
1774
1775 /* This function is an adaptation of make_core_safe_access_index but to be used
1776 in gimple format trees. It is used by execute_lower_bpf_core, when
1777 traversing the gimple tree looking for nodes that would have its type
1778 attributed with __preserve_access_index. In this particular cases any of
1779 the expressions using such attributed types must be made CO-RE safe. */
1780
1781 static tree
1782 make_gimple_core_safe_access_index (tree *tp,
1783 int *walk_subtrees ATTRIBUTE_UNUSED,
1784 void *data)
1785 {
1786 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
1787 bool valid = true;
1788 int n = 0;
1789
1790 tree *patch = tp;
1791 if (TREE_CODE (*patch) == ADDR_EXPR)
1792 patch = &(TREE_OPERAND (*tp, 0));
1793 tree orig_type = TREE_TYPE (*patch);
1794
1795 if ((is_attr_preserve_access (*patch)
1796 || core_is_access_index (maybe_get_base_for_field_expr (*patch)))
1797 && (n = compute_field_expr (*patch, NULL, &valid, NULL)) > 0
1798 && valid == true)
1799 {
1800 bool changed = false;
1801 tree expr_test = make_core_safe_access_index (*patch, &changed);
1802
1803
1804 gimple_seq before = NULL;
1805 push_gimplify_context ();
1806 gimplify_expr (&expr_test, &before, NULL, is_gimple_val, fb_rvalue);
1807
1808 /* In case the ADDR_EXPR bypassed above is no longer needed. */
1809 if (patch != tp && TREE_TYPE (expr_test) == TREE_TYPE (*tp))
1810 *tp = expr_test;
1811 /* For non pointer value accesses. */
1812 else if (TREE_TYPE (expr_test) == build_pointer_type (orig_type))
1813 *patch = fold_build2 (MEM_REF, TREE_TYPE (*patch),
1814 expr_test, build_int_cst (ptr_type_node, 0));
1815 else
1816 *patch = expr_test;
1817
1818 *tp = fold (*tp);
1819
1820 gsi_insert_seq_before (&(wi->gsi), before, GSI_LAST_NEW_STMT);
1821 pop_gimplify_context (NULL);
1822
1823 wi->changed = true;
1824 *walk_subtrees = false;
1825
1826 tree lhs;
1827 if (!wi->is_lhs
1828 && gimple_code (wi->stmt) != GIMPLE_CALL
1829 && (lhs = gimple_get_lhs (wi->stmt)) != NULL_TREE)
1830 core_mark_as_access_index (lhs);
1831 }
1832 return NULL_TREE;
1833 }
1834
1835 /* This is the entry point for the pass_data_lower_bpg_core. It walks all the
1836 statements in gimple, looking for expressions that are suppose to be CO-RE
1837 preserve_access_index attributed.
1838 Those expressions are processed and split by
1839 make_gimple_core_safe_access_index function, which will both create the
1840 calls to __build_core_reloc and split the expression in smaller parts in
1841 case it cannot be represented CO-RE safeguarded by a single CO-RE
1842 relocation. */
1843
1844 static unsigned int
1845 execute_lower_bpf_core (void)
1846 {
1847 remove_parser_plugin ();
1848 if (!TARGET_BPF_CORE)
1849 return 0;
1850
1851 gimple_seq body = gimple_body (current_function_decl);
1852
1853 struct walk_stmt_info wi;
1854 core_access_clean ();
1855
1856 memset (&wi, 0, sizeof (wi));
1857 wi.info = NULL;
1858
1859 /* Split preserve_access_index expressions when needed. */
1860 walk_gimple_seq_mod (&body, NULL, make_gimple_core_safe_access_index, &wi);
1861 return 0;
1862 }
1863
1864 namespace {
1865
1866 const pass_data pass_data_lower_bpf_core =
1867 {
1868 GIMPLE_PASS, /* type */
1869 "bpf_core_lower", /* name */
1870 OPTGROUP_NONE, /* optinfo_flags */
1871 TV_NONE, /* tv_id */
1872 PROP_gimple_any, /* properties_required */
1873 0, /* properties_provided */
1874 0, /* properties_destroyed */
1875 0, /* todo_flags_start */
1876 0, /* todo_flags_finish */
1877 };
1878
1879 class pass_lower_bpf_core: public gimple_opt_pass
1880 {
1881 public:
1882 pass_lower_bpf_core (gcc::context *ctxt)
1883 : gimple_opt_pass (pass_data_lower_bpf_core, ctxt)
1884 {}
1885
1886 /* opt_pass methods: */
1887 unsigned int execute (function *) final override
1888 {
1889 return execute_lower_bpf_core ();
1890 }
1891
1892 }; /* class pass_lower_bpf_core */
1893
1894 } /* anon namespace */
1895
1896 gimple_opt_pass *
1897 make_pass_lower_bpf_core (gcc::context *ctxt)
1898 {
1899 return new pass_lower_bpf_core (ctxt);
1900 }
1901
1902 #include "gt-core-builtins.h"