Daily bump.
[gcc.git] / gcc / gimple-array-bounds.cc
1 /* Array bounds checking.
2 Copyright (C) 2005-2021 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 #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 "gimple-array-bounds.h"
28 #include "gimple-iterator.h"
29 #include "gimple-walk.h"
30 #include "tree-dfa.h"
31 #include "fold-const.h"
32 #include "diagnostic-core.h"
33 #include "intl.h"
34 #include "tree-vrp.h"
35 #include "alloc-pool.h"
36 #include "vr-values.h"
37 #include "domwalk.h"
38 #include "tree-cfg.h"
39 #include "attribs.h"
40 #include "builtins.h"
41
42 // This purposely returns a value_range, not a value_range_equiv, to
43 // break the dependency on equivalences for this pass.
44
45 const value_range *
46 array_bounds_checker::get_value_range (const_tree op)
47 {
48 return ranges->get_value_range (op);
49 }
50
51 /* Try to determine the DECL that REF refers to. Return the DECL or
52 the expression closest to it. Used in informational notes pointing
53 to referenced objects or function parameters. */
54
55 static tree
56 get_base_decl (tree ref)
57 {
58 tree base = get_base_address (ref);
59 if (DECL_P (base))
60 return base;
61
62 if (TREE_CODE (base) == MEM_REF)
63 base = TREE_OPERAND (base, 0);
64
65 if (TREE_CODE (base) != SSA_NAME)
66 return base;
67
68 do
69 {
70 gimple *def = SSA_NAME_DEF_STMT (base);
71 if (gimple_assign_single_p (def))
72 {
73 base = gimple_assign_rhs1 (def);
74 if (TREE_CODE (base) != ASSERT_EXPR)
75 return base;
76
77 base = TREE_OPERAND (base, 0);
78 if (TREE_CODE (base) != SSA_NAME)
79 return base;
80
81 continue;
82 }
83
84 if (!gimple_nop_p (def))
85 return base;
86
87 break;
88 } while (true);
89
90 tree var = SSA_NAME_VAR (base);
91 if (TREE_CODE (var) != PARM_DECL)
92 return base;
93
94 return var;
95 }
96
97 /* Return the constant byte size of the object or type referenced by
98 the MEM_REF ARG. On success, set *PREF to the DECL or expression
99 ARG refers to. Otherwise return null. */
100
101 static tree
102 get_ref_size (tree arg, tree *pref)
103 {
104 if (TREE_CODE (arg) != MEM_REF)
105 return NULL_TREE;
106
107 arg = TREE_OPERAND (arg, 0);
108 tree type = TREE_TYPE (arg);
109 if (!POINTER_TYPE_P (type))
110 return NULL_TREE;
111
112 type = TREE_TYPE (type);
113 if (TREE_CODE (type) != ARRAY_TYPE)
114 return NULL_TREE;
115
116 tree nbytes = TYPE_SIZE_UNIT (type);
117 if (!nbytes || TREE_CODE (nbytes) != INTEGER_CST)
118 return NULL_TREE;
119
120 *pref = get_base_decl (arg);
121 return nbytes;
122 }
123
124 /* Return true if REF is (likely) an ARRAY_REF to a trailing array member
125 of a struct. It refines array_at_struct_end_p by detecting a pointer
126 to an array and an array parameter declared using the [N] syntax (as
127 opposed to a pointer) and returning false. Set *PREF to the decl or
128 expression REF refers to. */
129
130 static bool
131 trailing_array (tree arg, tree *pref)
132 {
133 tree ref = arg;
134 tree base = get_base_decl (arg);
135 while (TREE_CODE (ref) == ARRAY_REF || TREE_CODE (ref) == MEM_REF)
136 ref = TREE_OPERAND (ref, 0);
137
138 if (TREE_CODE (ref) == COMPONENT_REF)
139 {
140 *pref = TREE_OPERAND (ref, 1);
141 tree type = TREE_TYPE (*pref);
142 if (TREE_CODE (type) == ARRAY_TYPE)
143 {
144 /* A multidimensional trailing array is not considered special
145 no matter what its major bound is. */
146 type = TREE_TYPE (type);
147 if (TREE_CODE (type) == ARRAY_TYPE)
148 return false;
149 }
150 }
151 else
152 *pref = base;
153
154 tree basetype = TREE_TYPE (base);
155 if (TREE_CODE (base) == PARM_DECL
156 && POINTER_TYPE_P (basetype))
157 {
158 tree ptype = TREE_TYPE (basetype);
159 if (TREE_CODE (ptype) == ARRAY_TYPE)
160 return false;
161 }
162
163 return array_at_struct_end_p (arg);
164 }
165
166 /* Checks one ARRAY_REF in REF, located at LOCUS. Ignores flexible
167 arrays and "struct" hacks. If VRP can determine that the array
168 subscript is a constant, check if it is outside valid range. If
169 the array subscript is a RANGE, warn if it is non-overlapping with
170 valid range. IGNORE_OFF_BY_ONE is true if the ARRAY_REF is inside
171 a ADDR_EXPR. Return true if a warning has been issued or if
172 no-warning is set. */
173
174 bool
175 array_bounds_checker::check_array_ref (location_t location, tree ref,
176 bool ignore_off_by_one)
177 {
178 if (TREE_NO_WARNING (ref))
179 /* Return true to have the caller prevent warnings for enclosing
180 refs. */
181 return true;
182
183 tree low_sub = TREE_OPERAND (ref, 1);
184 tree up_sub = low_sub;
185 tree up_bound = array_ref_up_bound (ref);
186
187 /* Referenced decl if one can be determined. */
188 tree decl = NULL_TREE;
189
190 /* Set for accesses to interior zero-length arrays. */
191 special_array_member sam{ };
192
193 tree up_bound_p1;
194
195 if (!up_bound
196 || TREE_CODE (up_bound) != INTEGER_CST
197 || (warn_array_bounds < 2 && trailing_array (ref, &decl)))
198 {
199 /* Accesses to trailing arrays via pointers may access storage
200 beyond the types array bounds. For such arrays, or for flexible
201 array members, as well as for other arrays of an unknown size,
202 replace the upper bound with a more permissive one that assumes
203 the size of the largest object is PTRDIFF_MAX. */
204 tree eltsize = array_ref_element_size (ref);
205
206 if (TREE_CODE (eltsize) != INTEGER_CST
207 || integer_zerop (eltsize))
208 {
209 up_bound = NULL_TREE;
210 up_bound_p1 = NULL_TREE;
211 }
212 else
213 {
214 tree ptrdiff_max = TYPE_MAX_VALUE (ptrdiff_type_node);
215 tree maxbound = ptrdiff_max;
216 tree arg = TREE_OPERAND (ref, 0);
217
218 const bool compref = TREE_CODE (arg) == COMPONENT_REF;
219 if (compref)
220 {
221 /* Try to determine the size of the trailing array from
222 its initializer (if it has one). */
223 if (tree refsize = component_ref_size (arg, &sam))
224 if (TREE_CODE (refsize) == INTEGER_CST)
225 maxbound = refsize;
226 }
227
228 if (maxbound == ptrdiff_max)
229 {
230 /* Try to determine the size of the base object. Avoid
231 COMPONENT_REF already tried above. Using its DECL_SIZE
232 size wouldn't necessarily be correct if the reference is
233 to its flexible array member initialized in a different
234 translation unit. */
235 poly_int64 off;
236 if (tree base = get_addr_base_and_unit_offset (arg, &off))
237 {
238 if (TREE_CODE (base) == MEM_REF)
239 {
240 /* Try to determine the size from a pointer to
241 an array if BASE is one. */
242 if (tree size = get_ref_size (base, &decl))
243 maxbound = size;
244 }
245 else if (!compref && DECL_P (base))
246 if (tree basesize = DECL_SIZE_UNIT (base))
247 if (TREE_CODE (basesize) == INTEGER_CST)
248 {
249 maxbound = basesize;
250 decl = base;
251 }
252
253 if (known_gt (off, 0))
254 maxbound = wide_int_to_tree (sizetype,
255 wi::sub (wi::to_wide (maxbound),
256 off));
257 }
258 }
259 else
260 maxbound = fold_convert (sizetype, maxbound);
261
262 up_bound_p1 = int_const_binop (TRUNC_DIV_EXPR, maxbound, eltsize);
263
264 if (up_bound_p1 != NULL_TREE)
265 up_bound = int_const_binop (MINUS_EXPR, up_bound_p1,
266 build_int_cst (ptrdiff_type_node, 1));
267 else
268 up_bound = NULL_TREE;
269 }
270 }
271 else
272 up_bound_p1 = int_const_binop (PLUS_EXPR, up_bound,
273 build_int_cst (TREE_TYPE (up_bound), 1));
274
275 tree low_bound = array_ref_low_bound (ref);
276
277 tree artype = TREE_TYPE (TREE_OPERAND (ref, 0));
278
279 bool warned = false;
280
281 /* Empty array. */
282 if (up_bound && tree_int_cst_equal (low_bound, up_bound_p1))
283 warned = warning_at (location, OPT_Warray_bounds,
284 "array subscript %E is outside array bounds of %qT",
285 low_sub, artype);
286
287 const value_range *vr = NULL;
288 if (TREE_CODE (low_sub) == SSA_NAME)
289 {
290 vr = get_value_range (low_sub);
291 if (!vr->undefined_p () && !vr->varying_p ())
292 {
293 low_sub = vr->kind () == VR_RANGE ? vr->max () : vr->min ();
294 up_sub = vr->kind () == VR_RANGE ? vr->min () : vr->max ();
295 }
296 }
297
298 if (warned)
299 ; /* Do nothing. */
300 else if (vr && vr->kind () == VR_ANTI_RANGE)
301 {
302 if (up_bound
303 && TREE_CODE (up_sub) == INTEGER_CST
304 && (ignore_off_by_one
305 ? tree_int_cst_lt (up_bound, up_sub)
306 : tree_int_cst_le (up_bound, up_sub))
307 && TREE_CODE (low_sub) == INTEGER_CST
308 && tree_int_cst_le (low_sub, low_bound))
309 warned = warning_at (location, OPT_Warray_bounds,
310 "array subscript [%E, %E] is outside "
311 "array bounds of %qT",
312 low_sub, up_sub, artype);
313 }
314 else if (up_bound
315 && TREE_CODE (up_sub) == INTEGER_CST
316 && (ignore_off_by_one
317 ? !tree_int_cst_le (up_sub, up_bound_p1)
318 : !tree_int_cst_le (up_sub, up_bound)))
319 warned = warning_at (location, OPT_Warray_bounds,
320 "array subscript %E is above array bounds of %qT",
321 up_sub, artype);
322 else if (TREE_CODE (low_sub) == INTEGER_CST
323 && tree_int_cst_lt (low_sub, low_bound))
324 warned = warning_at (location, OPT_Warray_bounds,
325 "array subscript %E is below array bounds of %qT",
326 low_sub, artype);
327
328 if (!warned && sam == special_array_member::int_0)
329 warned = warning_at (location, OPT_Wzero_length_bounds,
330 (TREE_CODE (low_sub) == INTEGER_CST
331 ? G_("array subscript %E is outside the bounds "
332 "of an interior zero-length array %qT")
333 : G_("array subscript %qE is outside the bounds "
334 "of an interior zero-length array %qT")),
335 low_sub, artype);
336
337 if (warned)
338 {
339 if (dump_file && (dump_flags & TDF_DETAILS))
340 {
341 fprintf (dump_file, "Array bound warning for ");
342 dump_generic_expr (MSG_NOTE, TDF_SLIM, ref);
343 fprintf (dump_file, "\n");
344 }
345
346 /* Avoid more warnings when checking more significant subscripts
347 of the same expression. */
348 ref = TREE_OPERAND (ref, 0);
349 TREE_NO_WARNING (ref) = 1;
350
351 if (decl)
352 ref = decl;
353
354 tree rec = NULL_TREE;
355 if (TREE_CODE (ref) == COMPONENT_REF)
356 {
357 /* For a reference to a member of a struct object also mention
358 the object if it's known. It may be defined in a different
359 function than the out-of-bounds access. */
360 rec = TREE_OPERAND (ref, 0);
361 if (!VAR_P (rec))
362 rec = NULL_TREE;
363 ref = TREE_OPERAND (ref, 1);
364 }
365
366 if (DECL_P (ref))
367 inform (DECL_SOURCE_LOCATION (ref), "while referencing %qD", ref);
368 if (rec && DECL_P (rec))
369 inform (DECL_SOURCE_LOCATION (rec), "defined here %qD", rec);
370 }
371
372 return warned;
373 }
374
375 /* Hack around the internal representation constraints and build a zero
376 element array type that actually renders as T[0] in diagnostcs. */
377
378 static tree
379 build_zero_elt_array_type (tree eltype)
380 {
381 tree idxtype = build_range_type (sizetype, size_zero_node, NULL_TREE);
382 tree arrtype = build_array_type (eltype, idxtype);
383 arrtype = build_distinct_type_copy (TYPE_MAIN_VARIANT (arrtype));
384 TYPE_SIZE (arrtype) = bitsize_zero_node;
385 TYPE_SIZE_UNIT (arrtype) = size_zero_node;
386 return arrtype;
387 }
388
389 /* Checks one MEM_REF in REF, located at LOCATION, for out-of-bounds
390 references to string constants. If VRP can determine that the array
391 subscript is a constant, check if it is outside valid range.
392 If the array subscript is a RANGE, warn if it is non-overlapping
393 with valid range.
394 IGNORE_OFF_BY_ONE is true if the MEM_REF is inside an ADDR_EXPR
395 (used to allow one-past-the-end indices for code that takes
396 the address of the just-past-the-end element of an array).
397 Returns true if a warning has been issued. */
398
399 bool
400 array_bounds_checker::check_mem_ref (location_t location, tree ref,
401 bool ignore_off_by_one)
402 {
403 if (TREE_NO_WARNING (ref))
404 return false;
405
406 tree arg = TREE_OPERAND (ref, 0);
407 /* The constant and variable offset of the reference. */
408 tree cstoff = TREE_OPERAND (ref, 1);
409 tree varoff = NULL_TREE;
410
411 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
412
413 /* The zero-based array or string constant bounds in bytes. Initially
414 set to [-MAXOBJSIZE - 1, MAXOBJSIZE] until a tighter bound is
415 determined. */
416 offset_int arrbounds[2] = { -maxobjsize - 1, maxobjsize };
417
418 /* The minimum and maximum intermediate offset. For a reference
419 to be valid, not only does the final offset/subscript must be
420 in bounds but all intermediate offsets should be as well.
421 GCC may be able to deal gracefully with such out-of-bounds
422 offsets so the checking is only enabled at -Warray-bounds=2
423 where it may help detect bugs in uses of the intermediate
424 offsets that could otherwise not be detectable. */
425 offset_int ioff = wi::to_offset (fold_convert (ptrdiff_type_node, cstoff));
426 offset_int extrema[2] = { 0, wi::abs (ioff) };
427
428 /* The range of the byte offset into the reference. */
429 offset_int offrange[2] = { 0, 0 };
430
431 /* The statement used to allocate the array or null. */
432 gimple *alloc_stmt = NULL;
433 /* For an allocation statement, the low bound of the size range. */
434 offset_int minbound = 0;
435
436 /* Determine the offsets and increment OFFRANGE for the bounds of each.
437 The loop computes the range of the final offset for expressions such
438 as (A + i0 + ... + iN)[CSTOFF] where i0 through iN are SSA_NAMEs in
439 some range. */
440 const unsigned limit = param_ssa_name_def_chain_limit;
441 for (unsigned n = 0; TREE_CODE (arg) == SSA_NAME && n < limit; ++n)
442 {
443 gimple *def = SSA_NAME_DEF_STMT (arg);
444 if (is_gimple_call (def))
445 {
446 /* Determine the byte size of the array from an allocation call. */
447 wide_int sizrng[2];
448 if (gimple_call_alloc_size (def, sizrng))
449 {
450 arrbounds[0] = 0;
451 arrbounds[1] = offset_int::from (sizrng[1], UNSIGNED);
452 minbound = offset_int::from (sizrng[0], UNSIGNED);
453 alloc_stmt = def;
454 }
455 break;
456 }
457
458 if (gimple_nop_p (def))
459 {
460 /* For a function argument try to determine the byte size
461 of the array from the current function declaratation
462 (e.g., attribute access or related). */
463 wide_int wr[2];
464 tree ref = gimple_parm_array_size (arg, wr);
465 if (!ref)
466 break;
467 arrbounds[0] = offset_int::from (wr[0], UNSIGNED);
468 arrbounds[1] = offset_int::from (wr[1], UNSIGNED);
469 arg = ref;
470 break;
471 }
472
473 if (!is_gimple_assign (def))
474 break;
475
476 tree_code code = gimple_assign_rhs_code (def);
477 if (code == POINTER_PLUS_EXPR)
478 {
479 arg = gimple_assign_rhs1 (def);
480 varoff = gimple_assign_rhs2 (def);
481 }
482 else if (code == ASSERT_EXPR)
483 {
484 arg = TREE_OPERAND (gimple_assign_rhs1 (def), 0);
485 continue;
486 }
487 else
488 return false;
489
490 /* VAROFF should always be a SSA_NAME here (and not even
491 INTEGER_CST) but there's no point in taking chances. */
492 if (TREE_CODE (varoff) != SSA_NAME)
493 break;
494
495 const value_range* const vr = get_value_range (varoff);
496 if (!vr || vr->undefined_p () || vr->varying_p ())
497 break;
498
499 if (!vr->constant_p ())
500 break;
501
502 if (vr->kind () == VR_RANGE)
503 {
504 offset_int min
505 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->min ()));
506 offset_int max
507 = wi::to_offset (fold_convert (ptrdiff_type_node, vr->max ()));
508 if (min < max)
509 {
510 offrange[0] += min;
511 offrange[1] += max;
512 }
513 else
514 {
515 /* When MIN >= MAX, the offset is effectively in a union
516 of two ranges: [-MAXOBJSIZE -1, MAX] and [MIN, MAXOBJSIZE].
517 Since there is no way to represent such a range across
518 additions, conservatively add [-MAXOBJSIZE -1, MAXOBJSIZE]
519 to OFFRANGE. */
520 offrange[0] += arrbounds[0];
521 offrange[1] += arrbounds[1];
522 }
523 }
524 else
525 {
526 /* For an anti-range, analogously to the above, conservatively
527 add [-MAXOBJSIZE -1, MAXOBJSIZE] to OFFRANGE. */
528 offrange[0] += arrbounds[0];
529 offrange[1] += arrbounds[1];
530 }
531
532 /* Keep track of the minimum and maximum offset. */
533 if (offrange[1] < 0 && offrange[1] < extrema[0])
534 extrema[0] = offrange[1];
535 if (offrange[0] > 0 && offrange[0] > extrema[1])
536 extrema[1] = offrange[0];
537
538 if (offrange[0] < arrbounds[0])
539 offrange[0] = arrbounds[0];
540
541 if (offrange[1] > arrbounds[1])
542 offrange[1] = arrbounds[1];
543 }
544
545 tree reftype = NULL_TREE;
546 offset_int eltsize = -1;
547 if (arrbounds[0] >= 0)
548 {
549 /* The byte size of the array has already been determined above
550 based on a pointer ARG. Set ELTSIZE to the size of the type
551 it points to and REFTYPE to the array with the size, rounded
552 down as necessary. */
553 reftype = TREE_TYPE (TREE_TYPE (arg));
554 if (TREE_CODE (reftype) == ARRAY_TYPE)
555 reftype = TREE_TYPE (reftype);
556 if (tree refsize = TYPE_SIZE_UNIT (reftype))
557 if (TREE_CODE (refsize) == INTEGER_CST)
558 eltsize = wi::to_offset (refsize);
559
560 if (eltsize < 0)
561 return false;
562
563 offset_int nelts = arrbounds[1] / eltsize;
564 if (nelts == 0)
565 reftype = build_zero_elt_array_type (reftype);
566 else
567 reftype = build_array_type_nelts (reftype, nelts.to_uhwi ());
568 }
569 else if (TREE_CODE (arg) == ADDR_EXPR)
570 {
571 arg = TREE_OPERAND (arg, 0);
572 if (TREE_CODE (arg) != STRING_CST
573 && TREE_CODE (arg) != PARM_DECL
574 && TREE_CODE (arg) != VAR_DECL)
575 return false;
576
577 /* The type of the object being referred to. It can be an array,
578 string literal, or a non-array type when the MEM_REF represents
579 a reference/subscript via a pointer to an object that is not
580 an element of an array. Incomplete types are excluded as well
581 because their size is not known. */
582 reftype = TREE_TYPE (arg);
583 if (POINTER_TYPE_P (reftype)
584 || !COMPLETE_TYPE_P (reftype)
585 || TREE_CODE (TYPE_SIZE_UNIT (reftype)) != INTEGER_CST)
586 return false;
587
588 /* Except in declared objects, references to trailing array members
589 of structs and union objects are excluded because MEM_REF doesn't
590 make it possible to identify the member where the reference
591 originated. */
592 if (RECORD_OR_UNION_TYPE_P (reftype)
593 && (!VAR_P (arg)
594 || (DECL_EXTERNAL (arg) && array_at_struct_end_p (ref))))
595 return false;
596
597 /* FIXME: Should this be 1 for Fortran? */
598 arrbounds[0] = 0;
599
600 if (TREE_CODE (reftype) == ARRAY_TYPE)
601 {
602 /* Set to the size of the array element (and adjust below). */
603 eltsize = wi::to_offset (TYPE_SIZE_UNIT (TREE_TYPE (reftype)));
604 /* Use log2 of size to convert the array byte size in to its
605 upper bound in elements. */
606 const offset_int eltsizelog2 = wi::floor_log2 (eltsize);
607 if (tree dom = TYPE_DOMAIN (reftype))
608 {
609 tree bnds[] = { TYPE_MIN_VALUE (dom), TYPE_MAX_VALUE (dom) };
610 if (TREE_CODE (arg) == COMPONENT_REF)
611 {
612 offset_int size = maxobjsize;
613 if (tree fldsize = component_ref_size (arg))
614 size = wi::to_offset (fldsize);
615 arrbounds[1] = wi::lrshift (size, eltsizelog2);
616 }
617 else if (array_at_struct_end_p (arg) || !bnds[0] || !bnds[1])
618 arrbounds[1] = wi::lrshift (maxobjsize, eltsizelog2);
619 else
620 arrbounds[1] = (wi::to_offset (bnds[1]) - wi::to_offset (bnds[0])
621 + 1) * eltsize;
622 }
623 else
624 arrbounds[1] = wi::lrshift (maxobjsize, eltsizelog2);
625
626 /* Determine a tighter bound of the non-array element type. */
627 tree eltype = TREE_TYPE (reftype);
628 while (TREE_CODE (eltype) == ARRAY_TYPE)
629 eltype = TREE_TYPE (eltype);
630 eltsize = wi::to_offset (TYPE_SIZE_UNIT (eltype));
631 }
632 else
633 {
634 eltsize = 1;
635 tree size = TYPE_SIZE_UNIT (reftype);
636 if (VAR_P (arg))
637 if (tree initsize = DECL_SIZE_UNIT (arg))
638 if (tree_int_cst_lt (size, initsize))
639 size = initsize;
640
641 arrbounds[1] = wi::to_offset (size);
642 }
643 }
644 else
645 return false;
646
647 offrange[0] += ioff;
648 offrange[1] += ioff;
649
650 /* Compute the more permissive upper bound when IGNORE_OFF_BY_ONE
651 is set (when taking the address of the one-past-last element
652 of an array) but always use the stricter bound in diagnostics. */
653 offset_int ubound = arrbounds[1];
654 if (ignore_off_by_one)
655 ubound += eltsize;
656
657 bool warned = false;
658 /* Set if the lower bound of the subscript is out of bounds. */
659 const bool lboob = (arrbounds[0] == arrbounds[1]
660 || offrange[0] >= ubound
661 || offrange[1] < arrbounds[0]);
662 /* Set if only the upper bound of the subscript is out of bounds.
663 This can happen when using a bigger type to index into an array
664 of a smaller type, as is common with unsigned char. */
665 tree axstype = TREE_TYPE (ref);
666 offset_int axssize = 0;
667 if (TREE_CODE (axstype) != UNION_TYPE)
668 if (tree access_size = TYPE_SIZE_UNIT (axstype))
669 if (TREE_CODE (access_size) == INTEGER_CST)
670 axssize = wi::to_offset (access_size);
671
672 const bool uboob = !lboob && offrange[0] + axssize > ubound;
673 if (lboob || uboob)
674 {
675 /* Treat a reference to a non-array object as one to an array
676 of a single element. */
677 if (TREE_CODE (reftype) != ARRAY_TYPE)
678 reftype = build_array_type_nelts (reftype, 1);
679
680 /* Extract the element type out of MEM_REF and use its size
681 to compute the index to print in the diagnostic; arrays
682 in MEM_REF don't mean anything. A type with no size like
683 void is as good as having a size of 1. */
684 tree type = TREE_TYPE (ref);
685 while (TREE_CODE (type) == ARRAY_TYPE)
686 type = TREE_TYPE (type);
687 if (tree size = TYPE_SIZE_UNIT (type))
688 {
689 offrange[0] = offrange[0] / wi::to_offset (size);
690 offrange[1] = offrange[1] / wi::to_offset (size);
691 }
692 }
693
694 if (lboob)
695 {
696 if (offrange[0] == offrange[1])
697 warned = warning_at (location, OPT_Warray_bounds,
698 "array subscript %wi is outside array bounds "
699 "of %qT",
700 offrange[0].to_shwi (), reftype);
701 else
702 warned = warning_at (location, OPT_Warray_bounds,
703 "array subscript [%wi, %wi] is outside "
704 "array bounds of %qT",
705 offrange[0].to_shwi (),
706 offrange[1].to_shwi (), reftype);
707 }
708 else if (uboob && !ignore_off_by_one)
709 {
710 tree backtype = reftype;
711 if (alloc_stmt)
712 /* If the memory was dynamically allocated refer to it as if
713 it were an untyped array of bytes. */
714 backtype = build_array_type_nelts (unsigned_char_type_node,
715 arrbounds[1].to_uhwi ());
716
717 warned = warning_at (location, OPT_Warray_bounds,
718 "array subscript %<%T[%wi]%> is partly "
719 "outside array bounds of %qT",
720 axstype, offrange[0].to_shwi (), backtype);
721 }
722
723 if (warned)
724 {
725 if (DECL_P (arg))
726 inform (DECL_SOURCE_LOCATION (arg), "while referencing %qD", arg);
727 else if (alloc_stmt)
728 {
729 location_t loc = gimple_location (alloc_stmt);
730 if (gimple_call_builtin_p (alloc_stmt, BUILT_IN_ALLOCA_WITH_ALIGN))
731 {
732 if (minbound == arrbounds[1])
733 inform (loc, "referencing a variable length array "
734 "of size %wu", minbound.to_uhwi ());
735 else
736 inform (loc, "referencing a variable length array "
737 "of size between %wu and %wu",
738 minbound.to_uhwi (), arrbounds[1].to_uhwi ());
739 }
740 else if (tree fndecl = gimple_call_fndecl (alloc_stmt))
741 {
742 if (minbound == arrbounds[1])
743 inform (loc, "referencing an object of size %wu "
744 "allocated by %qD",
745 minbound.to_uhwi (), fndecl);
746 else
747 inform (loc, "referencing an object of size between "
748 "%wu and %wu allocated by %qD",
749 minbound.to_uhwi (), arrbounds[1].to_uhwi (), fndecl);
750 }
751 else
752 {
753 tree fntype = gimple_call_fntype (alloc_stmt);
754 if (minbound == arrbounds[1])
755 inform (loc, "referencing an object of size %wu "
756 "allocated by %qT",
757 minbound.to_uhwi (), fntype);
758 else
759 inform (loc, "referencing an object of size between "
760 "%wu and %wu allocated by %qT",
761 minbound.to_uhwi (), arrbounds[1].to_uhwi (), fntype);
762 }
763 }
764
765 TREE_NO_WARNING (ref) = 1;
766 return true;
767 }
768
769 if (warn_array_bounds < 2)
770 return false;
771
772 /* At level 2 check also intermediate offsets. */
773 int i = 0;
774 if (extrema[i] < -arrbounds[1] || extrema[i = 1] > ubound)
775 {
776 HOST_WIDE_INT tmpidx = extrema[i].to_shwi () / eltsize.to_shwi ();
777
778 if (warning_at (location, OPT_Warray_bounds,
779 "intermediate array offset %wi is outside array bounds "
780 "of %qT", tmpidx, reftype))
781 {
782 TREE_NO_WARNING (ref) = 1;
783 return true;
784 }
785 }
786
787 return false;
788 }
789
790 /* Searches if the expr T, located at LOCATION computes
791 address of an ARRAY_REF, and call check_array_ref on it. */
792
793 void
794 array_bounds_checker::check_addr_expr (location_t location, tree t)
795 {
796 /* For the most significant subscript only, accept taking the address
797 of the just-past-the-end element. */
798 bool ignore_off_by_one = true;
799
800 /* Check each ARRAY_REF and MEM_REF in the reference chain. */
801 do
802 {
803 bool warned = false;
804 if (TREE_CODE (t) == ARRAY_REF)
805 {
806 warned = check_array_ref (location, t, ignore_off_by_one);
807 ignore_off_by_one = false;
808 }
809 else if (TREE_CODE (t) == MEM_REF)
810 warned = check_mem_ref (location, t, ignore_off_by_one);
811
812 if (warned)
813 TREE_NO_WARNING (t) = true;
814
815 t = TREE_OPERAND (t, 0);
816 }
817 while (handled_component_p (t) || TREE_CODE (t) == MEM_REF);
818
819 if (TREE_CODE (t) != MEM_REF
820 || TREE_CODE (TREE_OPERAND (t, 0)) != ADDR_EXPR
821 || TREE_NO_WARNING (t))
822 return;
823
824 tree tem = TREE_OPERAND (TREE_OPERAND (t, 0), 0);
825 tree low_bound, up_bound, el_sz;
826 if (TREE_CODE (TREE_TYPE (tem)) != ARRAY_TYPE
827 || TREE_CODE (TREE_TYPE (TREE_TYPE (tem))) == ARRAY_TYPE
828 || !TYPE_DOMAIN (TREE_TYPE (tem)))
829 return;
830
831 low_bound = TYPE_MIN_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
832 up_bound = TYPE_MAX_VALUE (TYPE_DOMAIN (TREE_TYPE (tem)));
833 el_sz = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (tem)));
834 if (!low_bound
835 || TREE_CODE (low_bound) != INTEGER_CST
836 || !up_bound
837 || TREE_CODE (up_bound) != INTEGER_CST
838 || !el_sz
839 || TREE_CODE (el_sz) != INTEGER_CST)
840 return;
841
842 offset_int idx;
843 if (!mem_ref_offset (t).is_constant (&idx))
844 return;
845
846 bool warned = false;
847 idx = wi::sdiv_trunc (idx, wi::to_offset (el_sz));
848 if (idx < 0)
849 {
850 if (dump_file && (dump_flags & TDF_DETAILS))
851 {
852 fprintf (dump_file, "Array bound warning for ");
853 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
854 fprintf (dump_file, "\n");
855 }
856 warned = warning_at (location, OPT_Warray_bounds,
857 "array subscript %wi is below "
858 "array bounds of %qT",
859 idx.to_shwi (), TREE_TYPE (tem));
860 }
861 else if (idx > (wi::to_offset (up_bound)
862 - wi::to_offset (low_bound) + 1))
863 {
864 if (dump_file && (dump_flags & TDF_DETAILS))
865 {
866 fprintf (dump_file, "Array bound warning for ");
867 dump_generic_expr (MSG_NOTE, TDF_SLIM, t);
868 fprintf (dump_file, "\n");
869 }
870 warned = warning_at (location, OPT_Warray_bounds,
871 "array subscript %wu is above "
872 "array bounds of %qT",
873 idx.to_uhwi (), TREE_TYPE (tem));
874 }
875
876 if (warned)
877 {
878 if (DECL_P (t))
879 inform (DECL_SOURCE_LOCATION (t), "while referencing %qD", t);
880
881 TREE_NO_WARNING (t) = 1;
882 }
883 }
884
885 /* Callback for walk_tree to check a tree for out of bounds array
886 accesses. The array_bounds_checker class is passed in DATA. */
887
888 tree
889 array_bounds_checker::check_array_bounds (tree *tp, int *walk_subtree,
890 void *data)
891 {
892 tree t = *tp;
893 struct walk_stmt_info *wi = (struct walk_stmt_info *) data;
894 location_t location;
895
896 if (EXPR_HAS_LOCATION (t))
897 location = EXPR_LOCATION (t);
898 else
899 location = gimple_location (wi->stmt);
900
901 *walk_subtree = TRUE;
902
903 bool warned = false;
904 array_bounds_checker *checker = (array_bounds_checker *) wi->info;
905 if (TREE_CODE (t) == ARRAY_REF)
906 warned = checker->check_array_ref (location, t,
907 false/*ignore_off_by_one*/);
908 else if (TREE_CODE (t) == MEM_REF)
909 warned = checker->check_mem_ref (location, t,
910 false /*ignore_off_by_one*/);
911 else if (TREE_CODE (t) == ADDR_EXPR)
912 {
913 checker->check_addr_expr (location, t);
914 *walk_subtree = FALSE;
915 }
916 /* Propagate the no-warning bit to the outer expression. */
917 if (warned)
918 TREE_NO_WARNING (t) = true;
919
920 return NULL_TREE;
921 }
922
923 /* A dom_walker subclass for use by check_all_array_refs, to walk over
924 all statements of all reachable BBs and call check_array_bounds on
925 them. */
926
927 class check_array_bounds_dom_walker : public dom_walker
928 {
929 public:
930 check_array_bounds_dom_walker (array_bounds_checker *checker)
931 : dom_walker (CDI_DOMINATORS,
932 /* Discover non-executable edges, preserving EDGE_EXECUTABLE
933 flags, so that we can merge in information on
934 non-executable edges from vrp_folder . */
935 REACHABLE_BLOCKS_PRESERVING_FLAGS),
936 checker (checker) { }
937 ~check_array_bounds_dom_walker () {}
938
939 edge before_dom_children (basic_block) FINAL OVERRIDE;
940
941 private:
942 array_bounds_checker *checker;
943 };
944
945 /* Implementation of dom_walker::before_dom_children.
946
947 Walk over all statements of BB and call check_array_bounds on them,
948 and determine if there's a unique successor edge. */
949
950 edge
951 check_array_bounds_dom_walker::before_dom_children (basic_block bb)
952 {
953 gimple_stmt_iterator si;
954 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
955 {
956 gimple *stmt = gsi_stmt (si);
957 struct walk_stmt_info wi;
958 if (!gimple_has_location (stmt)
959 || is_gimple_debug (stmt))
960 continue;
961
962 memset (&wi, 0, sizeof (wi));
963
964 wi.info = checker;
965
966 walk_gimple_op (stmt, array_bounds_checker::check_array_bounds, &wi);
967 }
968
969 /* Determine if there's a unique successor edge, and if so, return
970 that back to dom_walker, ensuring that we don't visit blocks that
971 became unreachable during the VRP propagation
972 (PR tree-optimization/83312). */
973 return find_taken_edge (bb, NULL_TREE);
974 }
975
976 void
977 array_bounds_checker::check ()
978 {
979 check_array_bounds_dom_walker w (this);
980 w.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
981 }