gccrs: Add get_locus function for abstract class MetaItemInner.
[official-gcc.git] / gcc / gimple-array-bounds.cc
blob34e039adca7436f2fc67608810ed4e76895c9988
1 /* Array bounds checking.
2 Copyright (C) 2005-2023 Free Software Foundation, Inc.
4 This file is part of GCC.
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.
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.
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/>. */
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "tree.h"
25 #include "gimple.h"
26 #include "ssa.h"
27 #include "pointer-query.h"
28 #include "gimple-array-bounds.h"
29 #include "gimple-iterator.h"
30 #include "gimple-walk.h"
31 #include "tree-dfa.h"
32 #include "fold-const.h"
33 #include "diagnostic-core.h"
34 #include "intl.h"
35 #include "tree-vrp.h"
36 #include "alloc-pool.h"
37 #include "vr-values.h"
38 #include "domwalk.h"
39 #include "tree-cfg.h"
40 #include "attribs.h"
42 array_bounds_checker::array_bounds_checker (struct function *func,
43 range_query *qry)
44 : fun (func), m_ptr_qry (qry)
46 /* No-op. */
49 const value_range *
50 array_bounds_checker::get_value_range (const_tree op, gimple *stmt)
52 return m_ptr_qry.rvals->get_value_range (op, stmt);
55 /* Try to determine the DECL that REF refers to. Return the DECL or
56 the expression closest to it. Used in informational notes pointing
57 to referenced objects or function parameters. */
59 static tree
60 get_base_decl (tree ref)
62 tree base = get_base_address (ref);
63 if (DECL_P (base))
64 return base;
66 if (TREE_CODE (base) == MEM_REF)
67 base = TREE_OPERAND (base, 0);
69 if (TREE_CODE (base) != SSA_NAME)
70 return base;
74 gimple *def = SSA_NAME_DEF_STMT (base);
75 if (gimple_assign_single_p (def))
77 base = gimple_assign_rhs1 (def);
78 return base;
81 if (!gimple_nop_p (def))
82 return base;
84 break;
85 } while (true);
87 tree var = SSA_NAME_VAR (base);
88 if (TREE_CODE (var) != PARM_DECL)
89 return base;
91 return var;
94 /* Return the constant byte size of the object or type referenced by
95 the MEM_REF ARG. On success, set *PREF to the DECL or expression
96 ARG refers to. Otherwise return null. */
98 static tree
99 get_ref_size (tree arg, tree *pref)
101 if (TREE_CODE (arg) != MEM_REF)
102 return NULL_TREE;
104 arg = TREE_OPERAND (arg, 0);
105 tree type = TREE_TYPE (arg);
106 if (!POINTER_TYPE_P (type))
107 return NULL_TREE;
109 type = TREE_TYPE (type);
110 if (TREE_CODE (type) != ARRAY_TYPE)
111 return NULL_TREE;
113 tree nbytes = TYPE_SIZE_UNIT (type);
114 if (!nbytes || TREE_CODE (nbytes) != INTEGER_CST)
115 return NULL_TREE;
117 *pref = get_base_decl (arg);
118 return nbytes;
121 /* Return true if REF is (likely) an ARRAY_REF to a trailing array member
122 of a struct. It refines array_ref_flexible_size_p by detecting a pointer
123 to an array and an array parameter declared using the [N] syntax (as
124 opposed to a pointer) and returning false. Set *PREF to the decl or
125 expression REF refers to. */
127 static bool
128 trailing_array (tree arg, tree *pref)
130 tree ref = arg;
131 tree base = get_base_decl (arg);
132 while (TREE_CODE (ref) == ARRAY_REF || TREE_CODE (ref) == MEM_REF)
133 ref = TREE_OPERAND (ref, 0);
135 if (TREE_CODE (ref) == COMPONENT_REF)
137 *pref = TREE_OPERAND (ref, 1);
138 tree type = TREE_TYPE (*pref);
139 if (TREE_CODE (type) == ARRAY_TYPE)
141 /* A multidimensional trailing array is not considered special
142 no matter what its major bound is. */
143 type = TREE_TYPE (type);
144 if (TREE_CODE (type) == ARRAY_TYPE)
145 return false;
148 else
149 *pref = base;
151 tree basetype = TREE_TYPE (base);
152 if (TREE_CODE (base) == PARM_DECL
153 && POINTER_TYPE_P (basetype))
155 tree ptype = TREE_TYPE (basetype);
156 if (TREE_CODE (ptype) == ARRAY_TYPE)
157 return false;
160 return array_ref_flexible_size_p (arg);
163 /* Acquire the upper bound and upper bound plus one for the array
164 reference REF and record them into UP_BOUND and UP_BOUND_P1.
165 Set *DECL to the decl or expresssion REF refers to. */
167 static void
168 get_up_bounds_for_array_ref (tree ref, tree *decl,
169 tree *up_bound, tree *up_bound_p1)
171 if (!(*up_bound)
172 || TREE_CODE (*up_bound) != INTEGER_CST
173 || trailing_array (ref, decl))
175 /* Accesses to trailing arrays via pointers may access storage
176 beyond the types array bounds. For such arrays, or for flexible
177 array members, as well as for other arrays of an unknown size,
178 replace the upper bound with a more permissive one that assumes
179 the size of the largest object is PTRDIFF_MAX. */
180 tree eltsize = array_ref_element_size (ref);
182 if (TREE_CODE (eltsize) != INTEGER_CST
183 || integer_zerop (eltsize))
185 *up_bound = NULL_TREE;
186 *up_bound_p1 = NULL_TREE;
188 else
190 tree ptrdiff_max = TYPE_MAX_VALUE (ptrdiff_type_node);
191 tree maxbound = ptrdiff_max;
192 tree arg = TREE_OPERAND (ref, 0);
194 const bool compref = TREE_CODE (arg) == COMPONENT_REF;
195 if (compref)
197 /* Try to determine the size of the trailing array from
198 its initializer (if it has one). */
199 if (tree refsize = component_ref_size (arg))
200 if (TREE_CODE (refsize) == INTEGER_CST)
201 maxbound = refsize;
204 if (maxbound == ptrdiff_max)
206 /* Try to determine the size of the base object. Avoid
207 COMPONENT_REF already tried above. Using its DECL_SIZE
208 size wouldn't necessarily be correct if the reference is
209 to its flexible array member initialized in a different
210 translation unit. */
211 poly_int64 off;
212 if (tree base = get_addr_base_and_unit_offset (arg, &off))
214 if (TREE_CODE (base) == MEM_REF)
216 /* Try to determine the size from a pointer to
217 an array if BASE is one. */
218 if (tree size = get_ref_size (base, decl))
219 maxbound = size;
221 else if (!compref && DECL_P (base))
222 if (tree basesize = DECL_SIZE_UNIT (base))
223 if (TREE_CODE (basesize) == INTEGER_CST)
225 maxbound = basesize;
226 *decl = base;
229 if (known_gt (off, 0))
230 maxbound = wide_int_to_tree (sizetype,
231 wi::sub (wi::to_wide (maxbound),
232 off));
235 else
236 maxbound = fold_convert (sizetype, maxbound);
238 *up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
240 if (*up_bound_p1 != NULL_TREE)
241 *up_bound = int_const_binop (MINUS_EXPR, *up_bound_p1,
242 build_int_cst (ptrdiff_type_node, 1));
243 else
244 *up_bound = NULL_TREE;
247 else
248 *up_bound_p1 = int_const_binop (PLUS_EXPR, *up_bound,
249 build_int_cst (TREE_TYPE (*up_bound), 1));
250 return;
253 /* Given the LOW_SUB_ORG, LOW_SUB and UP_SUB, and the computed UP_BOUND
254 and UP_BOUND_P1, check whether the array reference REF is out of bound.
255 When out of bounds, set OUT_OF_BOUND to true.
256 Issue warnings if FOR_ARRAY_BOUND is true.
257 return TRUE if warnings are issued. */
259 static bool
260 check_out_of_bounds_and_warn (location_t location, tree ref,
261 tree low_sub_org, tree low_sub, tree up_sub,
262 tree up_bound, tree up_bound_p1,
263 const value_range *vr,
264 bool ignore_off_by_one, bool for_array_bound,
265 bool *out_of_bound)
267 tree low_bound = array_ref_low_bound (ref);
268 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
270 bool warned = false;
271 *out_of_bound = false;
273 /* Empty array. */
274 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
276 *out_of_bound = true;
277 if (for_array_bound)
278 warned = warning_at (location, OPT_Warray_bounds_,
279 "array subscript %E is outside array"
280 " bounds of %qT", low_sub_org, artype);
283 if (warned)
284 ; /* Do nothing. */
285 else if (vr && vr->kind () == VR_ANTI_RANGE)
287 if (up_bound
288 && TREE_CODE (up_sub) == INTEGER_CST
289 && (ignore_off_by_one
290 ? tree_int_cst_lt (up_bound, up_sub)
291 : tree_int_cst_le (up_bound, up_sub))
292 && TREE_CODE (low_sub) == INTEGER_CST
293 && tree_int_cst_le (low_sub, low_bound))
295 *out_of_bound = true;
296 if (for_array_bound)
297 warned = warning_at (location, OPT_Warray_bounds_,
298 "array subscript [%E, %E] is outside "
299 "array bounds of %qT",
300 low_sub, up_sub, artype);
303 else if (up_bound
304 && TREE_CODE (up_sub) == INTEGER_CST
305 && (ignore_off_by_one
306 ? !tree_int_cst_le (up_sub, up_bound_p1)
307 : !tree_int_cst_le (up_sub, up_bound)))
309 *out_of_bound = true;
310 if (for_array_bound)
311 warned = warning_at (location, OPT_Warray_bounds_,
312 "array subscript %E is above array bounds of %qT",
313 up_sub, artype);
315 else if (TREE_CODE (low_sub) == INTEGER_CST
316 && tree_int_cst_lt (low_sub, low_bound))
318 *out_of_bound = true;
319 if (for_array_bound)
320 warned = warning_at (location, OPT_Warray_bounds_,
321 "array subscript %E is below array bounds of %qT",
322 low_sub, artype);
324 return warned;
327 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible
328 arrays and "struct" hacks. If VRP can determine that the array
329 subscript is a constant, check if it is outside valid range. If
330 the array subscript is a RANGE, warn if it is non-overlapping with
331 valid range. IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside
332 a ADDR_EXPR. Return true if a warning has been issued or if
333 no-warning is set. */
335 bool
336 array_bounds_checker::check_array_ref (location_t location, tree ref,
337 gimple *stmt, bool ignore_off_by_one)
339 if (warning_suppressed_p (ref, OPT_Warray_bounds_))
340 /* Return true to have the caller prevent warnings for enclosing
341 refs. */
342 return true;
344 /* Upper bound and Upper bound plus one for -Warray-bounds. */
345 tree up_bound = array_ref_up_bound (ref);
346 tree up_bound_p1 = NULL_TREE;
348 /* Referenced decl if one can be determined. */
349 tree decl = NULL_TREE;
351 /* Set to the type of the special array member for a COMPONENT_REF. */
352 special_array_member sam{ };
353 tree afield_decl = NULL_TREE;
354 tree arg = TREE_OPERAND (ref, 0);
356 if (TREE_CODE (arg) == COMPONENT_REF)
358 /* Try to determine special array member type for this COMPONENT_REF. */
359 sam = component_ref_sam_type (arg);
360 afield_decl = TREE_OPERAND (arg, 1);
363 get_up_bounds_for_array_ref (ref, &decl, &up_bound, &up_bound_p1);
365 bool warned = false;
366 bool out_of_bound = false;
368 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
369 tree low_sub_org = TREE_OPERAND (ref, 1);
370 tree up_sub = low_sub_org;
371 tree low_sub = low_sub_org;
373 const value_range *vr = NULL;
374 if (TREE_CODE (low_sub_org) == SSA_NAME)
376 vr = get_value_range (low_sub_org, stmt);
377 if (!vr->undefined_p () && !vr->varying_p ())
379 low_sub = vr->kind () == VR_RANGE ? vr->max () : vr->min ();
380 up_sub = vr->kind () == VR_RANGE ? vr->min () : vr->max ();
384 warned = check_out_of_bounds_and_warn (location, ref,
385 low_sub_org, low_sub, up_sub,
386 up_bound, up_bound_p1, vr,
387 ignore_off_by_one, warn_array_bounds,
388 &out_of_bound);
391 if (!warned && sam == special_array_member::int_0)
392 warned = warning_at (location, OPT_Wzero_length_bounds,
393 (TREE_CODE (low_sub) == INTEGER_CST
394 ? G_("array subscript %E is outside the bounds "
395 "of an interior zero-length array %qT")
396 : G_("array subscript %qE is outside the bounds "
397 "of an interior zero-length array %qT")),
398 low_sub, artype);
400 if (warned && dump_file && (dump_flags & TDF_DETAILS))
402 fprintf (dump_file, "Array bound warning for ");
403 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
404 fprintf (dump_file, "\n");
407 /* Issue warnings for -Wstrict-flex-arrays according to the level of
408 flag_strict_flex_arrays. */
409 if (out_of_bound && warn_strict_flex_arrays
410 && (sam == special_array_member::trail_0
411 || sam == special_array_member::trail_1
412 || sam == special_array_member::trail_n)
413 && DECL_NOT_FLEXARRAY (afield_decl))
415 bool warned1
416 = warning_at (location, OPT_Wstrict_flex_arrays,
417 "trailing array %qT should not be used as "
418 "a flexible array member",
419 artype);
421 if (warned1 && dump_file && (dump_flags & TDF_DETAILS))
423 fprintf (dump_file, "Trailing non flexible-like array bound warning for ");
424 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
425 fprintf (dump_file, "\n");
427 warned |= warned1;
430 if (warned)
432 /* Avoid more warnings when checking more significant subscripts
433 of the same expression. */
434 ref = TREE_OPERAND (ref, 0);
435 suppress_warning (ref, OPT_Warray_bounds_);
436 suppress_warning (ref, OPT_Wstrict_flex_arrays);
438 if (decl)
439 ref = decl;
441 tree rec = NULL_TREE;
442 if (TREE_CODE (ref) == COMPONENT_REF)
444 /* For a reference to a member of a struct object also mention
445 the object if it's known. It may be defined in a different
446 function than the out-of-bounds access. */
447 rec = TREE_OPERAND (ref, 0);
448 if (!VAR_P (rec))
449 rec = NULL_TREE;
450 ref = TREE_OPERAND (ref, 1);
453 if (DECL_P (ref))
454 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
455 if (rec && DECL_P (rec))
456 inform (DECL_SOURCE_LOCATION (rec), "defined here %qD", rec);
459 return warned;
462 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
463 references to string constants. If VRP can determine that the array
464 subscript is a constant, check if it is outside valid range.
465 If the array subscript is a RANGE, warn if it is non-overlapping
466 with valid range.
467 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
468 (used to allow one-past-the-end indices for code that takes
469 the address of the just-past-the-end element of an array).
470 Returns true if a warning has been issued. */
472 bool
473 array_bounds_checker::check_mem_ref (location_t location, tree ref,
474 bool ignore_off_by_one)
476 if (warning_suppressed_p (ref, OPT_Warray_bounds_))
477 return false;
479 /* The statement used to allocate the array or null. */
480 gimple *alloc_stmt = NULL;
481 /* For an allocation statement, the low bound of the size range. */
482 offset_int minbound = 0;
483 /* The type and size of the access. */
484 tree axstype = TREE_TYPE (ref);
485 offset_int axssize = 0;
486 if (tree access_size = TYPE_SIZE_UNIT (axstype))
487 if (TREE_CODE (access_size) == INTEGER_CST)
488 axssize = wi::to_offset (access_size);
490 access_ref aref;
491 if (!m_ptr_qry.get_ref (ref, m_stmt, &aref, 0))
492 return false;
494 if (aref.offset_in_range (axssize))
495 return false;
497 if (TREE_CODE (aref.ref) == SSA_NAME)
499 gimple *def = SSA_NAME_DEF_STMT (aref.ref);
500 if (is_gimple_call (def))
502 /* Save the allocation call and the low bound on the size. */
503 alloc_stmt = def;
504 minbound = aref.sizrng[0];
508 /* The range of the byte offset into the reference. Adjusted below. */
509 offset_int offrange[2] = { aref.offrng[0], aref.offrng[1] };
511 /* The type of the referenced object. */
512 tree reftype = TREE_TYPE (aref.ref);
513 /* The size of the referenced array element. */
514 offset_int eltsize = 1;
515 if (POINTER_TYPE_P (reftype))
516 reftype = TREE_TYPE (reftype);
518 if (TREE_CODE (reftype) == FUNCTION_TYPE)
519 /* Restore the original (pointer) type and avoid trying to create
520 an array of functions (done below). */
521 reftype = TREE_TYPE (aref.ref);
522 else
524 /* The byte size of the array has already been determined above
525 based on a pointer ARG. Set ELTSIZE to the size of the type
526 it points to and REFTYPE to the array with the size, rounded
527 down as necessary. */
528 if (TREE_CODE (reftype) == ARRAY_TYPE)
529 reftype = TREE_TYPE (reftype);
530 if (tree refsize = TYPE_SIZE_UNIT (reftype))
531 if (TREE_CODE (refsize) == INTEGER_CST)
532 eltsize = wi::to_offset (refsize);
534 const offset_int nelts = aref.sizrng[1] / eltsize;
535 reftype = build_printable_array_type (reftype, nelts.to_uhwi ());
538 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
539 is set (when taking the address of the one-past-last element
540 of an array) but always use the stricter bound in diagnostics. */
541 offset_int ubound = aref.sizrng[1];
542 if (ignore_off_by_one)
543 ubound += eltsize;
545 /* Set if the lower bound of the subscript is out of bounds. */
546 const bool lboob = (aref.sizrng[1] == 0
547 || offrange[0] >= ubound
548 || offrange[1] < 0);
549 /* Set if only the upper bound of the subscript is out of bounds.
550 This can happen when using a bigger type to index into an array
551 of a smaller type, as is common with unsigned char. */
552 const bool uboob = !lboob && offrange[0] + axssize > ubound;
553 if (lboob || uboob)
555 /* Treat a reference to a non-array object as one to an array
556 of a single element. */
557 if (TREE_CODE (reftype) != ARRAY_TYPE)
558 reftype = build_printable_array_type (reftype, 1);
560 /* Extract the element type out of MEM_REF and use its size
561 to compute the index to print in the diagnostic; arrays
562 in MEM_REF don't mean anything. A type with no size like
563 void is as good as having a size of 1. */
564 tree type = strip_array_types (TREE_TYPE (ref));
565 if (tree size = TYPE_SIZE_UNIT (type))
567 offrange[0] = offrange[0] / wi::to_offset (size);
568 offrange[1] = offrange[1] / wi::to_offset (size);
572 bool warned = false;
573 if (lboob)
575 if (offrange[0] == offrange[1])
576 warned = warning_at (location, OPT_Warray_bounds_,
577 "array subscript %wi is outside array bounds "
578 "of %qT",
579 offrange[0].to_shwi (), reftype);
580 else
581 warned = warning_at (location, OPT_Warray_bounds_,
582 "array subscript [%wi, %wi] is outside "
583 "array bounds of %qT",
584 offrange[0].to_shwi (),
585 offrange[1].to_shwi (), reftype);
587 else if (uboob && !ignore_off_by_one)
589 tree backtype = reftype;
590 if (alloc_stmt)
591 /* If the memory was dynamically allocated refer to it as if
592 it were an untyped array of bytes. */
593 backtype = build_array_type_nelts (unsigned_char_type_node,
594 aref.sizrng[1].to_uhwi ());
596 warned = warning_at (location, OPT_Warray_bounds_,
597 "array subscript %<%T[%wi]%> is partly "
598 "outside array bounds of %qT",
599 axstype, offrange[0].to_shwi (), backtype);
602 if (warned)
604 /* TODO: Determine the access from the statement and use it. */
605 aref.inform_access (access_none);
606 suppress_warning (ref, OPT_Warray_bounds_);
607 return true;
610 if (warn_array_bounds < 2)
611 return false;
613 /* At level 2 check also intermediate offsets. */
614 int i = 0;
615 if (aref.offmax[i] < -aref.sizrng[1] || aref.offmax[i = 1] > ubound)
617 HOST_WIDE_INT tmpidx = (aref.offmax[i] / eltsize).to_shwi ();
619 if (warning_at (location, OPT_Warray_bounds_,
620 "intermediate array offset %wi is outside array bounds "
621 "of %qT", tmpidx, reftype))
623 suppress_warning (ref, OPT_Warray_bounds_);
624 return true;
628 return false;
631 /* Searches if the expr T, located at LOCATION computes
632 address of an ARRAY_REF, and call check_array_ref on it. */
634 void
635 array_bounds_checker::check_addr_expr (location_t location, tree t,
636 gimple *stmt)
638 /* For the most significant subscript only, accept taking the address
639 of the just-past-the-end element. */
640 bool ignore_off_by_one = true;
642 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
645 bool warned = false;
646 if (TREE_CODE (t) == ARRAY_REF)
648 warned = check_array_ref (location, t, stmt, ignore_off_by_one);
649 ignore_off_by_one = false;
651 else if (TREE_CODE (t) == MEM_REF)
652 warned = check_mem_ref (location, t, ignore_off_by_one);
654 if (warned)
655 suppress_warning (t, OPT_Warray_bounds_);
657 t = TREE_OPERAND (t, 0);
659 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
661 if (TREE_CODE (t) != MEM_REF
662 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
663 || warning_suppressed_p (t, OPT_Warray_bounds_))
664 return;
666 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
667 tree low_bound, up_bound, el_sz;
668 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
669 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
670 || !TYPE_DOMAIN (TREE_TYPE (tem)))
671 return;
673 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
674 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
675 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
676 if (!low_bound
677 || TREE_CODE (low_bound) != INTEGER_CST
678 || !up_bound
679 || TREE_CODE (up_bound) != INTEGER_CST
680 || !el_sz
681 || TREE_CODE (el_sz) != INTEGER_CST)
682 return;
684 offset_int idx;
685 if (!mem_ref_offset (t).is_constant (&idx))
686 return;
688 bool warned = false;
689 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
690 if (idx < 0)
692 if (dump_file && (dump_flags & TDF_DETAILS))
694 fprintf (dump_file, "Array bound warning for ");
695 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
696 fprintf (dump_file, "\n");
698 warned = warning_at (location, OPT_Warray_bounds_,
699 "array subscript %wi is below "
700 "array bounds of %qT",
701 idx.to_shwi (), TREE_TYPE (tem));
703 else if (idx > (wi::to_offset (up_bound)
704 - wi::to_offset (low_bound) + 1))
706 if (dump_file && (dump_flags & TDF_DETAILS))
708 fprintf (dump_file, "Array bound warning for ");
709 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
710 fprintf (dump_file, "\n");
712 warned = warning_at (location, OPT_Warray_bounds_,
713 "array subscript %wu is above "
714 "array bounds of %qT",
715 idx.to_uhwi (), TREE_TYPE (tem));
718 if (warned)
720 if (DECL_P (t))
721 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
723 suppress_warning (t, OPT_Warray_bounds_);
727 /* Return true if T is a reference to a member of a base class that's within
728 the bounds of the enclosing complete object. The function "hacks" around
729 problems discussed in pr98266 and pr97595. */
731 static bool
732 inbounds_memaccess_p (tree t, gimple *stmt)
734 if (TREE_CODE (t) != COMPONENT_REF)
735 return false;
737 tree mref = TREE_OPERAND (t, 0);
738 if (TREE_CODE (mref) != MEM_REF)
739 return false;
741 /* Consider the access if its type is a derived class. */
742 tree mreftype = TREE_TYPE (mref);
743 if (!RECORD_OR_UNION_TYPE_P (mreftype)
744 || !TYPE_BINFO (mreftype))
745 return false;
747 /* Compute the size of the referenced object (it could be dynamically
748 allocated). */
749 access_ref aref; // unused
750 tree refop = TREE_OPERAND (mref, 0);
751 tree refsize = compute_objsize (refop, stmt, 1, &aref);
752 if (!refsize || TREE_CODE (refsize) != INTEGER_CST)
753 return false;
755 /* Compute the byte offset of the member within its enclosing class. */
756 tree fld = TREE_OPERAND (t, 1);
757 tree fldpos = byte_position (fld);
758 if (TREE_CODE (fldpos) != INTEGER_CST)
759 return false;
761 /* Compute the byte offset of the member with the outermost complete
762 object by adding its offset computed above to the MEM_REF offset. */
763 tree refoff = TREE_OPERAND (mref, 1);
764 tree fldoff = int_const_binop (PLUS_EXPR, fldpos, refoff);
765 /* Return false if the member offset is greater or equal to the size
766 of the complete object. */
767 if (!tree_int_cst_lt (fldoff, refsize))
768 return false;
770 tree fldsiz = DECL_SIZE_UNIT (fld);
771 if (!fldsiz || TREE_CODE (fldsiz) != INTEGER_CST)
772 return false;
774 /* Return true if the offset just past the end of the member is less
775 than or equal to the size of the complete object. */
776 tree fldend = int_const_binop (PLUS_EXPR, fldoff, fldsiz);
777 return tree_int_cst_le (fldend, refsize);
780 /* Callback for walk_tree to check a tree for out of bounds array
781 accesses. The array_bounds_checker class is passed in DATA. */
783 tree
784 array_bounds_checker::check_array_bounds (tree *tp, int *walk_subtree,
785 void *data)
787 tree t = *tp;
788 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
790 location_t location;
792 if (EXPR_HAS_LOCATION (t))
793 location = EXPR_LOCATION (t);
794 else
795 location = gimple_location (wi->stmt);
797 *walk_subtree = TRUE;
799 bool warned = false;
800 array_bounds_checker *checker = (array_bounds_checker *) wi->info;
801 gcc_assert (checker->m_stmt == wi->stmt);
803 if (TREE_CODE (t) == ARRAY_REF)
804 warned = checker->check_array_ref (location, t, wi->stmt,
805 false/*ignore_off_by_one*/);
806 else if (TREE_CODE (t) == MEM_REF)
807 warned = checker->check_mem_ref (location, t,
808 false /*ignore_off_by_one*/);
809 else if (TREE_CODE (t) == ADDR_EXPR)
811 checker->check_addr_expr (location, t, wi->stmt);
812 *walk_subtree = false;
814 else if (inbounds_memaccess_p (t, wi->stmt))
815 /* Hack: Skip MEM_REF checks in accesses to a member of a base class
816 at an offset that's within the bounds of the enclosing object.
817 See pr98266 and pr97595. */
818 *walk_subtree = false;
820 /* Propagate the no-warning bit to the outer statement to avoid also
821 issuing -Wstringop-overflow/-overread for the out-of-bounds accesses. */
822 if (warned)
823 suppress_warning (wi->stmt, OPT_Warray_bounds_);
825 return NULL_TREE;
828 /* A dom_walker subclass for use by check_all_array_refs, to walk over
829 all statements of all reachable BBs and call check_array_bounds on
830 them. */
832 class check_array_bounds_dom_walker : public dom_walker
834 public:
835 check_array_bounds_dom_walker (array_bounds_checker *checker)
836 : dom_walker (CDI_DOMINATORS,
837 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
838 flags, so that we can merge in information on
839 non-executable edges from vrp_folder . */
840 REACHABLE_BLOCKS_PRESERVING_FLAGS),
841 checker (checker) { }
842 ~check_array_bounds_dom_walker () {}
844 edge before_dom_children (basic_block) final override;
846 private:
847 array_bounds_checker *checker;
850 /* Implementation of dom_walker::before_dom_children.
852 Walk over all statements of BB and call check_array_bounds on them,
853 and determine if there's a unique successor edge. */
855 edge
856 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
858 gimple_stmt_iterator si;
859 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
861 gimple *stmt = gsi_stmt (si);
862 if (!gimple_has_location (stmt)
863 || is_gimple_debug (stmt))
864 continue;
866 struct walk_stmt_info wi{ };
867 wi.info = checker;
868 checker->m_stmt = stmt;
870 walk_gimple_op (stmt, array_bounds_checker::check_array_bounds, &wi);
873 /* Determine if there's a unique successor edge, and if so, return
874 that back to dom_walker, ensuring that we don't visit blocks that
875 became unreachable during the VRP propagation
876 (PR tree-optimization/83312). */
877 return find_taken_edge (bb, NULL_TREE);
880 void
881 array_bounds_checker::check ()
883 check_array_bounds_dom_walker w (this);
884 w.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));