]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-ssa-strlen.c
* tree-ssa-strlen.c (maybe_invalidate): Use
[thirdparty/gcc.git] / gcc / tree-ssa-strlen.c
1 /* String length optimization
2 Copyright (C) 2011-2019 Free Software Foundation, Inc.
3 Contributed by Jakub Jelinek <jakub@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "alloc-pool.h"
29 #include "tree-pass.h"
30 #include "ssa.h"
31 #include "cgraph.h"
32 #include "gimple-pretty-print.h"
33 #include "gimple-ssa-warn-restrict.h"
34 #include "fold-const.h"
35 #include "stor-layout.h"
36 #include "gimple-fold.h"
37 #include "tree-eh.h"
38 #include "gimplify.h"
39 #include "gimple-iterator.h"
40 #include "gimplify-me.h"
41 #include "expr.h"
42 #include "tree-cfg.h"
43 #include "tree-dfa.h"
44 #include "domwalk.h"
45 #include "tree-ssa-alias.h"
46 #include "tree-ssa-propagate.h"
47 #include "tree-ssa-strlen.h"
48 #include "params.h"
49 #include "tree-hash-traits.h"
50 #include "tree-object-size.h"
51 #include "builtins.h"
52 #include "target.h"
53 #include "diagnostic-core.h"
54 #include "diagnostic.h"
55 #include "intl.h"
56 #include "attribs.h"
57 #include "calls.h"
58 #include "cfgloop.h"
59 #include "tree-ssa-loop.h"
60 #include "tree-scalar-evolution.h"
61
62 #include "vr-values.h"
63 #include "gimple-ssa-evrp-analyze.h"
64
65 /* A vector indexed by SSA_NAME_VERSION. 0 means unknown, positive value
66 is an index into strinfo vector, negative value stands for
67 string length of a string literal (~strlen). */
68 static vec<int> ssa_ver_to_stridx;
69
70 /* Number of currently active string indexes plus one. */
71 static int max_stridx;
72
73 /* Set to true to optimize, false when just checking. */
74 static bool strlen_optimize;
75
76 /* String information record. */
77 struct strinfo
78 {
79 /* Number of leading characters that are known to be nonzero. This is
80 also the length of the string if FULL_STRING_P.
81
82 The values in a list of related string pointers must be consistent;
83 that is, if strinfo B comes X bytes after strinfo A, it must be
84 the case that A->nonzero_chars == X + B->nonzero_chars. */
85 tree nonzero_chars;
86 /* Any of the corresponding pointers for querying alias oracle. */
87 tree ptr;
88 /* This is used for two things:
89
90 - To record the statement that should be used for delayed length
91 computations. We maintain the invariant that all related strinfos
92 have delayed lengths or none do.
93
94 - To record the malloc or calloc call that produced this result. */
95 gimple *stmt;
96 /* Pointer to '\0' if known, if NULL, it can be computed as
97 ptr + length. */
98 tree endptr;
99 /* Reference count. Any changes to strinfo entry possibly shared
100 with dominating basic blocks need unshare_strinfo first, except
101 for dont_invalidate which affects only the immediately next
102 maybe_invalidate. */
103 int refcount;
104 /* Copy of index. get_strinfo (si->idx) should return si; */
105 int idx;
106 /* These 3 fields are for chaining related string pointers together.
107 E.g. for
108 bl = strlen (b); dl = strlen (d); strcpy (a, b); c = a + bl;
109 strcpy (c, d); e = c + dl;
110 strinfo(a) -> strinfo(c) -> strinfo(e)
111 All have ->first field equal to strinfo(a)->idx and are doubly
112 chained through prev/next fields. The later strinfos are required
113 to point into the same string with zero or more bytes after
114 the previous pointer and all bytes in between the two pointers
115 must be non-zero. Functions like strcpy or memcpy are supposed
116 to adjust all previous strinfo lengths, but not following strinfo
117 lengths (those are uncertain, usually invalidated during
118 maybe_invalidate, except when the alias oracle knows better).
119 Functions like strcat on the other side adjust the whole
120 related strinfo chain.
121 They are updated lazily, so to use the chain the same first fields
122 and si->prev->next == si->idx needs to be verified. */
123 int first;
124 int next;
125 int prev;
126 /* A flag whether the string is known to be written in the current
127 function. */
128 bool writable;
129 /* A flag for the next maybe_invalidate that this strinfo shouldn't
130 be invalidated. Always cleared by maybe_invalidate. */
131 bool dont_invalidate;
132 /* True if the string is known to be nul-terminated after NONZERO_CHARS
133 characters. False is useful when detecting strings that are built
134 up via successive memcpys. */
135 bool full_string_p;
136 };
137
138 /* Pool for allocating strinfo_struct entries. */
139 static object_allocator<strinfo> strinfo_pool ("strinfo pool");
140
141 /* Vector mapping positive string indexes to strinfo, for the
142 current basic block. The first pointer in the vector is special,
143 it is either NULL, meaning the vector isn't shared, or it is
144 a basic block pointer to the owner basic_block if shared.
145 If some other bb wants to modify the vector, the vector needs
146 to be unshared first, and only the owner bb is supposed to free it. */
147 static vec<strinfo *, va_heap, vl_embed> *stridx_to_strinfo;
148
149 /* One OFFSET->IDX mapping. */
150 struct stridxlist
151 {
152 struct stridxlist *next;
153 HOST_WIDE_INT offset;
154 int idx;
155 };
156
157 /* Hash table entry, mapping a DECL to a chain of OFFSET->IDX mappings. */
158 struct decl_stridxlist_map
159 {
160 struct tree_map_base base;
161 struct stridxlist list;
162 };
163
164 /* Hash table for mapping decls to a chained list of offset -> idx
165 mappings. */
166 typedef hash_map<tree_decl_hash, stridxlist> decl_to_stridxlist_htab_t;
167 static decl_to_stridxlist_htab_t *decl_to_stridxlist_htab;
168
169 /* Hash table mapping strlen (or strnlen with constant bound and return
170 smaller than bound) calls to stridx instances describing
171 the calls' arguments. Non-null only when warn_stringop_truncation
172 is non-zero. */
173 typedef std::pair<int, location_t> stridx_strlenloc;
174 static hash_map<tree, stridx_strlenloc> *strlen_to_stridx;
175
176 /* Obstack for struct stridxlist and struct decl_stridxlist_map. */
177 static struct obstack stridx_obstack;
178
179 /* Last memcpy statement if it could be adjusted if the trailing
180 '\0' written is immediately overwritten, or
181 *x = '\0' store that could be removed if it is immediately overwritten. */
182 struct laststmt_struct
183 {
184 gimple *stmt;
185 tree len;
186 int stridx;
187 } laststmt;
188
189 static int get_stridx_plus_constant (strinfo *, unsigned HOST_WIDE_INT, tree);
190 static void handle_builtin_stxncpy (built_in_function, gimple_stmt_iterator *);
191
192 /* Return:
193
194 * +1 if SI is known to start with more than OFF nonzero characters.
195
196 * 0 if SI is known to start with OFF nonzero characters,
197 but is not known to start with more.
198
199 * -1 if SI might not start with OFF nonzero characters. */
200
201 static inline int
202 compare_nonzero_chars (strinfo *si, unsigned HOST_WIDE_INT off)
203 {
204 if (si->nonzero_chars
205 && TREE_CODE (si->nonzero_chars) == INTEGER_CST)
206 return compare_tree_int (si->nonzero_chars, off);
207 else
208 return -1;
209 }
210
211 /* Same as above but suitable also for strings with non-constant lengths.
212 Uses RVALS to determine length range. */
213
214 static int
215 compare_nonzero_chars (strinfo *si, unsigned HOST_WIDE_INT off,
216 const vr_values *rvals)
217 {
218 if (!si->nonzero_chars)
219 return -1;
220
221 if (TREE_CODE (si->nonzero_chars) == INTEGER_CST)
222 return compare_tree_int (si->nonzero_chars, off);
223
224 if (TREE_CODE (si->nonzero_chars) != SSA_NAME)
225 return -1;
226
227 const value_range *vr
228 = (CONST_CAST (class vr_values *, rvals)
229 ->get_value_range (si->nonzero_chars));
230
231 value_range_kind rng = vr->kind ();
232 if (rng != VR_RANGE || !range_int_cst_p (vr))
233 return -1;
234
235 return compare_tree_int (vr->min (), off);
236 }
237
238 /* Return true if SI is known to be a zero-length string. */
239
240 static inline bool
241 zero_length_string_p (strinfo *si)
242 {
243 return si->full_string_p && integer_zerop (si->nonzero_chars);
244 }
245
246 /* Return strinfo vector entry IDX. */
247
248 static inline strinfo *
249 get_strinfo (int idx)
250 {
251 if (vec_safe_length (stridx_to_strinfo) <= (unsigned int) idx)
252 return NULL;
253 return (*stridx_to_strinfo)[idx];
254 }
255
256 /* Get the next strinfo in the chain after SI, or null if none. */
257
258 static inline strinfo *
259 get_next_strinfo (strinfo *si)
260 {
261 if (si->next == 0)
262 return NULL;
263 strinfo *nextsi = get_strinfo (si->next);
264 if (nextsi == NULL || nextsi->first != si->first || nextsi->prev != si->idx)
265 return NULL;
266 return nextsi;
267 }
268
269 /* Helper function for get_stridx. Return the strinfo index of the address
270 of EXP, which is available in PTR if nonnull. If OFFSET_OUT, it is
271 OK to return the index for some X <= &EXP and store &EXP - X in
272 *OFFSET_OUT. */
273
274 static int
275 get_addr_stridx (tree exp, tree ptr, unsigned HOST_WIDE_INT *offset_out)
276 {
277 HOST_WIDE_INT off;
278 struct stridxlist *list, *last = NULL;
279 tree base;
280
281 if (!decl_to_stridxlist_htab)
282 return 0;
283
284 poly_int64 poff;
285 base = get_addr_base_and_unit_offset (exp, &poff);
286 if (base == NULL || !DECL_P (base) || !poff.is_constant (&off))
287 return 0;
288
289 list = decl_to_stridxlist_htab->get (base);
290 if (list == NULL)
291 return 0;
292
293 do
294 {
295 if (list->offset == off)
296 {
297 if (offset_out)
298 *offset_out = 0;
299 return list->idx;
300 }
301 if (list->offset > off)
302 return 0;
303 last = list;
304 list = list->next;
305 }
306 while (list);
307
308 if ((offset_out || ptr) && last && last->idx > 0)
309 {
310 unsigned HOST_WIDE_INT rel_off
311 = (unsigned HOST_WIDE_INT) off - last->offset;
312 strinfo *si = get_strinfo (last->idx);
313 if (si && compare_nonzero_chars (si, rel_off) >= 0)
314 {
315 if (offset_out)
316 {
317 *offset_out = rel_off;
318 return last->idx;
319 }
320 else
321 return get_stridx_plus_constant (si, rel_off, ptr);
322 }
323 }
324 return 0;
325 }
326
327 /* Return string index for EXP. */
328
329 static int
330 get_stridx (tree exp)
331 {
332 if (TREE_CODE (exp) == SSA_NAME)
333 {
334 if (ssa_ver_to_stridx[SSA_NAME_VERSION (exp)])
335 return ssa_ver_to_stridx[SSA_NAME_VERSION (exp)];
336
337 tree e = exp;
338 HOST_WIDE_INT offset = 0;
339 /* Follow a chain of at most 5 assignments. */
340 for (int i = 0; i < 5; i++)
341 {
342 gimple *def_stmt = SSA_NAME_DEF_STMT (e);
343 if (!is_gimple_assign (def_stmt))
344 return 0;
345
346 tree_code rhs_code = gimple_assign_rhs_code (def_stmt);
347 tree ptr, off;
348
349 if (rhs_code == ADDR_EXPR)
350 {
351 /* Handle indices/offsets into VLAs which are implemented
352 as pointers to arrays. */
353 ptr = gimple_assign_rhs1 (def_stmt);
354 ptr = TREE_OPERAND (ptr, 0);
355
356 /* Handle also VLAs of types larger than char. */
357 if (tree eltsize = TYPE_SIZE_UNIT (TREE_TYPE (ptr)))
358 {
359 if (TREE_CODE (ptr) == ARRAY_REF)
360 {
361 off = TREE_OPERAND (ptr, 1);
362 ptr = TREE_OPERAND (ptr, 0);
363 if (!integer_onep (eltsize))
364 {
365 /* Scale the array index by the size of the element
366 type in the rare case that it's greater than
367 the typical 1 for char, making sure both operands
368 have the same type. */
369 eltsize = fold_convert (ssizetype, eltsize);
370 off = fold_convert (ssizetype, off);
371 off = fold_build2 (MULT_EXPR, ssizetype, off, eltsize);
372 }
373 }
374 else
375 off = integer_zero_node;
376 }
377 else
378 return 0;
379
380 if (TREE_CODE (ptr) != MEM_REF)
381 return 0;
382
383 /* Add the MEM_REF byte offset. */
384 tree mem_off = TREE_OPERAND (ptr, 1);
385 off = fold_build2 (PLUS_EXPR, TREE_TYPE (off), off, mem_off);
386 ptr = TREE_OPERAND (ptr, 0);
387 }
388 else if (rhs_code == POINTER_PLUS_EXPR)
389 {
390 ptr = gimple_assign_rhs1 (def_stmt);
391 off = gimple_assign_rhs2 (def_stmt);
392 }
393 else
394 return 0;
395
396 if (TREE_CODE (ptr) != SSA_NAME
397 || !tree_fits_shwi_p (off))
398 return 0;
399 HOST_WIDE_INT this_off = tree_to_shwi (off);
400 if (this_off < 0)
401 return 0;
402 offset = (unsigned HOST_WIDE_INT) offset + this_off;
403 if (offset < 0)
404 return 0;
405 if (ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)])
406 {
407 strinfo *si
408 = get_strinfo (ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)]);
409 if (si && compare_nonzero_chars (si, offset) >= 0)
410 return get_stridx_plus_constant (si, offset, exp);
411 }
412 e = ptr;
413 }
414 return 0;
415 }
416
417 if (TREE_CODE (exp) == ADDR_EXPR)
418 {
419 int idx = get_addr_stridx (TREE_OPERAND (exp, 0), exp, NULL);
420 if (idx != 0)
421 return idx;
422 }
423
424 const char *p = c_getstr (exp);
425 if (p)
426 return ~(int) strlen (p);
427
428 return 0;
429 }
430
431 /* Return true if strinfo vector is shared with the immediate dominator. */
432
433 static inline bool
434 strinfo_shared (void)
435 {
436 return vec_safe_length (stridx_to_strinfo)
437 && (*stridx_to_strinfo)[0] != NULL;
438 }
439
440 /* Unshare strinfo vector that is shared with the immediate dominator. */
441
442 static void
443 unshare_strinfo_vec (void)
444 {
445 strinfo *si;
446 unsigned int i = 0;
447
448 gcc_assert (strinfo_shared ());
449 stridx_to_strinfo = vec_safe_copy (stridx_to_strinfo);
450 for (i = 1; vec_safe_iterate (stridx_to_strinfo, i, &si); ++i)
451 if (si != NULL)
452 si->refcount++;
453 (*stridx_to_strinfo)[0] = NULL;
454 }
455
456 /* Attempt to create a string index for exp, ADDR_EXPR's operand.
457 Return a pointer to the location where the string index can
458 be stored (if 0) or is stored, or NULL if this can't be tracked. */
459
460 static int *
461 addr_stridxptr (tree exp)
462 {
463 HOST_WIDE_INT off;
464
465 poly_int64 poff;
466 tree base = get_addr_base_and_unit_offset (exp, &poff);
467 if (base == NULL_TREE || !DECL_P (base) || !poff.is_constant (&off))
468 return NULL;
469
470 if (!decl_to_stridxlist_htab)
471 {
472 decl_to_stridxlist_htab
473 = new hash_map<tree_decl_hash, stridxlist> (64);
474 gcc_obstack_init (&stridx_obstack);
475 }
476
477 bool existed;
478 stridxlist *list = &decl_to_stridxlist_htab->get_or_insert (base, &existed);
479 if (existed)
480 {
481 int i;
482 stridxlist *before = NULL;
483 for (i = 0; i < 32; i++)
484 {
485 if (list->offset == off)
486 return &list->idx;
487 if (list->offset > off && before == NULL)
488 before = list;
489 if (list->next == NULL)
490 break;
491 list = list->next;
492 }
493 if (i == 32)
494 return NULL;
495 if (before)
496 {
497 list = before;
498 before = XOBNEW (&stridx_obstack, struct stridxlist);
499 *before = *list;
500 list->next = before;
501 list->offset = off;
502 list->idx = 0;
503 return &list->idx;
504 }
505 list->next = XOBNEW (&stridx_obstack, struct stridxlist);
506 list = list->next;
507 }
508
509 list->next = NULL;
510 list->offset = off;
511 list->idx = 0;
512 return &list->idx;
513 }
514
515 /* Create a new string index, or return 0 if reached limit. */
516
517 static int
518 new_stridx (tree exp)
519 {
520 int idx;
521 if (max_stridx >= PARAM_VALUE (PARAM_MAX_TRACKED_STRLENS))
522 return 0;
523 if (TREE_CODE (exp) == SSA_NAME)
524 {
525 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (exp))
526 return 0;
527 idx = max_stridx++;
528 ssa_ver_to_stridx[SSA_NAME_VERSION (exp)] = idx;
529 return idx;
530 }
531 if (TREE_CODE (exp) == ADDR_EXPR)
532 {
533 int *pidx = addr_stridxptr (TREE_OPERAND (exp, 0));
534 if (pidx != NULL)
535 {
536 gcc_assert (*pidx == 0);
537 *pidx = max_stridx++;
538 return *pidx;
539 }
540 }
541 return 0;
542 }
543
544 /* Like new_stridx, but for ADDR_EXPR's operand instead. */
545
546 static int
547 new_addr_stridx (tree exp)
548 {
549 int *pidx;
550 if (max_stridx >= PARAM_VALUE (PARAM_MAX_TRACKED_STRLENS))
551 return 0;
552 pidx = addr_stridxptr (exp);
553 if (pidx != NULL)
554 {
555 gcc_assert (*pidx == 0);
556 *pidx = max_stridx++;
557 return *pidx;
558 }
559 return 0;
560 }
561
562 /* Create a new strinfo. */
563
564 static strinfo *
565 new_strinfo (tree ptr, int idx, tree nonzero_chars, bool full_string_p)
566 {
567 strinfo *si = strinfo_pool.allocate ();
568 si->nonzero_chars = nonzero_chars;
569 si->ptr = ptr;
570 si->stmt = NULL;
571 si->endptr = NULL_TREE;
572 si->refcount = 1;
573 si->idx = idx;
574 si->first = 0;
575 si->prev = 0;
576 si->next = 0;
577 si->writable = false;
578 si->dont_invalidate = false;
579 si->full_string_p = full_string_p;
580 return si;
581 }
582
583 /* Decrease strinfo refcount and free it if not referenced anymore. */
584
585 static inline void
586 free_strinfo (strinfo *si)
587 {
588 if (si && --si->refcount == 0)
589 strinfo_pool.remove (si);
590 }
591
592 /* Set strinfo in the vector entry IDX to SI. */
593
594 static inline void
595 set_strinfo (int idx, strinfo *si)
596 {
597 if (vec_safe_length (stridx_to_strinfo) && (*stridx_to_strinfo)[0])
598 unshare_strinfo_vec ();
599 if (vec_safe_length (stridx_to_strinfo) <= (unsigned int) idx)
600 vec_safe_grow_cleared (stridx_to_strinfo, idx + 1);
601 (*stridx_to_strinfo)[idx] = si;
602 }
603
604 /* Return the first strinfo in the related strinfo chain
605 if all strinfos in between belong to the chain, otherwise NULL. */
606
607 static strinfo *
608 verify_related_strinfos (strinfo *origsi)
609 {
610 strinfo *si = origsi, *psi;
611
612 if (origsi->first == 0)
613 return NULL;
614 for (; si->prev; si = psi)
615 {
616 if (si->first != origsi->first)
617 return NULL;
618 psi = get_strinfo (si->prev);
619 if (psi == NULL)
620 return NULL;
621 if (psi->next != si->idx)
622 return NULL;
623 }
624 if (si->idx != si->first)
625 return NULL;
626 return si;
627 }
628
629 /* Set SI's endptr to ENDPTR and compute its length based on SI->ptr.
630 Use LOC for folding. */
631
632 static void
633 set_endptr_and_length (location_t loc, strinfo *si, tree endptr)
634 {
635 si->endptr = endptr;
636 si->stmt = NULL;
637 tree start_as_size = fold_convert_loc (loc, size_type_node, si->ptr);
638 tree end_as_size = fold_convert_loc (loc, size_type_node, endptr);
639 si->nonzero_chars = fold_build2_loc (loc, MINUS_EXPR, size_type_node,
640 end_as_size, start_as_size);
641 si->full_string_p = true;
642 }
643
644 /* Return the string length, or NULL if it can't be computed.
645 The length may but need not be constant. Instead, it might be
646 the result of a strlen() call. */
647
648 static tree
649 get_string_length (strinfo *si)
650 {
651 /* If the length has already been computed return it if it's exact
652 (i.e., the string is nul-terminated at NONZERO_CHARS), or return
653 null if it isn't. */
654 if (si->nonzero_chars)
655 return si->full_string_p ? si->nonzero_chars : NULL;
656
657 /* If the string is the result of one of the built-in calls below
658 attempt to compute the length from the call statement. */
659 if (si->stmt)
660 {
661 gimple *stmt = si->stmt, *lenstmt;
662 tree callee, lhs, fn, tem;
663 location_t loc;
664 gimple_stmt_iterator gsi;
665
666 gcc_assert (is_gimple_call (stmt));
667 callee = gimple_call_fndecl (stmt);
668 gcc_assert (callee && fndecl_built_in_p (callee, BUILT_IN_NORMAL));
669 lhs = gimple_call_lhs (stmt);
670 /* unshare_strinfo is intentionally not called here. The (delayed)
671 transformation of strcpy or strcat into stpcpy is done at the place
672 of the former strcpy/strcat call and so can affect all the strinfos
673 with the same stmt. If they were unshared before and transformation
674 has been already done, the handling of BUILT_IN_STPCPY{,_CHK} should
675 just compute the right length. */
676 switch (DECL_FUNCTION_CODE (callee))
677 {
678 case BUILT_IN_STRCAT:
679 case BUILT_IN_STRCAT_CHK:
680 gsi = gsi_for_stmt (stmt);
681 fn = builtin_decl_implicit (BUILT_IN_STRLEN);
682 gcc_assert (lhs == NULL_TREE);
683 tem = unshare_expr (gimple_call_arg (stmt, 0));
684 lenstmt = gimple_build_call (fn, 1, tem);
685 lhs = make_ssa_name (TREE_TYPE (TREE_TYPE (fn)), lenstmt);
686 gimple_call_set_lhs (lenstmt, lhs);
687 gimple_set_vuse (lenstmt, gimple_vuse (stmt));
688 gsi_insert_before (&gsi, lenstmt, GSI_SAME_STMT);
689 tem = gimple_call_arg (stmt, 0);
690 if (!ptrofftype_p (TREE_TYPE (lhs)))
691 {
692 lhs = convert_to_ptrofftype (lhs);
693 lhs = force_gimple_operand_gsi (&gsi, lhs, true, NULL_TREE,
694 true, GSI_SAME_STMT);
695 }
696 lenstmt = gimple_build_assign
697 (make_ssa_name (TREE_TYPE (gimple_call_arg (stmt, 0))),
698 POINTER_PLUS_EXPR,tem, lhs);
699 gsi_insert_before (&gsi, lenstmt, GSI_SAME_STMT);
700 gimple_call_set_arg (stmt, 0, gimple_assign_lhs (lenstmt));
701 lhs = NULL_TREE;
702 /* FALLTHRU */
703 case BUILT_IN_STRCPY:
704 case BUILT_IN_STRCPY_CHK:
705 gcc_assert (builtin_decl_implicit_p (BUILT_IN_STPCPY));
706 if (gimple_call_num_args (stmt) == 2)
707 fn = builtin_decl_implicit (BUILT_IN_STPCPY);
708 else
709 fn = builtin_decl_explicit (BUILT_IN_STPCPY_CHK);
710 gcc_assert (lhs == NULL_TREE);
711 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
712 {
713 fprintf (dump_file, "Optimizing: ");
714 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
715 }
716 gimple_call_set_fndecl (stmt, fn);
717 lhs = make_ssa_name (TREE_TYPE (TREE_TYPE (fn)), stmt);
718 gimple_call_set_lhs (stmt, lhs);
719 update_stmt (stmt);
720 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
721 {
722 fprintf (dump_file, "into: ");
723 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
724 }
725 /* FALLTHRU */
726 case BUILT_IN_STPCPY:
727 case BUILT_IN_STPCPY_CHK:
728 gcc_assert (lhs != NULL_TREE);
729 loc = gimple_location (stmt);
730 set_endptr_and_length (loc, si, lhs);
731 for (strinfo *chainsi = verify_related_strinfos (si);
732 chainsi != NULL;
733 chainsi = get_next_strinfo (chainsi))
734 if (chainsi->nonzero_chars == NULL)
735 set_endptr_and_length (loc, chainsi, lhs);
736 break;
737 case BUILT_IN_MALLOC:
738 break;
739 /* BUILT_IN_CALLOC always has si->nonzero_chars set. */
740 default:
741 gcc_unreachable ();
742 break;
743 }
744 }
745
746 return si->nonzero_chars;
747 }
748
749 /* Dump strlen data to FP for statement STMT. When non-null, RVALS
750 points to EVRP info and is used to dump strlen range for non-constant
751 results. */
752
753 DEBUG_FUNCTION void
754 dump_strlen_info (FILE *fp, gimple *stmt, const vr_values *rvals)
755 {
756 if (stmt)
757 {
758 fprintf (fp, "\nDumping strlen pass data after ");
759 print_gimple_expr (fp, stmt, TDF_LINENO);
760 fputc ('\n', fp);
761 }
762 else
763 fprintf (fp, "\nDumping strlen pass data\n");
764
765 fprintf (fp, "max_stridx = %i\n", max_stridx);
766 fprintf (fp, "ssa_ver_to_stridx has %u elements\n",
767 ssa_ver_to_stridx.length ());
768 fprintf (fp, "stridx_to_strinfo");
769 if (stridx_to_strinfo)
770 {
771 fprintf (fp, " has %u elements\n", stridx_to_strinfo->length ());
772 for (unsigned i = 0; i != stridx_to_strinfo->length (); ++i)
773 {
774 if (strinfo *si = (*stridx_to_strinfo)[i])
775 {
776 if (!si->idx)
777 continue;
778 fprintf (fp, " idx = %i", si->idx);
779 if (si->ptr)
780 {
781 fprintf (fp, ", ptr = ");
782 print_generic_expr (fp, si->ptr);
783 }
784 fprintf (fp, ", nonzero_chars = ");
785 print_generic_expr (fp, si->nonzero_chars);
786 if (TREE_CODE (si->nonzero_chars) == SSA_NAME)
787 {
788 value_range_kind rng = VR_UNDEFINED;
789 wide_int min, max;
790 if (rvals)
791 {
792 const value_range *vr
793 = CONST_CAST (class vr_values *, rvals)
794 ->get_value_range (si->nonzero_chars);
795 rng = vr->kind ();
796 if (range_int_cst_p (vr))
797 {
798 min = wi::to_wide (vr->min ());
799 max = wi::to_wide (vr->max ());
800 }
801 else
802 rng = VR_UNDEFINED;
803 }
804 else
805 rng = get_range_info (si->nonzero_chars, &min, &max);
806
807 if (rng == VR_RANGE || rng == VR_ANTI_RANGE)
808 {
809 fprintf (fp, " %s[%llu, %llu]",
810 rng == VR_RANGE ? "" : "~",
811 (long long) min.to_uhwi (),
812 (long long) max.to_uhwi ());
813 }
814 }
815 fprintf (fp, " , refcount = %i", si->refcount);
816 if (si->stmt)
817 {
818 fprintf (fp, ", stmt = ");
819 print_gimple_expr (fp, si->stmt, 0);
820 }
821 if (si->writable)
822 fprintf (fp, ", writable");
823 if (si->full_string_p)
824 fprintf (fp, ", full_string_p");
825 if (strinfo *next = get_next_strinfo (si))
826 {
827 fprintf (fp, ", {");
828 do
829 fprintf (fp, "%i%s", next->idx, next->first ? ", " : "");
830 while ((next = get_next_strinfo (next)));
831 fprintf (fp, "}");
832 }
833 fputs ("\n", fp);
834 }
835 }
836 }
837 else
838 fprintf (fp, " = null\n");
839
840 fprintf (fp, "decl_to_stridxlist_htab");
841 if (decl_to_stridxlist_htab)
842 {
843 fputs ("\n", fp);
844 typedef decl_to_stridxlist_htab_t::iterator iter_t;
845 for (iter_t it = decl_to_stridxlist_htab->begin ();
846 it != decl_to_stridxlist_htab->end (); ++it)
847 {
848 tree decl = (*it).first;
849 stridxlist *list = &(*it).second;
850 fprintf (fp, " decl = ");
851 print_generic_expr (fp, decl);
852 if (list)
853 {
854 fprintf (fp, ", offsets = {");
855 for (; list; list = list->next)
856 fprintf (fp, "%lli%s", (long long) list->offset,
857 list->next ? ", " : "");
858 fputs ("}", fp);
859 }
860 fputs ("\n", fp);
861 }
862 }
863 else
864 fprintf (fp, " = null\n");
865
866 if (laststmt.stmt)
867 {
868 fprintf (fp, "laststmt = ");
869 print_gimple_expr (fp, laststmt.stmt, 0);
870 fprintf (fp, ", len = ");
871 print_generic_expr (fp, laststmt.len);
872 fprintf (fp, ", stridx = %i\n", laststmt.stridx);
873 }
874 }
875
876 /* Attempt to determine the length of the string SRC. On success, store
877 the length in *PDATA and return true. Otherwise, return false.
878 VISITED is a bitmap of visited PHI nodes. RVALS points to EVRP info
879 and PSSA_DEF_MAX to an SSA_NAME assignment limit used to prevent runaway
880 recursion. */
881
882 static bool
883 get_range_strlen_dynamic (tree src, c_strlen_data *pdata, bitmap *visited,
884 const vr_values *rvals, unsigned *pssa_def_max)
885 {
886 int idx = get_stridx (src);
887 if (!idx)
888 {
889 if (TREE_CODE (src) == SSA_NAME)
890 {
891 gimple *def_stmt = SSA_NAME_DEF_STMT (src);
892 if (gimple_code (def_stmt) == GIMPLE_PHI)
893 {
894 if (!*visited)
895 *visited = BITMAP_ALLOC (NULL);
896
897 if (!bitmap_set_bit (*visited, SSA_NAME_VERSION (src)))
898 return true;
899
900 if (*pssa_def_max == 0)
901 return false;
902
903 --*pssa_def_max;
904
905 /* Iterate over the PHI arguments and determine the minimum
906 and maximum length/size of each and incorporate them into
907 the overall result. */
908 gphi *phi = as_a <gphi *> (def_stmt);
909 for (unsigned i = 0; i != gimple_phi_num_args (phi); ++i)
910 {
911 tree arg = gimple_phi_arg_def (phi, i);
912 if (arg == gimple_phi_result (def_stmt))
913 continue;
914
915 c_strlen_data argdata = { };
916 if (get_range_strlen_dynamic (arg, &argdata, visited, rvals,
917 pssa_def_max))
918 {
919 /* Set the DECL of an unterminated array this argument
920 refers to if one hasn't been found yet. */
921 if (!pdata->decl && argdata.decl)
922 pdata->decl = argdata.decl;
923
924 if (!argdata.minlen
925 || (integer_zerop (argdata.minlen)
926 && (!argdata.maxbound
927 || integer_all_onesp (argdata.maxbound))
928 && integer_all_onesp (argdata.maxlen)))
929 {
930 /* Set the upper bound of the length to unbounded. */
931 pdata->maxlen = build_all_ones_cst (size_type_node);
932 continue;
933 }
934
935 /* Adjust the minimum and maximum length determined
936 so far and the upper bound on the array size. */
937 if (!pdata->minlen
938 || tree_int_cst_lt (argdata.minlen, pdata->minlen))
939 pdata->minlen = argdata.minlen;
940 if (!pdata->maxlen
941 || (argdata.maxlen
942 && tree_int_cst_lt (pdata->maxlen, argdata.maxlen)))
943 pdata->maxlen = argdata.maxlen;
944 if (!pdata->maxbound
945 || TREE_CODE (pdata->maxbound) != INTEGER_CST
946 || (argdata.maxbound
947 && tree_int_cst_lt (pdata->maxbound,
948 argdata.maxbound)
949 && !integer_all_onesp (argdata.maxbound)))
950 pdata->maxbound = argdata.maxbound;
951 }
952 else
953 pdata->maxlen = build_all_ones_cst (size_type_node);
954 }
955
956 return true;
957 }
958 }
959
960 /* Return success regardless of the result and handle *PDATA
961 in the caller. */
962 get_range_strlen (src, pdata, 1);
963 return true;
964 }
965
966 if (idx < 0)
967 {
968 /* SRC is a string of constant length. */
969 pdata->minlen = build_int_cst (size_type_node, ~idx);
970 pdata->maxlen = pdata->minlen;
971 pdata->maxbound = pdata->maxlen;
972 return true;
973 }
974
975 if (strinfo *si = get_strinfo (idx))
976 {
977 pdata->minlen = get_string_length (si);
978 if (!pdata->minlen && si->nonzero_chars)
979 {
980 if (TREE_CODE (si->nonzero_chars) == INTEGER_CST)
981 pdata->minlen = si->nonzero_chars;
982 else if (TREE_CODE (si->nonzero_chars) == SSA_NAME)
983 {
984 const value_range *vr
985 = CONST_CAST (class vr_values *, rvals)
986 ->get_value_range (si->nonzero_chars);
987 if (vr->kind () == VR_RANGE
988 && range_int_cst_p (vr))
989 {
990 pdata->minlen = vr->min ();
991 pdata->maxlen = vr->max ();
992 }
993 else
994 pdata->minlen = build_zero_cst (size_type_node);
995 }
996 else
997 pdata->minlen = build_zero_cst (size_type_node);
998
999 tree base = si->ptr;
1000 if (TREE_CODE (base) == ADDR_EXPR)
1001 base = TREE_OPERAND (base, 0);
1002
1003 HOST_WIDE_INT off;
1004 poly_int64 poff;
1005 base = get_addr_base_and_unit_offset (base, &poff);
1006 if (base
1007 && DECL_P (base)
1008 && TREE_CODE (TREE_TYPE (base)) == ARRAY_TYPE
1009 && TYPE_SIZE_UNIT (TREE_TYPE (base))
1010 && poff.is_constant (&off))
1011 {
1012 tree basetype = TREE_TYPE (base);
1013 tree size = TYPE_SIZE_UNIT (basetype);
1014 ++off; /* Increment for the terminating nul. */
1015 pdata->maxlen = fold_build2 (MINUS_EXPR, size_type_node, size,
1016 build_int_cst (size_type_node, off));
1017 pdata->maxbound = pdata->maxlen;
1018 }
1019 else
1020 pdata->maxlen = build_all_ones_cst (size_type_node);
1021 }
1022 else if (pdata->minlen && TREE_CODE (pdata->minlen) == SSA_NAME)
1023 {
1024 const value_range *vr
1025 = CONST_CAST (class vr_values *, rvals)
1026 ->get_value_range (si->nonzero_chars);
1027 if (vr->kind () == VR_RANGE
1028 && range_int_cst_p (vr))
1029 {
1030 pdata->minlen = vr->min ();
1031 pdata->maxlen = vr->max ();
1032 pdata->maxbound = pdata->maxlen;
1033 }
1034 else
1035 {
1036 pdata->minlen = build_zero_cst (size_type_node);
1037 pdata->maxlen = build_all_ones_cst (size_type_node);
1038 }
1039 }
1040 else if (pdata->minlen && TREE_CODE (pdata->minlen) == INTEGER_CST)
1041 {
1042 pdata->maxlen = pdata->minlen;
1043 pdata->maxbound = pdata->minlen;
1044 }
1045 else
1046 {
1047 /* For PDATA->MINLEN that's a non-constant expression such
1048 as PLUS_EXPR whose value range is unknown, set the bounds
1049 to zero and SIZE_MAX. */
1050 pdata->minlen = build_zero_cst (size_type_node);
1051 pdata->maxlen = build_all_ones_cst (size_type_node);
1052 }
1053
1054 return true;
1055 }
1056
1057 return false;
1058 }
1059
1060 /* Analogous to get_range_strlen but for dynamically created strings,
1061 i.e., those created by calls to strcpy as opposed to just string
1062 constants.
1063 Try to obtain the range of the lengths of the string(s) referenced
1064 by SRC, or the size of the largest array SRC refers to if the range
1065 of lengths cannot be determined, and store all in *PDATA. RVALS
1066 points to EVRP info. */
1067
1068 void
1069 get_range_strlen_dynamic (tree src, c_strlen_data *pdata,
1070 const vr_values *rvals)
1071 {
1072 bitmap visited = NULL;
1073 tree maxbound = pdata->maxbound;
1074
1075 unsigned limit = PARAM_VALUE (PARAM_SSA_NAME_DEF_CHAIN_LIMIT);
1076 if (!get_range_strlen_dynamic (src, pdata, &visited, rvals, &limit))
1077 {
1078 /* On failure extend the length range to an impossible maximum
1079 (a valid MAXLEN must be less than PTRDIFF_MAX - 1). Other
1080 members can stay unchanged regardless. */
1081 pdata->minlen = ssize_int (0);
1082 pdata->maxlen = build_all_ones_cst (size_type_node);
1083 }
1084 else if (!pdata->minlen)
1085 pdata->minlen = ssize_int (0);
1086
1087 /* If it's unchanged from it initial non-null value, set the conservative
1088 MAXBOUND to SIZE_MAX. Otherwise leave it null (if it is null). */
1089 if (maxbound && pdata->maxbound == maxbound)
1090 pdata->maxbound = build_all_ones_cst (size_type_node);
1091
1092 if (visited)
1093 BITMAP_FREE (visited);
1094 }
1095
1096 /* Invalidate string length information for strings whose length
1097 might change due to stores in stmt, except those marked DON'T
1098 INVALIDATE. For string-modifying statements, ZERO_WRITE is
1099 set when the statement wrote only zeros. */
1100
1101 static bool
1102 maybe_invalidate (gimple *stmt, bool zero_write = false)
1103 {
1104 if (dump_file && (dump_flags & TDF_DETAILS))
1105 fprintf (dump_file, " %s()\n", __func__);
1106
1107 strinfo *si;
1108 unsigned int i;
1109 bool nonempty = false;
1110
1111 for (i = 1; vec_safe_iterate (stridx_to_strinfo, i, &si); ++i)
1112 if (si != NULL)
1113 {
1114 if (!si->dont_invalidate)
1115 {
1116 ao_ref r;
1117 tree size = NULL_TREE;
1118 if (si->nonzero_chars)
1119 {
1120 /* Include the terminating nul in the size of the string
1121 to consider when determining possible clobber. */
1122 tree type = TREE_TYPE (si->nonzero_chars);
1123 size = fold_build2 (PLUS_EXPR, type, si->nonzero_chars,
1124 build_int_cst (type, 1));
1125 }
1126 ao_ref_init_from_ptr_and_size (&r, si->ptr, size);
1127 if (stmt_may_clobber_ref_p_1 (stmt, &r))
1128 {
1129 if (dump_file && (dump_flags & TDF_DETAILS))
1130 {
1131 if (size && tree_fits_uhwi_p (size))
1132 fprintf (dump_file,
1133 " statement may clobber string "
1134 HOST_WIDE_INT_PRINT_UNSIGNED " long\n",
1135 tree_to_uhwi (size));
1136 else
1137 fprintf (dump_file,
1138 " statement may clobber string\n");
1139 }
1140
1141 set_strinfo (i, NULL);
1142 free_strinfo (si);
1143 continue;
1144 }
1145
1146 if (size
1147 && !zero_write
1148 && si->stmt
1149 && is_gimple_call (si->stmt)
1150 && (DECL_FUNCTION_CODE (gimple_call_fndecl (si->stmt))
1151 == BUILT_IN_CALLOC))
1152 {
1153 /* If the clobber test above considered the length of
1154 the string (including the nul), then for (potentially)
1155 non-zero writes that might modify storage allocated by
1156 calloc consider the whole object and if it might be
1157 clobbered by the statement reset the allocation
1158 statement. */
1159 ao_ref_init_from_ptr_and_size (&r, si->ptr, NULL_TREE);
1160 if (stmt_may_clobber_ref_p_1 (stmt, &r))
1161 si->stmt = NULL;
1162 }
1163 }
1164 si->dont_invalidate = false;
1165 nonempty = true;
1166 }
1167
1168 if (dump_file && (dump_flags & TDF_DETAILS))
1169 fprintf (dump_file, " %s() ==> %i\n", __func__, nonempty);
1170
1171 return nonempty;
1172 }
1173
1174 /* Unshare strinfo record SI, if it has refcount > 1 or
1175 if stridx_to_strinfo vector is shared with some other
1176 bbs. */
1177
1178 static strinfo *
1179 unshare_strinfo (strinfo *si)
1180 {
1181 strinfo *nsi;
1182
1183 if (si->refcount == 1 && !strinfo_shared ())
1184 return si;
1185
1186 nsi = new_strinfo (si->ptr, si->idx, si->nonzero_chars, si->full_string_p);
1187 nsi->stmt = si->stmt;
1188 nsi->endptr = si->endptr;
1189 nsi->first = si->first;
1190 nsi->prev = si->prev;
1191 nsi->next = si->next;
1192 nsi->writable = si->writable;
1193 set_strinfo (si->idx, nsi);
1194 free_strinfo (si);
1195 return nsi;
1196 }
1197
1198 /* Attempt to create a new strinfo for BASESI + OFF, or find existing
1199 strinfo if there is any. Return it's idx, or 0 if no strinfo has
1200 been created. */
1201
1202 static int
1203 get_stridx_plus_constant (strinfo *basesi, unsigned HOST_WIDE_INT off,
1204 tree ptr)
1205 {
1206 if (TREE_CODE (ptr) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ptr))
1207 return 0;
1208
1209 if (compare_nonzero_chars (basesi, off) < 0
1210 || !tree_fits_uhwi_p (basesi->nonzero_chars))
1211 return 0;
1212
1213 unsigned HOST_WIDE_INT nonzero_chars
1214 = tree_to_uhwi (basesi->nonzero_chars) - off;
1215 strinfo *si = basesi, *chainsi;
1216 if (si->first || si->prev || si->next)
1217 si = verify_related_strinfos (basesi);
1218 if (si == NULL
1219 || si->nonzero_chars == NULL_TREE
1220 || TREE_CODE (si->nonzero_chars) != INTEGER_CST)
1221 return 0;
1222
1223 if (TREE_CODE (ptr) == SSA_NAME
1224 && ssa_ver_to_stridx.length () <= SSA_NAME_VERSION (ptr))
1225 ssa_ver_to_stridx.safe_grow_cleared (num_ssa_names);
1226
1227 gcc_checking_assert (compare_tree_int (si->nonzero_chars, off) != -1);
1228 for (chainsi = si; chainsi->next; chainsi = si)
1229 {
1230 si = get_next_strinfo (chainsi);
1231 if (si == NULL
1232 || si->nonzero_chars == NULL_TREE
1233 || TREE_CODE (si->nonzero_chars) != INTEGER_CST)
1234 break;
1235 int r = compare_tree_int (si->nonzero_chars, nonzero_chars);
1236 if (r != 1)
1237 {
1238 if (r == 0)
1239 {
1240 if (TREE_CODE (ptr) == SSA_NAME)
1241 ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)] = si->idx;
1242 else
1243 {
1244 int *pidx = addr_stridxptr (TREE_OPERAND (ptr, 0));
1245 if (pidx != NULL && *pidx == 0)
1246 *pidx = si->idx;
1247 }
1248 return si->idx;
1249 }
1250 break;
1251 }
1252 }
1253
1254 int idx = new_stridx (ptr);
1255 if (idx == 0)
1256 return 0;
1257 si = new_strinfo (ptr, idx, build_int_cst (size_type_node, nonzero_chars),
1258 basesi->full_string_p);
1259 set_strinfo (idx, si);
1260 if (strinfo *nextsi = get_strinfo (chainsi->next))
1261 {
1262 nextsi = unshare_strinfo (nextsi);
1263 si->next = nextsi->idx;
1264 nextsi->prev = idx;
1265 }
1266 chainsi = unshare_strinfo (chainsi);
1267 if (chainsi->first == 0)
1268 chainsi->first = chainsi->idx;
1269 chainsi->next = idx;
1270 if (chainsi->endptr == NULL_TREE && zero_length_string_p (si))
1271 chainsi->endptr = ptr;
1272 si->endptr = chainsi->endptr;
1273 si->prev = chainsi->idx;
1274 si->first = chainsi->first;
1275 si->writable = chainsi->writable;
1276 return si->idx;
1277 }
1278
1279 /* Note that PTR, a pointer SSA_NAME initialized in the current stmt, points
1280 to a zero-length string and if possible chain it to a related strinfo
1281 chain whose part is or might be CHAINSI. */
1282
1283 static strinfo *
1284 zero_length_string (tree ptr, strinfo *chainsi)
1285 {
1286 strinfo *si;
1287 int idx;
1288 if (ssa_ver_to_stridx.length () <= SSA_NAME_VERSION (ptr))
1289 ssa_ver_to_stridx.safe_grow_cleared (num_ssa_names);
1290 gcc_checking_assert (TREE_CODE (ptr) == SSA_NAME
1291 && ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)] == 0);
1292
1293 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ptr))
1294 return NULL;
1295 if (chainsi != NULL)
1296 {
1297 si = verify_related_strinfos (chainsi);
1298 if (si)
1299 {
1300 do
1301 {
1302 /* We shouldn't mix delayed and non-delayed lengths. */
1303 gcc_assert (si->full_string_p);
1304 if (si->endptr == NULL_TREE)
1305 {
1306 si = unshare_strinfo (si);
1307 si->endptr = ptr;
1308 }
1309 chainsi = si;
1310 si = get_next_strinfo (si);
1311 }
1312 while (si != NULL);
1313 if (zero_length_string_p (chainsi))
1314 {
1315 if (chainsi->next)
1316 {
1317 chainsi = unshare_strinfo (chainsi);
1318 chainsi->next = 0;
1319 }
1320 ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)] = chainsi->idx;
1321 return chainsi;
1322 }
1323 }
1324 else
1325 {
1326 /* We shouldn't mix delayed and non-delayed lengths. */
1327 gcc_assert (chainsi->full_string_p);
1328 if (chainsi->first || chainsi->prev || chainsi->next)
1329 {
1330 chainsi = unshare_strinfo (chainsi);
1331 chainsi->first = 0;
1332 chainsi->prev = 0;
1333 chainsi->next = 0;
1334 }
1335 }
1336 }
1337 idx = new_stridx (ptr);
1338 if (idx == 0)
1339 return NULL;
1340 si = new_strinfo (ptr, idx, build_int_cst (size_type_node, 0), true);
1341 set_strinfo (idx, si);
1342 si->endptr = ptr;
1343 if (chainsi != NULL)
1344 {
1345 chainsi = unshare_strinfo (chainsi);
1346 if (chainsi->first == 0)
1347 chainsi->first = chainsi->idx;
1348 chainsi->next = idx;
1349 if (chainsi->endptr == NULL_TREE)
1350 chainsi->endptr = ptr;
1351 si->prev = chainsi->idx;
1352 si->first = chainsi->first;
1353 si->writable = chainsi->writable;
1354 }
1355 return si;
1356 }
1357
1358 /* For strinfo ORIGSI whose length has been just updated, adjust other
1359 related strinfos so that they match the new ORIGSI. This involves:
1360
1361 - adding ADJ to the nonzero_chars fields
1362 - copying full_string_p from the new ORIGSI. */
1363
1364 static void
1365 adjust_related_strinfos (location_t loc, strinfo *origsi, tree adj)
1366 {
1367 strinfo *si = verify_related_strinfos (origsi);
1368
1369 if (si == NULL)
1370 return;
1371
1372 while (1)
1373 {
1374 strinfo *nsi;
1375
1376 if (si != origsi)
1377 {
1378 tree tem;
1379
1380 si = unshare_strinfo (si);
1381 /* We shouldn't see delayed lengths here; the caller must
1382 have calculated the old length in order to calculate
1383 the adjustment. */
1384 gcc_assert (si->nonzero_chars);
1385 tem = fold_convert_loc (loc, TREE_TYPE (si->nonzero_chars), adj);
1386 si->nonzero_chars = fold_build2_loc (loc, PLUS_EXPR,
1387 TREE_TYPE (si->nonzero_chars),
1388 si->nonzero_chars, tem);
1389 si->full_string_p = origsi->full_string_p;
1390
1391 si->endptr = NULL_TREE;
1392 si->dont_invalidate = true;
1393 }
1394 nsi = get_next_strinfo (si);
1395 if (nsi == NULL)
1396 return;
1397 si = nsi;
1398 }
1399 }
1400
1401 /* Find if there are other SSA_NAME pointers equal to PTR
1402 for which we don't track their string lengths yet. If so, use
1403 IDX for them. */
1404
1405 static void
1406 find_equal_ptrs (tree ptr, int idx)
1407 {
1408 if (TREE_CODE (ptr) != SSA_NAME)
1409 return;
1410 while (1)
1411 {
1412 gimple *stmt = SSA_NAME_DEF_STMT (ptr);
1413 if (!is_gimple_assign (stmt))
1414 return;
1415 ptr = gimple_assign_rhs1 (stmt);
1416 switch (gimple_assign_rhs_code (stmt))
1417 {
1418 case SSA_NAME:
1419 break;
1420 CASE_CONVERT:
1421 if (!POINTER_TYPE_P (TREE_TYPE (ptr)))
1422 return;
1423 if (TREE_CODE (ptr) == SSA_NAME)
1424 break;
1425 if (TREE_CODE (ptr) != ADDR_EXPR)
1426 return;
1427 /* FALLTHRU */
1428 case ADDR_EXPR:
1429 {
1430 int *pidx = addr_stridxptr (TREE_OPERAND (ptr, 0));
1431 if (pidx != NULL && *pidx == 0)
1432 *pidx = idx;
1433 return;
1434 }
1435 default:
1436 return;
1437 }
1438
1439 /* We might find an endptr created in this pass. Grow the
1440 vector in that case. */
1441 if (ssa_ver_to_stridx.length () <= SSA_NAME_VERSION (ptr))
1442 ssa_ver_to_stridx.safe_grow_cleared (num_ssa_names);
1443
1444 if (ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)] != 0)
1445 return;
1446 ssa_ver_to_stridx[SSA_NAME_VERSION (ptr)] = idx;
1447 }
1448 }
1449
1450 /* Return true if STMT is a call to a builtin function with the right
1451 arguments and attributes that should be considered for optimization
1452 by this pass. */
1453
1454 static bool
1455 valid_builtin_call (gimple *stmt)
1456 {
1457 if (!gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
1458 return false;
1459
1460 tree callee = gimple_call_fndecl (stmt);
1461 tree decl = builtin_decl_explicit (DECL_FUNCTION_CODE (callee));
1462 if (decl
1463 && decl != callee
1464 && !gimple_builtin_call_types_compatible_p (stmt, decl))
1465 return false;
1466
1467 switch (DECL_FUNCTION_CODE (callee))
1468 {
1469 case BUILT_IN_MEMCMP:
1470 case BUILT_IN_MEMCMP_EQ:
1471 case BUILT_IN_STRCMP:
1472 case BUILT_IN_STRNCMP:
1473 case BUILT_IN_STRCHR:
1474 case BUILT_IN_STRLEN:
1475 case BUILT_IN_STRNLEN:
1476 /* The above functions should be pure. Punt if they aren't. */
1477 if (gimple_vdef (stmt) || gimple_vuse (stmt) == NULL_TREE)
1478 return false;
1479 break;
1480
1481 case BUILT_IN_CALLOC:
1482 case BUILT_IN_MALLOC:
1483 case BUILT_IN_MEMCPY:
1484 case BUILT_IN_MEMCPY_CHK:
1485 case BUILT_IN_MEMPCPY:
1486 case BUILT_IN_MEMPCPY_CHK:
1487 case BUILT_IN_MEMSET:
1488 case BUILT_IN_STPCPY:
1489 case BUILT_IN_STPCPY_CHK:
1490 case BUILT_IN_STPNCPY:
1491 case BUILT_IN_STPNCPY_CHK:
1492 case BUILT_IN_STRCAT:
1493 case BUILT_IN_STRCAT_CHK:
1494 case BUILT_IN_STRCPY:
1495 case BUILT_IN_STRCPY_CHK:
1496 case BUILT_IN_STRNCAT:
1497 case BUILT_IN_STRNCAT_CHK:
1498 case BUILT_IN_STRNCPY:
1499 case BUILT_IN_STRNCPY_CHK:
1500 /* The above functions should be neither const nor pure. Punt if they
1501 aren't. */
1502 if (gimple_vdef (stmt) == NULL_TREE || gimple_vuse (stmt) == NULL_TREE)
1503 return false;
1504 break;
1505
1506 default:
1507 break;
1508 }
1509
1510 return true;
1511 }
1512
1513 /* If the last .MEM setter statement before STMT is
1514 memcpy (x, y, strlen (y) + 1), the only .MEM use of it is STMT
1515 and STMT is known to overwrite x[strlen (x)], adjust the last memcpy to
1516 just memcpy (x, y, strlen (y)). SI must be the zero length
1517 strinfo. */
1518
1519 static void
1520 adjust_last_stmt (strinfo *si, gimple *stmt, bool is_strcat)
1521 {
1522 tree vuse, callee, len;
1523 struct laststmt_struct last = laststmt;
1524 strinfo *lastsi, *firstsi;
1525 unsigned len_arg_no = 2;
1526
1527 laststmt.stmt = NULL;
1528 laststmt.len = NULL_TREE;
1529 laststmt.stridx = 0;
1530
1531 if (last.stmt == NULL)
1532 return;
1533
1534 vuse = gimple_vuse (stmt);
1535 if (vuse == NULL_TREE
1536 || SSA_NAME_DEF_STMT (vuse) != last.stmt
1537 || !has_single_use (vuse))
1538 return;
1539
1540 gcc_assert (last.stridx > 0);
1541 lastsi = get_strinfo (last.stridx);
1542 if (lastsi == NULL)
1543 return;
1544
1545 if (lastsi != si)
1546 {
1547 if (lastsi->first == 0 || lastsi->first != si->first)
1548 return;
1549
1550 firstsi = verify_related_strinfos (si);
1551 if (firstsi == NULL)
1552 return;
1553 while (firstsi != lastsi)
1554 {
1555 firstsi = get_next_strinfo (firstsi);
1556 if (firstsi == NULL)
1557 return;
1558 }
1559 }
1560
1561 if (!is_strcat && !zero_length_string_p (si))
1562 return;
1563
1564 if (is_gimple_assign (last.stmt))
1565 {
1566 gimple_stmt_iterator gsi;
1567
1568 if (!integer_zerop (gimple_assign_rhs1 (last.stmt)))
1569 return;
1570 if (stmt_could_throw_p (cfun, last.stmt))
1571 return;
1572 gsi = gsi_for_stmt (last.stmt);
1573 unlink_stmt_vdef (last.stmt);
1574 release_defs (last.stmt);
1575 gsi_remove (&gsi, true);
1576 return;
1577 }
1578
1579 if (!valid_builtin_call (last.stmt))
1580 return;
1581
1582 callee = gimple_call_fndecl (last.stmt);
1583 switch (DECL_FUNCTION_CODE (callee))
1584 {
1585 case BUILT_IN_MEMCPY:
1586 case BUILT_IN_MEMCPY_CHK:
1587 break;
1588 default:
1589 return;
1590 }
1591
1592 len = gimple_call_arg (last.stmt, len_arg_no);
1593 if (tree_fits_uhwi_p (len))
1594 {
1595 if (!tree_fits_uhwi_p (last.len)
1596 || integer_zerop (len)
1597 || tree_to_uhwi (len) != tree_to_uhwi (last.len) + 1)
1598 return;
1599 /* Don't adjust the length if it is divisible by 4, it is more efficient
1600 to store the extra '\0' in that case. */
1601 if ((tree_to_uhwi (len) & 3) == 0)
1602 return;
1603
1604 /* Don't fold away an out of bounds access, as this defeats proper
1605 warnings. */
1606 tree dst = gimple_call_arg (last.stmt, 0);
1607 tree size = compute_objsize (dst, 0);
1608 if (size && tree_int_cst_lt (size, len))
1609 return;
1610 }
1611 else if (TREE_CODE (len) == SSA_NAME)
1612 {
1613 gimple *def_stmt = SSA_NAME_DEF_STMT (len);
1614 if (!is_gimple_assign (def_stmt)
1615 || gimple_assign_rhs_code (def_stmt) != PLUS_EXPR
1616 || gimple_assign_rhs1 (def_stmt) != last.len
1617 || !integer_onep (gimple_assign_rhs2 (def_stmt)))
1618 return;
1619 }
1620 else
1621 return;
1622
1623 gimple_call_set_arg (last.stmt, len_arg_no, last.len);
1624 update_stmt (last.stmt);
1625 }
1626
1627 /* For an LHS that is an SSA_NAME that is the result of a strlen()
1628 call, or when BOUND is non-null, of a strnlen() call, set LHS
1629 range info to [0, min (MAX, BOUND)] when the range includes more
1630 than one value and return LHS. Otherwise, when the range
1631 [MIN, MAX] is such that MIN == MAX, return the tree representation
1632 of (MIN). The latter allows callers to fold suitable strnlen() calls
1633 to constants. */
1634
1635 tree
1636 set_strlen_range (tree lhs, wide_int min, wide_int max,
1637 tree bound /* = NULL_TREE */)
1638 {
1639 if (TREE_CODE (lhs) != SSA_NAME
1640 || !INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
1641 return NULL_TREE;
1642
1643 if (bound)
1644 {
1645 /* For strnlen, adjust MIN and MAX as necessary. If the bound
1646 is less than the size of the array set MAX to it. It it's
1647 greater than MAX and MAX is non-zero bump MAX down to account
1648 for the necessary terminating nul. Otherwise leave it alone. */
1649 if (TREE_CODE (bound) == INTEGER_CST)
1650 {
1651 wide_int wibnd = wi::to_wide (bound);
1652 int cmp = wi::cmpu (wibnd, max);
1653 if (cmp < 0)
1654 max = wibnd;
1655 else if (cmp && wi::ne_p (max, min))
1656 --max;
1657 }
1658 else if (TREE_CODE (bound) == SSA_NAME)
1659 {
1660 wide_int minbound, maxbound;
1661 value_range_kind rng = get_range_info (bound, &minbound, &maxbound);
1662 if (rng == VR_RANGE)
1663 {
1664 /* For a bound in a known range, adjust the range determined
1665 above as necessary. For a bound in some anti-range or
1666 in an unknown range, use the range determined by callers. */
1667 if (wi::ltu_p (minbound, min))
1668 min = minbound;
1669 if (wi::ltu_p (maxbound, max))
1670 max = maxbound;
1671 }
1672 }
1673 }
1674
1675 if (min == max)
1676 return wide_int_to_tree (size_type_node, min);
1677
1678 set_range_info (lhs, VR_RANGE, min, max);
1679 return lhs;
1680 }
1681
1682 /* For an LHS that is an SSA_NAME and for strlen() or strnlen() argument
1683 SRC, set LHS range info to [0, min (N, BOUND)] if SRC refers to
1684 a character array A[N] with unknown length bounded by N, and for
1685 strnlen(), by min (N, BOUND). */
1686
1687 static tree
1688 maybe_set_strlen_range (tree lhs, tree src, tree bound)
1689 {
1690 if (TREE_CODE (lhs) != SSA_NAME
1691 || !INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
1692 return NULL_TREE;
1693
1694 if (TREE_CODE (src) == SSA_NAME)
1695 {
1696 gimple *def = SSA_NAME_DEF_STMT (src);
1697 if (is_gimple_assign (def)
1698 && gimple_assign_rhs_code (def) == ADDR_EXPR)
1699 src = gimple_assign_rhs1 (def);
1700 }
1701
1702 /* The longest string is PTRDIFF_MAX - 1 bytes including the final
1703 NUL so that the difference between a pointer to just past it and
1704 one to its beginning is positive. */
1705 wide_int max = wi::to_wide (TYPE_MAX_VALUE (ptrdiff_type_node)) - 2;
1706
1707 if (TREE_CODE (src) == ADDR_EXPR)
1708 {
1709 /* The last array member of a struct can be bigger than its size
1710 suggests if it's treated as a poor-man's flexible array member. */
1711 src = TREE_OPERAND (src, 0);
1712 if (TREE_CODE (src) != MEM_REF
1713 && !array_at_struct_end_p (src))
1714 {
1715 tree type = TREE_TYPE (src);
1716 tree size = TYPE_SIZE_UNIT (type);
1717 if (size
1718 && TREE_CODE (size) == INTEGER_CST
1719 && !integer_zerop (size))
1720 {
1721 /* Even though such uses of strlen would be undefined,
1722 avoid relying on arrays of arrays in case some genius
1723 decides to call strlen on an unterminated array element
1724 that's followed by a terminated one. Likewise, avoid
1725 assuming that a struct array member is necessarily
1726 nul-terminated (the nul may be in the member that
1727 follows). In those cases, assume that the length
1728 of the string stored in such an array is bounded
1729 by the size of the enclosing object if one can be
1730 determined. */
1731 tree base = get_base_address (src);
1732 if (VAR_P (base))
1733 {
1734 if (tree size = DECL_SIZE_UNIT (base))
1735 if (size
1736 && TREE_CODE (size) == INTEGER_CST
1737 && TREE_CODE (TREE_TYPE (base)) != POINTER_TYPE)
1738 max = wi::to_wide (size);
1739 }
1740 }
1741
1742 /* For strlen() the upper bound above is equal to
1743 the longest string that can be stored in the array
1744 (i.e., it accounts for the terminating nul. For
1745 strnlen() bump up the maximum by one since the array
1746 need not be nul-terminated. */
1747 if (!bound && max != 0)
1748 --max;
1749 }
1750 }
1751
1752 wide_int min = wi::zero (max.get_precision ());
1753 return set_strlen_range (lhs, min, max, bound);
1754 }
1755
1756 /* Handle a strlen call. If strlen of the argument is known, replace
1757 the strlen call with the known value, otherwise remember that strlen
1758 of the argument is stored in the lhs SSA_NAME. */
1759
1760 static void
1761 handle_builtin_strlen (gimple_stmt_iterator *gsi)
1762 {
1763 gimple *stmt = gsi_stmt (*gsi);
1764 tree lhs = gimple_call_lhs (stmt);
1765
1766 if (lhs == NULL_TREE)
1767 return;
1768
1769 location_t loc = gimple_location (stmt);
1770 tree callee = gimple_call_fndecl (stmt);
1771 tree src = gimple_call_arg (stmt, 0);
1772 tree bound = (DECL_FUNCTION_CODE (callee) == BUILT_IN_STRNLEN
1773 ? gimple_call_arg (stmt, 1) : NULL_TREE);
1774 int idx = get_stridx (src);
1775 if (idx || (bound && integer_zerop (bound)))
1776 {
1777 strinfo *si = NULL;
1778 tree rhs;
1779
1780 if (idx < 0)
1781 rhs = build_int_cst (TREE_TYPE (lhs), ~idx);
1782 else if (idx == 0)
1783 rhs = bound;
1784 else
1785 {
1786 rhs = NULL_TREE;
1787 si = get_strinfo (idx);
1788 if (si != NULL)
1789 {
1790 rhs = get_string_length (si);
1791 /* For strnlen, if bound is constant, even if si is not known
1792 to be zero terminated, if we know at least bound bytes are
1793 not zero, the return value will be bound. */
1794 if (rhs == NULL_TREE
1795 && bound != NULL_TREE
1796 && TREE_CODE (bound) == INTEGER_CST
1797 && si->nonzero_chars != NULL_TREE
1798 && TREE_CODE (si->nonzero_chars) == INTEGER_CST
1799 && tree_int_cst_le (bound, si->nonzero_chars))
1800 rhs = bound;
1801 }
1802 }
1803 if (rhs != NULL_TREE)
1804 {
1805 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
1806 {
1807 fprintf (dump_file, "Optimizing: ");
1808 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1809 }
1810 rhs = unshare_expr (rhs);
1811 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
1812 rhs = fold_convert_loc (loc, TREE_TYPE (lhs), rhs);
1813
1814 if (bound)
1815 rhs = fold_build2_loc (loc, MIN_EXPR, TREE_TYPE (rhs), rhs, bound);
1816
1817 if (!update_call_from_tree (gsi, rhs))
1818 gimplify_and_update_call_from_tree (gsi, rhs);
1819 stmt = gsi_stmt (*gsi);
1820 update_stmt (stmt);
1821 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
1822 {
1823 fprintf (dump_file, "into: ");
1824 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1825 }
1826
1827 if (si != NULL
1828 /* Don't update anything for strnlen. */
1829 && bound == NULL_TREE
1830 && TREE_CODE (si->nonzero_chars) != SSA_NAME
1831 && TREE_CODE (si->nonzero_chars) != INTEGER_CST
1832 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
1833 {
1834 si = unshare_strinfo (si);
1835 si->nonzero_chars = lhs;
1836 gcc_assert (si->full_string_p);
1837 }
1838
1839 if (strlen_to_stridx
1840 && (bound == NULL_TREE
1841 /* For strnlen record this only if the call is proven
1842 to return the same value as strlen would. */
1843 || (TREE_CODE (bound) == INTEGER_CST
1844 && TREE_CODE (rhs) == INTEGER_CST
1845 && tree_int_cst_lt (rhs, bound))))
1846 strlen_to_stridx->put (lhs, stridx_strlenloc (idx, loc));
1847
1848 return;
1849 }
1850 }
1851 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
1852 return;
1853
1854 if (idx == 0)
1855 idx = new_stridx (src);
1856 else
1857 {
1858 strinfo *si = get_strinfo (idx);
1859 if (si != NULL)
1860 {
1861 if (!si->full_string_p && !si->stmt)
1862 {
1863 /* Until now we only had a lower bound on the string length.
1864 Install LHS as the actual length. */
1865 si = unshare_strinfo (si);
1866 tree old = si->nonzero_chars;
1867 si->nonzero_chars = lhs;
1868 si->full_string_p = true;
1869 if (TREE_CODE (old) == INTEGER_CST)
1870 {
1871 old = fold_convert_loc (loc, TREE_TYPE (lhs), old);
1872 tree adj = fold_build2_loc (loc, MINUS_EXPR,
1873 TREE_TYPE (lhs), lhs, old);
1874 adjust_related_strinfos (loc, si, adj);
1875 /* Use the constant minimim length as the lower bound
1876 of the non-constant length. */
1877 wide_int min = wi::to_wide (old);
1878 wide_int max
1879 = wi::to_wide (TYPE_MAX_VALUE (ptrdiff_type_node)) - 2;
1880 set_strlen_range (lhs, min, max);
1881 }
1882 else
1883 {
1884 si->first = 0;
1885 si->prev = 0;
1886 si->next = 0;
1887 }
1888 }
1889 return;
1890 }
1891 }
1892 if (idx)
1893 {
1894 if (!bound)
1895 {
1896 /* Only store the new length information for calls to strlen(),
1897 not for those to strnlen(). */
1898 strinfo *si = new_strinfo (src, idx, lhs, true);
1899 set_strinfo (idx, si);
1900 find_equal_ptrs (src, idx);
1901 }
1902
1903 /* For SRC that is an array of N elements, set LHS's range
1904 to [0, min (N, BOUND)]. A constant return value means
1905 the range would have consisted of a single value. In
1906 that case, fold the result into the returned constant. */
1907 if (tree ret = maybe_set_strlen_range (lhs, src, bound))
1908 if (TREE_CODE (ret) == INTEGER_CST)
1909 {
1910 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
1911 {
1912 fprintf (dump_file, "Optimizing: ");
1913 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1914 }
1915 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (ret)))
1916 ret = fold_convert_loc (loc, TREE_TYPE (lhs), ret);
1917 if (!update_call_from_tree (gsi, ret))
1918 gimplify_and_update_call_from_tree (gsi, ret);
1919 stmt = gsi_stmt (*gsi);
1920 update_stmt (stmt);
1921 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
1922 {
1923 fprintf (dump_file, "into: ");
1924 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1925 }
1926 }
1927
1928 if (strlen_to_stridx && !bound)
1929 strlen_to_stridx->put (lhs, stridx_strlenloc (idx, loc));
1930 }
1931 }
1932
1933 /* Handle a strchr call. If strlen of the first argument is known, replace
1934 the strchr (x, 0) call with the endptr or x + strlen, otherwise remember
1935 that lhs of the call is endptr and strlen of the argument is endptr - x. */
1936
1937 static void
1938 handle_builtin_strchr (gimple_stmt_iterator *gsi)
1939 {
1940 int idx;
1941 tree src;
1942 gimple *stmt = gsi_stmt (*gsi);
1943 tree lhs = gimple_call_lhs (stmt);
1944
1945 if (lhs == NULL_TREE)
1946 return;
1947
1948 if (!integer_zerop (gimple_call_arg (stmt, 1)))
1949 return;
1950
1951 src = gimple_call_arg (stmt, 0);
1952 idx = get_stridx (src);
1953 if (idx)
1954 {
1955 strinfo *si = NULL;
1956 tree rhs;
1957
1958 if (idx < 0)
1959 rhs = build_int_cst (size_type_node, ~idx);
1960 else
1961 {
1962 rhs = NULL_TREE;
1963 si = get_strinfo (idx);
1964 if (si != NULL)
1965 rhs = get_string_length (si);
1966 }
1967 if (rhs != NULL_TREE)
1968 {
1969 location_t loc = gimple_location (stmt);
1970
1971 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
1972 {
1973 fprintf (dump_file, "Optimizing: ");
1974 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1975 }
1976 if (si != NULL && si->endptr != NULL_TREE)
1977 {
1978 rhs = unshare_expr (si->endptr);
1979 if (!useless_type_conversion_p (TREE_TYPE (lhs),
1980 TREE_TYPE (rhs)))
1981 rhs = fold_convert_loc (loc, TREE_TYPE (lhs), rhs);
1982 }
1983 else
1984 {
1985 rhs = fold_convert_loc (loc, sizetype, unshare_expr (rhs));
1986 rhs = fold_build2_loc (loc, POINTER_PLUS_EXPR,
1987 TREE_TYPE (src), src, rhs);
1988 if (!useless_type_conversion_p (TREE_TYPE (lhs),
1989 TREE_TYPE (rhs)))
1990 rhs = fold_convert_loc (loc, TREE_TYPE (lhs), rhs);
1991 }
1992 if (!update_call_from_tree (gsi, rhs))
1993 gimplify_and_update_call_from_tree (gsi, rhs);
1994 stmt = gsi_stmt (*gsi);
1995 update_stmt (stmt);
1996 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
1997 {
1998 fprintf (dump_file, "into: ");
1999 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2000 }
2001 if (si != NULL
2002 && si->endptr == NULL_TREE
2003 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
2004 {
2005 si = unshare_strinfo (si);
2006 si->endptr = lhs;
2007 }
2008 zero_length_string (lhs, si);
2009 return;
2010 }
2011 }
2012 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
2013 return;
2014 if (TREE_CODE (src) != SSA_NAME || !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (src))
2015 {
2016 if (idx == 0)
2017 idx = new_stridx (src);
2018 else if (get_strinfo (idx) != NULL)
2019 {
2020 zero_length_string (lhs, NULL);
2021 return;
2022 }
2023 if (idx)
2024 {
2025 location_t loc = gimple_location (stmt);
2026 tree lhsu = fold_convert_loc (loc, size_type_node, lhs);
2027 tree srcu = fold_convert_loc (loc, size_type_node, src);
2028 tree length = fold_build2_loc (loc, MINUS_EXPR,
2029 size_type_node, lhsu, srcu);
2030 strinfo *si = new_strinfo (src, idx, length, true);
2031 si->endptr = lhs;
2032 set_strinfo (idx, si);
2033 find_equal_ptrs (src, idx);
2034 zero_length_string (lhs, si);
2035 }
2036 }
2037 else
2038 zero_length_string (lhs, NULL);
2039 }
2040
2041 /* Handle a strcpy-like ({st{r,p}cpy,__st{r,p}cpy_chk}) call.
2042 If strlen of the second argument is known, strlen of the first argument
2043 is the same after this call. Furthermore, attempt to convert it to
2044 memcpy. */
2045
2046 static void
2047 handle_builtin_strcpy (enum built_in_function bcode, gimple_stmt_iterator *gsi)
2048 {
2049 int idx, didx;
2050 tree src, dst, srclen, len, lhs, type, fn, oldlen;
2051 bool success;
2052 gimple *stmt = gsi_stmt (*gsi);
2053 strinfo *si, *dsi, *olddsi, *zsi;
2054 location_t loc;
2055
2056 src = gimple_call_arg (stmt, 1);
2057 dst = gimple_call_arg (stmt, 0);
2058 lhs = gimple_call_lhs (stmt);
2059 idx = get_stridx (src);
2060 si = NULL;
2061 if (idx > 0)
2062 si = get_strinfo (idx);
2063
2064 didx = get_stridx (dst);
2065 olddsi = NULL;
2066 oldlen = NULL_TREE;
2067 if (didx > 0)
2068 olddsi = get_strinfo (didx);
2069 else if (didx < 0)
2070 return;
2071
2072 if (olddsi != NULL)
2073 adjust_last_stmt (olddsi, stmt, false);
2074
2075 srclen = NULL_TREE;
2076 if (si != NULL)
2077 srclen = get_string_length (si);
2078 else if (idx < 0)
2079 srclen = build_int_cst (size_type_node, ~idx);
2080
2081 loc = gimple_location (stmt);
2082 if (srclen == NULL_TREE)
2083 switch (bcode)
2084 {
2085 case BUILT_IN_STRCPY:
2086 case BUILT_IN_STRCPY_CHK:
2087 if (lhs != NULL_TREE || !builtin_decl_implicit_p (BUILT_IN_STPCPY))
2088 return;
2089 break;
2090 case BUILT_IN_STPCPY:
2091 case BUILT_IN_STPCPY_CHK:
2092 if (lhs == NULL_TREE)
2093 return;
2094 else
2095 {
2096 tree lhsuint = fold_convert_loc (loc, size_type_node, lhs);
2097 srclen = fold_convert_loc (loc, size_type_node, dst);
2098 srclen = fold_build2_loc (loc, MINUS_EXPR, size_type_node,
2099 lhsuint, srclen);
2100 }
2101 break;
2102 default:
2103 gcc_unreachable ();
2104 }
2105
2106 if (didx == 0)
2107 {
2108 didx = new_stridx (dst);
2109 if (didx == 0)
2110 return;
2111 }
2112 if (olddsi != NULL)
2113 {
2114 oldlen = olddsi->nonzero_chars;
2115 dsi = unshare_strinfo (olddsi);
2116 dsi->nonzero_chars = srclen;
2117 dsi->full_string_p = (srclen != NULL_TREE);
2118 /* Break the chain, so adjust_related_strinfo on later pointers in
2119 the chain won't adjust this one anymore. */
2120 dsi->next = 0;
2121 dsi->stmt = NULL;
2122 dsi->endptr = NULL_TREE;
2123 }
2124 else
2125 {
2126 dsi = new_strinfo (dst, didx, srclen, srclen != NULL_TREE);
2127 set_strinfo (didx, dsi);
2128 find_equal_ptrs (dst, didx);
2129 }
2130 dsi->writable = true;
2131 dsi->dont_invalidate = true;
2132
2133 if (dsi->nonzero_chars == NULL_TREE)
2134 {
2135 strinfo *chainsi;
2136
2137 /* If string length of src is unknown, use delayed length
2138 computation. If string lenth of dst will be needed, it
2139 can be computed by transforming this strcpy call into
2140 stpcpy and subtracting dst from the return value. */
2141
2142 /* Look for earlier strings whose length could be determined if
2143 this strcpy is turned into an stpcpy. */
2144
2145 if (dsi->prev != 0 && (chainsi = verify_related_strinfos (dsi)) != NULL)
2146 {
2147 for (; chainsi && chainsi != dsi; chainsi = get_strinfo (chainsi->next))
2148 {
2149 /* When setting a stmt for delayed length computation
2150 prevent all strinfos through dsi from being
2151 invalidated. */
2152 chainsi = unshare_strinfo (chainsi);
2153 chainsi->stmt = stmt;
2154 chainsi->nonzero_chars = NULL_TREE;
2155 chainsi->full_string_p = false;
2156 chainsi->endptr = NULL_TREE;
2157 chainsi->dont_invalidate = true;
2158 }
2159 }
2160 dsi->stmt = stmt;
2161
2162 /* Try to detect overlap before returning. This catches cases
2163 like strcpy (d, d + n) where n is non-constant whose range
2164 is such that (n <= strlen (d) holds).
2165
2166 OLDDSI->NONZERO_chars may have been reset by this point with
2167 oldlen holding it original value. */
2168 if (olddsi && oldlen)
2169 {
2170 /* Add 1 for the terminating NUL. */
2171 tree type = TREE_TYPE (oldlen);
2172 oldlen = fold_build2 (PLUS_EXPR, type, oldlen,
2173 build_int_cst (type, 1));
2174 check_bounds_or_overlap (stmt, olddsi->ptr, src, oldlen, NULL_TREE);
2175 }
2176
2177 return;
2178 }
2179
2180 if (olddsi != NULL)
2181 {
2182 tree adj = NULL_TREE;
2183 if (oldlen == NULL_TREE)
2184 ;
2185 else if (integer_zerop (oldlen))
2186 adj = srclen;
2187 else if (TREE_CODE (oldlen) == INTEGER_CST
2188 || TREE_CODE (srclen) == INTEGER_CST)
2189 adj = fold_build2_loc (loc, MINUS_EXPR,
2190 TREE_TYPE (srclen), srclen,
2191 fold_convert_loc (loc, TREE_TYPE (srclen),
2192 oldlen));
2193 if (adj != NULL_TREE)
2194 adjust_related_strinfos (loc, dsi, adj);
2195 else
2196 dsi->prev = 0;
2197 }
2198 /* strcpy src may not overlap dst, so src doesn't need to be
2199 invalidated either. */
2200 if (si != NULL)
2201 si->dont_invalidate = true;
2202
2203 fn = NULL_TREE;
2204 zsi = NULL;
2205 switch (bcode)
2206 {
2207 case BUILT_IN_STRCPY:
2208 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
2209 if (lhs)
2210 ssa_ver_to_stridx[SSA_NAME_VERSION (lhs)] = didx;
2211 break;
2212 case BUILT_IN_STRCPY_CHK:
2213 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
2214 if (lhs)
2215 ssa_ver_to_stridx[SSA_NAME_VERSION (lhs)] = didx;
2216 break;
2217 case BUILT_IN_STPCPY:
2218 /* This would need adjustment of the lhs (subtract one),
2219 or detection that the trailing '\0' doesn't need to be
2220 written, if it will be immediately overwritten.
2221 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY); */
2222 if (lhs)
2223 {
2224 dsi->endptr = lhs;
2225 zsi = zero_length_string (lhs, dsi);
2226 }
2227 break;
2228 case BUILT_IN_STPCPY_CHK:
2229 /* This would need adjustment of the lhs (subtract one),
2230 or detection that the trailing '\0' doesn't need to be
2231 written, if it will be immediately overwritten.
2232 fn = builtin_decl_explicit (BUILT_IN_MEMPCPY_CHK); */
2233 if (lhs)
2234 {
2235 dsi->endptr = lhs;
2236 zsi = zero_length_string (lhs, dsi);
2237 }
2238 break;
2239 default:
2240 gcc_unreachable ();
2241 }
2242 if (zsi != NULL)
2243 zsi->dont_invalidate = true;
2244
2245 if (fn)
2246 {
2247 tree args = TYPE_ARG_TYPES (TREE_TYPE (fn));
2248 type = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (args)));
2249 }
2250 else
2251 type = size_type_node;
2252
2253 len = fold_convert_loc (loc, type, unshare_expr (srclen));
2254 len = fold_build2_loc (loc, PLUS_EXPR, type, len, build_int_cst (type, 1));
2255
2256 /* Set the no-warning bit on the transformed statement? */
2257 bool set_no_warning = false;
2258
2259 if (const strinfo *chksi = olddsi ? olddsi : dsi)
2260 if (si
2261 && check_bounds_or_overlap (stmt, chksi->ptr, si->ptr, NULL_TREE, len))
2262 {
2263 gimple_set_no_warning (stmt, true);
2264 set_no_warning = true;
2265 }
2266
2267 if (fn == NULL_TREE)
2268 return;
2269
2270 len = force_gimple_operand_gsi (gsi, len, true, NULL_TREE, true,
2271 GSI_SAME_STMT);
2272 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2273 {
2274 fprintf (dump_file, "Optimizing: ");
2275 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2276 }
2277 if (gimple_call_num_args (stmt) == 2)
2278 success = update_gimple_call (gsi, fn, 3, dst, src, len);
2279 else
2280 success = update_gimple_call (gsi, fn, 4, dst, src, len,
2281 gimple_call_arg (stmt, 2));
2282 if (success)
2283 {
2284 stmt = gsi_stmt (*gsi);
2285 update_stmt (stmt);
2286 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2287 {
2288 fprintf (dump_file, "into: ");
2289 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
2290 }
2291 /* Allow adjust_last_stmt to decrease this memcpy's size. */
2292 laststmt.stmt = stmt;
2293 laststmt.len = srclen;
2294 laststmt.stridx = dsi->idx;
2295 }
2296 else if (dump_file && (dump_flags & TDF_DETAILS) != 0)
2297 fprintf (dump_file, "not possible.\n");
2298
2299 if (set_no_warning)
2300 gimple_set_no_warning (stmt, true);
2301 }
2302
2303 /* Check the size argument to the built-in forms of stpncpy and strncpy
2304 for out-of-bounds offsets or overlapping access, and to see if the
2305 size argument is derived from a call to strlen() on the source argument,
2306 and if so, issue an appropriate warning. */
2307
2308 static void
2309 handle_builtin_strncat (built_in_function bcode, gimple_stmt_iterator *gsi)
2310 {
2311 /* Same as stxncpy(). */
2312 handle_builtin_stxncpy (bcode, gsi);
2313 }
2314
2315 /* Return true if LEN depends on a call to strlen(SRC) in an interesting
2316 way. LEN can either be an integer expression, or a pointer (to char).
2317 When it is the latter (such as in recursive calls to self) is is
2318 assumed to be the argument in some call to strlen() whose relationship
2319 to SRC is being ascertained. */
2320
2321 bool
2322 is_strlen_related_p (tree src, tree len)
2323 {
2324 if (TREE_CODE (TREE_TYPE (len)) == POINTER_TYPE
2325 && operand_equal_p (src, len, 0))
2326 return true;
2327
2328 if (TREE_CODE (len) != SSA_NAME)
2329 return false;
2330
2331 gimple *def_stmt = SSA_NAME_DEF_STMT (len);
2332 if (!def_stmt)
2333 return false;
2334
2335 if (is_gimple_call (def_stmt))
2336 {
2337 tree func = gimple_call_fndecl (def_stmt);
2338 if (!valid_builtin_call (def_stmt)
2339 || DECL_FUNCTION_CODE (func) != BUILT_IN_STRLEN)
2340 return false;
2341
2342 tree arg = gimple_call_arg (def_stmt, 0);
2343 return is_strlen_related_p (src, arg);
2344 }
2345
2346 if (!is_gimple_assign (def_stmt))
2347 return false;
2348
2349 tree_code code = gimple_assign_rhs_code (def_stmt);
2350 tree rhs1 = gimple_assign_rhs1 (def_stmt);
2351 tree rhstype = TREE_TYPE (rhs1);
2352
2353 if ((TREE_CODE (rhstype) == POINTER_TYPE && code == POINTER_PLUS_EXPR)
2354 || (INTEGRAL_TYPE_P (rhstype)
2355 && (code == BIT_AND_EXPR
2356 || code == NOP_EXPR)))
2357 {
2358 /* Pointer plus (an integer), and truncation are considered among
2359 the (potentially) related expressions to strlen. */
2360 return is_strlen_related_p (src, rhs1);
2361 }
2362
2363 if (tree rhs2 = gimple_assign_rhs2 (def_stmt))
2364 {
2365 /* Integer subtraction is considered strlen-related when both
2366 arguments are integers and second one is strlen-related. */
2367 rhstype = TREE_TYPE (rhs2);
2368 if (INTEGRAL_TYPE_P (rhstype) && code == MINUS_EXPR)
2369 return is_strlen_related_p (src, rhs2);
2370 }
2371
2372 return false;
2373 }
2374
2375 /* Called by handle_builtin_stxncpy and by gimple_fold_builtin_strncpy
2376 in gimple-fold.c.
2377 Check to see if the specified bound is a) equal to the size of
2378 the destination DST and if so, b) if it's immediately followed by
2379 DST[CNT - 1] = '\0'. If a) holds and b) does not, warn. Otherwise,
2380 do nothing. Return true if diagnostic has been issued.
2381
2382 The purpose is to diagnose calls to strncpy and stpncpy that do
2383 not nul-terminate the copy while allowing for the idiom where
2384 such a call is immediately followed by setting the last element
2385 to nul, as in:
2386 char a[32];
2387 strncpy (a, s, sizeof a);
2388 a[sizeof a - 1] = '\0';
2389 */
2390
2391 bool
2392 maybe_diag_stxncpy_trunc (gimple_stmt_iterator gsi, tree src, tree cnt)
2393 {
2394 gimple *stmt = gsi_stmt (gsi);
2395 if (gimple_no_warning_p (stmt))
2396 return false;
2397
2398 wide_int cntrange[2];
2399
2400 if (TREE_CODE (cnt) == INTEGER_CST)
2401 cntrange[0] = cntrange[1] = wi::to_wide (cnt);
2402 else if (TREE_CODE (cnt) == SSA_NAME)
2403 {
2404 enum value_range_kind rng = get_range_info (cnt, cntrange, cntrange + 1);
2405 if (rng == VR_RANGE)
2406 ;
2407 else if (rng == VR_ANTI_RANGE)
2408 {
2409 wide_int maxobjsize = wi::to_wide (TYPE_MAX_VALUE (ptrdiff_type_node));
2410
2411 if (wi::ltu_p (cntrange[1], maxobjsize))
2412 {
2413 cntrange[0] = cntrange[1] + 1;
2414 cntrange[1] = maxobjsize;
2415 }
2416 else
2417 {
2418 cntrange[1] = cntrange[0] - 1;
2419 cntrange[0] = wi::zero (TYPE_PRECISION (TREE_TYPE (cnt)));
2420 }
2421 }
2422 else
2423 return false;
2424 }
2425 else
2426 return false;
2427
2428 /* Negative value is the constant string length. If it's less than
2429 the lower bound there is no truncation. Avoid calling get_stridx()
2430 when ssa_ver_to_stridx is empty. That implies the caller isn't
2431 running under the control of this pass and ssa_ver_to_stridx hasn't
2432 been created yet. */
2433 int sidx = ssa_ver_to_stridx.length () ? get_stridx (src) : 0;
2434 if (sidx < 0 && wi::gtu_p (cntrange[0], ~sidx))
2435 return false;
2436
2437 tree dst = gimple_call_arg (stmt, 0);
2438 tree dstdecl = dst;
2439 if (TREE_CODE (dstdecl) == ADDR_EXPR)
2440 dstdecl = TREE_OPERAND (dstdecl, 0);
2441
2442 tree ref = NULL_TREE;
2443
2444 if (!sidx)
2445 {
2446 /* If the source is a non-string return early to avoid warning
2447 for possible truncation (if the truncation is certain SIDX
2448 is non-zero). */
2449 tree srcdecl = gimple_call_arg (stmt, 1);
2450 if (TREE_CODE (srcdecl) == ADDR_EXPR)
2451 srcdecl = TREE_OPERAND (srcdecl, 0);
2452 if (get_attr_nonstring_decl (srcdecl, &ref))
2453 return false;
2454 }
2455
2456 /* Likewise, if the destination refers to a an array/pointer declared
2457 nonstring return early. */
2458 if (get_attr_nonstring_decl (dstdecl, &ref))
2459 return false;
2460
2461 /* Look for dst[i] = '\0'; after the stxncpy() call and if found
2462 avoid the truncation warning. */
2463 gsi_next_nondebug (&gsi);
2464 gimple *next_stmt = gsi_stmt (gsi);
2465 if (!next_stmt)
2466 {
2467 /* When there is no statement in the same basic block check
2468 the immediate successor block. */
2469 if (basic_block bb = gimple_bb (stmt))
2470 {
2471 if (single_succ_p (bb))
2472 {
2473 /* For simplicity, ignore blocks with multiple outgoing
2474 edges for now and only consider successor blocks along
2475 normal edges. */
2476 edge e = EDGE_SUCC (bb, 0);
2477 if (!(e->flags & EDGE_ABNORMAL))
2478 {
2479 gsi = gsi_start_bb (e->dest);
2480 next_stmt = gsi_stmt (gsi);
2481 if (next_stmt && is_gimple_debug (next_stmt))
2482 {
2483 gsi_next_nondebug (&gsi);
2484 next_stmt = gsi_stmt (gsi);
2485 }
2486 }
2487 }
2488 }
2489 }
2490
2491 if (next_stmt && is_gimple_assign (next_stmt))
2492 {
2493 tree lhs = gimple_assign_lhs (next_stmt);
2494 tree_code code = TREE_CODE (lhs);
2495 if (code == ARRAY_REF || code == MEM_REF)
2496 lhs = TREE_OPERAND (lhs, 0);
2497
2498 tree func = gimple_call_fndecl (stmt);
2499 if (DECL_FUNCTION_CODE (func) == BUILT_IN_STPNCPY)
2500 {
2501 tree ret = gimple_call_lhs (stmt);
2502 if (ret && operand_equal_p (ret, lhs, 0))
2503 return false;
2504 }
2505
2506 /* Determine the base address and offset of the reference,
2507 ignoring the innermost array index. */
2508 if (TREE_CODE (ref) == ARRAY_REF)
2509 ref = TREE_OPERAND (ref, 0);
2510
2511 poly_int64 dstoff;
2512 tree dstbase = get_addr_base_and_unit_offset (ref, &dstoff);
2513
2514 poly_int64 lhsoff;
2515 tree lhsbase = get_addr_base_and_unit_offset (lhs, &lhsoff);
2516 if (lhsbase
2517 && dstbase
2518 && known_eq (dstoff, lhsoff)
2519 && operand_equal_p (dstbase, lhsbase, 0))
2520 return false;
2521 }
2522
2523 int prec = TYPE_PRECISION (TREE_TYPE (cnt));
2524 wide_int lenrange[2];
2525 if (strinfo *sisrc = sidx > 0 ? get_strinfo (sidx) : NULL)
2526 {
2527 lenrange[0] = (sisrc->nonzero_chars
2528 && TREE_CODE (sisrc->nonzero_chars) == INTEGER_CST
2529 ? wi::to_wide (sisrc->nonzero_chars)
2530 : wi::zero (prec));
2531 lenrange[1] = lenrange[0];
2532 }
2533 else if (sidx < 0)
2534 lenrange[0] = lenrange[1] = wi::shwi (~sidx, prec);
2535 else
2536 {
2537 c_strlen_data lendata = { };
2538 /* Set MAXBOUND to an arbitrary non-null non-integer node as a request
2539 to have it set to the length of the longest string in a PHI. */
2540 lendata.maxbound = src;
2541 get_range_strlen (src, &lendata, /* eltsize = */1);
2542 if (TREE_CODE (lendata.minlen) == INTEGER_CST
2543 && TREE_CODE (lendata.maxbound) == INTEGER_CST)
2544 {
2545 /* When LENDATA.MAXLEN is unknown, reset LENDATA.MINLEN
2546 which stores the length of the shortest known string. */
2547 if (integer_all_onesp (lendata.maxlen))
2548 lenrange[0] = wi::shwi (0, prec);
2549 else
2550 lenrange[0] = wi::to_wide (lendata.minlen, prec);
2551 lenrange[1] = wi::to_wide (lendata.maxbound, prec);
2552 }
2553 else
2554 {
2555 lenrange[0] = wi::shwi (0, prec);
2556 lenrange[1] = wi::shwi (-1, prec);
2557 }
2558 }
2559
2560 location_t callloc = gimple_nonartificial_location (stmt);
2561 callloc = expansion_point_location_if_in_system_header (callloc);
2562
2563 tree func = gimple_call_fndecl (stmt);
2564
2565 if (lenrange[0] != 0 || !wi::neg_p (lenrange[1]))
2566 {
2567 /* If the longest source string is shorter than the lower bound
2568 of the specified count the copy is definitely nul-terminated. */
2569 if (wi::ltu_p (lenrange[1], cntrange[0]))
2570 return false;
2571
2572 if (wi::neg_p (lenrange[1]))
2573 {
2574 /* The length of one of the strings is unknown but at least
2575 one has non-zero length and that length is stored in
2576 LENRANGE[1]. Swap the bounds to force a "may be truncated"
2577 warning below. */
2578 lenrange[1] = lenrange[0];
2579 lenrange[0] = wi::shwi (0, prec);
2580 }
2581
2582 /* Set to true for strncat whose bound is derived from the length
2583 of the destination (the expected usage pattern). */
2584 bool cat_dstlen_bounded = false;
2585 if (DECL_FUNCTION_CODE (func) == BUILT_IN_STRNCAT)
2586 cat_dstlen_bounded = is_strlen_related_p (dst, cnt);
2587
2588 if (lenrange[0] == cntrange[1] && cntrange[0] == cntrange[1])
2589 return warning_n (callloc, OPT_Wstringop_truncation,
2590 cntrange[0].to_uhwi (),
2591 "%G%qD output truncated before terminating "
2592 "nul copying %E byte from a string of the "
2593 "same length",
2594 "%G%qD output truncated before terminating nul "
2595 "copying %E bytes from a string of the same "
2596 "length",
2597 stmt, func, cnt);
2598 else if (!cat_dstlen_bounded)
2599 {
2600 if (wi::geu_p (lenrange[0], cntrange[1]))
2601 {
2602 /* The shortest string is longer than the upper bound of
2603 the count so the truncation is certain. */
2604 if (cntrange[0] == cntrange[1])
2605 return warning_n (callloc, OPT_Wstringop_truncation,
2606 cntrange[0].to_uhwi (),
2607 "%G%qD output truncated copying %E byte "
2608 "from a string of length %wu",
2609 "%G%qD output truncated copying %E bytes "
2610 "from a string of length %wu",
2611 stmt, func, cnt, lenrange[0].to_uhwi ());
2612
2613 return warning_at (callloc, OPT_Wstringop_truncation,
2614 "%G%qD output truncated copying between %wu "
2615 "and %wu bytes from a string of length %wu",
2616 stmt, func, cntrange[0].to_uhwi (),
2617 cntrange[1].to_uhwi (), lenrange[0].to_uhwi ());
2618 }
2619 else if (wi::geu_p (lenrange[1], cntrange[1]))
2620 {
2621 /* The longest string is longer than the upper bound of
2622 the count so the truncation is possible. */
2623 if (cntrange[0] == cntrange[1])
2624 return warning_n (callloc, OPT_Wstringop_truncation,
2625 cntrange[0].to_uhwi (),
2626 "%G%qD output may be truncated copying %E "
2627 "byte from a string of length %wu",
2628 "%G%qD output may be truncated copying %E "
2629 "bytes from a string of length %wu",
2630 stmt, func, cnt, lenrange[1].to_uhwi ());
2631
2632 return warning_at (callloc, OPT_Wstringop_truncation,
2633 "%G%qD output may be truncated copying between "
2634 "%wu and %wu bytes from a string of length %wu",
2635 stmt, func, cntrange[0].to_uhwi (),
2636 cntrange[1].to_uhwi (), lenrange[1].to_uhwi ());
2637 }
2638 }
2639
2640 if (!cat_dstlen_bounded
2641 && cntrange[0] != cntrange[1]
2642 && wi::leu_p (cntrange[0], lenrange[0])
2643 && wi::leu_p (cntrange[1], lenrange[0] + 1))
2644 {
2645 /* If the source (including the terminating nul) is longer than
2646 the lower bound of the specified count but shorter than the
2647 upper bound the copy may (but need not) be truncated. */
2648 return warning_at (callloc, OPT_Wstringop_truncation,
2649 "%G%qD output may be truncated copying between "
2650 "%wu and %wu bytes from a string of length %wu",
2651 stmt, func, cntrange[0].to_uhwi (),
2652 cntrange[1].to_uhwi (), lenrange[0].to_uhwi ());
2653 }
2654 }
2655
2656 if (tree dstsize = compute_objsize (dst, 1))
2657 {
2658 /* The source length is uknown. Try to determine the destination
2659 size and see if it matches the specified bound. If not, bail.
2660 Otherwise go on to see if it should be diagnosed for possible
2661 truncation. */
2662 if (!dstsize)
2663 return false;
2664
2665 if (wi::to_wide (dstsize) != cntrange[1])
2666 return false;
2667
2668 /* Avoid warning for strncpy(a, b, N) calls where the following
2669 equalities hold:
2670 N == sizeof a && N == sizeof b */
2671 if (tree srcsize = compute_objsize (src, 1))
2672 if (wi::to_wide (srcsize) == cntrange[1])
2673 return false;
2674
2675 if (cntrange[0] == cntrange[1])
2676 return warning_at (callloc, OPT_Wstringop_truncation,
2677 "%G%qD specified bound %E equals destination size",
2678 stmt, func, cnt);
2679 }
2680
2681 return false;
2682 }
2683
2684 /* Check the arguments to the built-in forms of stpncpy and strncpy for
2685 out-of-bounds offsets or overlapping access, and to see if the size
2686 is derived from calling strlen() on the source argument, and if so,
2687 issue the appropriate warning. */
2688
2689 static void
2690 handle_builtin_stxncpy (built_in_function, gimple_stmt_iterator *gsi)
2691 {
2692 if (!strlen_to_stridx)
2693 return;
2694
2695 gimple *stmt = gsi_stmt (*gsi);
2696
2697 tree dst = gimple_call_arg (stmt, 0);
2698 tree src = gimple_call_arg (stmt, 1);
2699 tree len = gimple_call_arg (stmt, 2);
2700 tree dstsize = NULL_TREE, srcsize = NULL_TREE;
2701
2702 int didx = get_stridx (dst);
2703 if (strinfo *sidst = didx > 0 ? get_strinfo (didx) : NULL)
2704 {
2705 /* Compute the size of the destination string including the nul
2706 if it is known to be nul-terminated. */
2707 if (sidst->nonzero_chars)
2708 {
2709 if (sidst->full_string_p)
2710 {
2711 /* String is known to be nul-terminated. */
2712 tree type = TREE_TYPE (sidst->nonzero_chars);
2713 dstsize = fold_build2 (PLUS_EXPR, type, sidst->nonzero_chars,
2714 build_int_cst (type, 1));
2715 }
2716 else
2717 dstsize = sidst->nonzero_chars;
2718 }
2719
2720 dst = sidst->ptr;
2721 }
2722
2723 int sidx = get_stridx (src);
2724 strinfo *sisrc = sidx > 0 ? get_strinfo (sidx) : NULL;
2725 if (sisrc)
2726 {
2727 /* strncat() and strncpy() can modify the source string by writing
2728 over the terminating nul so SISRC->DONT_INVALIDATE must be left
2729 clear. */
2730
2731 /* Compute the size of the source string including the terminating
2732 nul if its known to be nul-terminated. */
2733 if (sisrc->nonzero_chars)
2734 {
2735 if (sisrc->full_string_p)
2736 {
2737 tree type = TREE_TYPE (sisrc->nonzero_chars);
2738 srcsize = fold_build2 (PLUS_EXPR, type, sisrc->nonzero_chars,
2739 build_int_cst (type, 1));
2740 }
2741 else
2742 srcsize = sisrc->nonzero_chars;
2743 }
2744
2745 src = sisrc->ptr;
2746 }
2747 else
2748 srcsize = NULL_TREE;
2749
2750 if (check_bounds_or_overlap (stmt, dst, src, dstsize, srcsize))
2751 {
2752 gimple_set_no_warning (stmt, true);
2753 return;
2754 }
2755
2756 /* If the length argument was computed from strlen(S) for some string
2757 S retrieve the strinfo index for the string (PSS->FIRST) alonng with
2758 the location of the strlen() call (PSS->SECOND). */
2759 stridx_strlenloc *pss = strlen_to_stridx->get (len);
2760 if (!pss || pss->first <= 0)
2761 {
2762 if (maybe_diag_stxncpy_trunc (*gsi, src, len))
2763 gimple_set_no_warning (stmt, true);
2764
2765 return;
2766 }
2767
2768 /* Retrieve the strinfo data for the string S that LEN was computed
2769 from as some function F of strlen (S) (i.e., LEN need not be equal
2770 to strlen(S)). */
2771 strinfo *silen = get_strinfo (pss->first);
2772
2773 location_t callloc = gimple_nonartificial_location (stmt);
2774 callloc = expansion_point_location_if_in_system_header (callloc);
2775
2776 tree func = gimple_call_fndecl (stmt);
2777
2778 bool warned = false;
2779
2780 /* When -Wstringop-truncation is set, try to determine truncation
2781 before diagnosing possible overflow. Truncation is implied by
2782 the LEN argument being equal to strlen(SRC), regardless of
2783 whether its value is known. Otherwise, issue the more generic
2784 -Wstringop-overflow which triggers for LEN arguments that in
2785 any meaningful way depend on strlen(SRC). */
2786 if (sisrc == silen
2787 && is_strlen_related_p (src, len)
2788 && warning_at (callloc, OPT_Wstringop_truncation,
2789 "%G%qD output truncated before terminating nul "
2790 "copying as many bytes from a string as its length",
2791 stmt, func))
2792 warned = true;
2793 else if (silen && is_strlen_related_p (src, silen->ptr))
2794 warned = warning_at (callloc, OPT_Wstringop_overflow_,
2795 "%G%qD specified bound depends on the length "
2796 "of the source argument",
2797 stmt, func);
2798 if (warned)
2799 {
2800 location_t strlenloc = pss->second;
2801 if (strlenloc != UNKNOWN_LOCATION && strlenloc != callloc)
2802 inform (strlenloc, "length computed here");
2803 }
2804 }
2805
2806 /* Handle a memcpy-like ({mem{,p}cpy,__mem{,p}cpy_chk}) call.
2807 If strlen of the second argument is known and length of the third argument
2808 is that plus one, strlen of the first argument is the same after this
2809 call. */
2810
2811 static void
2812 handle_builtin_memcpy (enum built_in_function bcode, gimple_stmt_iterator *gsi)
2813 {
2814 int idx, didx;
2815 tree src, dst, len, lhs, oldlen, newlen;
2816 gimple *stmt = gsi_stmt (*gsi);
2817 strinfo *si, *dsi, *olddsi;
2818
2819 len = gimple_call_arg (stmt, 2);
2820 src = gimple_call_arg (stmt, 1);
2821 dst = gimple_call_arg (stmt, 0);
2822 idx = get_stridx (src);
2823 if (idx == 0)
2824 return;
2825
2826 didx = get_stridx (dst);
2827 olddsi = NULL;
2828 if (didx > 0)
2829 olddsi = get_strinfo (didx);
2830 else if (didx < 0)
2831 return;
2832
2833 if (olddsi != NULL
2834 && tree_fits_uhwi_p (len)
2835 && !integer_zerop (len))
2836 adjust_last_stmt (olddsi, stmt, false);
2837
2838 bool full_string_p;
2839 if (idx > 0)
2840 {
2841 gimple *def_stmt;
2842
2843 /* Handle memcpy (x, y, l) where l's relationship with strlen (y)
2844 is known. */
2845 si = get_strinfo (idx);
2846 if (si == NULL || si->nonzero_chars == NULL_TREE)
2847 return;
2848 if (TREE_CODE (len) == INTEGER_CST
2849 && TREE_CODE (si->nonzero_chars) == INTEGER_CST)
2850 {
2851 if (tree_int_cst_le (len, si->nonzero_chars))
2852 {
2853 /* Copying LEN nonzero characters, where LEN is constant. */
2854 newlen = len;
2855 full_string_p = false;
2856 }
2857 else
2858 {
2859 /* Copying the whole of the analyzed part of SI. */
2860 newlen = si->nonzero_chars;
2861 full_string_p = si->full_string_p;
2862 }
2863 }
2864 else
2865 {
2866 if (!si->full_string_p)
2867 return;
2868 if (TREE_CODE (len) != SSA_NAME)
2869 return;
2870 def_stmt = SSA_NAME_DEF_STMT (len);
2871 if (!is_gimple_assign (def_stmt)
2872 || gimple_assign_rhs_code (def_stmt) != PLUS_EXPR
2873 || gimple_assign_rhs1 (def_stmt) != si->nonzero_chars
2874 || !integer_onep (gimple_assign_rhs2 (def_stmt)))
2875 return;
2876 /* Copying variable-length string SI (and no more). */
2877 newlen = si->nonzero_chars;
2878 full_string_p = true;
2879 }
2880 }
2881 else
2882 {
2883 si = NULL;
2884 /* Handle memcpy (x, "abcd", 5) or
2885 memcpy (x, "abc\0uvw", 7). */
2886 if (!tree_fits_uhwi_p (len))
2887 return;
2888
2889 unsigned HOST_WIDE_INT clen = tree_to_uhwi (len);
2890 unsigned HOST_WIDE_INT nonzero_chars = ~idx;
2891 newlen = build_int_cst (size_type_node, MIN (nonzero_chars, clen));
2892 full_string_p = clen > nonzero_chars;
2893 }
2894
2895 if (!full_string_p
2896 && olddsi
2897 && olddsi->nonzero_chars
2898 && TREE_CODE (olddsi->nonzero_chars) == INTEGER_CST
2899 && tree_int_cst_le (newlen, olddsi->nonzero_chars))
2900 {
2901 /* The SRC substring being written strictly overlaps
2902 a subsequence of the existing string OLDDSI. */
2903 newlen = olddsi->nonzero_chars;
2904 full_string_p = olddsi->full_string_p;
2905 }
2906
2907 if (olddsi != NULL && TREE_CODE (len) == SSA_NAME)
2908 adjust_last_stmt (olddsi, stmt, false);
2909
2910 if (didx == 0)
2911 {
2912 didx = new_stridx (dst);
2913 if (didx == 0)
2914 return;
2915 }
2916 oldlen = NULL_TREE;
2917 if (olddsi != NULL)
2918 {
2919 dsi = unshare_strinfo (olddsi);
2920 oldlen = olddsi->nonzero_chars;
2921 dsi->nonzero_chars = newlen;
2922 dsi->full_string_p = full_string_p;
2923 /* Break the chain, so adjust_related_strinfo on later pointers in
2924 the chain won't adjust this one anymore. */
2925 dsi->next = 0;
2926 dsi->stmt = NULL;
2927 dsi->endptr = NULL_TREE;
2928 }
2929 else
2930 {
2931 dsi = new_strinfo (dst, didx, newlen, full_string_p);
2932 set_strinfo (didx, dsi);
2933 find_equal_ptrs (dst, didx);
2934 }
2935 dsi->writable = true;
2936 dsi->dont_invalidate = true;
2937 if (olddsi != NULL)
2938 {
2939 tree adj = NULL_TREE;
2940 location_t loc = gimple_location (stmt);
2941 if (oldlen == NULL_TREE)
2942 ;
2943 else if (integer_zerop (oldlen))
2944 adj = newlen;
2945 else if (TREE_CODE (oldlen) == INTEGER_CST
2946 || TREE_CODE (newlen) == INTEGER_CST)
2947 adj = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (newlen), newlen,
2948 fold_convert_loc (loc, TREE_TYPE (newlen),
2949 oldlen));
2950 if (adj != NULL_TREE)
2951 adjust_related_strinfos (loc, dsi, adj);
2952 else
2953 dsi->prev = 0;
2954 }
2955 /* memcpy src may not overlap dst, so src doesn't need to be
2956 invalidated either. */
2957 if (si != NULL)
2958 si->dont_invalidate = true;
2959
2960 if (full_string_p)
2961 {
2962 lhs = gimple_call_lhs (stmt);
2963 switch (bcode)
2964 {
2965 case BUILT_IN_MEMCPY:
2966 case BUILT_IN_MEMCPY_CHK:
2967 /* Allow adjust_last_stmt to decrease this memcpy's size. */
2968 laststmt.stmt = stmt;
2969 laststmt.len = dsi->nonzero_chars;
2970 laststmt.stridx = dsi->idx;
2971 if (lhs)
2972 ssa_ver_to_stridx[SSA_NAME_VERSION (lhs)] = didx;
2973 break;
2974 case BUILT_IN_MEMPCPY:
2975 case BUILT_IN_MEMPCPY_CHK:
2976 break;
2977 default:
2978 gcc_unreachable ();
2979 }
2980 }
2981 }
2982
2983 /* Handle a strcat-like ({strcat,__strcat_chk}) call.
2984 If strlen of the second argument is known, strlen of the first argument
2985 is increased by the length of the second argument. Furthermore, attempt
2986 to convert it to memcpy/strcpy if the length of the first argument
2987 is known. */
2988
2989 static void
2990 handle_builtin_strcat (enum built_in_function bcode, gimple_stmt_iterator *gsi)
2991 {
2992 int idx, didx;
2993 tree srclen, args, type, fn, objsz, endptr;
2994 bool success;
2995 gimple *stmt = gsi_stmt (*gsi);
2996 strinfo *si, *dsi;
2997 location_t loc = gimple_location (stmt);
2998
2999 tree src = gimple_call_arg (stmt, 1);
3000 tree dst = gimple_call_arg (stmt, 0);
3001
3002 /* Bail if the source is the same as destination. It will be diagnosed
3003 elsewhere. */
3004 if (operand_equal_p (src, dst, 0))
3005 return;
3006
3007 tree lhs = gimple_call_lhs (stmt);
3008
3009 didx = get_stridx (dst);
3010 if (didx < 0)
3011 return;
3012
3013 dsi = NULL;
3014 if (didx > 0)
3015 dsi = get_strinfo (didx);
3016
3017 srclen = NULL_TREE;
3018 si = NULL;
3019 idx = get_stridx (src);
3020 if (idx < 0)
3021 srclen = build_int_cst (size_type_node, ~idx);
3022 else if (idx > 0)
3023 {
3024 si = get_strinfo (idx);
3025 if (si != NULL)
3026 srclen = get_string_length (si);
3027 }
3028
3029 /* Set the no-warning bit on the transformed statement? */
3030 bool set_no_warning = false;
3031
3032 if (dsi == NULL || get_string_length (dsi) == NULL_TREE)
3033 {
3034 {
3035 /* The concatenation always involves copying at least one byte
3036 (the terminating nul), even if the source string is empty.
3037 If the source is unknown assume it's one character long and
3038 used that as both sizes. */
3039 tree slen = srclen;
3040 if (slen)
3041 {
3042 tree type = TREE_TYPE (slen);
3043 slen = fold_build2 (PLUS_EXPR, type, slen, build_int_cst (type, 1));
3044 }
3045
3046 tree sptr = si && si->ptr ? si->ptr : src;
3047
3048 if (check_bounds_or_overlap (stmt, dst, sptr, NULL_TREE, slen))
3049 {
3050 gimple_set_no_warning (stmt, true);
3051 set_no_warning = true;
3052 }
3053 }
3054
3055 /* strcat (p, q) can be transformed into
3056 tmp = p + strlen (p); endptr = stpcpy (tmp, q);
3057 with length endptr - p if we need to compute the length
3058 later on. Don't do this transformation if we don't need
3059 it. */
3060 if (builtin_decl_implicit_p (BUILT_IN_STPCPY) && lhs == NULL_TREE)
3061 {
3062 if (didx == 0)
3063 {
3064 didx = new_stridx (dst);
3065 if (didx == 0)
3066 return;
3067 }
3068 if (dsi == NULL)
3069 {
3070 dsi = new_strinfo (dst, didx, NULL_TREE, false);
3071 set_strinfo (didx, dsi);
3072 find_equal_ptrs (dst, didx);
3073 }
3074 else
3075 {
3076 dsi = unshare_strinfo (dsi);
3077 dsi->nonzero_chars = NULL_TREE;
3078 dsi->full_string_p = false;
3079 dsi->next = 0;
3080 dsi->endptr = NULL_TREE;
3081 }
3082 dsi->writable = true;
3083 dsi->stmt = stmt;
3084 dsi->dont_invalidate = true;
3085 }
3086 return;
3087 }
3088
3089 tree dstlen = dsi->nonzero_chars;
3090 endptr = dsi->endptr;
3091
3092 dsi = unshare_strinfo (dsi);
3093 dsi->endptr = NULL_TREE;
3094 dsi->stmt = NULL;
3095 dsi->writable = true;
3096
3097 if (srclen != NULL_TREE)
3098 {
3099 dsi->nonzero_chars = fold_build2_loc (loc, PLUS_EXPR,
3100 TREE_TYPE (dsi->nonzero_chars),
3101 dsi->nonzero_chars, srclen);
3102 gcc_assert (dsi->full_string_p);
3103 adjust_related_strinfos (loc, dsi, srclen);
3104 dsi->dont_invalidate = true;
3105 }
3106 else
3107 {
3108 dsi->nonzero_chars = NULL;
3109 dsi->full_string_p = false;
3110 if (lhs == NULL_TREE && builtin_decl_implicit_p (BUILT_IN_STPCPY))
3111 dsi->dont_invalidate = true;
3112 }
3113
3114 if (si != NULL)
3115 /* strcat src may not overlap dst, so src doesn't need to be
3116 invalidated either. */
3117 si->dont_invalidate = true;
3118
3119 /* For now. Could remove the lhs from the call and add
3120 lhs = dst; afterwards. */
3121 if (lhs)
3122 return;
3123
3124 fn = NULL_TREE;
3125 objsz = NULL_TREE;
3126 switch (bcode)
3127 {
3128 case BUILT_IN_STRCAT:
3129 if (srclen != NULL_TREE)
3130 fn = builtin_decl_implicit (BUILT_IN_MEMCPY);
3131 else
3132 fn = builtin_decl_implicit (BUILT_IN_STRCPY);
3133 break;
3134 case BUILT_IN_STRCAT_CHK:
3135 if (srclen != NULL_TREE)
3136 fn = builtin_decl_explicit (BUILT_IN_MEMCPY_CHK);
3137 else
3138 fn = builtin_decl_explicit (BUILT_IN_STRCPY_CHK);
3139 objsz = gimple_call_arg (stmt, 2);
3140 break;
3141 default:
3142 gcc_unreachable ();
3143 }
3144
3145 if (fn == NULL_TREE)
3146 return;
3147
3148 if (dsi && dstlen)
3149 {
3150 tree type = TREE_TYPE (dstlen);
3151
3152 /* Compute the size of the source sequence, including the nul. */
3153 tree srcsize = srclen ? srclen : size_zero_node;
3154 tree one = build_int_cst (type, 1);
3155 srcsize = fold_build2 (PLUS_EXPR, type, srcsize, one);
3156 tree dstsize = fold_build2 (PLUS_EXPR, type, dstlen, one);
3157 tree sptr = si && si->ptr ? si->ptr : src;
3158
3159 if (check_bounds_or_overlap (stmt, dst, sptr, dstsize, srcsize))
3160 {
3161 gimple_set_no_warning (stmt, true);
3162 set_no_warning = true;
3163 }
3164 }
3165
3166 tree len = NULL_TREE;
3167 if (srclen != NULL_TREE)
3168 {
3169 args = TYPE_ARG_TYPES (TREE_TYPE (fn));
3170 type = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (args)));
3171
3172 len = fold_convert_loc (loc, type, unshare_expr (srclen));
3173 len = fold_build2_loc (loc, PLUS_EXPR, type, len,
3174 build_int_cst (type, 1));
3175 len = force_gimple_operand_gsi (gsi, len, true, NULL_TREE, true,
3176 GSI_SAME_STMT);
3177 }
3178 if (endptr)
3179 dst = fold_convert_loc (loc, TREE_TYPE (dst), unshare_expr (endptr));
3180 else
3181 dst = fold_build2_loc (loc, POINTER_PLUS_EXPR, TREE_TYPE (dst), dst,
3182 fold_convert_loc (loc, sizetype,
3183 unshare_expr (dstlen)));
3184 dst = force_gimple_operand_gsi (gsi, dst, true, NULL_TREE, true,
3185 GSI_SAME_STMT);
3186 if (objsz)
3187 {
3188 objsz = fold_build2_loc (loc, MINUS_EXPR, TREE_TYPE (objsz), objsz,
3189 fold_convert_loc (loc, TREE_TYPE (objsz),
3190 unshare_expr (dstlen)));
3191 objsz = force_gimple_operand_gsi (gsi, objsz, true, NULL_TREE, true,
3192 GSI_SAME_STMT);
3193 }
3194 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
3195 {
3196 fprintf (dump_file, "Optimizing: ");
3197 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3198 }
3199 if (srclen != NULL_TREE)
3200 success = update_gimple_call (gsi, fn, 3 + (objsz != NULL_TREE),
3201 dst, src, len, objsz);
3202 else
3203 success = update_gimple_call (gsi, fn, 2 + (objsz != NULL_TREE),
3204 dst, src, objsz);
3205 if (success)
3206 {
3207 stmt = gsi_stmt (*gsi);
3208 update_stmt (stmt);
3209 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
3210 {
3211 fprintf (dump_file, "into: ");
3212 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
3213 }
3214 /* If srclen == NULL, note that current string length can be
3215 computed by transforming this strcpy into stpcpy. */
3216 if (srclen == NULL_TREE && dsi->dont_invalidate)
3217 dsi->stmt = stmt;
3218 adjust_last_stmt (dsi, stmt, true);
3219 if (srclen != NULL_TREE)
3220 {
3221 laststmt.stmt = stmt;
3222 laststmt.len = srclen;
3223 laststmt.stridx = dsi->idx;
3224 }
3225 }
3226 else if (dump_file && (dump_flags & TDF_DETAILS) != 0)
3227 fprintf (dump_file, "not possible.\n");
3228
3229 if (set_no_warning)
3230 gimple_set_no_warning (stmt, true);
3231 }
3232
3233 /* Handle a call to malloc or calloc. */
3234
3235 static void
3236 handle_builtin_malloc (enum built_in_function bcode, gimple_stmt_iterator *gsi)
3237 {
3238 gimple *stmt = gsi_stmt (*gsi);
3239 tree lhs = gimple_call_lhs (stmt);
3240 if (lhs == NULL_TREE)
3241 return;
3242
3243 gcc_assert (get_stridx (lhs) == 0);
3244 int idx = new_stridx (lhs);
3245 tree length = NULL_TREE;
3246 if (bcode == BUILT_IN_CALLOC)
3247 length = build_int_cst (size_type_node, 0);
3248 strinfo *si = new_strinfo (lhs, idx, length, length != NULL_TREE);
3249 if (bcode == BUILT_IN_CALLOC)
3250 si->endptr = lhs;
3251 set_strinfo (idx, si);
3252 si->writable = true;
3253 si->stmt = stmt;
3254 si->dont_invalidate = true;
3255 }
3256
3257 /* Handle a call to memset.
3258 After a call to calloc, memset(,0,) is unnecessary.
3259 memset(malloc(n),0,n) is calloc(n,1).
3260 return true when the call is transfomred, false otherwise. */
3261
3262 static bool
3263 handle_builtin_memset (gimple_stmt_iterator *gsi, bool *zero_write)
3264 {
3265 gimple *stmt2 = gsi_stmt (*gsi);
3266 if (!integer_zerop (gimple_call_arg (stmt2, 1)))
3267 return false;
3268
3269 /* Let the caller know the memset call cleared the destination. */
3270 *zero_write = true;
3271
3272 tree ptr = gimple_call_arg (stmt2, 0);
3273 int idx1 = get_stridx (ptr);
3274 if (idx1 <= 0)
3275 return false;
3276 strinfo *si1 = get_strinfo (idx1);
3277 if (!si1)
3278 return false;
3279 gimple *stmt1 = si1->stmt;
3280 if (!stmt1 || !is_gimple_call (stmt1))
3281 return false;
3282 tree callee1 = gimple_call_fndecl (stmt1);
3283 if (!valid_builtin_call (stmt1))
3284 return false;
3285 enum built_in_function code1 = DECL_FUNCTION_CODE (callee1);
3286 tree size = gimple_call_arg (stmt2, 2);
3287 if (code1 == BUILT_IN_CALLOC)
3288 /* Not touching stmt1 */ ;
3289 else if (code1 == BUILT_IN_MALLOC
3290 && operand_equal_p (gimple_call_arg (stmt1, 0), size, 0))
3291 {
3292 gimple_stmt_iterator gsi1 = gsi_for_stmt (stmt1);
3293 update_gimple_call (&gsi1, builtin_decl_implicit (BUILT_IN_CALLOC), 2,
3294 size, build_one_cst (size_type_node));
3295 si1->nonzero_chars = build_int_cst (size_type_node, 0);
3296 si1->full_string_p = true;
3297 si1->stmt = gsi_stmt (gsi1);
3298 }
3299 else
3300 return false;
3301 tree lhs = gimple_call_lhs (stmt2);
3302 unlink_stmt_vdef (stmt2);
3303 if (lhs)
3304 {
3305 gimple *assign = gimple_build_assign (lhs, ptr);
3306 gsi_replace (gsi, assign, false);
3307 }
3308 else
3309 {
3310 gsi_remove (gsi, true);
3311 release_defs (stmt2);
3312 }
3313
3314 return true;
3315 }
3316
3317 /* Return a pointer to the first such equality expression if RES is used
3318 only in expressions testing its equality to zero, and null otherwise. */
3319
3320 static gimple *
3321 used_only_for_zero_equality (tree res)
3322 {
3323 gimple *first_use = NULL;
3324
3325 use_operand_p use_p;
3326 imm_use_iterator iter;
3327
3328 FOR_EACH_IMM_USE_FAST (use_p, iter, res)
3329 {
3330 gimple *use_stmt = USE_STMT (use_p);
3331
3332 if (is_gimple_debug (use_stmt))
3333 continue;
3334 if (gimple_code (use_stmt) == GIMPLE_ASSIGN)
3335 {
3336 tree_code code = gimple_assign_rhs_code (use_stmt);
3337 if (code == COND_EXPR)
3338 {
3339 tree cond_expr = gimple_assign_rhs1 (use_stmt);
3340 if ((TREE_CODE (cond_expr) != EQ_EXPR
3341 && (TREE_CODE (cond_expr) != NE_EXPR))
3342 || !integer_zerop (TREE_OPERAND (cond_expr, 1)))
3343 return NULL;
3344 }
3345 else if (code == EQ_EXPR || code == NE_EXPR)
3346 {
3347 if (!integer_zerop (gimple_assign_rhs2 (use_stmt)))
3348 return NULL;
3349 }
3350 else
3351 return NULL;
3352 }
3353 else if (gimple_code (use_stmt) == GIMPLE_COND)
3354 {
3355 tree_code code = gimple_cond_code (use_stmt);
3356 if ((code != EQ_EXPR && code != NE_EXPR)
3357 || !integer_zerop (gimple_cond_rhs (use_stmt)))
3358 return NULL;
3359 }
3360 else
3361 return NULL;
3362
3363 if (!first_use)
3364 first_use = use_stmt;
3365 }
3366
3367 return first_use;
3368 }
3369
3370 /* Handle a call to memcmp. We try to handle small comparisons by
3371 converting them to load and compare, and replacing the call to memcmp
3372 with a __builtin_memcmp_eq call where possible.
3373 return true when call is transformed, return false otherwise. */
3374
3375 static bool
3376 handle_builtin_memcmp (gimple_stmt_iterator *gsi)
3377 {
3378 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3379 tree res = gimple_call_lhs (stmt);
3380
3381 if (!res || !used_only_for_zero_equality (res))
3382 return false;
3383
3384 tree arg1 = gimple_call_arg (stmt, 0);
3385 tree arg2 = gimple_call_arg (stmt, 1);
3386 tree len = gimple_call_arg (stmt, 2);
3387 unsigned HOST_WIDE_INT leni;
3388
3389 if (tree_fits_uhwi_p (len)
3390 && (leni = tree_to_uhwi (len)) <= GET_MODE_SIZE (word_mode)
3391 && pow2p_hwi (leni))
3392 {
3393 leni *= CHAR_TYPE_SIZE;
3394 unsigned align1 = get_pointer_alignment (arg1);
3395 unsigned align2 = get_pointer_alignment (arg2);
3396 unsigned align = MIN (align1, align2);
3397 scalar_int_mode mode;
3398 if (int_mode_for_size (leni, 1).exists (&mode)
3399 && (align >= leni || !targetm.slow_unaligned_access (mode, align)))
3400 {
3401 location_t loc = gimple_location (stmt);
3402 tree type, off;
3403 type = build_nonstandard_integer_type (leni, 1);
3404 gcc_assert (known_eq (GET_MODE_BITSIZE (TYPE_MODE (type)), leni));
3405 tree ptrtype = build_pointer_type_for_mode (char_type_node,
3406 ptr_mode, true);
3407 off = build_int_cst (ptrtype, 0);
3408 arg1 = build2_loc (loc, MEM_REF, type, arg1, off);
3409 arg2 = build2_loc (loc, MEM_REF, type, arg2, off);
3410 tree tem1 = fold_const_aggregate_ref (arg1);
3411 if (tem1)
3412 arg1 = tem1;
3413 tree tem2 = fold_const_aggregate_ref (arg2);
3414 if (tem2)
3415 arg2 = tem2;
3416 res = fold_convert_loc (loc, TREE_TYPE (res),
3417 fold_build2_loc (loc, NE_EXPR,
3418 boolean_type_node,
3419 arg1, arg2));
3420 gimplify_and_update_call_from_tree (gsi, res);
3421 return true;
3422 }
3423 }
3424
3425 gimple_call_set_fndecl (stmt, builtin_decl_explicit (BUILT_IN_MEMCMP_EQ));
3426 return true;
3427 }
3428
3429 /* Given an index to the strinfo vector, compute the string length
3430 for the corresponding string. Return -1 when unknown. */
3431
3432 static HOST_WIDE_INT
3433 compute_string_length (int idx)
3434 {
3435 HOST_WIDE_INT string_leni = -1;
3436 gcc_assert (idx != 0);
3437
3438 if (idx < 0)
3439 return ~idx;
3440
3441 strinfo *si = get_strinfo (idx);
3442 if (si)
3443 {
3444 tree const_string_len = get_string_length (si);
3445 if (const_string_len && tree_fits_shwi_p (const_string_len))
3446 string_leni = tree_to_shwi (const_string_len);
3447 }
3448
3449 if (string_leni < 0)
3450 return -1;
3451
3452 return string_leni;
3453 }
3454
3455 /* Determine the minimum size of the object referenced by DEST expression
3456 which must have a pointer type.
3457 Return the minimum size of the object if successful or HWI_M1U when
3458 the size cannot be determined. */
3459
3460 static unsigned HOST_WIDE_INT
3461 determine_min_objsize (tree dest)
3462 {
3463 unsigned HOST_WIDE_INT size = 0;
3464
3465 if (compute_builtin_object_size (dest, 2, &size))
3466 return size;
3467
3468 /* Try to determine the size of the object through the RHS
3469 of the assign statement. */
3470 if (TREE_CODE (dest) == SSA_NAME)
3471 {
3472 gimple *stmt = SSA_NAME_DEF_STMT (dest);
3473 if (!is_gimple_assign (stmt))
3474 return HOST_WIDE_INT_M1U;
3475
3476 if (!gimple_assign_single_p (stmt)
3477 && !gimple_assign_unary_nop_p (stmt))
3478 return HOST_WIDE_INT_M1U;
3479
3480 dest = gimple_assign_rhs1 (stmt);
3481 return determine_min_objsize (dest);
3482 }
3483
3484 /* Try to determine the size of the object from its type. */
3485 if (TREE_CODE (dest) != ADDR_EXPR)
3486 return HOST_WIDE_INT_M1U;
3487
3488 tree type = TREE_TYPE (dest);
3489 if (TREE_CODE (type) == POINTER_TYPE)
3490 type = TREE_TYPE (type);
3491
3492 type = TYPE_MAIN_VARIANT (type);
3493
3494 /* The size of a flexible array cannot be determined. Otherwise,
3495 for arrays with more than one element, return the size of its
3496 type. GCC itself misuses arrays of both zero and one elements
3497 as flexible array members so they are excluded as well. */
3498 if (TREE_CODE (type) != ARRAY_TYPE
3499 || !array_at_struct_end_p (dest))
3500 {
3501 tree type_size = TYPE_SIZE_UNIT (type);
3502 if (type_size && TREE_CODE (type_size) == INTEGER_CST
3503 && !integer_onep (type_size)
3504 && !integer_zerop (type_size))
3505 return tree_to_uhwi (type_size);
3506 }
3507
3508 return HOST_WIDE_INT_M1U;
3509 }
3510
3511 /* Given strinfo IDX for ARG, set LENRNG[] to the range of lengths
3512 of the string(s) referenced by ARG if it can be determined.
3513 If the length cannot be determined, set *SIZE to the size of
3514 the array the string is stored in, if any. If no such array is
3515 known, set *SIZE to -1. When the strings are nul-terminated set
3516 *NULTERM to true, otherwise to false. Return true on success. */
3517
3518 static bool
3519 get_len_or_size (tree arg, int idx, unsigned HOST_WIDE_INT lenrng[2],
3520 unsigned HOST_WIDE_INT *size, bool *nulterm)
3521 {
3522 /* Set so that both LEN and ~LEN are invalid lengths, i.e.,
3523 maximum possible length + 1. */
3524 lenrng[0] = lenrng[1] = HOST_WIDE_INT_MAX;
3525
3526 *size = HOST_WIDE_INT_M1U;
3527
3528 if (idx < 0)
3529 {
3530 /* IDX is the inverted constant string length. */
3531 lenrng[0] = ~idx;
3532 lenrng[1] = lenrng[0];
3533 *nulterm = true;
3534 }
3535 else if (idx == 0)
3536 ; /* Handled below. */
3537 else if (strinfo *si = get_strinfo (idx))
3538 {
3539 if (!si->nonzero_chars)
3540 arg = si->ptr;
3541 else if (tree_fits_uhwi_p (si->nonzero_chars))
3542 {
3543 lenrng[0] = tree_to_uhwi (si->nonzero_chars);
3544 *nulterm = si->full_string_p;
3545 /* Set the upper bound only if the string is known to be
3546 nul-terminated, otherwise leave it at maximum + 1. */
3547 if (*nulterm)
3548 lenrng[1] = lenrng[0];
3549 }
3550 else if (TREE_CODE (si->nonzero_chars) == SSA_NAME)
3551 {
3552 wide_int min, max;
3553 value_range_kind rng = get_range_info (si->nonzero_chars, &min, &max);
3554 if (rng == VR_RANGE)
3555 {
3556 lenrng[0] = min.to_uhwi ();
3557 lenrng[1] = max.to_uhwi ();
3558 *nulterm = si->full_string_p;
3559 }
3560 }
3561 else if (si->ptr)
3562 arg = si->ptr;
3563 }
3564
3565 if (lenrng[0] == HOST_WIDE_INT_MAX)
3566 {
3567 /* Compute the minimum and maximum real or possible lengths. */
3568 c_strlen_data lendata = { };
3569 if (get_range_strlen (arg, &lendata, /* eltsize = */1))
3570 {
3571 if (tree_fits_shwi_p (lendata.maxlen) && !lendata.maxbound)
3572 {
3573 lenrng[0] = tree_to_shwi (lendata.minlen);
3574 lenrng[1] = tree_to_shwi (lendata.maxlen);
3575 *nulterm = true;
3576 }
3577 else if (lendata.maxbound && tree_fits_shwi_p (lendata.maxbound))
3578 {
3579 /* Set *SIZE to the conservative LENDATA.MAXBOUND which
3580 is a conservative estimate of the longest string based
3581 on the sizes of the arrays referenced by ARG. */
3582 *size = tree_to_uhwi (lendata.maxbound) + 1;
3583 *nulterm = false;
3584 }
3585 }
3586 else
3587 {
3588 /* Set *SIZE to the size of the smallest object referenced
3589 by ARG if ARG denotes a single object, or to HWI_M1U
3590 otherwise. */
3591 *size = determine_min_objsize (arg);
3592 *nulterm = false;
3593 }
3594 }
3595
3596 return lenrng[0] != HOST_WIDE_INT_MAX || *size != HOST_WIDE_INT_M1U;
3597 }
3598
3599 /* If IDX1 and IDX2 refer to strings A and B of unequal lengths, return
3600 the result of 0 == strncmp (A, B, BOUND) (which is the same as strcmp
3601 for a sufficiently large BOUND). If the result is based on the length
3602 of one string being greater than the longest string that would fit in
3603 the array pointer to by the argument, set *PLEN and *PSIZE to
3604 the corresponding length (or its complement when the string is known
3605 to be at least as long and need not be nul-terminated) and size.
3606 Otherwise return null. */
3607
3608 static tree
3609 strxcmp_eqz_result (tree arg1, int idx1, tree arg2, int idx2,
3610 unsigned HOST_WIDE_INT bound, unsigned HOST_WIDE_INT len[2],
3611 unsigned HOST_WIDE_INT *psize)
3612 {
3613 /* Determine the range the length of each string is in and whether it's
3614 known to be nul-terminated, or the size of the array it's stored in. */
3615 bool nul1, nul2;
3616 unsigned HOST_WIDE_INT siz1, siz2;
3617 unsigned HOST_WIDE_INT len1rng[2], len2rng[2];
3618 if (!get_len_or_size (arg1, idx1, len1rng, &siz1, &nul1)
3619 || !get_len_or_size (arg2, idx2, len2rng, &siz2, &nul2))
3620 return NULL_TREE;
3621
3622 /* BOUND is set to HWI_M1U for strcmp and less to strncmp, and LENiRNG
3623 to HWI_MAX when invalid. Adjust the length of each string to consider
3624 to be no more than BOUND. */
3625 if (len1rng[0] < HOST_WIDE_INT_MAX && len1rng[0] > bound)
3626 len1rng[0] = bound;
3627 if (len1rng[1] < HOST_WIDE_INT_MAX && len1rng[1] > bound)
3628 len1rng[1] = bound;
3629 if (len2rng[0] < HOST_WIDE_INT_MAX && len2rng[0] > bound)
3630 len2rng[0] = bound;
3631 if (len2rng[1] < HOST_WIDE_INT_MAX && len2rng[1] > bound)
3632 len2rng[1] = bound;
3633
3634 /* Two empty strings are equal. */
3635 if (len1rng[1] == 0 && len2rng[1] == 0)
3636 return integer_one_node;
3637
3638 /* The strings are definitely unequal when the lower bound of the length
3639 of one of them is greater than the length of the longest string that
3640 would fit into the other array. */
3641 if (len1rng[0] == HOST_WIDE_INT_MAX
3642 && len2rng[0] != HOST_WIDE_INT_MAX
3643 && ((len2rng[0] < bound && len2rng[0] >= siz1)
3644 || len2rng[0] > siz1))
3645 {
3646 *psize = siz1;
3647 len[0] = len1rng[0];
3648 /* Set LEN[0] to the lower bound of ARG1's length when it's
3649 nul-terminated or to the complement of its minimum length
3650 otherwise, */
3651 len[1] = nul2 ? len2rng[0] : ~len2rng[0];
3652 return integer_zero_node;
3653 }
3654
3655 if (len2rng[0] == HOST_WIDE_INT_MAX
3656 && len1rng[0] != HOST_WIDE_INT_MAX
3657 && ((len1rng[0] < bound && len1rng[0] >= siz2)
3658 || len1rng[0] > siz2))
3659 {
3660 *psize = siz2;
3661 len[0] = nul1 ? len1rng[0] : ~len1rng[0];
3662 len[1] = len2rng[0];
3663 return integer_zero_node;
3664 }
3665
3666 /* The strings are also definitely unequal when their lengths are unequal
3667 and at least one is nul-terminated. */
3668 if (len1rng[0] != HOST_WIDE_INT_MAX
3669 && len2rng[0] != HOST_WIDE_INT_MAX
3670 && ((len1rng[1] < len2rng[0] && nul1)
3671 || (len2rng[1] < len1rng[0] && nul2)))
3672 {
3673 if (bound <= len1rng[0] || bound <= len2rng[0])
3674 *psize = bound;
3675 else
3676 *psize = HOST_WIDE_INT_M1U;
3677
3678 len[0] = len1rng[0];
3679 len[1] = len2rng[0];
3680 return integer_zero_node;
3681 }
3682
3683 /* The string lengths may be equal or unequal. Even when equal and
3684 both strings nul-terminated, without the string contents there's
3685 no way to determine whether they are equal. */
3686 return NULL_TREE;
3687 }
3688
3689 /* Diagnose pointless calls to strcmp or strncmp STMT with string
3690 arguments of lengths LEN or size SIZ and (for strncmp) BOUND,
3691 whose result is used in equality expressions that evaluate to
3692 a constant due to one argument being longer than the size of
3693 the other. */
3694
3695 static void
3696 maybe_warn_pointless_strcmp (gimple *stmt, HOST_WIDE_INT bound,
3697 unsigned HOST_WIDE_INT len[2],
3698 unsigned HOST_WIDE_INT siz)
3699 {
3700 tree lhs = gimple_call_lhs (stmt);
3701 gimple *use = used_only_for_zero_equality (lhs);
3702 if (!use)
3703 return;
3704
3705 bool at_least = false;
3706
3707 /* Excessive LEN[i] indicates a lower bound. */
3708 if (len[0] > HOST_WIDE_INT_MAX)
3709 {
3710 at_least = true;
3711 len[0] = ~len[0];
3712 }
3713
3714 if (len[1] > HOST_WIDE_INT_MAX)
3715 {
3716 at_least = true;
3717 len[1] = ~len[1];
3718 }
3719
3720 unsigned HOST_WIDE_INT minlen = MIN (len[0], len[1]);
3721
3722 /* FIXME: Include a note pointing to the declaration of the smaller
3723 array. */
3724 location_t stmt_loc = gimple_nonartificial_location (stmt);
3725 if (stmt_loc == UNKNOWN_LOCATION && EXPR_HAS_LOCATION (lhs))
3726 stmt_loc = tree_nonartificial_location (lhs);
3727 stmt_loc = expansion_point_location_if_in_system_header (stmt_loc);
3728
3729 tree callee = gimple_call_fndecl (stmt);
3730 bool warned = false;
3731 if (siz <= minlen && bound == -1)
3732 warned = warning_at (stmt_loc, OPT_Wstring_compare,
3733 (at_least
3734 ? G_("%G%qD of a string of length %wu or more and "
3735 "an array of size %wu evaluates to nonzero")
3736 : G_("%G%qD of a string of length %wu and an array "
3737 "of size %wu evaluates to nonzero")),
3738 stmt, callee, minlen, siz);
3739 else if (!at_least && siz <= HOST_WIDE_INT_MAX)
3740 {
3741 if (len[0] != HOST_WIDE_INT_MAX && len[1] != HOST_WIDE_INT_MAX)
3742 warned = warning_at (stmt_loc, OPT_Wstring_compare,
3743 "%G%qD of strings of length %wu and %wu "
3744 "and bound of %wu evaluates to nonzero",
3745 stmt, callee, len[0], len[1], bound);
3746 else
3747 warned = warning_at (stmt_loc, OPT_Wstring_compare,
3748 "%G%qD of a string of length %wu, an array "
3749 "of size %wu and bound of %wu evaluates to "
3750 "nonzero",
3751 stmt, callee, minlen, siz, bound);
3752 }
3753
3754 if (warned)
3755 {
3756 location_t use_loc = gimple_location (use);
3757 if (LOCATION_LINE (stmt_loc) != LOCATION_LINE (use_loc))
3758 inform (use_loc, "in this expression");
3759 }
3760 }
3761
3762
3763 /* Optimize a call to strcmp or strncmp either by folding it to a constant
3764 when possible or by transforming the latter to the former. Warn about
3765 calls where the length of one argument is greater than the size of
3766 the array to which the other argument points if the latter's length
3767 is not known. Return true when the call has been transformed into
3768 another and false otherwise. */
3769
3770 static bool
3771 handle_builtin_string_cmp (gimple_stmt_iterator *gsi)
3772 {
3773 gcall *stmt = as_a <gcall *> (gsi_stmt (*gsi));
3774 tree lhs = gimple_call_lhs (stmt);
3775
3776 if (!lhs)
3777 return false;
3778
3779 tree arg1 = gimple_call_arg (stmt, 0);
3780 tree arg2 = gimple_call_arg (stmt, 1);
3781 int idx1 = get_stridx (arg1);
3782 int idx2 = get_stridx (arg2);
3783
3784 /* For strncmp set to the the value of the third argument if known. */
3785 HOST_WIDE_INT bound = -1;
3786
3787 /* Extract the strncmp bound. */
3788 if (gimple_call_num_args (stmt) == 3)
3789 {
3790 tree len = gimple_call_arg (stmt, 2);
3791 if (tree_fits_shwi_p (len))
3792 bound = tree_to_shwi (len);
3793
3794 /* If the bound argument is NOT known, do nothing. */
3795 if (bound < 0)
3796 return false;
3797 }
3798
3799 {
3800 /* Set to the length of one argument (or its complement if it's
3801 the lower bound of a range) and the size of the array storing
3802 the other if the result is based on the former being equal to
3803 or greater than the latter. */
3804 unsigned HOST_WIDE_INT len[2] = { HOST_WIDE_INT_MAX, HOST_WIDE_INT_MAX };
3805 unsigned HOST_WIDE_INT siz = HOST_WIDE_INT_M1U;
3806
3807 /* Try to determine if the two strings are either definitely equal
3808 or definitely unequal and if so, either fold the result to zero
3809 (when equal) or set the range of the result to ~[0, 0] otherwise. */
3810 if (tree eqz = strxcmp_eqz_result (arg1, idx1, arg2, idx2, bound,
3811 len, &siz))
3812 {
3813 if (integer_zerop (eqz))
3814 {
3815 maybe_warn_pointless_strcmp (stmt, bound, len, siz);
3816
3817 /* When the lengths of the first two string arguments are
3818 known to be unequal set the range of the result to non-zero.
3819 This allows the call to be eliminated if its result is only
3820 used in tests for equality to zero. */
3821 wide_int zero = wi::zero (TYPE_PRECISION (TREE_TYPE (lhs)));
3822 set_range_info (lhs, VR_ANTI_RANGE, zero, zero);
3823 return false;
3824 }
3825 /* When the two strings are definitely equal (such as when they
3826 are both empty) fold the call to the constant result. */
3827 replace_call_with_value (gsi, integer_zero_node);
3828 return true;
3829 }
3830 }
3831
3832 /* Return if nothing is known about the strings pointed to by ARG1
3833 and ARG2. */
3834 if (idx1 == 0 && idx2 == 0)
3835 return false;
3836
3837 /* Determine either the length or the size of each of the strings,
3838 whichever is available. */
3839 HOST_WIDE_INT cstlen1 = -1, cstlen2 = -1;
3840 HOST_WIDE_INT arysiz1 = -1, arysiz2 = -1;
3841
3842 if (idx1)
3843 cstlen1 = compute_string_length (idx1) + 1;
3844 else
3845 arysiz1 = determine_min_objsize (arg1);
3846
3847 /* Bail if neither the string length nor the size of the array
3848 it is stored in can be determined. */
3849 if (cstlen1 < 0 && arysiz1 < 0)
3850 return false;
3851
3852 /* Repeat for the second argument. */
3853 if (idx2)
3854 cstlen2 = compute_string_length (idx2) + 1;
3855 else
3856 arysiz2 = determine_min_objsize (arg2);
3857
3858 if (cstlen2 < 0 && arysiz2 < 0)
3859 return false;
3860
3861 /* The exact number of characters to compare. */
3862 HOST_WIDE_INT cmpsiz = bound < 0 ? cstlen1 < 0 ? cstlen2 : cstlen1 : bound;
3863 /* The size of the array in which the unknown string is stored. */
3864 HOST_WIDE_INT varsiz = arysiz1 < 0 ? arysiz2 : arysiz1;
3865
3866 if (cmpsiz < varsiz && used_only_for_zero_equality (lhs))
3867 {
3868 /* If the known length is less than the size of the other array
3869 and the strcmp result is only used to test equality to zero,
3870 transform the call to the equivalent _eq call. */
3871 if (tree fn = builtin_decl_implicit (bound < 0 ? BUILT_IN_STRCMP_EQ
3872 : BUILT_IN_STRNCMP_EQ))
3873 {
3874 tree n = build_int_cst (size_type_node, cmpsiz);
3875 update_gimple_call (gsi, fn, 3, arg1, arg2, n);
3876 return true;
3877 }
3878 }
3879
3880 return false;
3881 }
3882
3883 /* Handle a POINTER_PLUS_EXPR statement.
3884 For p = "abcd" + 2; compute associated length, or if
3885 p = q + off is pointing to a '\0' character of a string, call
3886 zero_length_string on it. */
3887
3888 static void
3889 handle_pointer_plus (gimple_stmt_iterator *gsi)
3890 {
3891 gimple *stmt = gsi_stmt (*gsi);
3892 tree lhs = gimple_assign_lhs (stmt), off;
3893 int idx = get_stridx (gimple_assign_rhs1 (stmt));
3894 strinfo *si, *zsi;
3895
3896 if (idx == 0)
3897 return;
3898
3899 if (idx < 0)
3900 {
3901 tree off = gimple_assign_rhs2 (stmt);
3902 if (tree_fits_uhwi_p (off)
3903 && tree_to_uhwi (off) <= (unsigned HOST_WIDE_INT) ~idx)
3904 ssa_ver_to_stridx[SSA_NAME_VERSION (lhs)]
3905 = ~(~idx - (int) tree_to_uhwi (off));
3906 return;
3907 }
3908
3909 si = get_strinfo (idx);
3910 if (si == NULL || si->nonzero_chars == NULL_TREE)
3911 return;
3912
3913 off = gimple_assign_rhs2 (stmt);
3914 zsi = NULL;
3915 if (si->full_string_p && operand_equal_p (si->nonzero_chars, off, 0))
3916 zsi = zero_length_string (lhs, si);
3917 else if (TREE_CODE (off) == SSA_NAME)
3918 {
3919 gimple *def_stmt = SSA_NAME_DEF_STMT (off);
3920 if (gimple_assign_single_p (def_stmt)
3921 && si->full_string_p
3922 && operand_equal_p (si->nonzero_chars,
3923 gimple_assign_rhs1 (def_stmt), 0))
3924 zsi = zero_length_string (lhs, si);
3925 }
3926 if (zsi != NULL
3927 && si->endptr != NULL_TREE
3928 && si->endptr != lhs
3929 && TREE_CODE (si->endptr) == SSA_NAME)
3930 {
3931 enum tree_code rhs_code
3932 = useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (si->endptr))
3933 ? SSA_NAME : NOP_EXPR;
3934 gimple_assign_set_rhs_with_ops (gsi, rhs_code, si->endptr);
3935 gcc_assert (gsi_stmt (*gsi) == stmt);
3936 update_stmt (stmt);
3937 }
3938 }
3939
3940 /* Describes recursion limits used by count_nonzero_bytes. */
3941
3942 class ssa_name_limit_t
3943 {
3944 bitmap visited; /* Bitmap of visited SSA_NAMEs. */
3945 unsigned ssa_def_max; /* Longest chain of SSA_NAMEs to follow. */
3946
3947 /* Not copyable or assignable. */
3948 ssa_name_limit_t (ssa_name_limit_t&);
3949 void operator= (ssa_name_limit_t&);
3950
3951 public:
3952
3953 ssa_name_limit_t ()
3954 : visited (NULL),
3955 ssa_def_max (PARAM_VALUE (PARAM_SSA_NAME_DEF_CHAIN_LIMIT)) { }
3956
3957 int next_ssa_name (tree);
3958
3959 ~ssa_name_limit_t ()
3960 {
3961 if (visited)
3962 BITMAP_FREE (visited);
3963 }
3964 };
3965
3966 /* If the SSA_NAME has already been "seen" return a positive value.
3967 Otherwise add it to VISITED. If the SSA_NAME limit has been
3968 reached, return a negative value. Otherwise return zero. */
3969
3970 int ssa_name_limit_t::next_ssa_name (tree ssa_name)
3971 {
3972 if (!visited)
3973 visited = BITMAP_ALLOC (NULL);
3974
3975 /* Return a positive value if SSA_NAME has already been visited. */
3976 if (!bitmap_set_bit (visited, SSA_NAME_VERSION (ssa_name)))
3977 return 1;
3978
3979 /* Return a negative value to let caller avoid recursing beyond
3980 the specified limit. */
3981 if (ssa_def_max == 0)
3982 return -1;
3983
3984 --ssa_def_max;
3985
3986 return 0;
3987 }
3988
3989 /* Determines the minimum and maximum number of leading non-zero bytes
3990 in the representation of EXP and set LENRANGE[0] and LENRANGE[1]
3991 to each. Sets LENRANGE[2] to the total number of bytes in
3992 the representation. Sets *NULTREM if the representation contains
3993 a zero byte, and sets *ALLNUL if all the bytes are zero.
3994 OFFSET and NBYTES are the offset into the representation and
3995 the size of the access to it determined from a MEM_REF or zero
3996 for other expressions.
3997 Avoid recursing deeper than the limits in SNLIM allow.
3998 Returns true on success and false otherwise. */
3999
4000 static bool
4001 count_nonzero_bytes (tree exp, unsigned HOST_WIDE_INT offset,
4002 unsigned HOST_WIDE_INT nbytes,
4003 unsigned lenrange[3], bool *nulterm,
4004 bool *allnul, bool *allnonnul, const vr_values *rvals,
4005 ssa_name_limit_t &snlim)
4006 {
4007 int idx = get_stridx (exp);
4008 if (idx > 0)
4009 {
4010 strinfo *si = get_strinfo (idx);
4011 if (!si)
4012 return false;
4013
4014 /* Handle both constant lengths as well non-constant lengths
4015 in some range. */
4016 unsigned HOST_WIDE_INT minlen, maxlen;
4017 if (tree_fits_shwi_p (si->nonzero_chars))
4018 minlen = maxlen = tree_to_shwi (si->nonzero_chars);
4019 else if (nbytes
4020 && si->nonzero_chars
4021 && TREE_CODE (si->nonzero_chars) == SSA_NAME)
4022 {
4023 const value_range *vr
4024 = CONST_CAST (class vr_values *, rvals)
4025 ->get_value_range (si->nonzero_chars);
4026 if (vr->kind () != VR_RANGE
4027 || !range_int_cst_p (vr))
4028 return false;
4029
4030 minlen = tree_to_uhwi (vr->min ());
4031 maxlen = tree_to_uhwi (vr->max ());
4032 }
4033 else
4034 return false;
4035
4036 if (maxlen < offset)
4037 return false;
4038
4039 minlen = minlen < offset ? 0 : minlen - offset;
4040 maxlen -= offset;
4041 if (maxlen + 1 < nbytes)
4042 return false;
4043
4044 if (nbytes <= minlen)
4045 *nulterm = false;
4046
4047 if (nbytes < minlen)
4048 {
4049 minlen = nbytes;
4050 if (nbytes < maxlen)
4051 maxlen = nbytes;
4052 }
4053
4054 if (minlen < lenrange[0])
4055 lenrange[0] = minlen;
4056 if (lenrange[1] < maxlen)
4057 lenrange[1] = maxlen;
4058
4059 if (lenrange[2] < nbytes)
4060 (lenrange[2] = nbytes);
4061
4062 /* Since only the length of the string are known and not its contents,
4063 clear ALLNUL and ALLNONNUL purely on the basis of the length. */
4064 *allnul = false;
4065 if (minlen < nbytes)
4066 *allnonnul = false;
4067
4068 return true;
4069 }
4070
4071 if (TREE_CODE (exp) == ADDR_EXPR)
4072 exp = TREE_OPERAND (exp, 0);
4073
4074 if (TREE_CODE (exp) == SSA_NAME)
4075 {
4076 /* Handle non-zero single-character stores specially. */
4077 tree type = TREE_TYPE (exp);
4078 if (TREE_CODE (type) == INTEGER_TYPE
4079 && TYPE_MODE (type) == TYPE_MODE (char_type_node)
4080 && TYPE_PRECISION (type) == TYPE_PRECISION (char_type_node)
4081 && tree_expr_nonzero_p (exp))
4082 {
4083 /* If the character EXP is known to be non-zero (even if its
4084 exact value is not known) recurse once to set the range
4085 for an arbitrary constant. */
4086 exp = build_int_cst (type, 1);
4087 return count_nonzero_bytes (exp, offset, 1, lenrange,
4088 nulterm, allnul, allnonnul, rvals, snlim);
4089 }
4090
4091 gimple *stmt = SSA_NAME_DEF_STMT (exp);
4092 if (gimple_assign_single_p (stmt))
4093 {
4094 exp = gimple_assign_rhs1 (stmt);
4095 if (TREE_CODE (exp) != MEM_REF)
4096 return false;
4097 /* Handle MEM_REF below. */
4098 }
4099 else if (gimple_code (stmt) == GIMPLE_PHI)
4100 {
4101 /* Avoid processing an SSA_NAME that has already been visited
4102 or if an SSA_NAME limit has been reached. Indicate success
4103 if the former and failure if the latter. */
4104 if (int res = snlim.next_ssa_name (exp))
4105 return res > 0;
4106
4107 /* Determine the minimum and maximum from the PHI arguments. */
4108 unsigned int n = gimple_phi_num_args (stmt);
4109 for (unsigned i = 0; i != n; i++)
4110 {
4111 tree def = gimple_phi_arg_def (stmt, i);
4112 if (!count_nonzero_bytes (def, offset, nbytes, lenrange, nulterm,
4113 allnul, allnonnul, rvals, snlim))
4114 return false;
4115 }
4116
4117 return true;
4118 }
4119 }
4120
4121 if (TREE_CODE (exp) == MEM_REF)
4122 {
4123 if (nbytes)
4124 return false;
4125
4126 tree arg = TREE_OPERAND (exp, 0);
4127 tree off = TREE_OPERAND (exp, 1);
4128
4129 if (TREE_CODE (off) != INTEGER_CST
4130 || !tree_fits_uhwi_p (off))
4131 return false;
4132
4133 unsigned HOST_WIDE_INT wioff = tree_to_uhwi (off);
4134 if (INT_MAX < wioff)
4135 return false;
4136
4137 offset += wioff;
4138 if (INT_MAX < offset)
4139 return false;
4140
4141 /* The size of the MEM_REF access determines the number of bytes. */
4142 tree type = TREE_TYPE (exp);
4143 tree typesize = TYPE_SIZE_UNIT (type);
4144 if (!typesize || !tree_fits_uhwi_p (typesize))
4145 return false;
4146 nbytes = tree_to_uhwi (typesize);
4147
4148 /* Handle MEM_REF = SSA_NAME types of assignments. */
4149 return count_nonzero_bytes (arg, offset, nbytes, lenrange, nulterm,
4150 allnul, allnonnul, rvals, snlim);
4151 }
4152
4153 if (TREE_CODE (exp) == VAR_DECL && TREE_READONLY (exp))
4154 {
4155 exp = DECL_INITIAL (exp);
4156 if (!exp)
4157 return false;
4158 }
4159
4160 const char *prep = NULL;
4161 if (TREE_CODE (exp) == STRING_CST)
4162 {
4163 unsigned nchars = TREE_STRING_LENGTH (exp);
4164 if (nchars < offset)
4165 return false;
4166
4167 if (!nbytes)
4168 /* If NBYTES hasn't been determined earlier from MEM_REF,
4169 set it here. It includes all internal nuls, including
4170 the terminating one if the string has one. */
4171 nbytes = nchars - offset;
4172
4173 prep = TREE_STRING_POINTER (exp) + offset;
4174 }
4175
4176 unsigned char buf[256];
4177 if (!prep)
4178 {
4179 /* If the pointer to representation hasn't been set above
4180 for STRING_CST point it at the buffer. */
4181 prep = reinterpret_cast <char *>(buf);
4182 /* Try to extract the representation of the constant object
4183 or expression starting from the offset. */
4184 unsigned repsize = native_encode_expr (exp, buf, sizeof buf, offset);
4185 if (repsize < nbytes)
4186 {
4187 /* This should only happen when REPSIZE is zero because EXP
4188 doesn't denote an object with a known initializer, except
4189 perhaps when the reference reads past its end. */
4190 lenrange[0] = 0;
4191 prep = NULL;
4192 }
4193 else if (!nbytes)
4194 nbytes = repsize;
4195 else if (nbytes < repsize)
4196 return false;
4197 }
4198
4199 if (!nbytes)
4200 return false;
4201
4202 /* Compute the number of leading nonzero bytes in the representation
4203 and update the minimum and maximum. */
4204 unsigned n = prep ? strnlen (prep, nbytes) : nbytes;
4205
4206 if (n < lenrange[0])
4207 lenrange[0] = n;
4208 if (lenrange[1] < n)
4209 lenrange[1] = n;
4210
4211 /* Set the size of the representation. */
4212 if (lenrange[2] < nbytes)
4213 lenrange[2] = nbytes;
4214
4215 /* Clear NULTERM if none of the bytes is zero. */
4216 if (n == nbytes)
4217 *nulterm = false;
4218
4219 if (n)
4220 {
4221 /* When the initial number of non-zero bytes N is non-zero, reset
4222 *ALLNUL; if N is less than that the size of the representation
4223 also clear *ALLNONNUL. */
4224 *allnul = false;
4225 if (n < nbytes)
4226 *allnonnul = false;
4227 }
4228 else if (*allnul || *allnonnul)
4229 {
4230 *allnonnul = false;
4231
4232 if (*allnul)
4233 {
4234 /* When either ALLNUL is set and N is zero, also determine
4235 whether all subsequent bytes after the first one (which
4236 is nul) are zero or nonzero and clear ALLNUL if not. */
4237 for (const char *p = prep; p != prep + nbytes; ++p)
4238 if (*p)
4239 {
4240 *allnul = false;
4241 break;
4242 }
4243 }
4244 }
4245
4246 return true;
4247 }
4248
4249 /* Same as above except with an implicit SSA_NAME limit. RVALS is used
4250 to determine ranges of dynamically computed string lengths (the results
4251 of strlen). */
4252
4253 static bool
4254 count_nonzero_bytes (tree exp, unsigned lenrange[3], bool *nulterm,
4255 bool *allnul, bool *allnonnul, const vr_values *rvals)
4256 {
4257 /* Set to optimistic values so the caller doesn't have to worry about
4258 initializing these and to what. On success, the function will clear
4259 these if it determines their values are different but being recursive
4260 it never sets either to true. On failure, their values are
4261 unspecified. */
4262 *nulterm = true;
4263 *allnul = true;
4264 *allnonnul = true;
4265
4266 ssa_name_limit_t snlim;
4267 return count_nonzero_bytes (exp, 0, 0, lenrange, nulterm, allnul, allnonnul,
4268 rvals, snlim);
4269 }
4270
4271 /* Handle a single or multibyte store other than by a built-in function,
4272 either via a single character assignment or by multi-byte assignment
4273 either via MEM_REF or via a type other than char (such as in
4274 '*(int*)a = 12345'). Return true when handled. */
4275
4276 static bool
4277 handle_store (gimple_stmt_iterator *gsi, bool *zero_write, const vr_values *rvals)
4278 {
4279 int idx = -1;
4280 strinfo *si = NULL;
4281 gimple *stmt = gsi_stmt (*gsi);
4282 tree ssaname = NULL_TREE, lhs = gimple_assign_lhs (stmt);
4283 tree rhs = gimple_assign_rhs1 (stmt);
4284
4285 /* The offset of the first byte in LHS modified by the the store. */
4286 unsigned HOST_WIDE_INT offset = 0;
4287
4288 if (TREE_CODE (lhs) == MEM_REF
4289 && TREE_CODE (TREE_OPERAND (lhs, 0)) == SSA_NAME)
4290 {
4291 tree mem_offset = TREE_OPERAND (lhs, 1);
4292 if (tree_fits_uhwi_p (mem_offset))
4293 {
4294 /* Get the strinfo for the base, and use it if it starts with at
4295 least OFFSET nonzero characters. This is trivially true if
4296 OFFSET is zero. */
4297 offset = tree_to_uhwi (mem_offset);
4298 idx = get_stridx (TREE_OPERAND (lhs, 0));
4299 if (idx > 0)
4300 si = get_strinfo (idx);
4301 if (offset == 0)
4302 ssaname = TREE_OPERAND (lhs, 0);
4303 else if (si == NULL || compare_nonzero_chars (si, offset, rvals) < 0)
4304 {
4305 *zero_write = initializer_zerop (rhs);
4306 return true;
4307 }
4308 }
4309 }
4310 else
4311 {
4312 idx = get_addr_stridx (lhs, NULL_TREE, &offset);
4313 if (idx > 0)
4314 si = get_strinfo (idx);
4315 }
4316
4317 /* Minimum and maximum leading non-zero bytes and the size of the store. */
4318 unsigned lenrange[] = { UINT_MAX, 0, 0 };
4319
4320 /* Set to the minimum length of the string being assigned if known. */
4321 unsigned HOST_WIDE_INT rhs_minlen;
4322
4323 /* STORING_NONZERO_P is true iff not all stored characters are zero.
4324 STORING_ALL_NONZERO_P is true if all stored characters are zero.
4325 STORING_ALL_ZEROS_P is true iff all stored characters are zero.
4326 Both are false when it's impossible to determine which is true. */
4327 bool storing_nonzero_p;
4328 bool storing_all_nonzero_p;
4329 bool storing_all_zeros_p;
4330 /* FULL_STRING_P is set when the stored sequence of characters form
4331 a nul-terminated string. */
4332 bool full_string_p;
4333
4334 const bool ranges_valid
4335 = count_nonzero_bytes (rhs, lenrange, &full_string_p,
4336 &storing_all_zeros_p, &storing_all_nonzero_p,
4337 rvals);
4338 if (ranges_valid)
4339 {
4340 rhs_minlen = lenrange[0];
4341 storing_nonzero_p = lenrange[1] > 0;
4342 *zero_write = storing_all_zeros_p;
4343
4344 /* Avoid issuing multiple warnings for the same LHS or statement.
4345 For example, -Warray-bounds may have already been issued for
4346 an out-of-bounds subscript. */
4347 if (!TREE_NO_WARNING (lhs) && !gimple_no_warning_p (stmt))
4348 {
4349 /* Set to the declaration referenced by LHS (if known). */
4350 tree decl = NULL_TREE;
4351 if (tree dstsize = compute_objsize (lhs, 1, &decl))
4352 if (compare_tree_int (dstsize, lenrange[2]) < 0)
4353 {
4354 /* Fall back on the LHS location if the statement
4355 doesn't have one. */
4356 location_t loc = gimple_nonartificial_location (stmt);
4357 if (loc == UNKNOWN_LOCATION && EXPR_HAS_LOCATION (lhs))
4358 loc = tree_nonartificial_location (lhs);
4359 loc = expansion_point_location_if_in_system_header (loc);
4360 if (warning_n (loc, OPT_Wstringop_overflow_,
4361 lenrange[2],
4362 "%Gwriting %u byte into a region of size %E",
4363 "%Gwriting %u bytes into a region of size %E",
4364 stmt, lenrange[2], dstsize))
4365 {
4366 if (decl)
4367 inform (DECL_SOURCE_LOCATION (decl),
4368 "destination object declared here");
4369 gimple_set_no_warning (stmt, true);
4370 }
4371 }
4372 }
4373 }
4374 else
4375 {
4376 rhs_minlen = HOST_WIDE_INT_M1U;
4377 full_string_p = false;
4378 storing_nonzero_p = false;
4379 storing_all_zeros_p = false;
4380 storing_all_nonzero_p = false;
4381 }
4382
4383 if (si != NULL)
4384 {
4385 /* The corresponding element is set to 1 if the first and last
4386 element, respectively, of the sequence of characters being
4387 written over the string described by SI ends before
4388 the terminating nul (if it has one), to zero if the nul is
4389 being overwritten but not beyond, or negative otherwise. */
4390 int store_before_nul[2];
4391 if (ranges_valid)
4392 {
4393 /* The offset of the last stored byte. */
4394 unsigned HOST_WIDE_INT endoff = offset + lenrange[2] - 1;
4395 store_before_nul[0] = compare_nonzero_chars (si, offset, rvals);
4396 if (endoff == offset)
4397 store_before_nul[1] = store_before_nul[0];
4398 else
4399 store_before_nul[1] = compare_nonzero_chars (si, endoff, rvals);
4400 }
4401 else
4402 {
4403 store_before_nul[0] = compare_nonzero_chars (si, offset, rvals);
4404 store_before_nul[1] = store_before_nul[0];
4405 gcc_assert (offset == 0 || store_before_nul[0] >= 0);
4406 }
4407
4408 if (storing_all_zeros_p
4409 && store_before_nul[0] == 0
4410 && store_before_nul[1] == 0
4411 && si->full_string_p)
4412 {
4413 /* When overwriting a '\0' with a '\0', the store can be removed
4414 if we know it has been stored in the current function. */
4415 if (!stmt_could_throw_p (cfun, stmt) && si->writable)
4416 {
4417 unlink_stmt_vdef (stmt);
4418 release_defs (stmt);
4419 gsi_remove (gsi, true);
4420 return false;
4421 }
4422 else
4423 {
4424 si->writable = true;
4425 gsi_next (gsi);
4426 return false;
4427 }
4428 }
4429
4430 if (store_before_nul[1] > 0
4431 && storing_nonzero_p
4432 && lenrange[0] == lenrange[1]
4433 && lenrange[0] == lenrange[2]
4434 && TREE_CODE (TREE_TYPE (rhs)) == INTEGER_TYPE)
4435 {
4436 /* Handle a store of one or more non-nul characters that ends
4437 before the terminating nul of the destination and so does
4438 not affect its length
4439 If si->nonzero_chars > OFFSET, we aren't overwriting '\0',
4440 and if we aren't storing '\0', we know that the length of
4441 the string and any other zero terminated string in memory
4442 remains the same. In that case we move to the next gimple
4443 statement and return to signal the caller that it shouldn't
4444 invalidate anything.
4445
4446 This is benefical for cases like:
4447
4448 char p[20];
4449 void foo (char *q)
4450 {
4451 strcpy (p, "foobar");
4452 size_t len = strlen (p); // can be folded to 6
4453 size_t len2 = strlen (q); // has to be computed
4454 p[0] = 'X';
4455 size_t len3 = strlen (p); // can be folded to 6
4456 size_t len4 = strlen (q); // can be folded to len2
4457 bar (len, len2, len3, len4);
4458 } */
4459 gsi_next (gsi);
4460 return false;
4461 }
4462
4463 if (storing_all_zeros_p
4464 || storing_nonzero_p
4465 || (offset != 0 && store_before_nul[1] > 0))
4466 {
4467 /* When STORING_NONZERO_P, we know that the string will start
4468 with at least OFFSET + 1 nonzero characters. If storing
4469 a single character, set si->NONZERO_CHARS to the result.
4470 If storing multiple characters, try to determine the number
4471 of leading non-zero characters and set si->NONZERO_CHARS to
4472 the result instead.
4473
4474 When STORING_ALL_ZEROS_P, we know that the string is now
4475 OFFSET characters long.
4476
4477 Otherwise, we're storing an unknown value at offset OFFSET,
4478 so need to clip the nonzero_chars to OFFSET.
4479 Use the minimum length of the string (or individual character)
4480 being stored if it's known. Otherwise, STORING_NONZERO_P
4481 guarantees it's at least 1. */
4482 HOST_WIDE_INT len
4483 = storing_nonzero_p && ranges_valid ? lenrange[0] : 1;
4484 location_t loc = gimple_location (stmt);
4485 tree oldlen = si->nonzero_chars;
4486 if (store_before_nul[1] == 0 && si->full_string_p)
4487 /* We're overwriting the nul terminator with a nonzero or
4488 unknown character. If the previous stmt was a memcpy,
4489 its length may be decreased. */
4490 adjust_last_stmt (si, stmt, false);
4491 si = unshare_strinfo (si);
4492 if (storing_nonzero_p)
4493 {
4494 gcc_assert (len >= 0);
4495 si->nonzero_chars = build_int_cst (size_type_node, offset + len);
4496 }
4497 else
4498 si->nonzero_chars = build_int_cst (size_type_node, offset);
4499
4500 /* Set FULL_STRING_P only if the length of the strings being
4501 written is the same, and clear it if the strings have
4502 different lengths. In the latter case the length stored
4503 in si->NONZERO_CHARS becomes the lower bound.
4504 FIXME: Handle the upper bound of the length if possible. */
4505 si->full_string_p = full_string_p && lenrange[0] == lenrange[1];
4506
4507 if (storing_all_zeros_p
4508 && ssaname
4509 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ssaname))
4510 si->endptr = ssaname;
4511 else
4512 si->endptr = NULL;
4513 si->next = 0;
4514 si->stmt = NULL;
4515 si->writable = true;
4516 si->dont_invalidate = true;
4517 if (oldlen)
4518 {
4519 tree adj = fold_build2_loc (loc, MINUS_EXPR, size_type_node,
4520 si->nonzero_chars, oldlen);
4521 adjust_related_strinfos (loc, si, adj);
4522 }
4523 else
4524 si->prev = 0;
4525 }
4526 }
4527 else if (idx == 0 && (storing_all_zeros_p || storing_nonzero_p))
4528 {
4529 if (ssaname)
4530 idx = new_stridx (ssaname);
4531 else
4532 idx = new_addr_stridx (lhs);
4533 if (idx != 0)
4534 {
4535 tree ptr = (ssaname ? ssaname : build_fold_addr_expr (lhs));
4536
4537 HOST_WIDE_INT slen;
4538 if (storing_all_zeros_p)
4539 slen = 0;
4540 else if (storing_nonzero_p && ranges_valid)
4541 {
4542 /* FIXME: Handle the upper bound of the length when
4543 LENRANGE[0] != LENRANGE[1]. */
4544 slen = lenrange[0];
4545 if (lenrange[0] != lenrange[1])
4546 /* Set the minimum length but ignore the maximum
4547 for now. */
4548 full_string_p = false;
4549 }
4550 else
4551 slen = -1;
4552
4553 tree len = (slen <= 0
4554 ? size_zero_node
4555 : build_int_cst (size_type_node, slen));
4556 si = new_strinfo (ptr, idx, len, slen >= 0 && full_string_p);
4557 set_strinfo (idx, si);
4558 if (storing_all_zeros_p
4559 && ssaname
4560 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ssaname))
4561 si->endptr = ssaname;
4562 si->dont_invalidate = true;
4563 si->writable = true;
4564 }
4565 }
4566 else if (idx == 0
4567 && rhs_minlen < HOST_WIDE_INT_M1U
4568 && ssaname == NULL_TREE
4569 && TREE_CODE (TREE_TYPE (lhs)) == ARRAY_TYPE)
4570 {
4571 HOST_WIDE_INT a = int_size_in_bytes (TREE_TYPE (lhs));
4572 if (a > 0 && (unsigned HOST_WIDE_INT) a > rhs_minlen)
4573 {
4574 int idx = new_addr_stridx (lhs);
4575 if (idx != 0)
4576 {
4577 si = new_strinfo (build_fold_addr_expr (lhs), idx,
4578 build_int_cst (size_type_node, rhs_minlen),
4579 full_string_p);
4580 set_strinfo (idx, si);
4581 si->dont_invalidate = true;
4582 }
4583 }
4584 }
4585
4586 if (si != NULL && offset == 0 && storing_all_zeros_p)
4587 {
4588 /* Allow adjust_last_stmt to remove it if the stored '\0'
4589 is immediately overwritten. */
4590 laststmt.stmt = stmt;
4591 laststmt.len = build_int_cst (size_type_node, 1);
4592 laststmt.stridx = si->idx;
4593 }
4594 return true;
4595 }
4596
4597 /* Try to fold strstr (s, t) eq/ne s to strncmp (s, t, strlen (t)) eq/ne 0. */
4598
4599 static void
4600 fold_strstr_to_strncmp (tree rhs1, tree rhs2, gimple *stmt)
4601 {
4602 if (TREE_CODE (rhs1) != SSA_NAME
4603 || TREE_CODE (rhs2) != SSA_NAME)
4604 return;
4605
4606 gimple *call_stmt = NULL;
4607 for (int pass = 0; pass < 2; pass++)
4608 {
4609 gimple *g = SSA_NAME_DEF_STMT (rhs1);
4610 if (gimple_call_builtin_p (g, BUILT_IN_STRSTR)
4611 && has_single_use (rhs1)
4612 && gimple_call_arg (g, 0) == rhs2)
4613 {
4614 call_stmt = g;
4615 break;
4616 }
4617 std::swap (rhs1, rhs2);
4618 }
4619
4620 if (call_stmt)
4621 {
4622 tree arg0 = gimple_call_arg (call_stmt, 0);
4623
4624 if (arg0 == rhs2)
4625 {
4626 tree arg1 = gimple_call_arg (call_stmt, 1);
4627 tree arg1_len = NULL_TREE;
4628 int idx = get_stridx (arg1);
4629
4630 if (idx)
4631 {
4632 if (idx < 0)
4633 arg1_len = build_int_cst (size_type_node, ~idx);
4634 else
4635 {
4636 strinfo *si = get_strinfo (idx);
4637 if (si)
4638 arg1_len = get_string_length (si);
4639 }
4640 }
4641
4642 if (arg1_len != NULL_TREE)
4643 {
4644 gimple_stmt_iterator gsi = gsi_for_stmt (call_stmt);
4645 tree strncmp_decl = builtin_decl_explicit (BUILT_IN_STRNCMP);
4646
4647 if (!is_gimple_val (arg1_len))
4648 {
4649 tree arg1_len_tmp = make_ssa_name (TREE_TYPE (arg1_len));
4650 gassign *arg1_stmt = gimple_build_assign (arg1_len_tmp,
4651 arg1_len);
4652 gsi_insert_before (&gsi, arg1_stmt, GSI_SAME_STMT);
4653 arg1_len = arg1_len_tmp;
4654 }
4655
4656 gcall *strncmp_call = gimple_build_call (strncmp_decl, 3,
4657 arg0, arg1, arg1_len);
4658 tree strncmp_lhs = make_ssa_name (integer_type_node);
4659 gimple_set_vuse (strncmp_call, gimple_vuse (call_stmt));
4660 gimple_call_set_lhs (strncmp_call, strncmp_lhs);
4661 gsi_remove (&gsi, true);
4662 gsi_insert_before (&gsi, strncmp_call, GSI_SAME_STMT);
4663 tree zero = build_zero_cst (TREE_TYPE (strncmp_lhs));
4664
4665 if (is_gimple_assign (stmt))
4666 {
4667 if (gimple_assign_rhs_code (stmt) == COND_EXPR)
4668 {
4669 tree cond = gimple_assign_rhs1 (stmt);
4670 TREE_OPERAND (cond, 0) = strncmp_lhs;
4671 TREE_OPERAND (cond, 1) = zero;
4672 }
4673 else
4674 {
4675 gimple_assign_set_rhs1 (stmt, strncmp_lhs);
4676 gimple_assign_set_rhs2 (stmt, zero);
4677 }
4678 }
4679 else
4680 {
4681 gcond *cond = as_a<gcond *> (stmt);
4682 gimple_cond_set_lhs (cond, strncmp_lhs);
4683 gimple_cond_set_rhs (cond, zero);
4684 }
4685 update_stmt (stmt);
4686 }
4687 }
4688 }
4689 }
4690
4691 /* Return true if TYPE corresponds to a narrow character type. */
4692
4693 static bool
4694 is_char_type (tree type)
4695 {
4696 return (TREE_CODE (type) == INTEGER_TYPE
4697 && TYPE_MODE (type) == TYPE_MODE (char_type_node)
4698 && TYPE_PRECISION (type) == TYPE_PRECISION (char_type_node));
4699 }
4700
4701 /* Check the built-in call at GSI for validity and optimize it.
4702 Return true to let the caller advance *GSI to the statement
4703 in the CFG and false otherwise. */
4704
4705 static bool
4706 strlen_check_and_optimize_call (gimple_stmt_iterator *gsi,
4707 bool *zero_write,
4708 const vr_values *rvals)
4709 {
4710 gimple *stmt = gsi_stmt (*gsi);
4711
4712 if (!flag_optimize_strlen
4713 || !strlen_optimize
4714 || !valid_builtin_call (stmt))
4715 {
4716 /* When not optimizing we must be checking printf calls which
4717 we do even for user-defined functions when they are declared
4718 with attribute format. */
4719 handle_printf_call (gsi, rvals);
4720 return true;
4721 }
4722
4723 tree callee = gimple_call_fndecl (stmt);
4724 switch (DECL_FUNCTION_CODE (callee))
4725 {
4726 case BUILT_IN_STRLEN:
4727 case BUILT_IN_STRNLEN:
4728 handle_builtin_strlen (gsi);
4729 break;
4730 case BUILT_IN_STRCHR:
4731 handle_builtin_strchr (gsi);
4732 break;
4733 case BUILT_IN_STRCPY:
4734 case BUILT_IN_STRCPY_CHK:
4735 case BUILT_IN_STPCPY:
4736 case BUILT_IN_STPCPY_CHK:
4737 handle_builtin_strcpy (DECL_FUNCTION_CODE (callee), gsi);
4738 break;
4739
4740 case BUILT_IN_STRNCAT:
4741 case BUILT_IN_STRNCAT_CHK:
4742 handle_builtin_strncat (DECL_FUNCTION_CODE (callee), gsi);
4743 break;
4744
4745 case BUILT_IN_STPNCPY:
4746 case BUILT_IN_STPNCPY_CHK:
4747 case BUILT_IN_STRNCPY:
4748 case BUILT_IN_STRNCPY_CHK:
4749 handle_builtin_stxncpy (DECL_FUNCTION_CODE (callee), gsi);
4750 break;
4751
4752 case BUILT_IN_MEMCPY:
4753 case BUILT_IN_MEMCPY_CHK:
4754 case BUILT_IN_MEMPCPY:
4755 case BUILT_IN_MEMPCPY_CHK:
4756 handle_builtin_memcpy (DECL_FUNCTION_CODE (callee), gsi);
4757 break;
4758 case BUILT_IN_STRCAT:
4759 case BUILT_IN_STRCAT_CHK:
4760 handle_builtin_strcat (DECL_FUNCTION_CODE (callee), gsi);
4761 break;
4762 case BUILT_IN_MALLOC:
4763 case BUILT_IN_CALLOC:
4764 handle_builtin_malloc (DECL_FUNCTION_CODE (callee), gsi);
4765 break;
4766 case BUILT_IN_MEMSET:
4767 if (handle_builtin_memset (gsi, zero_write))
4768 return false;
4769 break;
4770 case BUILT_IN_MEMCMP:
4771 if (handle_builtin_memcmp (gsi))
4772 return false;
4773 break;
4774 case BUILT_IN_STRCMP:
4775 case BUILT_IN_STRNCMP:
4776 if (handle_builtin_string_cmp (gsi))
4777 return false;
4778 break;
4779 default:
4780 handle_printf_call (gsi, rvals);
4781 break;
4782 }
4783
4784 return true;
4785 }
4786
4787 /* Handle an assignment statement at *GSI to a LHS of integral type.
4788 If GSI's basic block needs clean-up of EH, set *CLEANUP_EH to true. */
4789
4790 static void
4791 handle_integral_assign (gimple_stmt_iterator *gsi, bool *cleanup_eh)
4792 {
4793 gimple *stmt = gsi_stmt (*gsi);
4794 tree lhs = gimple_assign_lhs (stmt);
4795 tree lhs_type = TREE_TYPE (lhs);
4796
4797 enum tree_code code = gimple_assign_rhs_code (stmt);
4798 if (code == COND_EXPR)
4799 {
4800 tree cond = gimple_assign_rhs1 (stmt);
4801 enum tree_code cond_code = TREE_CODE (cond);
4802
4803 if (cond_code == EQ_EXPR || cond_code == NE_EXPR)
4804 fold_strstr_to_strncmp (TREE_OPERAND (cond, 0),
4805 TREE_OPERAND (cond, 1), stmt);
4806 }
4807 else if (code == EQ_EXPR || code == NE_EXPR)
4808 fold_strstr_to_strncmp (gimple_assign_rhs1 (stmt),
4809 gimple_assign_rhs2 (stmt), stmt);
4810 else if (gimple_assign_load_p (stmt)
4811 && TREE_CODE (lhs_type) == INTEGER_TYPE
4812 && TYPE_MODE (lhs_type) == TYPE_MODE (char_type_node)
4813 && (TYPE_PRECISION (lhs_type)
4814 == TYPE_PRECISION (char_type_node))
4815 && !gimple_has_volatile_ops (stmt))
4816 {
4817 tree off = integer_zero_node;
4818 unsigned HOST_WIDE_INT coff = 0;
4819 int idx = 0;
4820 tree rhs1 = gimple_assign_rhs1 (stmt);
4821 if (code == MEM_REF)
4822 {
4823 idx = get_stridx (TREE_OPERAND (rhs1, 0));
4824 if (idx > 0)
4825 {
4826 strinfo *si = get_strinfo (idx);
4827 if (si
4828 && si->nonzero_chars
4829 && TREE_CODE (si->nonzero_chars) == INTEGER_CST
4830 && (wi::to_widest (si->nonzero_chars)
4831 >= wi::to_widest (off)))
4832 off = TREE_OPERAND (rhs1, 1);
4833 else
4834 /* This case is not useful. See if get_addr_stridx
4835 returns something usable. */
4836 idx = 0;
4837 }
4838 }
4839 if (idx <= 0)
4840 idx = get_addr_stridx (rhs1, NULL_TREE, &coff);
4841 if (idx > 0)
4842 {
4843 strinfo *si = get_strinfo (idx);
4844 if (si
4845 && si->nonzero_chars
4846 && TREE_CODE (si->nonzero_chars) == INTEGER_CST)
4847 {
4848 widest_int w1 = wi::to_widest (si->nonzero_chars);
4849 widest_int w2 = wi::to_widest (off) + coff;
4850 if (w1 == w2
4851 && si->full_string_p)
4852 {
4853 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
4854 {
4855 fprintf (dump_file, "Optimizing: ");
4856 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
4857 }
4858
4859 /* Reading the final '\0' character. */
4860 tree zero = build_int_cst (lhs_type, 0);
4861 gimple_set_vuse (stmt, NULL_TREE);
4862 gimple_assign_set_rhs_from_tree (gsi, zero);
4863 *cleanup_eh
4864 |= maybe_clean_or_replace_eh_stmt (stmt,
4865 gsi_stmt (*gsi));
4866 stmt = gsi_stmt (*gsi);
4867 update_stmt (stmt);
4868
4869 if (dump_file && (dump_flags & TDF_DETAILS) != 0)
4870 {
4871 fprintf (dump_file, "into: ");
4872 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
4873 }
4874 }
4875 else if (w1 > w2)
4876 {
4877 /* Reading a character before the final '\0'
4878 character. Just set the value range to ~[0, 0]
4879 if we don't have anything better. */
4880 wide_int min, max;
4881 signop sign = TYPE_SIGN (lhs_type);
4882 int prec = TYPE_PRECISION (lhs_type);
4883 value_range_kind vr = get_range_info (lhs, &min, &max);
4884 if (vr == VR_VARYING
4885 || (vr == VR_RANGE
4886 && min == wi::min_value (prec, sign)
4887 && max == wi::max_value (prec, sign)))
4888 set_range_info (lhs, VR_ANTI_RANGE,
4889 wi::zero (prec), wi::zero (prec));
4890 }
4891 }
4892 }
4893 }
4894
4895 if (strlen_to_stridx)
4896 {
4897 tree rhs1 = gimple_assign_rhs1 (stmt);
4898 if (stridx_strlenloc *ps = strlen_to_stridx->get (rhs1))
4899 strlen_to_stridx->put (lhs, stridx_strlenloc (*ps));
4900 }
4901 }
4902
4903 /* Attempt to check for validity of the performed access a single statement
4904 at *GSI using string length knowledge, and to optimize it.
4905 If the given basic block needs clean-up of EH, CLEANUP_EH is set to
4906 true. */
4907
4908 static bool
4909 check_and_optimize_stmt (gimple_stmt_iterator *gsi, bool *cleanup_eh,
4910 const vr_values *rvals)
4911 {
4912 gimple *stmt = gsi_stmt (*gsi);
4913
4914 /* For statements that modify a string, set to true if the write
4915 is only zeros. */
4916 bool zero_write = false;
4917
4918 if (is_gimple_call (stmt))
4919 {
4920 if (!strlen_check_and_optimize_call (gsi, &zero_write, rvals))
4921 return false;
4922 }
4923 else if (!flag_optimize_strlen || !strlen_optimize)
4924 return true;
4925 else if (is_gimple_assign (stmt) && !gimple_clobber_p (stmt))
4926 {
4927 /* Handle non-clobbering assignment. */
4928 tree lhs = gimple_assign_lhs (stmt);
4929 tree lhs_type = TREE_TYPE (lhs);
4930
4931 if (TREE_CODE (lhs) == SSA_NAME && POINTER_TYPE_P (lhs_type))
4932 {
4933 if (gimple_assign_single_p (stmt)
4934 || (gimple_assign_cast_p (stmt)
4935 && POINTER_TYPE_P (TREE_TYPE (gimple_assign_rhs1 (stmt)))))
4936 {
4937 int idx = get_stridx (gimple_assign_rhs1 (stmt));
4938 ssa_ver_to_stridx[SSA_NAME_VERSION (lhs)] = idx;
4939 }
4940 else if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
4941 handle_pointer_plus (gsi);
4942 }
4943 else if (TREE_CODE (lhs) == SSA_NAME && INTEGRAL_TYPE_P (lhs_type))
4944 /* Handle assignment to a character. */
4945 handle_integral_assign (gsi, cleanup_eh);
4946 else if (TREE_CODE (lhs) != SSA_NAME && !TREE_SIDE_EFFECTS (lhs))
4947 {
4948 tree type = TREE_TYPE (lhs);
4949 if (TREE_CODE (type) == ARRAY_TYPE)
4950 type = TREE_TYPE (type);
4951
4952 bool is_char_store = is_char_type (type);
4953 if (!is_char_store && TREE_CODE (lhs) == MEM_REF)
4954 {
4955 /* To consider stores into char objects via integer types
4956 other than char but not those to non-character objects,
4957 determine the type of the destination rather than just
4958 the type of the access. */
4959 tree ref = TREE_OPERAND (lhs, 0);
4960 type = TREE_TYPE (ref);
4961 if (TREE_CODE (type) == POINTER_TYPE)
4962 type = TREE_TYPE (type);
4963 if (TREE_CODE (type) == ARRAY_TYPE)
4964 type = TREE_TYPE (type);
4965 if (is_char_type (type))
4966 is_char_store = true;
4967 }
4968
4969 /* Handle a single or multibyte assignment. */
4970 if (is_char_store && !handle_store (gsi, &zero_write, rvals))
4971 return false;
4972 }
4973 }
4974 else if (gcond *cond = dyn_cast<gcond *> (stmt))
4975 {
4976 enum tree_code code = gimple_cond_code (cond);
4977 if (code == EQ_EXPR || code == NE_EXPR)
4978 fold_strstr_to_strncmp (gimple_cond_lhs (stmt),
4979 gimple_cond_rhs (stmt), stmt);
4980 }
4981
4982 if (gimple_vdef (stmt))
4983 maybe_invalidate (stmt, zero_write);
4984 return true;
4985 }
4986
4987 /* Recursively call maybe_invalidate on stmts that might be executed
4988 in between dombb and current bb and that contain a vdef. Stop when
4989 *count stmts are inspected, or if the whole strinfo vector has
4990 been invalidated. */
4991
4992 static void
4993 do_invalidate (basic_block dombb, gimple *phi, bitmap visited, int *count)
4994 {
4995 unsigned int i, n = gimple_phi_num_args (phi);
4996
4997 for (i = 0; i < n; i++)
4998 {
4999 tree vuse = gimple_phi_arg_def (phi, i);
5000 gimple *stmt = SSA_NAME_DEF_STMT (vuse);
5001 basic_block bb = gimple_bb (stmt);
5002 if (bb == NULL
5003 || bb == dombb
5004 || !bitmap_set_bit (visited, bb->index)
5005 || !dominated_by_p (CDI_DOMINATORS, bb, dombb))
5006 continue;
5007 while (1)
5008 {
5009 if (gimple_code (stmt) == GIMPLE_PHI)
5010 {
5011 do_invalidate (dombb, stmt, visited, count);
5012 if (*count == 0)
5013 return;
5014 break;
5015 }
5016 if (--*count == 0)
5017 return;
5018 if (!maybe_invalidate (stmt))
5019 {
5020 *count = 0;
5021 return;
5022 }
5023 vuse = gimple_vuse (stmt);
5024 stmt = SSA_NAME_DEF_STMT (vuse);
5025 if (gimple_bb (stmt) != bb)
5026 {
5027 bb = gimple_bb (stmt);
5028 if (bb == NULL
5029 || bb == dombb
5030 || !bitmap_set_bit (visited, bb->index)
5031 || !dominated_by_p (CDI_DOMINATORS, bb, dombb))
5032 break;
5033 }
5034 }
5035 }
5036 }
5037
5038 class strlen_dom_walker : public dom_walker
5039 {
5040 public:
5041 strlen_dom_walker (cdi_direction direction)
5042 : dom_walker (direction),
5043 evrp (false),
5044 m_cleanup_cfg (false)
5045 {}
5046
5047 virtual edge before_dom_children (basic_block);
5048 virtual void after_dom_children (basic_block);
5049
5050 /* EVRP analyzer used for printf argument range processing, and
5051 to track strlen results across integer variable assignments. */
5052 evrp_range_analyzer evrp;
5053
5054 /* Flag that will trigger TODO_cleanup_cfg to be returned in strlen
5055 execute function. */
5056 bool m_cleanup_cfg;
5057 };
5058
5059 /* Callback for walk_dominator_tree. Attempt to optimize various
5060 string ops by remembering string lengths pointed by pointer SSA_NAMEs. */
5061
5062 edge
5063 strlen_dom_walker::before_dom_children (basic_block bb)
5064 {
5065 evrp.enter (bb);
5066
5067 basic_block dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
5068
5069 if (dombb == NULL)
5070 stridx_to_strinfo = NULL;
5071 else
5072 {
5073 stridx_to_strinfo = ((vec<strinfo *, va_heap, vl_embed> *) dombb->aux);
5074 if (stridx_to_strinfo)
5075 {
5076 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
5077 gsi_next (&gsi))
5078 {
5079 gphi *phi = gsi.phi ();
5080 if (virtual_operand_p (gimple_phi_result (phi)))
5081 {
5082 bitmap visited = BITMAP_ALLOC (NULL);
5083 int count_vdef = 100;
5084 do_invalidate (dombb, phi, visited, &count_vdef);
5085 BITMAP_FREE (visited);
5086 if (count_vdef == 0)
5087 {
5088 /* If there were too many vdefs in between immediate
5089 dominator and current bb, invalidate everything.
5090 If stridx_to_strinfo has been unshared, we need
5091 to free it, otherwise just set it to NULL. */
5092 if (!strinfo_shared ())
5093 {
5094 unsigned int i;
5095 strinfo *si;
5096
5097 for (i = 1;
5098 vec_safe_iterate (stridx_to_strinfo, i, &si);
5099 ++i)
5100 {
5101 free_strinfo (si);
5102 (*stridx_to_strinfo)[i] = NULL;
5103 }
5104 }
5105 else
5106 stridx_to_strinfo = NULL;
5107 }
5108 break;
5109 }
5110 }
5111 }
5112 }
5113
5114 /* If all PHI arguments have the same string index, the PHI result
5115 has it as well. */
5116 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
5117 gsi_next (&gsi))
5118 {
5119 gphi *phi = gsi.phi ();
5120 tree result = gimple_phi_result (phi);
5121 if (!virtual_operand_p (result) && POINTER_TYPE_P (TREE_TYPE (result)))
5122 {
5123 int idx = get_stridx (gimple_phi_arg_def (phi, 0));
5124 if (idx != 0)
5125 {
5126 unsigned int i, n = gimple_phi_num_args (phi);
5127 for (i = 1; i < n; i++)
5128 if (idx != get_stridx (gimple_phi_arg_def (phi, i)))
5129 break;
5130 if (i == n)
5131 ssa_ver_to_stridx[SSA_NAME_VERSION (result)] = idx;
5132 }
5133 }
5134 }
5135
5136 bool cleanup_eh = false;
5137
5138 /* Attempt to optimize individual statements. */
5139 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
5140 {
5141 gimple *stmt = gsi_stmt (gsi);
5142
5143 /* First record ranges generated by this statement so they
5144 can be used by printf argument processing. */
5145 evrp.record_ranges_from_stmt (stmt, false);
5146
5147 if (check_and_optimize_stmt (&gsi, &cleanup_eh, evrp.get_vr_values ()))
5148 gsi_next (&gsi);
5149 }
5150
5151 if (cleanup_eh && gimple_purge_dead_eh_edges (bb))
5152 m_cleanup_cfg = true;
5153
5154 bb->aux = stridx_to_strinfo;
5155 if (vec_safe_length (stridx_to_strinfo) && !strinfo_shared ())
5156 (*stridx_to_strinfo)[0] = (strinfo *) bb;
5157 return NULL;
5158 }
5159
5160 /* Callback for walk_dominator_tree. Free strinfo vector if it is
5161 owned by the current bb, clear bb->aux. */
5162
5163 void
5164 strlen_dom_walker::after_dom_children (basic_block bb)
5165 {
5166 evrp.leave (bb);
5167
5168 if (bb->aux)
5169 {
5170 stridx_to_strinfo = ((vec<strinfo *, va_heap, vl_embed> *) bb->aux);
5171 if (vec_safe_length (stridx_to_strinfo)
5172 && (*stridx_to_strinfo)[0] == (strinfo *) bb)
5173 {
5174 unsigned int i;
5175 strinfo *si;
5176
5177 for (i = 1; vec_safe_iterate (stridx_to_strinfo, i, &si); ++i)
5178 free_strinfo (si);
5179 vec_free (stridx_to_strinfo);
5180 }
5181 bb->aux = NULL;
5182 }
5183 }
5184
5185 namespace {
5186
5187 static unsigned int
5188 printf_strlen_execute (function *fun, bool warn_only)
5189 {
5190 strlen_optimize = !warn_only;
5191
5192 calculate_dominance_info (CDI_DOMINATORS);
5193
5194 bool use_scev = optimize > 0 && flag_printf_return_value;
5195 if (use_scev)
5196 {
5197 loop_optimizer_init (LOOPS_NORMAL);
5198 scev_initialize ();
5199 }
5200
5201 gcc_assert (!strlen_to_stridx);
5202 if (warn_stringop_overflow || warn_stringop_truncation)
5203 strlen_to_stridx = new hash_map<tree, stridx_strlenloc> ();
5204
5205 /* This has to happen after initializing the loop optimizer
5206 and initializing SCEV as they create new SSA_NAMEs. */
5207 ssa_ver_to_stridx.safe_grow_cleared (num_ssa_names);
5208 max_stridx = 1;
5209
5210 /* String length optimization is implemented as a walk of the dominator
5211 tree and a forward walk of statements within each block. */
5212 strlen_dom_walker walker (CDI_DOMINATORS);
5213 walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
5214
5215 ssa_ver_to_stridx.release ();
5216 strinfo_pool.release ();
5217 if (decl_to_stridxlist_htab)
5218 {
5219 obstack_free (&stridx_obstack, NULL);
5220 delete decl_to_stridxlist_htab;
5221 decl_to_stridxlist_htab = NULL;
5222 }
5223 laststmt.stmt = NULL;
5224 laststmt.len = NULL_TREE;
5225 laststmt.stridx = 0;
5226
5227 if (strlen_to_stridx)
5228 {
5229 strlen_to_stridx->empty ();
5230 delete strlen_to_stridx;
5231 strlen_to_stridx = NULL;
5232 }
5233
5234 if (use_scev)
5235 {
5236 scev_finalize ();
5237 loop_optimizer_finalize ();
5238 }
5239
5240 /* Clean up object size info. */
5241 fini_object_sizes ();
5242
5243 return walker.m_cleanup_cfg ? TODO_cleanup_cfg : 0;
5244 }
5245
5246 /* This file defines two passes: one for warnings that runs only when
5247 optimization is disabled, and another that implements optimizations
5248 and also issues warnings. */
5249
5250 const pass_data pass_data_warn_printf =
5251 {
5252 GIMPLE_PASS, /* type */
5253 "warn-printf", /* name */
5254 OPTGROUP_NONE, /* optinfo_flags */
5255 TV_NONE, /* tv_id */
5256 /* Normally an optimization pass would require PROP_ssa but because
5257 this pass runs early, with no optimization, to do sprintf format
5258 checking, it only requires PROP_cfg. */
5259 PROP_cfg, /* properties_required */
5260 0, /* properties_provided */
5261 0, /* properties_destroyed */
5262 0, /* todo_flags_start */
5263 0, /* todo_flags_finish */
5264 };
5265
5266 class pass_warn_printf : public gimple_opt_pass
5267 {
5268 public:
5269 pass_warn_printf (gcc::context *ctxt)
5270 : gimple_opt_pass (pass_data_warn_printf, ctxt)
5271 {}
5272
5273 virtual bool gate (function *);
5274 virtual unsigned int execute (function *fun)
5275 {
5276 return printf_strlen_execute (fun, true);
5277 }
5278 };
5279
5280
5281 /* Return true to run the warning pass only when not optimizing and
5282 iff either -Wformat-overflow or -Wformat-truncation is specified. */
5283
5284 bool
5285 pass_warn_printf::gate (function *)
5286 {
5287 return !optimize && (warn_format_overflow > 0 || warn_format_trunc > 0);
5288 }
5289
5290 const pass_data pass_data_strlen =
5291 {
5292 GIMPLE_PASS, /* type */
5293 "strlen", /* name */
5294 OPTGROUP_NONE, /* optinfo_flags */
5295 TV_TREE_STRLEN, /* tv_id */
5296 PROP_cfg | PROP_ssa, /* properties_required */
5297 0, /* properties_provided */
5298 0, /* properties_destroyed */
5299 0, /* todo_flags_start */
5300 0, /* todo_flags_finish */
5301 };
5302
5303 class pass_strlen : public gimple_opt_pass
5304 {
5305 public:
5306 pass_strlen (gcc::context *ctxt)
5307 : gimple_opt_pass (pass_data_strlen, ctxt)
5308 {}
5309
5310 opt_pass * clone () { return new pass_strlen (m_ctxt); }
5311
5312 virtual bool gate (function *);
5313 virtual unsigned int execute (function *fun)
5314 {
5315 return printf_strlen_execute (fun, false);
5316 }
5317 };
5318
5319 /* Return true to run the pass only when the sprintf and/or strlen
5320 optimizations are enabled and -Wformat-overflow or -Wformat-truncation
5321 are specified. */
5322
5323 bool
5324 pass_strlen::gate (function *)
5325 {
5326 return ((warn_format_overflow > 0
5327 || warn_format_trunc > 0
5328 || flag_optimize_strlen > 0
5329 || flag_printf_return_value)
5330 && optimize > 0);
5331 }
5332
5333 } // anon namespace
5334
5335 gimple_opt_pass *
5336 make_pass_warn_printf (gcc::context *ctxt)
5337 {
5338 return new pass_warn_printf (ctxt);
5339 }
5340
5341 gimple_opt_pass *
5342 make_pass_strlen (gcc::context *ctxt)
5343 {
5344 return new pass_strlen (ctxt);
5345 }