Home | History | Annotate | Line # | Download | only in gcc
gimple-ssa-warn-access.cc revision 1.1.1.1
      1 /* Pass to detect and issue warnings for invalid accesses, including
      2    invalid or mismatched allocation/deallocation calls.
      3 
      4    Copyright (C) 2020-2022 Free Software Foundation, Inc.
      5    Contributed by Martin Sebor <msebor (at) redhat.com>.
      6 
      7    This file is part of GCC.
      8 
      9    GCC is free software; you can redistribute it and/or modify it under
     10    the terms of the GNU General Public License as published by the Free
     11    Software Foundation; either version 3, or (at your option) any later
     12    version.
     13 
     14    GCC is distributed in the hope that it will be useful, but WITHOUT ANY
     15    WARRANTY; without even the implied warranty of MERCHANTABILITY or
     16    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
     17    for more details.
     18 
     19    You should have received a copy of the GNU General Public License
     20    along with GCC; see the file COPYING3.  If not see
     21    <http://www.gnu.org/licenses/>.  */
     22 
     23 #define INCLUDE_STRING
     24 #include "config.h"
     25 #include "system.h"
     26 #include "coretypes.h"
     27 #include "backend.h"
     28 #include "tree.h"
     29 #include "gimple.h"
     30 #include "tree-pass.h"
     31 #include "builtins.h"
     32 #include "diagnostic.h"
     33 #include "ssa.h"
     34 #include "gimple-pretty-print.h"
     35 #include "gimple-ssa-warn-access.h"
     36 #include "gimple-ssa-warn-restrict.h"
     37 #include "diagnostic-core.h"
     38 #include "fold-const.h"
     39 #include "gimple-fold.h"
     40 #include "gimple-iterator.h"
     41 #include "langhooks.h"
     42 #include "memmodel.h"
     43 #include "target.h"
     44 #include "tree-dfa.h"
     45 #include "tree-ssa.h"
     46 #include "tree-cfg.h"
     47 #include "tree-object-size.h"
     48 #include "tree-ssa-strlen.h"
     49 #include "calls.h"
     50 #include "cfganal.h"
     51 #include "intl.h"
     52 #include "gimple-range.h"
     53 #include "stringpool.h"
     54 #include "attribs.h"
     55 #include "demangle.h"
     56 #include "attr-fnspec.h"
     57 #include "pointer-query.h"
     58 
     59 /* Return true if tree node X has an associated location.  */
     60 
     61 static inline location_t
     62 has_location (const_tree x)
     63 {
     64   if (DECL_P (x))
     65     return DECL_SOURCE_LOCATION (x) != UNKNOWN_LOCATION;
     66 
     67   if (EXPR_P (x))
     68     return EXPR_HAS_LOCATION (x);
     69 
     70   return false;
     71 }
     72 
     73 /* Return the associated location of STMT.  */
     74 
     75 static inline location_t
     76 get_location (const gimple *stmt)
     77 {
     78   return gimple_location (stmt);
     79 }
     80 
     81 /* Return the associated location of tree node X.  */
     82 
     83 static inline location_t
     84 get_location (tree x)
     85 {
     86   if (DECL_P (x))
     87     return DECL_SOURCE_LOCATION (x);
     88 
     89   if (EXPR_P (x))
     90     return EXPR_LOCATION (x);
     91 
     92   return UNKNOWN_LOCATION;
     93 }
     94 
     95 /* Overload of the nascent tree function for GIMPLE STMT.  */
     96 
     97 static inline tree
     98 get_callee_fndecl (const gimple *stmt)
     99 {
    100   return gimple_call_fndecl (stmt);
    101 }
    102 
    103 static inline unsigned
    104 call_nargs (const gimple *stmt)
    105 {
    106   return gimple_call_num_args (stmt);
    107 }
    108 
    109 static inline unsigned
    110 call_nargs (const_tree expr)
    111 {
    112   return call_expr_nargs (expr);
    113 }
    114 
    115 
    116 static inline tree
    117 call_arg (const gimple *stmt, unsigned argno)
    118 {
    119   return gimple_call_arg (stmt, argno);
    120 }
    121 
    122 static inline tree
    123 call_arg (tree expr, unsigned argno)
    124 {
    125   return CALL_EXPR_ARG (expr, argno);
    126 }
    127 
    128 /* For a call EXPR at LOC to a function FNAME that expects a string
    129    in the argument ARG, issue a diagnostic due to it being a called
    130    with an argument that is a character array with no terminating
    131    NUL.  SIZE is the EXACT size of the array, and BNDRNG the number
    132    of characters in which the NUL is expected.  Either EXPR or FNAME
    133    may be null but noth both.  SIZE may be null when BNDRNG is null.  */
    134 
    135 template <class GimpleOrTree>
    136 static void
    137 warn_string_no_nul (location_t loc, GimpleOrTree expr, const char *fname,
    138 		    tree arg, tree decl, tree size, bool exact,
    139 		    const wide_int bndrng[2] /* = NULL */)
    140 {
    141   const opt_code opt = OPT_Wstringop_overread;
    142   if ((expr && warning_suppressed_p (expr, opt))
    143       || warning_suppressed_p (arg, opt))
    144     return;
    145 
    146   loc = expansion_point_location_if_in_system_header (loc);
    147   bool warned;
    148 
    149   /* Format the bound range as a string to keep the number of messages
    150      from exploding.  */
    151   char bndstr[80];
    152   *bndstr = 0;
    153   if (bndrng)
    154     {
    155       if (bndrng[0] == bndrng[1])
    156 	sprintf (bndstr, "%llu", (unsigned long long) bndrng[0].to_uhwi ());
    157       else
    158 	sprintf (bndstr, "[%llu, %llu]",
    159 		 (unsigned long long) bndrng[0].to_uhwi (),
    160 		 (unsigned long long) bndrng[1].to_uhwi ());
    161     }
    162 
    163   const tree maxobjsize = max_object_size ();
    164   const wide_int maxsiz = wi::to_wide (maxobjsize);
    165   if (expr)
    166     {
    167       tree func = get_callee_fndecl (expr);
    168       if (bndrng)
    169 	{
    170 	  if (wi::ltu_p (maxsiz, bndrng[0]))
    171 	    warned = warning_at (loc, opt,
    172 				 "%qD specified bound %s exceeds "
    173 				 "maximum object size %E",
    174 				 func, bndstr, maxobjsize);
    175 	  else
    176 	    {
    177 	      bool maybe = wi::to_wide (size) == bndrng[0];
    178 	      warned = warning_at (loc, opt,
    179 				   exact
    180 				   ? G_("%qD specified bound %s exceeds "
    181 					"the size %E of unterminated array")
    182 				   : (maybe
    183 				      ? G_("%qD specified bound %s may "
    184 					   "exceed the size of at most %E "
    185 					   "of unterminated array")
    186 				      : G_("%qD specified bound %s exceeds "
    187 					   "the size of at most %E "
    188 					   "of unterminated array")),
    189 				   func, bndstr, size);
    190 	    }
    191 	}
    192       else
    193 	warned = warning_at (loc, opt,
    194 			     "%qD argument missing terminating nul",
    195 			     func);
    196     }
    197   else
    198     {
    199       if (bndrng)
    200 	{
    201 	  if (wi::ltu_p (maxsiz, bndrng[0]))
    202 	    warned = warning_at (loc, opt,
    203 				 "%qs specified bound %s exceeds "
    204 				 "maximum object size %E",
    205 				 fname, bndstr, maxobjsize);
    206 	  else
    207 	    {
    208 	      bool maybe = wi::to_wide (size) == bndrng[0];
    209 	      warned = warning_at (loc, opt,
    210 				   exact
    211 				   ? G_("%qs specified bound %s exceeds "
    212 					"the size %E of unterminated array")
    213 				   : (maybe
    214 				      ? G_("%qs specified bound %s may "
    215 					   "exceed the size of at most %E "
    216 					   "of unterminated array")
    217 				      : G_("%qs specified bound %s exceeds "
    218 					   "the size of at most %E "
    219 					   "of unterminated array")),
    220 				   fname, bndstr, size);
    221 	    }
    222 	}
    223       else
    224 	warned = warning_at (loc, opt,
    225 			     "%qs argument missing terminating nul",
    226 			     fname);
    227     }
    228 
    229   if (warned)
    230     {
    231       inform (get_location (decl),
    232 	      "referenced argument declared here");
    233       suppress_warning (arg, opt);
    234       if (expr)
    235 	suppress_warning (expr, opt);
    236     }
    237 }
    238 
    239 void
    240 warn_string_no_nul (location_t loc, gimple *stmt, const char *fname,
    241 		    tree arg, tree decl, tree size /* = NULL_TREE */,
    242 		    bool exact /* = false */,
    243 		    const wide_int bndrng[2] /* = NULL */)
    244 {
    245   return warn_string_no_nul<gimple *> (loc, stmt, fname,
    246 				       arg, decl, size, exact, bndrng);
    247 }
    248 
    249 void
    250 warn_string_no_nul (location_t loc, tree expr, const char *fname,
    251 		    tree arg, tree decl, tree size /* = NULL_TREE */,
    252 		    bool exact /* = false */,
    253 		    const wide_int bndrng[2] /* = NULL */)
    254 {
    255   return warn_string_no_nul<tree> (loc, expr, fname,
    256 				   arg, decl, size, exact, bndrng);
    257 }
    258 
    259 /* If EXP refers to an unterminated constant character array return
    260    the declaration of the object of which the array is a member or
    261    element and if SIZE is not null, set *SIZE to the size of
    262    the unterminated array and set *EXACT if the size is exact or
    263    clear it otherwise.  Otherwise return null.  */
    264 
    265 tree
    266 unterminated_array (tree exp, tree *size /* = NULL */, bool *exact /* = NULL */)
    267 {
    268   /* C_STRLEN will return NULL and set DECL in the info
    269      structure if EXP references a unterminated array.  */
    270   c_strlen_data lendata = { };
    271   tree len = c_strlen (exp, 1, &lendata);
    272   if (len || !lendata.minlen || !lendata.decl)
    273     return NULL_TREE;
    274 
    275   if (!size)
    276     return lendata.decl;
    277 
    278   len = lendata.minlen;
    279   if (lendata.off)
    280     {
    281       /* Constant offsets are already accounted for in LENDATA.MINLEN,
    282 	 but not in a SSA_NAME + CST expression.  */
    283       if (TREE_CODE (lendata.off) == INTEGER_CST)
    284 	*exact = true;
    285       else if (TREE_CODE (lendata.off) == PLUS_EXPR
    286 	       && TREE_CODE (TREE_OPERAND (lendata.off, 1)) == INTEGER_CST)
    287 	{
    288 	  /* Subtract the offset from the size of the array.  */
    289 	  *exact = false;
    290 	  tree temp = TREE_OPERAND (lendata.off, 1);
    291 	  temp = fold_convert (ssizetype, temp);
    292 	  len = fold_build2 (MINUS_EXPR, ssizetype, len, temp);
    293 	}
    294       else
    295 	*exact = false;
    296     }
    297   else
    298     *exact = true;
    299 
    300   *size = len;
    301   return lendata.decl;
    302 }
    303 
    304 /* For a call EXPR (which may be null) that expects a string argument
    305    SRC as an argument, returns false if SRC is a character array with
    306    no terminating NUL.  When nonnull, BOUND is the number of characters
    307    in which to expect the terminating NUL.  When EXPR is nonnull also
    308    issues a warning.  */
    309 
    310 template <class GimpleOrTree>
    311 static bool
    312 check_nul_terminated_array (GimpleOrTree expr, tree src, tree bound)
    313 {
    314   /* The constant size of the array SRC points to.  The actual size
    315      may be less of EXACT is true, but not more.  */
    316   tree size;
    317   /* True if SRC involves a non-constant offset into the array.  */
    318   bool exact;
    319   /* The unterminated constant array SRC points to.  */
    320   tree nonstr = unterminated_array (src, &size, &exact);
    321   if (!nonstr)
    322     return true;
    323 
    324   /* NONSTR refers to the non-nul terminated constant array and SIZE
    325      is the constant size of the array in bytes.  EXACT is true when
    326      SIZE is exact.  */
    327 
    328   wide_int bndrng[2];
    329   if (bound)
    330     {
    331       value_range r;
    332 
    333       get_global_range_query ()->range_of_expr (r, bound);
    334 
    335       if (r.kind () != VR_RANGE)
    336 	return true;
    337 
    338       bndrng[0] = r.lower_bound ();
    339       bndrng[1] = r.upper_bound ();
    340 
    341       if (exact)
    342 	{
    343 	  if (wi::leu_p (bndrng[0], wi::to_wide (size)))
    344 	    return true;
    345 	}
    346       else if (wi::lt_p (bndrng[0], wi::to_wide (size), UNSIGNED))
    347 	return true;
    348     }
    349 
    350   if (expr)
    351     warn_string_no_nul (get_location (expr), expr, NULL, src, nonstr,
    352 			size, exact, bound ? bndrng : NULL);
    353 
    354   return false;
    355 }
    356 
    357 bool
    358 check_nul_terminated_array (gimple *stmt, tree src, tree bound /* = NULL_TREE */)
    359 {
    360   return check_nul_terminated_array<gimple *>(stmt, src, bound);
    361 }
    362 
    363 bool
    364 check_nul_terminated_array (tree expr, tree src, tree bound /* = NULL_TREE */)
    365 {
    366   return check_nul_terminated_array<tree>(expr, src, bound);
    367 }
    368 
    369 /* Warn about passing a non-string array/pointer to a built-in function
    370    that expects a nul-terminated string argument.  Returns true if
    371    a warning has been issued.*/
    372 
    373 template <class GimpleOrTree>
    374 static bool
    375 maybe_warn_nonstring_arg (tree fndecl, GimpleOrTree exp)
    376 {
    377   if (!fndecl || !fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
    378     return false;
    379 
    380   if (!warn_stringop_overread
    381       || warning_suppressed_p (exp, OPT_Wstringop_overread))
    382     return false;
    383 
    384   /* Avoid clearly invalid calls (more checking done below).  */
    385   unsigned nargs = call_nargs (exp);
    386   if (!nargs)
    387     return false;
    388 
    389   /* The bound argument to a bounded string function like strncpy.  */
    390   tree bound = NULL_TREE;
    391 
    392   /* The longest known or possible string argument to one of the comparison
    393      functions.  If the length is less than the bound it is used instead.
    394      Since the length is only used for warning and not for code generation
    395      disable strict mode in the calls to get_range_strlen below.  */
    396   tree maxlen = NULL_TREE;
    397 
    398   /* It's safe to call "bounded" string functions with a non-string
    399      argument since the functions provide an explicit bound for this
    400      purpose.  The exception is strncat where the bound may refer to
    401      either the destination or the source.  */
    402   int fncode = DECL_FUNCTION_CODE (fndecl);
    403   switch (fncode)
    404     {
    405     case BUILT_IN_STRCMP:
    406     case BUILT_IN_STRNCMP:
    407     case BUILT_IN_STRNCASECMP:
    408       {
    409 	/* For these, if one argument refers to one or more of a set
    410 	   of string constants or arrays of known size, determine
    411 	   the range of their known or possible lengths and use it
    412 	   conservatively as the bound for the unbounded function,
    413 	   and to adjust the range of the bound of the bounded ones.  */
    414 	for (unsigned argno = 0;
    415 	     argno < MIN (nargs, 2)
    416 	       && !(maxlen && TREE_CODE (maxlen) == INTEGER_CST); argno++)
    417 	  {
    418 	    tree arg = call_arg (exp, argno);
    419 	    if (!get_attr_nonstring_decl (arg))
    420 	      {
    421 		c_strlen_data lendata = { };
    422 		/* Set MAXBOUND to an arbitrary non-null non-integer
    423 		   node as a request to have it set to the length of
    424 		   the longest string in a PHI.  */
    425 		lendata.maxbound = arg;
    426 		get_range_strlen (arg, &lendata, /* eltsize = */ 1);
    427 		maxlen = lendata.maxbound;
    428 	      }
    429 	  }
    430       }
    431       /* Fall through.  */
    432 
    433     case BUILT_IN_STRNCAT:
    434     case BUILT_IN_STPNCPY:
    435     case BUILT_IN_STRNCPY:
    436       if (nargs > 2)
    437 	bound = call_arg (exp, 2);
    438       break;
    439 
    440     case BUILT_IN_STRNDUP:
    441       if (nargs < 2)
    442 	return false;
    443       bound = call_arg (exp, 1);
    444       break;
    445 
    446     case BUILT_IN_STRNLEN:
    447       {
    448 	tree arg = call_arg (exp, 0);
    449 	if (!get_attr_nonstring_decl (arg))
    450 	  {
    451 	    c_strlen_data lendata = { };
    452 	    /* Set MAXBOUND to an arbitrary non-null non-integer
    453 	       node as a request to have it set to the length of
    454 	       the longest string in a PHI.  */
    455 	    lendata.maxbound = arg;
    456 	    get_range_strlen (arg, &lendata, /* eltsize = */ 1);
    457 	    maxlen = lendata.maxbound;
    458 	  }
    459 	if (nargs > 1)
    460 	  bound = call_arg (exp, 1);
    461 	break;
    462       }
    463 
    464     default:
    465       break;
    466     }
    467 
    468   /* Determine the range of the bound argument (if specified).  */
    469   tree bndrng[2] = { NULL_TREE, NULL_TREE };
    470   if (bound)
    471     {
    472       STRIP_NOPS (bound);
    473       get_size_range (bound, bndrng);
    474     }
    475 
    476   location_t loc = get_location (exp);
    477 
    478   if (bndrng[0])
    479     {
    480       /* Diagnose excessive bound prior to the adjustment below and
    481 	 regardless of attribute nonstring.  */
    482       tree maxobjsize = max_object_size ();
    483       if (tree_int_cst_lt (maxobjsize, bndrng[0]))
    484 	{
    485 	  bool warned = false;
    486 	  if (tree_int_cst_equal (bndrng[0], bndrng[1]))
    487 	    warned = warning_at (loc, OPT_Wstringop_overread,
    488 				 "%qD specified bound %E "
    489 				 "exceeds maximum object size %E",
    490 				 fndecl, bndrng[0], maxobjsize);
    491 	  else
    492 	    warned = warning_at (loc, OPT_Wstringop_overread,
    493 				 "%qD specified bound [%E, %E] "
    494 				 "exceeds maximum object size %E",
    495 				 fndecl, bndrng[0], bndrng[1],
    496 				 maxobjsize);
    497 	  if (warned)
    498 	    suppress_warning (exp, OPT_Wstringop_overread);
    499 
    500 	  return warned;
    501 	}
    502     }
    503 
    504   if (maxlen && !integer_all_onesp (maxlen))
    505     {
    506       /* Add one for the nul.  */
    507       maxlen = const_binop (PLUS_EXPR, TREE_TYPE (maxlen), maxlen,
    508 			    size_one_node);
    509 
    510       if (!bndrng[0])
    511 	{
    512 	  /* Conservatively use the upper bound of the lengths for
    513 	     both the lower and the upper bound of the operation.  */
    514 	  bndrng[0] = maxlen;
    515 	  bndrng[1] = maxlen;
    516 	  bound = void_type_node;
    517 	}
    518       else if (maxlen)
    519 	{
    520 	  /* Replace the bound on the operation with the upper bound
    521 	     of the length of the string if the latter is smaller.  */
    522 	  if (tree_int_cst_lt (maxlen, bndrng[0]))
    523 	    bndrng[0] = maxlen;
    524 	  else if (tree_int_cst_lt (maxlen, bndrng[1]))
    525 	    bndrng[1] = maxlen;
    526 	}
    527     }
    528 
    529   bool any_arg_warned = false;
    530   /* Iterate over the built-in function's formal arguments and check
    531      each const char* against the actual argument.  If the actual
    532      argument is declared attribute non-string issue a warning unless
    533      the argument's maximum length is bounded.  */
    534   function_args_iterator it;
    535   function_args_iter_init (&it, TREE_TYPE (fndecl));
    536 
    537   for (unsigned argno = 0; ; ++argno, function_args_iter_next (&it))
    538     {
    539       /* Avoid iterating past the declared argument in a call
    540 	 to function declared without a prototype.  */
    541       if (argno >= nargs)
    542 	break;
    543 
    544       tree argtype = function_args_iter_cond (&it);
    545       if (!argtype)
    546 	break;
    547 
    548       if (TREE_CODE (argtype) != POINTER_TYPE)
    549 	continue;
    550 
    551       argtype = TREE_TYPE (argtype);
    552 
    553       if (TREE_CODE (argtype) != INTEGER_TYPE
    554 	  || !TYPE_READONLY (argtype))
    555 	continue;
    556 
    557       argtype = TYPE_MAIN_VARIANT (argtype);
    558       if (argtype != char_type_node)
    559 	continue;
    560 
    561       tree callarg = call_arg (exp, argno);
    562       if (TREE_CODE (callarg) == ADDR_EXPR)
    563 	callarg = TREE_OPERAND (callarg, 0);
    564 
    565       /* See if the destination is declared with attribute "nonstring".  */
    566       tree decl = get_attr_nonstring_decl (callarg);
    567       if (!decl)
    568 	continue;
    569 
    570       /* The maximum number of array elements accessed.  */
    571       offset_int wibnd = 0;
    572 
    573       if (argno && fncode == BUILT_IN_STRNCAT)
    574 	{
    575 	  /* See if the bound in strncat is derived from the length
    576 	     of the strlen of the destination (as it's expected to be).
    577 	     If so, reset BOUND and FNCODE to trigger a warning.  */
    578 	  tree dstarg = call_arg (exp, 0);
    579 	  if (is_strlen_related_p (dstarg, bound))
    580 	    {
    581 	      /* The bound applies to the destination, not to the source,
    582 		 so reset these to trigger a warning without mentioning
    583 		 the bound.  */
    584 	      bound = NULL;
    585 	      fncode = 0;
    586 	    }
    587 	  else if (bndrng[1])
    588 	    /* Use the upper bound of the range for strncat.  */
    589 	    wibnd = wi::to_offset (bndrng[1]);
    590 	}
    591       else if (bndrng[0])
    592 	/* Use the lower bound of the range for functions other than
    593 	   strncat.  */
    594 	wibnd = wi::to_offset (bndrng[0]);
    595 
    596       /* Determine the size of the argument array if it is one.  */
    597       offset_int asize = wibnd;
    598       bool known_size = false;
    599       tree type = TREE_TYPE (decl);
    600 
    601       /* Determine the array size.  For arrays of unknown bound and
    602 	 pointers reset BOUND to trigger the appropriate warning.  */
    603       if (TREE_CODE (type) == ARRAY_TYPE)
    604 	{
    605 	  if (tree arrbnd = TYPE_DOMAIN (type))
    606 	    {
    607 	      if ((arrbnd = TYPE_MAX_VALUE (arrbnd))
    608 		  && TREE_CODE (arrbnd) == INTEGER_CST)
    609 		{
    610 		  asize = wi::to_offset (arrbnd) + 1;
    611 		  known_size = true;
    612 		}
    613 	    }
    614 	  else if (bound == void_type_node)
    615 	    bound = NULL_TREE;
    616 	}
    617       else if (bound == void_type_node)
    618 	bound = NULL_TREE;
    619 
    620       /* In a call to strncat with a bound in a range whose lower but
    621 	 not upper bound is less than the array size, reset ASIZE to
    622 	 be the same as the bound and the other variable to trigger
    623 	 the appropriate warning below.  */
    624       if (fncode == BUILT_IN_STRNCAT
    625 	  && bndrng[0] != bndrng[1]
    626 	  && wi::ltu_p (wi::to_offset (bndrng[0]), asize)
    627 	  && (!known_size
    628 	      || wi::ltu_p (asize, wibnd)))
    629 	{
    630 	  asize = wibnd;
    631 	  bound = NULL_TREE;
    632 	  fncode = 0;
    633 	}
    634 
    635       bool warned = false;
    636 
    637       auto_diagnostic_group d;
    638       if (wi::ltu_p (asize, wibnd))
    639 	{
    640 	  if (bndrng[0] == bndrng[1])
    641 	    warned = warning_at (loc, OPT_Wstringop_overread,
    642 				 "%qD argument %i declared attribute "
    643 				 "%<nonstring%> is smaller than the specified "
    644 				 "bound %wu",
    645 				 fndecl, argno + 1, wibnd.to_uhwi ());
    646 	  else if (wi::ltu_p (asize, wi::to_offset (bndrng[0])))
    647 	    warned = warning_at (loc, OPT_Wstringop_overread,
    648 				 "%qD argument %i declared attribute "
    649 				 "%<nonstring%> is smaller than "
    650 				 "the specified bound [%E, %E]",
    651 				 fndecl, argno + 1, bndrng[0], bndrng[1]);
    652 	  else
    653 	    warned = warning_at (loc, OPT_Wstringop_overread,
    654 				 "%qD argument %i declared attribute "
    655 				 "%<nonstring%> may be smaller than "
    656 				 "the specified bound [%E, %E]",
    657 				 fndecl, argno + 1, bndrng[0], bndrng[1]);
    658 	}
    659       else if (fncode == BUILT_IN_STRNCAT)
    660 	; /* Avoid warning for calls to strncat() when the bound
    661 	     is equal to the size of the non-string argument.  */
    662       else if (!bound)
    663 	warned = warning_at (loc, OPT_Wstringop_overread,
    664 			     "%qD argument %i declared attribute %<nonstring%>",
    665 			     fndecl, argno + 1);
    666 
    667       if (warned)
    668 	{
    669 	  inform (DECL_SOURCE_LOCATION (decl),
    670 		  "argument %qD declared here", decl);
    671 	  any_arg_warned = true;
    672 	}
    673     }
    674 
    675   if (any_arg_warned)
    676     suppress_warning (exp, OPT_Wstringop_overread);
    677 
    678   return any_arg_warned;
    679 }
    680 
    681 bool
    682 maybe_warn_nonstring_arg (tree fndecl, gimple *stmt)
    683 {
    684   return maybe_warn_nonstring_arg<gimple *>(fndecl, stmt);
    685 }
    686 
    687 
    688 bool
    689 maybe_warn_nonstring_arg (tree fndecl, tree expr)
    690 {
    691   return maybe_warn_nonstring_arg<tree>(fndecl, expr);
    692 }
    693 
    694 /* Issue a warning OPT for a bounded call EXP with a bound in RANGE
    695    accessing an object with SIZE.  */
    696 
    697 template <class GimpleOrTree>
    698 static bool
    699 maybe_warn_for_bound (opt_code opt, location_t loc, GimpleOrTree exp, tree func,
    700 		      tree bndrng[2], tree size, const access_data *pad)
    701 {
    702   if (!bndrng[0] || warning_suppressed_p (exp, opt))
    703     return false;
    704 
    705   tree maxobjsize = max_object_size ();
    706 
    707   bool warned = false;
    708 
    709   if (opt == OPT_Wstringop_overread)
    710     {
    711       bool maybe = pad && pad->src.phi ();
    712       if (maybe)
    713 	{
    714 	  /* Issue a "maybe" warning only if the PHI refers to objects
    715 	     at least one of which has more space remaining than the bound.
    716 	     Otherwise, if the bound is greater, use the definitive form.  */
    717 	  offset_int remmax = pad->src.size_remaining ();
    718 	  if (remmax < wi::to_offset (bndrng[0]))
    719 	    maybe = false;
    720 	}
    721 
    722       if (tree_int_cst_lt (maxobjsize, bndrng[0]))
    723 	{
    724 	  if (bndrng[0] == bndrng[1])
    725 	    warned = (func
    726 		      ? warning_at (loc, opt,
    727 				    (maybe
    728 				     ? G_("%qD specified bound %E may "
    729 					  "exceed maximum object size %E")
    730 				     : G_("%qD specified bound %E "
    731 					  "exceeds maximum object size %E")),
    732 				    func, bndrng[0], maxobjsize)
    733 		      : warning_at (loc, opt,
    734 				    (maybe
    735 				     ? G_("specified bound %E may "
    736 					  "exceed maximum object size %E")
    737 				     : G_("specified bound %E "
    738 					  "exceeds maximum object size %E")),
    739 				    bndrng[0], maxobjsize));
    740 	  else
    741 	    warned = (func
    742 		      ? warning_at (loc, opt,
    743 				    (maybe
    744 				     ? G_("%qD specified bound [%E, %E] may "
    745 					  "exceed maximum object size %E")
    746 				     : G_("%qD specified bound [%E, %E] "
    747 					  "exceeds maximum object size %E")),
    748 				    func,
    749 				    bndrng[0], bndrng[1], maxobjsize)
    750 		      : warning_at (loc, opt,
    751 				    (maybe
    752 				     ? G_("specified bound [%E, %E] may "
    753 					  "exceed maximum object size %E")
    754 				     : G_("specified bound [%E, %E] "
    755 					  "exceeds maximum object size %E")),
    756 				    bndrng[0], bndrng[1], maxobjsize));
    757 	}
    758       else if (!size || tree_int_cst_le (bndrng[0], size))
    759 	return false;
    760       else if (tree_int_cst_equal (bndrng[0], bndrng[1]))
    761 	warned = (func
    762 		  ? warning_at (loc, opt,
    763 				(maybe
    764 				 ? G_("%qD specified bound %E may exceed "
    765 				      "source size %E")
    766 				 : G_("%qD specified bound %E exceeds "
    767 				      "source size %E")),
    768 				func, bndrng[0], size)
    769 		  : warning_at (loc, opt,
    770 				(maybe
    771 				 ? G_("specified bound %E may exceed "
    772 				      "source size %E")
    773 				 : G_("specified bound %E exceeds "
    774 				      "source size %E")),
    775 				bndrng[0], size));
    776       else
    777 	warned = (func
    778 		  ? warning_at (loc, opt,
    779 				(maybe
    780 				 ? G_("%qD specified bound [%E, %E] may "
    781 				      "exceed source size %E")
    782 				 : G_("%qD specified bound [%E, %E] exceeds "
    783 				      "source size %E")),
    784 				func, bndrng[0], bndrng[1], size)
    785 		  : warning_at (loc, opt,
    786 				(maybe
    787 				 ? G_("specified bound [%E, %E] may exceed "
    788 				      "source size %E")
    789 				 : G_("specified bound [%E, %E] exceeds "
    790 				      "source size %E")),
    791 				bndrng[0], bndrng[1], size));
    792       if (warned)
    793 	{
    794 	  if (pad && pad->src.ref
    795 	      && has_location (pad->src.ref))
    796 	    inform (get_location (pad->src.ref),
    797 		    "source object allocated here");
    798 	  suppress_warning (exp, opt);
    799 	}
    800 
    801       return warned;
    802     }
    803 
    804   bool maybe = pad && pad->dst.phi ();
    805   if (maybe)
    806     {
    807       /* Issue a "maybe" warning only if the PHI refers to objects
    808 	 at least one of which has more space remaining than the bound.
    809 	 Otherwise, if the bound is greater, use the definitive form.  */
    810       offset_int remmax = pad->dst.size_remaining ();
    811       if (remmax < wi::to_offset (bndrng[0]))
    812 	maybe = false;
    813     }
    814   if (tree_int_cst_lt (maxobjsize, bndrng[0]))
    815     {
    816       if (bndrng[0] == bndrng[1])
    817 	warned = (func
    818 		  ? warning_at (loc, opt,
    819 				(maybe
    820 				 ? G_("%qD specified size %E may "
    821 				      "exceed maximum object size %E")
    822 				 : G_("%qD specified size %E "
    823 				      "exceeds maximum object size %E")),
    824 				func, bndrng[0], maxobjsize)
    825 		  : warning_at (loc, opt,
    826 				(maybe
    827 				 ? G_("specified size %E may exceed "
    828 				      "maximum object size %E")
    829 				 : G_("specified size %E exceeds "
    830 				      "maximum object size %E")),
    831 				bndrng[0], maxobjsize));
    832       else
    833 	warned = (func
    834 		  ? warning_at (loc, opt,
    835 				(maybe
    836 				 ? G_("%qD specified size between %E and %E "
    837 				      "may exceed maximum object size %E")
    838 				 : G_("%qD specified size between %E and %E "
    839 				      "exceeds maximum object size %E")),
    840 				func, bndrng[0], bndrng[1], maxobjsize)
    841 		  : warning_at (loc, opt,
    842 				(maybe
    843 				 ? G_("specified size between %E and %E "
    844 				      "may exceed maximum object size %E")
    845 				 : G_("specified size between %E and %E "
    846 				      "exceeds maximum object size %E")),
    847 				bndrng[0], bndrng[1], maxobjsize));
    848     }
    849   else if (!size || tree_int_cst_le (bndrng[0], size))
    850     return false;
    851   else if (tree_int_cst_equal (bndrng[0], bndrng[1]))
    852     warned = (func
    853 	      ? warning_at (loc, opt,
    854 			    (maybe
    855 			     ? G_("%qD specified bound %E may exceed "
    856 				  "destination size %E")
    857 			     : G_("%qD specified bound %E exceeds "
    858 				  "destination size %E")),
    859 			    func, bndrng[0], size)
    860 	      : warning_at (loc, opt,
    861 			    (maybe
    862 			     ? G_("specified bound %E may exceed "
    863 				  "destination size %E")
    864 			     : G_("specified bound %E exceeds "
    865 				  "destination size %E")),
    866 			    bndrng[0], size));
    867   else
    868     warned = (func
    869 	      ? warning_at (loc, opt,
    870 			    (maybe
    871 			     ? G_("%qD specified bound [%E, %E] may exceed "
    872 				  "destination size %E")
    873 			     : G_("%qD specified bound [%E, %E] exceeds "
    874 				  "destination size %E")),
    875 			    func, bndrng[0], bndrng[1], size)
    876 	      : warning_at (loc, opt,
    877 			    (maybe
    878 			     ? G_("specified bound [%E, %E] exceeds "
    879 				  "destination size %E")
    880 			     : G_("specified bound [%E, %E] exceeds "
    881 				  "destination size %E")),
    882 			    bndrng[0], bndrng[1], size));
    883 
    884   if (warned)
    885     {
    886       if (pad && pad->dst.ref
    887 	  && has_location (pad->dst.ref))
    888 	inform (get_location (pad->dst.ref),
    889 		"destination object allocated here");
    890       suppress_warning (exp, opt);
    891     }
    892 
    893   return warned;
    894 }
    895 
    896 bool
    897 maybe_warn_for_bound (opt_code opt, location_t loc, gimple *stmt, tree func,
    898 		      tree bndrng[2], tree size,
    899 		      const access_data *pad /* = NULL */)
    900 {
    901   return maybe_warn_for_bound<gimple *> (opt, loc, stmt, func, bndrng, size,
    902 					 pad);
    903 }
    904 
    905 bool
    906 maybe_warn_for_bound (opt_code opt, location_t loc, tree expr, tree func,
    907 		      tree bndrng[2], tree size,
    908 		      const access_data *pad /* = NULL */)
    909 {
    910   return maybe_warn_for_bound<tree> (opt, loc, expr, func, bndrng, size, pad);
    911 }
    912 
    913 /* For an expression EXP issue an access warning controlled by option OPT
    914    with access to a region SIZE bytes in size in the RANGE of sizes.
    915    WRITE is true for a write access, READ for a read access, neither for
    916    call that may or may not perform an access but for which the range
    917    is expected to valid.
    918    Returns true when a warning has been issued.  */
    919 
    920 template <class GimpleOrTree>
    921 static bool
    922 warn_for_access (location_t loc, tree func, GimpleOrTree exp, int opt,
    923 		 tree range[2], tree size, bool write, bool read, bool maybe)
    924 {
    925   bool warned = false;
    926 
    927   if (write && read)
    928     {
    929       if (tree_int_cst_equal (range[0], range[1]))
    930 	warned = (func
    931 		  ? warning_n (loc, opt, tree_to_uhwi (range[0]),
    932 			       (maybe
    933 				? G_("%qD may access %E byte in a region "
    934 				     "of size %E")
    935 				: G_("%qD accessing %E byte in a region "
    936 				     "of size %E")),
    937 				(maybe
    938 				 ? G_ ("%qD may access %E bytes in a region "
    939 				       "of size %E")
    940 				 : G_ ("%qD accessing %E bytes in a region "
    941 				       "of size %E")),
    942 			       func, range[0], size)
    943 		  : warning_n (loc, opt, tree_to_uhwi (range[0]),
    944 			       (maybe
    945 				? G_("may access %E byte in a region "
    946 				     "of size %E")
    947 				: G_("accessing %E byte in a region "
    948 				     "of size %E")),
    949 			       (maybe
    950 				? G_("may access %E bytes in a region "
    951 				     "of size %E")
    952 				: G_("accessing %E bytes in a region "
    953 				     "of size %E")),
    954 			       range[0], size));
    955       else if (tree_int_cst_sign_bit (range[1]))
    956 	{
    957 	  /* Avoid printing the upper bound if it's invalid.  */
    958 	  warned = (func
    959 		    ? warning_at (loc, opt,
    960 				  (maybe
    961 				   ? G_("%qD may access %E or more bytes "
    962 					"in a region of size %E")
    963 				   : G_("%qD accessing %E or more bytes "
    964 					"in a region of size %E")),
    965 				  func, range[0], size)
    966 		    : warning_at (loc, opt,
    967 				  (maybe
    968 				   ? G_("may access %E or more bytes "
    969 					"in a region of size %E")
    970 				   : G_("accessing %E or more bytes "
    971 					"in a region of size %E")),
    972 				  range[0], size));
    973 	}
    974       else
    975 	warned = (func
    976 		  ? warning_at (loc, opt,
    977 				(maybe
    978 				 ? G_("%qD may access between %E and %E "
    979 				      "bytes in a region of size %E")
    980 				 : G_("%qD accessing between %E and %E "
    981 				      "bytes in a region of size %E")),
    982 				func, range[0], range[1], size)
    983 		  : warning_at (loc, opt,
    984 				(maybe
    985 				 ? G_("may access between %E and %E bytes "
    986 				      "in a region of size %E")
    987 				 : G_("accessing between %E and %E bytes "
    988 				      "in a region of size %E")),
    989 				range[0], range[1], size));
    990       return warned;
    991     }
    992 
    993   if (write)
    994     {
    995       if (tree_int_cst_equal (range[0], range[1]))
    996 	warned = (func
    997 		  ? warning_n (loc, opt, tree_to_uhwi (range[0]),
    998 			       (maybe
    999 				? G_("%qD may write %E byte into a region "
   1000 				     "of size %E")
   1001 				: G_("%qD writing %E byte into a region "
   1002 				     "of size %E overflows the destination")),
   1003 			       (maybe
   1004 				? G_("%qD may write %E bytes into a region "
   1005 				     "of size %E")
   1006 				: G_("%qD writing %E bytes into a region "
   1007 				     "of size %E overflows the destination")),
   1008 			       func, range[0], size)
   1009 		  : warning_n (loc, opt, tree_to_uhwi (range[0]),
   1010 			       (maybe
   1011 				? G_("may write %E byte into a region "
   1012 				     "of size %E")
   1013 				: G_("writing %E byte into a region "
   1014 				     "of size %E overflows the destination")),
   1015 			       (maybe
   1016 				? G_("may write %E bytes into a region "
   1017 				     "of size %E")
   1018 				: G_("writing %E bytes into a region "
   1019 				     "of size %E overflows the destination")),
   1020 			       range[0], size));
   1021       else if (tree_int_cst_sign_bit (range[1]))
   1022 	{
   1023 	  /* Avoid printing the upper bound if it's invalid.  */
   1024 	  warned = (func
   1025 		    ? warning_at (loc, opt,
   1026 				  (maybe
   1027 				   ? G_("%qD may write %E or more bytes "
   1028 					"into a region of size %E")
   1029 				   : G_("%qD writing %E or more bytes "
   1030 					"into a region of size %E overflows "
   1031 					"the destination")),
   1032 				  func, range[0], size)
   1033 		    : warning_at (loc, opt,
   1034 				  (maybe
   1035 				   ? G_("may write %E or more bytes into "
   1036 					"a region of size %E")
   1037 				   : G_("writing %E or more bytes into "
   1038 					"a region of size %E overflows "
   1039 					"the destination")),
   1040 				  range[0], size));
   1041 	}
   1042       else
   1043 	warned = (func
   1044 		  ? warning_at (loc, opt,
   1045 				(maybe
   1046 				 ? G_("%qD may write between %E and %E bytes "
   1047 				      "into a region of size %E")
   1048 				 : G_("%qD writing between %E and %E bytes "
   1049 				      "into a region of size %E overflows "
   1050 				      "the destination")),
   1051 				func, range[0], range[1], size)
   1052 		  : warning_at (loc, opt,
   1053 				(maybe
   1054 				 ? G_("may write between %E and %E bytes "
   1055 				      "into a region of size %E")
   1056 				 : G_("writing between %E and %E bytes "
   1057 				      "into a region of size %E overflows "
   1058 				      "the destination")),
   1059 				range[0], range[1], size));
   1060       return warned;
   1061     }
   1062 
   1063   if (read)
   1064     {
   1065       if (tree_int_cst_equal (range[0], range[1]))
   1066 	warned = (func
   1067 		  ? warning_n (loc, OPT_Wstringop_overread,
   1068 			       tree_to_uhwi (range[0]),
   1069 			       (maybe
   1070 				? G_("%qD may read %E byte from a region "
   1071 				     "of size %E")
   1072 				: G_("%qD reading %E byte from a region "
   1073 				     "of size %E")),
   1074 			       (maybe
   1075 				? G_("%qD may read %E bytes from a region "
   1076 				     "of size %E")
   1077 				: G_("%qD reading %E bytes from a region "
   1078 				     "of size %E")),
   1079 			       func, range[0], size)
   1080 		  : warning_n (loc, OPT_Wstringop_overread,
   1081 			       tree_to_uhwi (range[0]),
   1082 			       (maybe
   1083 				? G_("may read %E byte from a region "
   1084 				     "of size %E")
   1085 				: G_("reading %E byte from a region "
   1086 				     "of size %E")),
   1087 			       (maybe
   1088 				? G_("may read %E bytes from a region "
   1089 				     "of size %E")
   1090 				: G_("reading %E bytes from a region "
   1091 				     "of size %E")),
   1092 			       range[0], size));
   1093       else if (tree_int_cst_sign_bit (range[1]))
   1094 	{
   1095 	  /* Avoid printing the upper bound if it's invalid.  */
   1096 	  warned = (func
   1097 		    ? warning_at (loc, OPT_Wstringop_overread,
   1098 				  (maybe
   1099 				   ? G_("%qD may read %E or more bytes "
   1100 					"from a region of size %E")
   1101 				   : G_("%qD reading %E or more bytes "
   1102 					"from a region of size %E")),
   1103 				  func, range[0], size)
   1104 		    : warning_at (loc, OPT_Wstringop_overread,
   1105 				  (maybe
   1106 				   ? G_("may read %E or more bytes "
   1107 					"from a region of size %E")
   1108 				   : G_("reading %E or more bytes "
   1109 					"from a region of size %E")),
   1110 				  range[0], size));
   1111 	}
   1112       else
   1113 	warned = (func
   1114 		  ? warning_at (loc, OPT_Wstringop_overread,
   1115 				(maybe
   1116 				 ? G_("%qD may read between %E and %E bytes "
   1117 				      "from a region of size %E")
   1118 				 : G_("%qD reading between %E and %E bytes "
   1119 				      "from a region of size %E")),
   1120 				func, range[0], range[1], size)
   1121 		  : warning_at (loc, opt,
   1122 				(maybe
   1123 				 ? G_("may read between %E and %E bytes "
   1124 				      "from a region of size %E")
   1125 				 : G_("reading between %E and %E bytes "
   1126 				      "from a region of size %E")),
   1127 				range[0], range[1], size));
   1128 
   1129       if (warned)
   1130 	suppress_warning (exp, OPT_Wstringop_overread);
   1131 
   1132       return warned;
   1133     }
   1134 
   1135   if (tree_int_cst_equal (range[0], range[1])
   1136       || tree_int_cst_sign_bit (range[1]))
   1137     warned = (func
   1138 	      ? warning_n (loc, OPT_Wstringop_overread,
   1139 			   tree_to_uhwi (range[0]),
   1140 			   "%qD expecting %E byte in a region of size %E",
   1141 			   "%qD expecting %E bytes in a region of size %E",
   1142 			   func, range[0], size)
   1143 	      : warning_n (loc, OPT_Wstringop_overread,
   1144 			   tree_to_uhwi (range[0]),
   1145 			   "expecting %E byte in a region of size %E",
   1146 			   "expecting %E bytes in a region of size %E",
   1147 			   range[0], size));
   1148   else if (tree_int_cst_sign_bit (range[1]))
   1149     {
   1150       /* Avoid printing the upper bound if it's invalid.  */
   1151       warned = (func
   1152 		? warning_at (loc, OPT_Wstringop_overread,
   1153 			      "%qD expecting %E or more bytes in a region "
   1154 			      "of size %E",
   1155 			      func, range[0], size)
   1156 		: warning_at (loc, OPT_Wstringop_overread,
   1157 			      "expecting %E or more bytes in a region "
   1158 			      "of size %E",
   1159 			      range[0], size));
   1160     }
   1161   else
   1162     warned = (func
   1163 	      ? warning_at (loc, OPT_Wstringop_overread,
   1164 			    "%qD expecting between %E and %E bytes in "
   1165 			    "a region of size %E",
   1166 			    func, range[0], range[1], size)
   1167 	      : warning_at (loc, OPT_Wstringop_overread,
   1168 			    "expecting between %E and %E bytes in "
   1169 			    "a region of size %E",
   1170 			    range[0], range[1], size));
   1171 
   1172   if (warned)
   1173     suppress_warning (exp, OPT_Wstringop_overread);
   1174 
   1175   return warned;
   1176 }
   1177 
   1178 static bool
   1179 warn_for_access (location_t loc, tree func, gimple *stmt, int opt,
   1180 		 tree range[2], tree size, bool write, bool read, bool maybe)
   1181 {
   1182   return warn_for_access<gimple *>(loc, func, stmt, opt, range, size,
   1183 				   write, read, maybe);
   1184 }
   1185 
   1186 static bool
   1187 warn_for_access (location_t loc, tree func, tree expr, int opt,
   1188 		 tree range[2], tree size, bool write, bool read, bool maybe)
   1189 {
   1190   return warn_for_access<tree>(loc, func, expr, opt, range, size,
   1191 			       write, read, maybe);
   1192 }
   1193 
   1194 /* Helper to set RANGE to the range of BOUND if it's nonnull, bounded
   1195    by BNDRNG if nonnull and valid.  */
   1196 
   1197 static void
   1198 get_size_range (range_query *query, tree bound, gimple *stmt, tree range[2],
   1199 		const offset_int bndrng[2])
   1200 {
   1201   if (bound)
   1202     get_size_range (query, bound, stmt, range);
   1203 
   1204   if (!bndrng || (bndrng[0] == 0 && bndrng[1] == HOST_WIDE_INT_M1U))
   1205     return;
   1206 
   1207   if (range[0] && TREE_CODE (range[0]) == INTEGER_CST)
   1208     {
   1209       offset_int r[] =
   1210 	{ wi::to_offset (range[0]), wi::to_offset (range[1]) };
   1211       if (r[0] < bndrng[0])
   1212 	range[0] = wide_int_to_tree (sizetype, bndrng[0]);
   1213       if (bndrng[1] < r[1])
   1214 	range[1] = wide_int_to_tree (sizetype, bndrng[1]);
   1215     }
   1216   else
   1217     {
   1218       range[0] = wide_int_to_tree (sizetype, bndrng[0]);
   1219       range[1] = wide_int_to_tree (sizetype, bndrng[1]);
   1220     }
   1221 }
   1222 
   1223 /* Try to verify that the sizes and lengths of the arguments to a string
   1224    manipulation function given by EXP are within valid bounds and that
   1225    the operation does not lead to buffer overflow or read past the end.
   1226    Arguments other than EXP may be null.  When non-null, the arguments
   1227    have the following meaning:
   1228    DST is the destination of a copy call or NULL otherwise.
   1229    SRC is the source of a copy call or NULL otherwise.
   1230    DSTWRITE is the number of bytes written into the destination obtained
   1231    from the user-supplied size argument to the function (such as in
   1232    memcpy(DST, SRCs, DSTWRITE) or strncpy(DST, DRC, DSTWRITE).
   1233    MAXREAD is the user-supplied bound on the length of the source sequence
   1234    (such as in strncat(d, s, N).  It specifies the upper limit on the number
   1235    of bytes to write.  If NULL, it's taken to be the same as DSTWRITE.
   1236    SRCSTR is the source string (such as in strcpy(DST, SRC)) when the
   1237    expression EXP is a string function call (as opposed to a memory call
   1238    like memcpy).  As an exception, SRCSTR can also be an integer denoting
   1239    the precomputed size of the source string or object (for functions like
   1240    memcpy).
   1241    DSTSIZE is the size of the destination object.
   1242 
   1243    When DSTWRITE is null LEN is checked to verify that it doesn't exceed
   1244    SIZE_MAX.
   1245 
   1246    WRITE is true for write accesses, READ is true for reads.  Both are
   1247    false for simple size checks in calls to functions that neither read
   1248    from nor write to the region.
   1249 
   1250    When nonnull, PAD points to a more detailed description of the access.
   1251 
   1252    If the call is successfully verified as safe return true, otherwise
   1253    return false.  */
   1254 
   1255 template <class GimpleOrTree>
   1256 static bool
   1257 check_access (GimpleOrTree exp, tree dstwrite,
   1258 	      tree maxread, tree srcstr, tree dstsize,
   1259 	      access_mode mode, const access_data *pad,
   1260 	      range_query *rvals)
   1261 {
   1262   /* The size of the largest object is half the address space, or
   1263      PTRDIFF_MAX.  (This is way too permissive.)  */
   1264   tree maxobjsize = max_object_size ();
   1265 
   1266   /* Either an approximate/minimum the length of the source string for
   1267      string functions or the size of the source object for raw memory
   1268      functions.  */
   1269   tree slen = NULL_TREE;
   1270 
   1271   /* The range of the access in bytes; first set to the write access
   1272      for functions that write and then read for those that also (or
   1273      just) read.  */
   1274   tree range[2] = { NULL_TREE, NULL_TREE };
   1275 
   1276   /* Set to true when the exact number of bytes written by a string
   1277      function like strcpy is not known and the only thing that is
   1278      known is that it must be at least one (for the terminating nul).  */
   1279   bool at_least_one = false;
   1280   if (srcstr)
   1281     {
   1282       /* SRCSTR is normally a pointer to string but as a special case
   1283 	 it can be an integer denoting the length of a string.  */
   1284       if (POINTER_TYPE_P (TREE_TYPE (srcstr)))
   1285 	{
   1286 	  if (!check_nul_terminated_array (exp, srcstr, maxread))
   1287 	    /* Return if the array is not nul-terminated and a warning
   1288 	       has been issued.  */
   1289 	    return false;
   1290 
   1291 	  /* Try to determine the range of lengths the source string
   1292 	     refers to.  If it can be determined and is less than
   1293 	     the upper bound given by MAXREAD add one to it for
   1294 	     the terminating nul.  Otherwise, set it to one for
   1295 	     the same reason, or to MAXREAD as appropriate.  */
   1296 	  c_strlen_data lendata = { };
   1297 	  get_range_strlen (srcstr, &lendata, /* eltsize = */ 1);
   1298 	  range[0] = lendata.minlen;
   1299 	  range[1] = lendata.maxbound ? lendata.maxbound : lendata.maxlen;
   1300 	  if (range[0]
   1301 	      && TREE_CODE (range[0]) == INTEGER_CST
   1302 	      && TREE_CODE (range[1]) == INTEGER_CST
   1303 	      && (!maxread || TREE_CODE (maxread) == INTEGER_CST))
   1304 	    {
   1305 	      if (maxread && tree_int_cst_le (maxread, range[0]))
   1306 		range[0] = range[1] = maxread;
   1307 	      else
   1308 		range[0] = fold_build2 (PLUS_EXPR, size_type_node,
   1309 					range[0], size_one_node);
   1310 
   1311 	      if (maxread && tree_int_cst_le (maxread, range[1]))
   1312 		range[1] = maxread;
   1313 	      else if (!integer_all_onesp (range[1]))
   1314 		range[1] = fold_build2 (PLUS_EXPR, size_type_node,
   1315 					range[1], size_one_node);
   1316 
   1317 	      slen = range[0];
   1318 	    }
   1319 	  else
   1320 	    {
   1321 	      at_least_one = true;
   1322 	      slen = size_one_node;
   1323 	    }
   1324 	}
   1325       else
   1326 	slen = srcstr;
   1327     }
   1328 
   1329   if (!dstwrite && !maxread)
   1330     {
   1331       /* When the only available piece of data is the object size
   1332 	 there is nothing to do.  */
   1333       if (!slen)
   1334 	return true;
   1335 
   1336       /* Otherwise, when the length of the source sequence is known
   1337 	 (as with strlen), set DSTWRITE to it.  */
   1338       if (!range[0])
   1339 	dstwrite = slen;
   1340     }
   1341 
   1342   if (!dstsize)
   1343     dstsize = maxobjsize;
   1344 
   1345   /* Set RANGE to that of DSTWRITE if non-null, bounded by PAD->DST_BNDRNG
   1346      if valid.  */
   1347   gimple *stmt = pad ? pad->stmt : nullptr;
   1348   get_size_range (rvals, dstwrite, stmt, range, pad ? pad->dst_bndrng : NULL);
   1349 
   1350   tree func = get_callee_fndecl (exp);
   1351   /* Read vs write access by built-ins can be determined from the const
   1352      qualifiers on the pointer argument.  In the absence of attribute
   1353      access, non-const qualified pointer arguments to user-defined
   1354      functions are assumed to both read and write the objects.  */
   1355   const bool builtin = func ? fndecl_built_in_p (func) : false;
   1356 
   1357   /* First check the number of bytes to be written against the maximum
   1358      object size.  */
   1359   if (range[0]
   1360       && TREE_CODE (range[0]) == INTEGER_CST
   1361       && tree_int_cst_lt (maxobjsize, range[0]))
   1362     {
   1363       location_t loc = get_location (exp);
   1364       maybe_warn_for_bound (OPT_Wstringop_overflow_, loc, exp, func, range,
   1365 			    NULL_TREE, pad);
   1366       return false;
   1367     }
   1368 
   1369   /* The number of bytes to write is "exact" if DSTWRITE is non-null,
   1370      constant, and in range of unsigned HOST_WIDE_INT.  */
   1371   bool exactwrite = dstwrite && tree_fits_uhwi_p (dstwrite);
   1372 
   1373   /* Next check the number of bytes to be written against the destination
   1374      object size.  */
   1375   if (range[0] || !exactwrite || integer_all_onesp (dstwrite))
   1376     {
   1377       if (range[0]
   1378 	  && TREE_CODE (range[0]) == INTEGER_CST
   1379 	  && ((tree_fits_uhwi_p (dstsize)
   1380 	       && tree_int_cst_lt (dstsize, range[0]))
   1381 	      || (dstwrite
   1382 		  && tree_fits_uhwi_p (dstwrite)
   1383 		  && tree_int_cst_lt (dstwrite, range[0]))))
   1384 	{
   1385 	  const opt_code opt = OPT_Wstringop_overflow_;
   1386 	  if (warning_suppressed_p (exp, opt)
   1387 	      || (pad && pad->dst.ref
   1388 		  && warning_suppressed_p (pad->dst.ref, opt)))
   1389 	    return false;
   1390 
   1391 	  location_t loc = get_location (exp);
   1392 	  bool warned = false;
   1393 	  if (dstwrite == slen && at_least_one)
   1394 	    {
   1395 	      /* This is a call to strcpy with a destination of 0 size
   1396 		 and a source of unknown length.  The call will write
   1397 		 at least one byte past the end of the destination.  */
   1398 	      warned = (func
   1399 			? warning_at (loc, opt,
   1400 				      "%qD writing %E or more bytes into "
   1401 				      "a region of size %E overflows "
   1402 				      "the destination",
   1403 				      func, range[0], dstsize)
   1404 			: warning_at (loc, opt,
   1405 				      "writing %E or more bytes into "
   1406 				      "a region of size %E overflows "
   1407 				      "the destination",
   1408 				      range[0], dstsize));
   1409 	    }
   1410 	  else
   1411 	    {
   1412 	      const bool read
   1413 		= mode == access_read_only || mode == access_read_write;
   1414 	      const bool write
   1415 		= mode == access_write_only || mode == access_read_write;
   1416 	      const bool maybe = pad && pad->dst.parmarray;
   1417 	      warned = warn_for_access (loc, func, exp,
   1418 					OPT_Wstringop_overflow_,
   1419 					range, dstsize,
   1420 					write, read && !builtin, maybe);
   1421 	    }
   1422 
   1423 	  if (warned)
   1424 	    {
   1425 	      suppress_warning (exp, OPT_Wstringop_overflow_);
   1426 	      if (pad)
   1427 		pad->dst.inform_access (pad->mode);
   1428 	    }
   1429 
   1430 	  /* Return error when an overflow has been detected.  */
   1431 	  return false;
   1432 	}
   1433     }
   1434 
   1435   /* Check the maximum length of the source sequence against the size
   1436      of the destination object if known, or against the maximum size
   1437      of an object.  */
   1438   if (maxread)
   1439     {
   1440       /* Set RANGE to that of MAXREAD, bounded by PAD->SRC_BNDRNG if
   1441 	 PAD is nonnull and BNDRNG is valid.  */
   1442       get_size_range (rvals, maxread, stmt, range, pad ? pad->src_bndrng : NULL);
   1443 
   1444       location_t loc = get_location (exp);
   1445       tree size = dstsize;
   1446       if (pad && pad->mode == access_read_only)
   1447 	size = wide_int_to_tree (sizetype, pad->src.size_remaining ());
   1448 
   1449       if (range[0] && maxread && tree_fits_uhwi_p (size))
   1450 	{
   1451 	  if (tree_int_cst_lt (maxobjsize, range[0]))
   1452 	    {
   1453 	      maybe_warn_for_bound (OPT_Wstringop_overread, loc, exp, func,
   1454 				    range, size, pad);
   1455 	      return false;
   1456 	    }
   1457 
   1458 	  if (size != maxobjsize && tree_int_cst_lt (size, range[0]))
   1459 	    {
   1460 	      opt_code opt = (dstwrite || mode != access_read_only
   1461 			      ? OPT_Wstringop_overflow_
   1462 			      : OPT_Wstringop_overread);
   1463 	      maybe_warn_for_bound (opt, loc, exp, func, range, size, pad);
   1464 	      return false;
   1465 	    }
   1466 	}
   1467 
   1468       maybe_warn_nonstring_arg (func, exp);
   1469     }
   1470 
   1471   /* Check for reading past the end of SRC.  */
   1472   bool overread = (slen
   1473 		   && slen == srcstr
   1474 		   && dstwrite
   1475 		   && range[0]
   1476 		   && TREE_CODE (slen) == INTEGER_CST
   1477 		   && tree_int_cst_lt (slen, range[0]));
   1478   /* If none is determined try to get a better answer based on the details
   1479      in PAD.  */
   1480   if (!overread
   1481       && pad
   1482       && pad->src.sizrng[1] >= 0
   1483       && pad->src.offrng[0] >= 0
   1484       && (pad->src.offrng[1] < 0
   1485 	  || pad->src.offrng[0] <= pad->src.offrng[1]))
   1486     {
   1487       /* Set RANGE to that of MAXREAD, bounded by PAD->SRC_BNDRNG if
   1488 	 PAD is nonnull and BNDRNG is valid.  */
   1489       get_size_range (rvals, maxread, stmt, range, pad ? pad->src_bndrng : NULL);
   1490       /* Set OVERREAD for reads starting just past the end of an object.  */
   1491       overread = pad->src.sizrng[1] - pad->src.offrng[0] < pad->src_bndrng[0];
   1492       range[0] = wide_int_to_tree (sizetype, pad->src_bndrng[0]);
   1493       slen = size_zero_node;
   1494     }
   1495 
   1496   if (overread)
   1497     {
   1498       const opt_code opt = OPT_Wstringop_overread;
   1499       if (warning_suppressed_p (exp, opt)
   1500 	  || (srcstr && warning_suppressed_p (srcstr, opt))
   1501 	  || (pad && pad->src.ref
   1502 	      && warning_suppressed_p (pad->src.ref, opt)))
   1503 	return false;
   1504 
   1505       location_t loc = get_location (exp);
   1506       const bool read
   1507 	= mode == access_read_only || mode == access_read_write;
   1508       const bool maybe = pad && pad->dst.parmarray;
   1509       if (warn_for_access (loc, func, exp, opt, range, slen, false, read,
   1510 			   maybe))
   1511 	{
   1512 	  suppress_warning (exp, opt);
   1513 	  if (pad)
   1514 	    pad->src.inform_access (access_read_only);
   1515 	}
   1516       return false;
   1517     }
   1518 
   1519   return true;
   1520 }
   1521 
   1522 static bool
   1523 check_access (gimple *stmt, tree dstwrite,
   1524 	      tree maxread, tree srcstr, tree dstsize,
   1525 	      access_mode mode, const access_data *pad,
   1526 	      range_query *rvals)
   1527 {
   1528   return check_access<gimple *> (stmt, dstwrite, maxread, srcstr, dstsize,
   1529 				 mode, pad, rvals);
   1530 }
   1531 
   1532 bool
   1533 check_access (tree expr, tree dstwrite,
   1534 	      tree maxread, tree srcstr, tree dstsize,
   1535 	      access_mode mode, const access_data *pad /* = NULL */)
   1536 {
   1537   return check_access<tree> (expr, dstwrite, maxread, srcstr, dstsize,
   1538 			     mode, pad, nullptr);
   1539 }
   1540 
   1541 /* Return true if STMT is a call to an allocation function.  Unless
   1542    ALL_ALLOC is set, consider only functions that return dynamically
   1543    allocated objects.  Otherwise return true even for all forms of
   1544    alloca (including VLA).  */
   1545 
   1546 static bool
   1547 fndecl_alloc_p (tree fndecl, bool all_alloc)
   1548 {
   1549   if (!fndecl)
   1550     return false;
   1551 
   1552   /* A call to operator new isn't recognized as one to a built-in.  */
   1553   if (DECL_IS_OPERATOR_NEW_P (fndecl))
   1554     return true;
   1555 
   1556   if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
   1557     {
   1558       switch (DECL_FUNCTION_CODE (fndecl))
   1559 	{
   1560 	case BUILT_IN_ALLOCA:
   1561 	case BUILT_IN_ALLOCA_WITH_ALIGN:
   1562 	  return all_alloc;
   1563 	case BUILT_IN_ALIGNED_ALLOC:
   1564 	case BUILT_IN_CALLOC:
   1565 	case BUILT_IN_GOMP_ALLOC:
   1566 	case BUILT_IN_MALLOC:
   1567 	case BUILT_IN_REALLOC:
   1568 	case BUILT_IN_STRDUP:
   1569 	case BUILT_IN_STRNDUP:
   1570 	  return true;
   1571 	default:
   1572 	  break;
   1573 	}
   1574     }
   1575 
   1576   /* A function is considered an allocation function if it's declared
   1577      with attribute malloc with an argument naming its associated
   1578      deallocation function.  */
   1579   tree attrs = DECL_ATTRIBUTES (fndecl);
   1580   if (!attrs)
   1581     return false;
   1582 
   1583   for (tree allocs = attrs;
   1584        (allocs = lookup_attribute ("malloc", allocs));
   1585        allocs = TREE_CHAIN (allocs))
   1586     {
   1587       tree args = TREE_VALUE (allocs);
   1588       if (!args)
   1589 	continue;
   1590 
   1591       if (TREE_VALUE (args))
   1592 	return true;
   1593     }
   1594 
   1595   return false;
   1596 }
   1597 
   1598 /* Return true if STMT is a call to an allocation function.  A wrapper
   1599    around fndecl_alloc_p.  */
   1600 
   1601 static bool
   1602 gimple_call_alloc_p (gimple *stmt, bool all_alloc = false)
   1603 {
   1604   return fndecl_alloc_p (gimple_call_fndecl (stmt), all_alloc);
   1605 }
   1606 
   1607 /* Return true if DELC doesn't refer to an operator delete that's
   1608    suitable to call with a pointer returned from the operator new
   1609    described by NEWC.  */
   1610 
   1611 static bool
   1612 new_delete_mismatch_p (const demangle_component &newc,
   1613 		       const demangle_component &delc)
   1614 {
   1615   if (newc.type != delc.type)
   1616     return true;
   1617 
   1618   switch (newc.type)
   1619     {
   1620     case DEMANGLE_COMPONENT_NAME:
   1621       {
   1622 	int len = newc.u.s_name.len;
   1623 	const char *news = newc.u.s_name.s;
   1624 	const char *dels = delc.u.s_name.s;
   1625 	if (len != delc.u.s_name.len || memcmp (news, dels, len))
   1626 	  return true;
   1627 
   1628 	if (news[len] == 'n')
   1629 	  {
   1630 	    if (news[len + 1] == 'a')
   1631 	      return dels[len] != 'd' || dels[len + 1] != 'a';
   1632 	    if (news[len + 1] == 'w')
   1633 	      return dels[len] != 'd' || dels[len + 1] != 'l';
   1634 	  }
   1635 	return false;
   1636       }
   1637 
   1638     case DEMANGLE_COMPONENT_OPERATOR:
   1639       /* Operator mismatches are handled above.  */
   1640       return false;
   1641 
   1642     case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
   1643       if (newc.u.s_extended_operator.args != delc.u.s_extended_operator.args)
   1644 	return true;
   1645       return new_delete_mismatch_p (*newc.u.s_extended_operator.name,
   1646 				    *delc.u.s_extended_operator.name);
   1647 
   1648     case DEMANGLE_COMPONENT_FIXED_TYPE:
   1649       if (newc.u.s_fixed.accum != delc.u.s_fixed.accum
   1650 	  || newc.u.s_fixed.sat != delc.u.s_fixed.sat)
   1651 	return true;
   1652       return new_delete_mismatch_p (*newc.u.s_fixed.length,
   1653 				    *delc.u.s_fixed.length);
   1654 
   1655     case DEMANGLE_COMPONENT_CTOR:
   1656       if (newc.u.s_ctor.kind != delc.u.s_ctor.kind)
   1657 	return true;
   1658       return new_delete_mismatch_p (*newc.u.s_ctor.name,
   1659 				    *delc.u.s_ctor.name);
   1660 
   1661     case DEMANGLE_COMPONENT_DTOR:
   1662       if (newc.u.s_dtor.kind != delc.u.s_dtor.kind)
   1663 	return true;
   1664       return new_delete_mismatch_p (*newc.u.s_dtor.name,
   1665 				    *delc.u.s_dtor.name);
   1666 
   1667     case DEMANGLE_COMPONENT_BUILTIN_TYPE:
   1668       {
   1669 	/* The demangler API provides no better way to compare built-in
   1670 	   types except to by comparing their demangled names. */
   1671 	size_t nsz, dsz;
   1672 	demangle_component *pnc = const_cast<demangle_component *>(&newc);
   1673 	demangle_component *pdc = const_cast<demangle_component *>(&delc);
   1674 	char *nts = cplus_demangle_print (0, pnc, 16, &nsz);
   1675 	char *dts = cplus_demangle_print (0, pdc, 16, &dsz);
   1676 	if (!nts != !dts)
   1677 	  return true;
   1678 	bool mismatch = strcmp (nts, dts);
   1679 	free (nts);
   1680 	free (dts);
   1681 	return mismatch;
   1682       }
   1683 
   1684     case DEMANGLE_COMPONENT_SUB_STD:
   1685       if (newc.u.s_string.len != delc.u.s_string.len)
   1686 	return true;
   1687       return memcmp (newc.u.s_string.string, delc.u.s_string.string,
   1688 		     newc.u.s_string.len);
   1689 
   1690     case DEMANGLE_COMPONENT_FUNCTION_PARAM:
   1691     case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
   1692     case DEMANGLE_COMPONENT_UNNAMED_TYPE:
   1693       return newc.u.s_number.number != delc.u.s_number.number;
   1694 
   1695     case DEMANGLE_COMPONENT_CHARACTER:
   1696       return newc.u.s_character.character != delc.u.s_character.character;
   1697 
   1698     case DEMANGLE_COMPONENT_DEFAULT_ARG:
   1699     case DEMANGLE_COMPONENT_LAMBDA:
   1700       if (newc.u.s_unary_num.num != delc.u.s_unary_num.num)
   1701 	return true;
   1702       return new_delete_mismatch_p (*newc.u.s_unary_num.sub,
   1703 				    *delc.u.s_unary_num.sub);
   1704     default:
   1705       break;
   1706     }
   1707 
   1708   if (!newc.u.s_binary.left != !delc.u.s_binary.left)
   1709     return true;
   1710 
   1711   if (!newc.u.s_binary.left)
   1712     return false;
   1713 
   1714   if (new_delete_mismatch_p (*newc.u.s_binary.left, *delc.u.s_binary.left)
   1715       || !newc.u.s_binary.right != !delc.u.s_binary.right)
   1716     return true;
   1717 
   1718   if (newc.u.s_binary.right)
   1719     return new_delete_mismatch_p (*newc.u.s_binary.right,
   1720 				  *delc.u.s_binary.right);
   1721   return false;
   1722 }
   1723 
   1724 /* Return true if DELETE_DECL is an operator delete that's not suitable
   1725    to call with a pointer returned from NEW_DECL.  */
   1726 
   1727 static bool
   1728 new_delete_mismatch_p (tree new_decl, tree delete_decl)
   1729 {
   1730   tree new_name = DECL_ASSEMBLER_NAME (new_decl);
   1731   tree delete_name = DECL_ASSEMBLER_NAME (delete_decl);
   1732 
   1733   /* valid_new_delete_pair_p() returns a conservative result (currently
   1734      it only handles global operators).  A true result is reliable but
   1735      a false result doesn't necessarily mean the operators don't match
   1736      unless CERTAIN is set.  */
   1737   bool certain;
   1738   if (valid_new_delete_pair_p (new_name, delete_name, &certain))
   1739     return false;
   1740   /* CERTAIN is set when the negative result is certain.  */
   1741   if (certain)
   1742     return true;
   1743 
   1744   /* For anything not handled by valid_new_delete_pair_p() such as member
   1745      operators compare the individual demangled components of the mangled
   1746      name.  */
   1747   const char *new_str = IDENTIFIER_POINTER (new_name);
   1748   const char *del_str = IDENTIFIER_POINTER (delete_name);
   1749 
   1750   void *np = NULL, *dp = NULL;
   1751   demangle_component *ndc = cplus_demangle_v3_components (new_str, 0, &np);
   1752   demangle_component *ddc = cplus_demangle_v3_components (del_str, 0, &dp);
   1753   bool mismatch = new_delete_mismatch_p (*ndc, *ddc);
   1754   free (np);
   1755   free (dp);
   1756   return mismatch;
   1757 }
   1758 
   1759 /* ALLOC_DECL and DEALLOC_DECL are pair of allocation and deallocation
   1760    functions.  Return true if the latter is suitable to deallocate objects
   1761    allocated by calls to the former.  */
   1762 
   1763 static bool
   1764 matching_alloc_calls_p (tree alloc_decl, tree dealloc_decl)
   1765 {
   1766   /* Set to alloc_kind_t::builtin if ALLOC_DECL is associated with
   1767      a built-in deallocator.  */
   1768   enum class alloc_kind_t { none, builtin, user }
   1769   alloc_dealloc_kind = alloc_kind_t::none;
   1770 
   1771   if (DECL_IS_OPERATOR_NEW_P (alloc_decl))
   1772     {
   1773       if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl))
   1774 	/* Return true iff both functions are of the same array or
   1775 	   singleton form and false otherwise.  */
   1776 	return !new_delete_mismatch_p (alloc_decl, dealloc_decl);
   1777 
   1778       /* Return false for deallocation functions that are known not
   1779 	 to match.  */
   1780       if (fndecl_built_in_p (dealloc_decl, BUILT_IN_FREE)
   1781 	  || fndecl_built_in_p (dealloc_decl, BUILT_IN_REALLOC))
   1782 	return false;
   1783       /* Otherwise proceed below to check the deallocation function's
   1784 	 "*dealloc" attributes to look for one that mentions this operator
   1785 	 new.  */
   1786     }
   1787   else if (fndecl_built_in_p (alloc_decl, BUILT_IN_NORMAL))
   1788     {
   1789       switch (DECL_FUNCTION_CODE (alloc_decl))
   1790 	{
   1791 	case BUILT_IN_ALLOCA:
   1792 	case BUILT_IN_ALLOCA_WITH_ALIGN:
   1793 	  return false;
   1794 
   1795 	case BUILT_IN_ALIGNED_ALLOC:
   1796 	case BUILT_IN_CALLOC:
   1797 	case BUILT_IN_GOMP_ALLOC:
   1798 	case BUILT_IN_MALLOC:
   1799 	case BUILT_IN_REALLOC:
   1800 	case BUILT_IN_STRDUP:
   1801 	case BUILT_IN_STRNDUP:
   1802 	  if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl))
   1803 	    return false;
   1804 
   1805 	  if (fndecl_built_in_p (dealloc_decl, BUILT_IN_FREE)
   1806 	      || fndecl_built_in_p (dealloc_decl, BUILT_IN_REALLOC))
   1807 	    return true;
   1808 
   1809 	  alloc_dealloc_kind = alloc_kind_t::builtin;
   1810 	  break;
   1811 
   1812 	default:
   1813 	  break;
   1814 	}
   1815     }
   1816 
   1817   /* Set if DEALLOC_DECL both allocates and deallocates.  */
   1818   alloc_kind_t realloc_kind = alloc_kind_t::none;
   1819 
   1820   if (fndecl_built_in_p (dealloc_decl, BUILT_IN_NORMAL))
   1821     {
   1822       built_in_function dealloc_code = DECL_FUNCTION_CODE (dealloc_decl);
   1823       if (dealloc_code == BUILT_IN_REALLOC)
   1824 	realloc_kind = alloc_kind_t::builtin;
   1825 
   1826       for (tree amats = DECL_ATTRIBUTES (alloc_decl);
   1827 	   (amats = lookup_attribute ("malloc", amats));
   1828 	   amats = TREE_CHAIN (amats))
   1829 	{
   1830 	  tree args = TREE_VALUE (amats);
   1831 	  if (!args)
   1832 	    continue;
   1833 
   1834 	  tree fndecl = TREE_VALUE (args);
   1835 	  if (!fndecl || !DECL_P (fndecl))
   1836 	    continue;
   1837 
   1838 	  if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL)
   1839 	      && dealloc_code == DECL_FUNCTION_CODE (fndecl))
   1840 	    return true;
   1841 	}
   1842     }
   1843 
   1844   const bool alloc_builtin = fndecl_built_in_p (alloc_decl, BUILT_IN_NORMAL);
   1845   alloc_kind_t realloc_dealloc_kind = alloc_kind_t::none;
   1846 
   1847   /* If DEALLOC_DECL has an internal "*dealloc" attribute scan the list
   1848      of its associated allocation functions for ALLOC_DECL.
   1849      If the corresponding ALLOC_DECL is found they're a matching pair,
   1850      otherwise they're not.
   1851      With DDATS set to the Deallocator's *Dealloc ATtributes...  */
   1852   for (tree ddats = DECL_ATTRIBUTES (dealloc_decl);
   1853        (ddats = lookup_attribute ("*dealloc", ddats));
   1854        ddats = TREE_CHAIN (ddats))
   1855     {
   1856       tree args = TREE_VALUE (ddats);
   1857       if (!args)
   1858 	continue;
   1859 
   1860       tree alloc = TREE_VALUE (args);
   1861       if (!alloc)
   1862 	continue;
   1863 
   1864       if (alloc == DECL_NAME (dealloc_decl))
   1865 	realloc_kind = alloc_kind_t::user;
   1866 
   1867       if (DECL_P (alloc))
   1868 	{
   1869 	  gcc_checking_assert (fndecl_built_in_p (alloc, BUILT_IN_NORMAL));
   1870 
   1871 	  switch (DECL_FUNCTION_CODE (alloc))
   1872 	    {
   1873 	    case BUILT_IN_ALIGNED_ALLOC:
   1874 	    case BUILT_IN_CALLOC:
   1875 	    case BUILT_IN_GOMP_ALLOC:
   1876 	    case BUILT_IN_MALLOC:
   1877 	    case BUILT_IN_REALLOC:
   1878 	    case BUILT_IN_STRDUP:
   1879 	    case BUILT_IN_STRNDUP:
   1880 	      realloc_dealloc_kind = alloc_kind_t::builtin;
   1881 	      break;
   1882 	    default:
   1883 	      break;
   1884 	    }
   1885 
   1886 	  if (!alloc_builtin)
   1887 	    continue;
   1888 
   1889 	  if (DECL_FUNCTION_CODE (alloc) != DECL_FUNCTION_CODE (alloc_decl))
   1890 	    continue;
   1891 
   1892 	  return true;
   1893 	}
   1894 
   1895       if (alloc == DECL_NAME (alloc_decl))
   1896 	return true;
   1897     }
   1898 
   1899   if (realloc_kind == alloc_kind_t::none)
   1900     return false;
   1901 
   1902   hash_set<tree> common_deallocs;
   1903   /* Special handling for deallocators.  Iterate over both the allocator's
   1904      and the reallocator's associated deallocator functions looking for
   1905      the first one in common.  If one is found, the de/reallocator is
   1906      a match for the allocator even though the latter isn't directly
   1907      associated with the former.  This simplifies declarations in system
   1908      headers.
   1909      With AMATS set to the Allocator's Malloc ATtributes,
   1910      and  RMATS set to Reallocator's Malloc ATtributes...  */
   1911   for (tree amats = DECL_ATTRIBUTES (alloc_decl);
   1912        (amats = lookup_attribute ("malloc", amats));
   1913        amats = amats ? TREE_CHAIN (amats) : NULL_TREE)
   1914     if (tree args = amats ? TREE_VALUE (amats) : NULL_TREE)
   1915       if (tree adealloc = TREE_VALUE (args))
   1916 	{
   1917 	  if (DECL_P (adealloc)
   1918 	      && fndecl_built_in_p (adealloc, BUILT_IN_NORMAL))
   1919 	    {
   1920 	      built_in_function fncode = DECL_FUNCTION_CODE (adealloc);
   1921 	      if (fncode == BUILT_IN_FREE || fncode == BUILT_IN_REALLOC)
   1922 		{
   1923 		  if (realloc_kind == alloc_kind_t::builtin)
   1924 		    return true;
   1925 		  alloc_dealloc_kind = alloc_kind_t::builtin;
   1926 		}
   1927 	      continue;
   1928 	    }
   1929 
   1930 	  common_deallocs.add (adealloc);
   1931 	}
   1932   for (tree rmats = DECL_ATTRIBUTES (dealloc_decl);
   1933        (rmats = lookup_attribute ("malloc", rmats));
   1934        rmats = rmats ? TREE_CHAIN (rmats) : NULL_TREE)
   1935     if (tree args = rmats ? TREE_VALUE (rmats) : NULL_TREE)
   1936       if (tree ddealloc = TREE_VALUE (args))
   1937 	{
   1938 	  if (DECL_P (ddealloc)
   1939 	      && fndecl_built_in_p (ddealloc, BUILT_IN_NORMAL))
   1940 	    {
   1941 	      built_in_function fncode = DECL_FUNCTION_CODE (ddealloc);
   1942 	      if (fncode == BUILT_IN_FREE || fncode == BUILT_IN_REALLOC)
   1943 		{
   1944 		  if (alloc_dealloc_kind == alloc_kind_t::builtin)
   1945 		    return true;
   1946 		  realloc_dealloc_kind = alloc_kind_t::builtin;
   1947 		}
   1948 	      continue;
   1949 	    }
   1950 
   1951 	  if (common_deallocs.contains (ddealloc))
   1952 	    return true;
   1953 	}
   1954 
   1955   /* Succeed only if ALLOC_DECL and the reallocator DEALLOC_DECL share
   1956      a built-in deallocator.  */
   1957   return  (alloc_dealloc_kind == alloc_kind_t::builtin
   1958 	   && realloc_dealloc_kind == alloc_kind_t::builtin);
   1959 }
   1960 
   1961 /* Return true if DEALLOC_DECL is a function suitable to deallocate
   1962    objects allocated by the ALLOC call.  */
   1963 
   1964 static bool
   1965 matching_alloc_calls_p (gimple *alloc, tree dealloc_decl)
   1966 {
   1967   tree alloc_decl = gimple_call_fndecl (alloc);
   1968   if (!alloc_decl)
   1969     return true;
   1970 
   1971   return matching_alloc_calls_p (alloc_decl, dealloc_decl);
   1972 }
   1973 
   1974 /* Diagnose a call EXP to deallocate a pointer referenced by AREF if it
   1975    includes a nonzero offset.  Such a pointer cannot refer to the beginning
   1976    of an allocated object.  A negative offset may refer to it only if
   1977    the target pointer is unknown.  */
   1978 
   1979 static bool
   1980 warn_dealloc_offset (location_t loc, gimple *call, const access_ref &aref)
   1981 {
   1982   if (aref.deref || aref.offrng[0] <= 0 || aref.offrng[1] <= 0)
   1983     return false;
   1984 
   1985   tree dealloc_decl = gimple_call_fndecl (call);
   1986   if (!dealloc_decl)
   1987     return false;
   1988 
   1989   if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl)
   1990       && !DECL_IS_REPLACEABLE_OPERATOR (dealloc_decl))
   1991     {
   1992       /* A call to a user-defined operator delete with a pointer plus offset
   1993 	 may be valid if it's returned from an unknown function (i.e., one
   1994 	 that's not operator new).  */
   1995       if (TREE_CODE (aref.ref) == SSA_NAME)
   1996 	{
   1997 	  gimple *def_stmt = SSA_NAME_DEF_STMT (aref.ref);
   1998 	  if (is_gimple_call (def_stmt))
   1999 	    {
   2000 	      tree alloc_decl = gimple_call_fndecl (def_stmt);
   2001 	      if (!alloc_decl || !DECL_IS_OPERATOR_NEW_P (alloc_decl))
   2002 		return false;
   2003 	    }
   2004 	}
   2005     }
   2006 
   2007   char offstr[80];
   2008   offstr[0] = '\0';
   2009   if (wi::fits_shwi_p (aref.offrng[0]))
   2010     {
   2011       if (aref.offrng[0] == aref.offrng[1]
   2012 	  || !wi::fits_shwi_p (aref.offrng[1]))
   2013 	sprintf (offstr, " %lli",
   2014 		 (long long)aref.offrng[0].to_shwi ());
   2015       else
   2016 	sprintf (offstr, " [%lli, %lli]",
   2017 		 (long long)aref.offrng[0].to_shwi (),
   2018 		 (long long)aref.offrng[1].to_shwi ());
   2019     }
   2020 
   2021   if (!warning_at (loc, OPT_Wfree_nonheap_object,
   2022 		   "%qD called on pointer %qE with nonzero offset%s",
   2023 		   dealloc_decl, aref.ref, offstr))
   2024     return false;
   2025 
   2026   if (DECL_P (aref.ref))
   2027     inform (get_location (aref.ref), "declared here");
   2028   else if (TREE_CODE (aref.ref) == SSA_NAME)
   2029     {
   2030       gimple *def_stmt = SSA_NAME_DEF_STMT (aref.ref);
   2031       if (is_gimple_call (def_stmt))
   2032 	{
   2033 	  location_t def_loc = get_location (def_stmt);
   2034 	  tree alloc_decl = gimple_call_fndecl (def_stmt);
   2035 	  if (alloc_decl)
   2036 	    inform (def_loc,
   2037 		    "returned from %qD", alloc_decl);
   2038 	  else if (tree alloc_fntype = gimple_call_fntype (def_stmt))
   2039 	    inform (def_loc,
   2040 		    "returned from %qT", alloc_fntype);
   2041 	  else
   2042 	    inform (def_loc,  "obtained here");
   2043 	}
   2044     }
   2045 
   2046   return true;
   2047 }
   2048 
   2049 namespace {
   2050 
   2051 const pass_data pass_data_waccess = {
   2052   GIMPLE_PASS,
   2053   "waccess",
   2054   OPTGROUP_NONE,
   2055   TV_WARN_ACCESS, /* timer variable */
   2056   PROP_cfg, /* properties_required  */
   2057   0,	    /* properties_provided  */
   2058   0,	    /* properties_destroyed  */
   2059   0,	    /* properties_start */
   2060   0,	    /* properties_finish */
   2061 };
   2062 
   2063 /* Pass to detect invalid accesses.  */
   2064 class pass_waccess : public gimple_opt_pass
   2065 {
   2066  public:
   2067   pass_waccess (gcc::context *);
   2068 
   2069   ~pass_waccess ();
   2070 
   2071   opt_pass *clone ();
   2072 
   2073   virtual bool gate (function *);
   2074 
   2075   void set_pass_param (unsigned, bool);
   2076 
   2077   virtual unsigned int execute (function *);
   2078 
   2079 private:
   2080   /* Not copyable or assignable.  */
   2081   pass_waccess (pass_waccess &) = delete;
   2082   void operator= (pass_waccess &) = delete;
   2083 
   2084   /* Check a call to an atomic built-in function.  */
   2085   bool check_atomic_builtin (gcall *);
   2086 
   2087   /* Check a call to a built-in function.  */
   2088   bool check_builtin (gcall *);
   2089 
   2090   /* Check a call to an ordinary function for invalid accesses.  */
   2091   bool check_call_access (gcall *);
   2092 
   2093   /* Check a non-call statement.  */
   2094   void check_stmt (gimple *);
   2095 
   2096   /* Check statements in a basic block.  */
   2097   void check_block (basic_block);
   2098 
   2099   /* Check a call to a function.  */
   2100   void check_call (gcall *);
   2101 
   2102   /* Check a call to the named built-in function.  */
   2103   void check_alloca (gcall *);
   2104   void check_alloc_size_call (gcall *);
   2105   void check_strcat (gcall *);
   2106   void check_strncat (gcall *);
   2107   void check_stxcpy (gcall *);
   2108   void check_stxncpy (gcall *);
   2109   void check_strncmp (gcall *);
   2110   void check_memop_access (gimple *, tree, tree, tree);
   2111   void check_read_access (gimple *, tree, tree = NULL_TREE, int = 1);
   2112 
   2113   void maybe_check_dealloc_call (gcall *);
   2114   void maybe_check_access_sizes (rdwr_map *, tree, tree, gimple *);
   2115   bool maybe_warn_memmodel (gimple *, tree, tree, const unsigned char *);
   2116   void check_atomic_memmodel (gimple *, tree, tree, const unsigned char *);
   2117 
   2118   /* Check for uses of indeterminate pointers.  */
   2119   void check_pointer_uses (gimple *, tree, tree = NULL_TREE, bool = false);
   2120 
   2121   /* Return the argument that a call returns.  */
   2122   tree gimple_call_return_arg (gcall *);
   2123 
   2124   /* Check a call for uses of a dangling pointer arguments.  */
   2125   void check_call_dangling (gcall *);
   2126 
   2127   /* Check uses of a dangling pointer or those derived from it.  */
   2128   void check_dangling_uses (tree, tree, bool = false, bool = false);
   2129   void check_dangling_uses ();
   2130   void check_dangling_stores ();
   2131   void check_dangling_stores (basic_block, hash_set<tree> &, auto_bitmap &);
   2132 
   2133   void warn_invalid_pointer (tree, gimple *, gimple *, tree, bool, bool = false);
   2134 
   2135   /* Return true if use follows an invalidating statement.  */
   2136   bool use_after_inval_p (gimple *, gimple *, bool = false);
   2137 
   2138   /* A pointer_query object to store information about pointers and
   2139      their targets in.  */
   2140   pointer_query m_ptr_qry;
   2141   /* Mapping from DECLs and their clobber statements in the function.  */
   2142   hash_map<tree, gimple *> m_clobbers;
   2143   /* A bit is set for each basic block whose statements have been assigned
   2144      valid UIDs.  */
   2145   bitmap m_bb_uids_set;
   2146   /* The current function.  */
   2147   function *m_func;
   2148   /* True to run checks for uses of dangling pointers.  */
   2149   bool m_check_dangling_p;
   2150   /* True to run checks early on in the optimization pipeline.  */
   2151   bool m_early_checks_p;
   2152 };
   2153 
   2154 /* Construct the pass.  */
   2155 
   2156 pass_waccess::pass_waccess (gcc::context *ctxt)
   2157   : gimple_opt_pass (pass_data_waccess, ctxt),
   2158     m_ptr_qry (NULL),
   2159     m_clobbers (),
   2160     m_bb_uids_set (),
   2161     m_func (),
   2162     m_check_dangling_p (),
   2163     m_early_checks_p ()
   2164 {
   2165 }
   2166 
   2167 /* Return a copy of the pass with RUN_NUMBER one greater than THIS.  */
   2168 
   2169 opt_pass*
   2170 pass_waccess::clone ()
   2171 {
   2172   return new pass_waccess (m_ctxt);
   2173 }
   2174 
   2175 /* Release pointer_query cache.  */
   2176 
   2177 pass_waccess::~pass_waccess ()
   2178 {
   2179   m_ptr_qry.flush_cache ();
   2180 }
   2181 
   2182 void
   2183 pass_waccess::set_pass_param (unsigned int n, bool early)
   2184 {
   2185   gcc_assert (n == 0);
   2186 
   2187   m_early_checks_p = early;
   2188 }
   2189 
   2190 /* Return true when any checks performed by the pass are enabled.  */
   2191 
   2192 bool
   2193 pass_waccess::gate (function *)
   2194 {
   2195   return (warn_free_nonheap_object
   2196 	  || warn_mismatched_alloc
   2197 	  || warn_mismatched_new_delete);
   2198 }
   2199 
   2200 /* Initialize ALLOC_OBJECT_SIZE_LIMIT based on the -Walloc-size-larger-than=
   2201    setting if the option is specified, or to the maximum object size if it
   2202    is not.  Return the initialized value.  */
   2203 
   2204 static tree
   2205 alloc_max_size (void)
   2206 {
   2207   HOST_WIDE_INT limit = warn_alloc_size_limit;
   2208   if (limit == HOST_WIDE_INT_MAX)
   2209     limit = tree_to_shwi (TYPE_MAX_VALUE (ptrdiff_type_node));
   2210 
   2211   return build_int_cst (size_type_node, limit);
   2212 }
   2213 
   2214 /* Diagnose a call EXP to function FN decorated with attribute alloc_size
   2215    whose argument numbers given by IDX with values given by ARGS exceed
   2216    the maximum object size or cause an unsigned overflow (wrapping) when
   2217    multiplied.  FN is null when EXP is a call via a function pointer.
   2218    When ARGS[0] is null the function does nothing.  ARGS[1] may be null
   2219    for functions like malloc, and non-null for those like calloc that
   2220    are decorated with a two-argument attribute alloc_size.  */
   2221 
   2222 void
   2223 maybe_warn_alloc_args_overflow (gimple *stmt, const tree args[2],
   2224 				const int idx[2])
   2225 {
   2226   /* The range each of the (up to) two arguments is known to be in.  */
   2227   tree argrange[2][2] = { { NULL_TREE, NULL_TREE }, { NULL_TREE, NULL_TREE } };
   2228 
   2229   /* Maximum object size set by -Walloc-size-larger-than= or SIZE_MAX / 2.  */
   2230   tree maxobjsize = alloc_max_size ();
   2231 
   2232   location_t loc = get_location (stmt);
   2233 
   2234   tree fn = gimple_call_fndecl (stmt);
   2235   tree fntype = fn ? TREE_TYPE (fn) : gimple_call_fntype (stmt);
   2236   bool warned = false;
   2237 
   2238   /* Validate each argument individually.  */
   2239   for (unsigned i = 0; i != 2 && args[i]; ++i)
   2240     {
   2241       if (TREE_CODE (args[i]) == INTEGER_CST)
   2242 	{
   2243 	  argrange[i][0] = args[i];
   2244 	  argrange[i][1] = args[i];
   2245 
   2246 	  if (tree_int_cst_lt (args[i], integer_zero_node))
   2247 	    {
   2248 	      warned = warning_at (loc, OPT_Walloc_size_larger_than_,
   2249 				   "argument %i value %qE is negative",
   2250 				   idx[i] + 1, args[i]);
   2251 	    }
   2252 	  else if (integer_zerop (args[i]))
   2253 	    {
   2254 	      /* Avoid issuing -Walloc-zero for allocation functions other
   2255 		 than __builtin_alloca that are declared with attribute
   2256 		 returns_nonnull because there's no portability risk.  This
   2257 		 avoids warning for such calls to libiberty's xmalloc and
   2258 		 friends.
   2259 		 Also avoid issuing the warning for calls to function named
   2260 		 "alloca".  */
   2261 	      if (fn && fndecl_built_in_p (fn, BUILT_IN_ALLOCA)
   2262 		  ? IDENTIFIER_LENGTH (DECL_NAME (fn)) != 6
   2263 		  : !lookup_attribute ("returns_nonnull",
   2264 				       TYPE_ATTRIBUTES (fntype)))
   2265 		warned = warning_at (loc, OPT_Walloc_zero,
   2266 				     "argument %i value is zero",
   2267 				     idx[i] + 1);
   2268 	    }
   2269 	  else if (tree_int_cst_lt (maxobjsize, args[i]))
   2270 	    {
   2271 	      /* G++ emits calls to ::operator new[](SIZE_MAX) in C++98
   2272 		 mode and with -fno-exceptions as a way to indicate array
   2273 		 size overflow.  There's no good way to detect C++98 here
   2274 		 so avoid diagnosing these calls for all C++ modes.  */
   2275 	      if (i == 0
   2276 		  && fn
   2277 		  && !args[1]
   2278 		  && lang_GNU_CXX ()
   2279 		  && DECL_IS_OPERATOR_NEW_P (fn)
   2280 		  && integer_all_onesp (args[i]))
   2281 		continue;
   2282 
   2283 	      warned = warning_at (loc, OPT_Walloc_size_larger_than_,
   2284 				   "argument %i value %qE exceeds "
   2285 				   "maximum object size %E",
   2286 				   idx[i] + 1, args[i], maxobjsize);
   2287 	    }
   2288 	}
   2289       else if (TREE_CODE (args[i]) == SSA_NAME
   2290 	       && get_size_range (args[i], argrange[i]))
   2291 	{
   2292 	  /* Verify that the argument's range is not negative (including
   2293 	     upper bound of zero).  */
   2294 	  if (tree_int_cst_lt (argrange[i][0], integer_zero_node)
   2295 	      && tree_int_cst_le (argrange[i][1], integer_zero_node))
   2296 	    {
   2297 	      warned = warning_at (loc, OPT_Walloc_size_larger_than_,
   2298 				   "argument %i range [%E, %E] is negative",
   2299 				   idx[i] + 1,
   2300 				   argrange[i][0], argrange[i][1]);
   2301 	    }
   2302 	  else if (tree_int_cst_lt (maxobjsize, argrange[i][0]))
   2303 	    {
   2304 	      warned = warning_at (loc, OPT_Walloc_size_larger_than_,
   2305 				   "argument %i range [%E, %E] exceeds "
   2306 				   "maximum object size %E",
   2307 				   idx[i] + 1,
   2308 				   argrange[i][0], argrange[i][1],
   2309 				   maxobjsize);
   2310 	    }
   2311 	}
   2312     }
   2313 
   2314   if (!argrange[0][0])
   2315     return;
   2316 
   2317   /* For a two-argument alloc_size, validate the product of the two
   2318      arguments if both of their values or ranges are known.  */
   2319   if (!warned && tree_fits_uhwi_p (argrange[0][0])
   2320       && argrange[1][0] && tree_fits_uhwi_p (argrange[1][0])
   2321       && !integer_onep (argrange[0][0])
   2322       && !integer_onep (argrange[1][0]))
   2323     {
   2324       /* Check for overflow in the product of a function decorated with
   2325 	 attribute alloc_size (X, Y).  */
   2326       unsigned szprec = TYPE_PRECISION (size_type_node);
   2327       wide_int x = wi::to_wide (argrange[0][0], szprec);
   2328       wide_int y = wi::to_wide (argrange[1][0], szprec);
   2329 
   2330       wi::overflow_type vflow;
   2331       wide_int prod = wi::umul (x, y, &vflow);
   2332 
   2333       if (vflow)
   2334 	warned = warning_at (loc, OPT_Walloc_size_larger_than_,
   2335 			     "product %<%E * %E%> of arguments %i and %i "
   2336 			     "exceeds %<SIZE_MAX%>",
   2337 			     argrange[0][0], argrange[1][0],
   2338 			     idx[0] + 1, idx[1] + 1);
   2339       else if (wi::ltu_p (wi::to_wide (maxobjsize, szprec), prod))
   2340 	warned = warning_at (loc, OPT_Walloc_size_larger_than_,
   2341 			     "product %<%E * %E%> of arguments %i and %i "
   2342 			     "exceeds maximum object size %E",
   2343 			     argrange[0][0], argrange[1][0],
   2344 			     idx[0] + 1, idx[1] + 1,
   2345 			     maxobjsize);
   2346 
   2347       if (warned)
   2348 	{
   2349 	  /* Print the full range of each of the two arguments to make
   2350 	     it clear when it is, in fact, in a range and not constant.  */
   2351 	  if (argrange[0][0] != argrange [0][1])
   2352 	    inform (loc, "argument %i in the range [%E, %E]",
   2353 		    idx[0] + 1, argrange[0][0], argrange[0][1]);
   2354 	  if (argrange[1][0] != argrange [1][1])
   2355 	    inform (loc, "argument %i in the range [%E, %E]",
   2356 		    idx[1] + 1, argrange[1][0], argrange[1][1]);
   2357 	}
   2358     }
   2359 
   2360   if (warned && fn)
   2361     {
   2362       location_t fnloc = DECL_SOURCE_LOCATION (fn);
   2363 
   2364       if (DECL_IS_UNDECLARED_BUILTIN (fn))
   2365 	inform (loc,
   2366 		"in a call to built-in allocation function %qD", fn);
   2367       else
   2368 	inform (fnloc,
   2369 		"in a call to allocation function %qD declared here", fn);
   2370     }
   2371 }
   2372 
   2373 /* Check a call to an alloca function for an excessive size.  */
   2374 
   2375 void
   2376 pass_waccess::check_alloca (gcall *stmt)
   2377 {
   2378   if (m_early_checks_p)
   2379     return;
   2380 
   2381   if ((warn_vla_limit >= HOST_WIDE_INT_MAX
   2382        && warn_alloc_size_limit < warn_vla_limit)
   2383       || (warn_alloca_limit >= HOST_WIDE_INT_MAX
   2384 	  && warn_alloc_size_limit < warn_alloca_limit))
   2385     {
   2386       /* -Walloca-larger-than and -Wvla-larger-than settings of less
   2387 	 than  HWI_MAX override the more general -Walloc-size-larger-than
   2388 	 so unless either of the former options is smaller than the last
   2389 	 one (which would imply that the call was already checked), check
   2390 	 the alloca arguments for overflow.  */
   2391       const tree alloc_args[] = { call_arg (stmt, 0), NULL_TREE };
   2392       const int idx[] = { 0, -1 };
   2393       maybe_warn_alloc_args_overflow (stmt, alloc_args, idx);
   2394     }
   2395 }
   2396 
   2397 /* Check a call to an allocation function for an excessive size.  */
   2398 
   2399 void
   2400 pass_waccess::check_alloc_size_call (gcall *stmt)
   2401 {
   2402   if (m_early_checks_p)
   2403     return;
   2404 
   2405   if (gimple_call_num_args (stmt) < 1)
   2406     /* Avoid invalid calls to functions without a prototype.  */
   2407     return;
   2408 
   2409   tree fndecl = gimple_call_fndecl (stmt);
   2410   if (fndecl && gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
   2411     {
   2412       /* Alloca is handled separately.  */
   2413       switch (DECL_FUNCTION_CODE (fndecl))
   2414 	{
   2415 	case BUILT_IN_ALLOCA:
   2416 	case BUILT_IN_ALLOCA_WITH_ALIGN:
   2417 	case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
   2418 	  return;
   2419 	default:
   2420 	  break;
   2421 	}
   2422     }
   2423 
   2424   tree fntype = gimple_call_fntype (stmt);
   2425   tree fntypeattrs = TYPE_ATTRIBUTES (fntype);
   2426 
   2427   tree alloc_size = lookup_attribute ("alloc_size", fntypeattrs);
   2428   if (!alloc_size)
   2429     return;
   2430 
   2431   /* Extract attribute alloc_size from the type of the called expression
   2432      (which could be a function or a function pointer) and if set, store
   2433      the indices of the corresponding arguments in ALLOC_IDX, and then
   2434      the actual argument(s) at those indices in ALLOC_ARGS.  */
   2435   int idx[2] = { -1, -1 };
   2436   tree alloc_args[] = { NULL_TREE, NULL_TREE };
   2437   unsigned nargs = gimple_call_num_args (stmt);
   2438 
   2439   tree args = TREE_VALUE (alloc_size);
   2440   idx[0] = TREE_INT_CST_LOW (TREE_VALUE (args)) - 1;
   2441   /* Avoid invalid calls to functions without a prototype.  */
   2442   if ((unsigned) idx[0] >= nargs)
   2443     return;
   2444   alloc_args[0] = call_arg (stmt, idx[0]);
   2445   if (TREE_CHAIN (args))
   2446     {
   2447       idx[1] = TREE_INT_CST_LOW (TREE_VALUE (TREE_CHAIN (args))) - 1;
   2448       if ((unsigned) idx[1] >= nargs)
   2449 	return;
   2450       alloc_args[1] = call_arg (stmt, idx[1]);
   2451     }
   2452 
   2453   maybe_warn_alloc_args_overflow (stmt, alloc_args, idx);
   2454 }
   2455 
   2456 /* Check a call STMT to strcat() for overflow and warn if it does.  */
   2457 
   2458 void
   2459 pass_waccess::check_strcat (gcall *stmt)
   2460 {
   2461   if (m_early_checks_p)
   2462     return;
   2463 
   2464   if (!warn_stringop_overflow && !warn_stringop_overread)
   2465     return;
   2466 
   2467   tree dest = call_arg (stmt, 0);
   2468   tree src = call_arg (stmt, 1);
   2469 
   2470   /* There is no way here to determine the length of the string in
   2471      the destination to which the SRC string is being appended so
   2472      just diagnose cases when the source string is longer than
   2473      the destination object.  */
   2474   access_data data (m_ptr_qry.rvals, stmt, access_read_write, NULL_TREE,
   2475 		    true, NULL_TREE, true);
   2476   const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
   2477   compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
   2478   tree destsize = compute_objsize (dest, stmt, ost, &data.dst, &m_ptr_qry);
   2479 
   2480   check_access (stmt, /*dstwrite=*/NULL_TREE, /*maxread=*/NULL_TREE,
   2481 		src, destsize, data.mode, &data, m_ptr_qry.rvals);
   2482 }
   2483 
   2484 /* Check a call STMT to strcat() for overflow and warn if it does.  */
   2485 
   2486 void
   2487 pass_waccess::check_strncat (gcall *stmt)
   2488 {
   2489   if (m_early_checks_p)
   2490     return;
   2491 
   2492   if (!warn_stringop_overflow && !warn_stringop_overread)
   2493     return;
   2494 
   2495   tree dest = call_arg (stmt, 0);
   2496   tree src = call_arg (stmt, 1);
   2497   /* The upper bound on the number of bytes to write.  */
   2498   tree maxread = call_arg (stmt, 2);
   2499 
   2500   /* Detect unterminated source (only).  */
   2501   if (!check_nul_terminated_array (stmt, src, maxread))
   2502     return;
   2503 
   2504   /* The length of the source sequence.  */
   2505   tree slen = c_strlen (src, 1);
   2506 
   2507   /* Try to determine the range of lengths that the source expression
   2508      refers to.  Since the lengths are only used for warning and not
   2509      for code generation disable strict mode below.  */
   2510   tree maxlen = slen;
   2511   if (!maxlen)
   2512     {
   2513       c_strlen_data lendata = { };
   2514       get_range_strlen (src, &lendata, /* eltsize = */ 1);
   2515       maxlen = lendata.maxbound;
   2516     }
   2517 
   2518   access_data data (m_ptr_qry.rvals, stmt, access_read_write);
   2519   /* Try to verify that the destination is big enough for the shortest
   2520      string.  First try to determine the size of the destination object
   2521      into which the source is being copied.  */
   2522   const int ost = warn_stringop_overflow - 1;
   2523   tree destsize = compute_objsize (dest, stmt, ost, &data.dst, &m_ptr_qry);
   2524 
   2525   /* Add one for the terminating nul.  */
   2526   tree srclen = (maxlen
   2527 		 ? fold_build2 (PLUS_EXPR, size_type_node, maxlen,
   2528 				size_one_node)
   2529 		 : NULL_TREE);
   2530 
   2531   /* The strncat function copies at most MAXREAD bytes and always appends
   2532      the terminating nul so the specified upper bound should never be equal
   2533      to (or greater than) the size of the destination.  */
   2534   if (tree_fits_uhwi_p (maxread) && tree_fits_uhwi_p (destsize)
   2535       && tree_int_cst_equal (destsize, maxread))
   2536     {
   2537       location_t loc = get_location (stmt);
   2538       warning_at (loc, OPT_Wstringop_overflow_,
   2539 		  "%qD specified bound %E equals destination size",
   2540 		  get_callee_fndecl (stmt), maxread);
   2541 
   2542       return;
   2543     }
   2544 
   2545   if (!srclen
   2546       || (maxread && tree_fits_uhwi_p (maxread)
   2547 	  && tree_fits_uhwi_p (srclen)
   2548 	  && tree_int_cst_lt (maxread, srclen)))
   2549     srclen = maxread;
   2550 
   2551   check_access (stmt, /*dstwrite=*/NULL_TREE, maxread, srclen,
   2552 		destsize, data.mode, &data, m_ptr_qry.rvals);
   2553 }
   2554 
   2555 /* Check a call STMT to stpcpy() or strcpy() for overflow and warn
   2556    if it does.  */
   2557 
   2558 void
   2559 pass_waccess::check_stxcpy (gcall *stmt)
   2560 {
   2561   if (m_early_checks_p)
   2562     return;
   2563 
   2564   tree dst = call_arg (stmt, 0);
   2565   tree src = call_arg (stmt, 1);
   2566 
   2567   tree size;
   2568   bool exact;
   2569   if (tree nonstr = unterminated_array (src, &size, &exact))
   2570     {
   2571       /* NONSTR refers to the non-nul terminated constant array.  */
   2572       warn_string_no_nul (get_location (stmt), stmt, NULL, src, nonstr,
   2573 			  size, exact);
   2574       return;
   2575     }
   2576 
   2577   if (warn_stringop_overflow)
   2578     {
   2579       access_data data (m_ptr_qry.rvals, stmt, access_read_write, NULL_TREE,
   2580 			true, NULL_TREE, true);
   2581       const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
   2582       compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
   2583       tree dstsize = compute_objsize (dst, stmt, ost, &data.dst, &m_ptr_qry);
   2584       check_access (stmt, /*dstwrite=*/ NULL_TREE,
   2585 		    /*maxread=*/ NULL_TREE, /*srcstr=*/ src,
   2586 		    dstsize, data.mode, &data, m_ptr_qry.rvals);
   2587     }
   2588 
   2589   /* Check to see if the argument was declared attribute nonstring
   2590      and if so, issue a warning since at this point it's not known
   2591      to be nul-terminated.  */
   2592   tree fndecl = get_callee_fndecl (stmt);
   2593   maybe_warn_nonstring_arg (fndecl, stmt);
   2594 }
   2595 
   2596 /* Check a call STMT to stpncpy() or strncpy() for overflow and warn
   2597    if it does.  */
   2598 
   2599 void
   2600 pass_waccess::check_stxncpy (gcall *stmt)
   2601 {
   2602   if (m_early_checks_p || !warn_stringop_overflow)
   2603     return;
   2604 
   2605   tree dst = call_arg (stmt, 0);
   2606   tree src = call_arg (stmt, 1);
   2607   /* The number of bytes to write (not the maximum).  */
   2608   tree len = call_arg (stmt, 2);
   2609 
   2610   access_data data (m_ptr_qry.rvals, stmt, access_read_write, len, true, len,
   2611 		    true);
   2612   const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
   2613   compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
   2614   tree dstsize = compute_objsize (dst, stmt, ost, &data.dst, &m_ptr_qry);
   2615 
   2616   check_access (stmt, /*dstwrite=*/len, /*maxread=*/len, src, dstsize,
   2617 		data.mode, &data, m_ptr_qry.rvals);
   2618 }
   2619 
   2620 /* Check a call STMT to stpncpy() or strncpy() for overflow and warn
   2621    if it does.  */
   2622 
   2623 void
   2624 pass_waccess::check_strncmp (gcall *stmt)
   2625 {
   2626   if (m_early_checks_p || !warn_stringop_overread)
   2627     return;
   2628 
   2629   tree arg1 = call_arg (stmt, 0);
   2630   tree arg2 = call_arg (stmt, 1);
   2631   tree bound = call_arg (stmt, 2);
   2632 
   2633   /* First check each argument separately, considering the bound.  */
   2634   if (!check_nul_terminated_array (stmt, arg1, bound)
   2635       || !check_nul_terminated_array (stmt, arg2, bound))
   2636     return;
   2637 
   2638   /* A strncmp read from each argument is constrained not just by
   2639      the bound but also by the length of the shorter string.  Specifying
   2640      a bound that's larger than the size of either array makes no sense
   2641      and is likely a bug.  When the length of neither of the two strings
   2642      is known but the sizes of both of the arrays they are stored in is,
   2643      issue a warning if the bound is larger than the size of
   2644      the larger of the two arrays.  */
   2645 
   2646   c_strlen_data lendata1{ }, lendata2{ };
   2647   tree len1 = c_strlen (arg1, 1, &lendata1);
   2648   tree len2 = c_strlen (arg2, 1, &lendata2);
   2649 
   2650   if (len1 && TREE_CODE (len1) != INTEGER_CST)
   2651     len1 = NULL_TREE;
   2652   if (len2 && TREE_CODE (len2) != INTEGER_CST)
   2653     len2 = NULL_TREE;
   2654 
   2655   if (len1 && len2)
   2656     /* If the length of both arguments was computed they must both be
   2657        nul-terminated and no further checking is necessary regardless
   2658        of the bound.  */
   2659     return;
   2660 
   2661   /* Check to see if the argument was declared with attribute nonstring
   2662      and if so, issue a warning since at this point it's not known to be
   2663      nul-terminated.  */
   2664   if (maybe_warn_nonstring_arg (get_callee_fndecl (stmt), stmt))
   2665     return;
   2666 
   2667   access_data adata1 (m_ptr_qry.rvals, stmt, access_read_only, NULL_TREE, false,
   2668 		      bound, true);
   2669   access_data adata2 (m_ptr_qry.rvals, stmt, access_read_only, NULL_TREE, false,
   2670 		      bound, true);
   2671 
   2672   /* Determine the range of the bound first and bail if it fails; it's
   2673      cheaper than computing the size of the objects.  */
   2674   tree bndrng[2] = { NULL_TREE, NULL_TREE };
   2675   get_size_range (m_ptr_qry.rvals, bound, stmt, bndrng, adata1.src_bndrng);
   2676   if (!bndrng[0] || integer_zerop (bndrng[0]))
   2677     return;
   2678 
   2679   if (len1 && tree_int_cst_lt (len1, bndrng[0]))
   2680     bndrng[0] = len1;
   2681   if (len2 && tree_int_cst_lt (len2, bndrng[0]))
   2682     bndrng[0] = len2;
   2683 
   2684   /* compute_objsize almost never fails (and ultimately should never
   2685      fail).  Don't bother to handle the rare case when it does.  */
   2686   if (!compute_objsize (arg1, stmt, 1, &adata1.src, &m_ptr_qry)
   2687       || !compute_objsize (arg2, stmt, 1, &adata2.src, &m_ptr_qry))
   2688     return;
   2689 
   2690   /* Compute the size of the remaining space in each array after
   2691      subtracting any offset into it.  */
   2692   offset_int rem1 = adata1.src.size_remaining ();
   2693   offset_int rem2 = adata2.src.size_remaining ();
   2694 
   2695   /* Cap REM1 and REM2 at the other if the other's argument is known
   2696      to be an unterminated array, either because there's no space
   2697      left in it after adding its offset or because it's constant and
   2698      has no nul.  */
   2699   if (rem1 == 0 || (rem1 < rem2 && lendata1.decl))
   2700     rem2 = rem1;
   2701   else if (rem2 == 0 || (rem2 < rem1 && lendata2.decl))
   2702     rem1 = rem2;
   2703 
   2704   /* Point PAD at the array to reference in the note if a warning
   2705      is issued.  */
   2706   access_data *pad = len1 ? &adata2 : &adata1;
   2707   offset_int maxrem = wi::max (rem1, rem2, UNSIGNED);
   2708   if (lendata1.decl || lendata2.decl
   2709       || maxrem < wi::to_offset (bndrng[0]))
   2710     {
   2711       /* Warn when either argument isn't nul-terminated or the maximum
   2712 	 remaining space in the two arrays is less than the bound.  */
   2713       tree func = get_callee_fndecl (stmt);
   2714       location_t loc = gimple_location (stmt);
   2715       maybe_warn_for_bound (OPT_Wstringop_overread, loc, stmt, func,
   2716 			    bndrng, wide_int_to_tree (sizetype, maxrem),
   2717 			    pad);
   2718     }
   2719 }
   2720 
   2721 /* Determine and check the sizes of the source and the destination
   2722    of calls to __builtin_{bzero,memcpy,mempcpy,memset} calls.  STMT is
   2723    the call statement, DEST is the destination argument, SRC is the source
   2724    argument or null, and SIZE is the number of bytes being accessed.  Use
   2725    Object Size type-0 regardless of the OPT_Wstringop_overflow_ setting.
   2726    Return true on success (no overflow or invalid sizes), false otherwise.  */
   2727 
   2728 void
   2729 pass_waccess::check_memop_access (gimple *stmt, tree dest, tree src, tree size)
   2730 {
   2731   if (m_early_checks_p)
   2732     return;
   2733 
   2734   /* For functions like memset and memcpy that operate on raw memory
   2735      try to determine the size of the largest source and destination
   2736      object using type-0 Object Size regardless of the object size
   2737      type specified by the option.  */
   2738   access_data data (m_ptr_qry.rvals, stmt, access_read_write);
   2739   tree srcsize
   2740     = src ? compute_objsize (src, stmt, 0, &data.src, &m_ptr_qry) : NULL_TREE;
   2741   tree dstsize = compute_objsize (dest, stmt, 0, &data.dst, &m_ptr_qry);
   2742 
   2743   check_access (stmt, size, /*maxread=*/NULL_TREE, srcsize, dstsize,
   2744 		data.mode, &data, m_ptr_qry.rvals);
   2745 }
   2746 
   2747 /* A convenience wrapper for check_access to check access by a read-only
   2748    function like puts or strcmp.  */
   2749 
   2750 void
   2751 pass_waccess::check_read_access (gimple *stmt, tree src,
   2752 				 tree bound /* = NULL_TREE */,
   2753 				 int ost /* = 1 */)
   2754 {
   2755   if (m_early_checks_p || !warn_stringop_overread)
   2756     return;
   2757 
   2758   if (bound && !useless_type_conversion_p (size_type_node, TREE_TYPE (bound)))
   2759     bound = fold_convert (size_type_node, bound);
   2760 
   2761   tree fndecl = get_callee_fndecl (stmt);
   2762   maybe_warn_nonstring_arg (fndecl, stmt);
   2763 
   2764   access_data data (m_ptr_qry.rvals, stmt, access_read_only, NULL_TREE,
   2765 		   false, bound, true);
   2766   compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
   2767   check_access (stmt, /*dstwrite=*/ NULL_TREE, /*maxread=*/ bound,
   2768 		/*srcstr=*/ src, /*dstsize=*/ NULL_TREE, data.mode,
   2769 		&data, m_ptr_qry.rvals);
   2770 }
   2771 
   2772 /* Return true if memory model ORD is constant in the context of STMT and
   2773    set *CSTVAL to the constant value.  Otherwise return false.  Warn for
   2774    invalid ORD.  */
   2775 
   2776 bool
   2777 memmodel_to_uhwi (tree ord, gimple *stmt, unsigned HOST_WIDE_INT *cstval)
   2778 {
   2779   unsigned HOST_WIDE_INT val;
   2780 
   2781   if (TREE_CODE (ord) == INTEGER_CST)
   2782     {
   2783       if (!tree_fits_uhwi_p (ord))
   2784 	return false;
   2785       val = tree_to_uhwi (ord);
   2786     }
   2787   else
   2788     {
   2789       /* Use the range query to determine constant values in the absence
   2790 	 of constant propagation (such as at -O0).  */
   2791       value_range rng;
   2792       if (!get_range_query (cfun)->range_of_expr (rng, ord, stmt)
   2793 	  || !rng.constant_p ()
   2794 	  || !rng.singleton_p (&ord))
   2795 	return false;
   2796 
   2797       wide_int lob = rng.lower_bound ();
   2798       if (!wi::fits_uhwi_p (lob))
   2799 	return false;
   2800 
   2801       val = lob.to_shwi ();
   2802     }
   2803 
   2804   if (targetm.memmodel_check)
   2805     /* This might warn for an invalid VAL but return a conservatively
   2806        valid result.  */
   2807     val = targetm.memmodel_check (val);
   2808   else if (val & ~MEMMODEL_MASK)
   2809     {
   2810       tree fndecl = gimple_call_fndecl (stmt);
   2811       location_t loc = gimple_location (stmt);
   2812       loc = expansion_point_location_if_in_system_header (loc);
   2813 
   2814       warning_at (loc, OPT_Winvalid_memory_model,
   2815 		  "unknown architecture specifier in memory model "
   2816 		  "%wi for %qD", val, fndecl);
   2817       return false;
   2818     }
   2819 
   2820   *cstval = val;
   2821 
   2822   return true;
   2823 }
   2824 
   2825 /* Valid memory model for each set of atomic built-in functions.  */
   2826 
   2827 struct memmodel_pair
   2828 {
   2829   memmodel modval;
   2830   const char* modname;
   2831 
   2832 #define MEMMODEL_PAIR(val, str)			\
   2833   { MEMMODEL_ ## val, "memory_order_" str }
   2834 };
   2835 
   2836 /* Valid memory models in the order of increasing strength.  */
   2837 
   2838 static const memmodel_pair memory_models[] =
   2839   { MEMMODEL_PAIR (RELAXED, "relaxed"),
   2840     MEMMODEL_PAIR (SEQ_CST, "seq_cst"),
   2841     MEMMODEL_PAIR (ACQUIRE, "acquire"),
   2842     MEMMODEL_PAIR (CONSUME, "consume"),
   2843     MEMMODEL_PAIR (RELEASE, "release"),
   2844     MEMMODEL_PAIR (ACQ_REL, "acq_rel")
   2845   };
   2846 
   2847 /* Return the name of the memory model VAL.  */
   2848 
   2849 static const char*
   2850 memmodel_name (unsigned HOST_WIDE_INT val)
   2851 {
   2852   val = memmodel_base (val);
   2853 
   2854   for (unsigned i = 0; i != sizeof memory_models / sizeof *memory_models; ++i)
   2855     {
   2856       if (val == memory_models[i].modval)
   2857 	return memory_models[i].modname;
   2858     }
   2859   return NULL;
   2860 }
   2861 
   2862 /* Indices of valid MEMORY_MODELS above for corresponding atomic operations.  */
   2863 static const unsigned char load_models[] = { 0, 1, 2, 3, UCHAR_MAX };
   2864 static const unsigned char store_models[] = { 0, 1, 4, UCHAR_MAX };
   2865 static const unsigned char xchg_models[] = { 0, 1, 3, 4, 5, UCHAR_MAX };
   2866 static const unsigned char flag_clr_models[] = { 0, 1, 4, UCHAR_MAX };
   2867 static const unsigned char all_models[] = { 0, 1, 2, 3, 4, 5, UCHAR_MAX };
   2868 
   2869 /* Check the success memory model argument ORD_SUCS to the call STMT to
   2870    an atomic function and warn if it's invalid.  If nonnull, also check
   2871    the failure memory model ORD_FAIL and warn if it's invalid.  Return
   2872    true if a warning has been issued.  */
   2873 
   2874 bool
   2875 pass_waccess::maybe_warn_memmodel (gimple *stmt, tree ord_sucs,
   2876 				   tree ord_fail, const unsigned char *valid)
   2877 {
   2878   unsigned HOST_WIDE_INT sucs, fail = 0;
   2879   if (!memmodel_to_uhwi (ord_sucs, stmt, &sucs)
   2880       || (ord_fail && !memmodel_to_uhwi (ord_fail, stmt, &fail)))
   2881     return false;
   2882 
   2883   bool is_valid = false;
   2884   if (valid)
   2885     for (unsigned i = 0; valid[i] != UCHAR_MAX; ++i)
   2886       {
   2887 	memmodel model = memory_models[valid[i]].modval;
   2888 	if (memmodel_base (sucs) == model)
   2889 	  {
   2890 	    is_valid = true;
   2891 	    break;
   2892 	  }
   2893       }
   2894   else
   2895     is_valid = true;
   2896 
   2897   tree fndecl = gimple_call_fndecl (stmt);
   2898   location_t loc = gimple_location (stmt);
   2899   loc = expansion_point_location_if_in_system_header (loc);
   2900 
   2901   if (!is_valid)
   2902     {
   2903       bool warned = false;
   2904       if (const char *modname = memmodel_name (sucs))
   2905 	warned = warning_at (loc, OPT_Winvalid_memory_model,
   2906 			     "invalid memory model %qs for %qD",
   2907 			     modname, fndecl);
   2908       else
   2909 	warned = warning_at (loc, OPT_Winvalid_memory_model,
   2910 			     "invalid memory model %wi for %qD",
   2911 			     sucs, fndecl);
   2912 
   2913       if (!warned)
   2914 	return false;
   2915 
   2916       /* Print a note with the valid memory models.  */
   2917       pretty_printer pp;
   2918       pp_show_color (&pp) = pp_show_color (global_dc->printer);
   2919       for (unsigned i = 0; valid[i] != UCHAR_MAX; ++i)
   2920 	{
   2921 	  const char *modname = memory_models[valid[i]].modname;
   2922 	  pp_printf (&pp, "%s%qs", i ? ", " : "", modname);
   2923 	}
   2924 
   2925       inform (loc, "valid models are %s", pp_formatted_text (&pp));
   2926       return true;
   2927     }
   2928 
   2929   if (!ord_fail)
   2930     return false;
   2931 
   2932   if (fail == MEMMODEL_RELEASE || fail == MEMMODEL_ACQ_REL)
   2933     if (const char *failname = memmodel_name (fail))
   2934       {
   2935 	/* If both memory model arguments are valid but their combination
   2936 	   is not, use their names in the warning.  */
   2937 	if (!warning_at (loc, OPT_Winvalid_memory_model,
   2938 			 "invalid failure memory model %qs for %qD",
   2939 			 failname, fndecl))
   2940 	  return false;
   2941 
   2942 	inform (loc,
   2943 		"valid failure models are %qs, %qs, %qs, %qs",
   2944 		"memory_order_relaxed", "memory_order_seq_cst",
   2945 		"memory_order_acquire", "memory_order_consume");
   2946 	return true;
   2947       }
   2948 
   2949   if (memmodel_base (fail) <= memmodel_base (sucs))
   2950     return false;
   2951 
   2952   if (const char *sucsname = memmodel_name (sucs))
   2953     if (const char *failname = memmodel_name (fail))
   2954       {
   2955 	/* If both memory model arguments are valid but their combination
   2956 	   is not, use their names in the warning.  */
   2957 	if (!warning_at (loc, OPT_Winvalid_memory_model,
   2958 			 "failure memory model %qs cannot be stronger "
   2959 			 "than success memory model %qs for %qD",
   2960 			 failname, sucsname, fndecl))
   2961 	  return false;
   2962 
   2963 	/* Print a note with the valid failure memory models which are
   2964 	   those with a value less than or equal to the success mode.  */
   2965 	char buf[120];
   2966 	*buf = '\0';
   2967 	for (unsigned i = 0;
   2968 	     memory_models[i].modval <= memmodel_base (sucs); ++i)
   2969 	  {
   2970 	    if (*buf)
   2971 	      strcat (buf, ", ");
   2972 
   2973 	    const char *modname = memory_models[valid[i]].modname;
   2974 	    sprintf (buf + strlen (buf), "'%s'", modname);
   2975 	  }
   2976 
   2977 	inform (loc, "valid models are %s", buf);
   2978 	return true;
   2979       }
   2980 
   2981   /* If either memory model argument value is invalid use the numerical
   2982      value of both in the message.  */
   2983   return warning_at (loc, OPT_Winvalid_memory_model,
   2984 		     "failure memory model %wi cannot be stronger "
   2985 		     "than success memory model %wi for %qD",
   2986 		     fail, sucs, fndecl);
   2987 }
   2988 
   2989 /* Wrapper for the above.  */
   2990 
   2991 void
   2992 pass_waccess::check_atomic_memmodel (gimple *stmt, tree ord_sucs,
   2993 				     tree ord_fail, const unsigned char *valid)
   2994 {
   2995   if (warning_suppressed_p (stmt, OPT_Winvalid_memory_model))
   2996     return;
   2997 
   2998   if (!maybe_warn_memmodel (stmt, ord_sucs, ord_fail, valid))
   2999     return;
   3000 
   3001   suppress_warning (stmt, OPT_Winvalid_memory_model);
   3002 }
   3003 
   3004 /* Check a call STMT to an atomic or sync built-in.  */
   3005 
   3006 bool
   3007 pass_waccess::check_atomic_builtin (gcall *stmt)
   3008 {
   3009   tree callee = gimple_call_fndecl (stmt);
   3010   if (!callee)
   3011     return false;
   3012 
   3013   /* The size in bytes of the access by the function, and the number
   3014      of the second argument to check (if any).  */
   3015   unsigned bytes = 0, arg2 = UINT_MAX;
   3016   unsigned sucs_arg = UINT_MAX, fail_arg = UINT_MAX;
   3017   /* Points to the array of indices of valid memory models.  */
   3018   const unsigned char *pvalid_models = NULL;
   3019 
   3020   switch (DECL_FUNCTION_CODE (callee))
   3021     {
   3022 #define BUILTIN_ACCESS_SIZE_FNSPEC(N)			\
   3023       BUILT_IN_SYNC_FETCH_AND_ADD_ ## N:		\
   3024     case BUILT_IN_SYNC_FETCH_AND_SUB_ ## N:		\
   3025     case BUILT_IN_SYNC_FETCH_AND_OR_ ## N:		\
   3026     case BUILT_IN_SYNC_FETCH_AND_AND_ ## N:		\
   3027     case BUILT_IN_SYNC_FETCH_AND_XOR_ ## N:		\
   3028     case BUILT_IN_SYNC_FETCH_AND_NAND_ ## N:		\
   3029     case BUILT_IN_SYNC_ADD_AND_FETCH_ ## N:		\
   3030     case BUILT_IN_SYNC_SUB_AND_FETCH_ ## N:		\
   3031     case BUILT_IN_SYNC_OR_AND_FETCH_ ## N:		\
   3032     case BUILT_IN_SYNC_AND_AND_FETCH_ ## N:		\
   3033     case BUILT_IN_SYNC_XOR_AND_FETCH_ ## N:		\
   3034     case BUILT_IN_SYNC_NAND_AND_FETCH_ ## N:		\
   3035     case BUILT_IN_SYNC_LOCK_TEST_AND_SET_ ## N:		\
   3036     case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_ ## N:	\
   3037     case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_ ## N:	\
   3038     case BUILT_IN_SYNC_LOCK_RELEASE_ ## N:		\
   3039       bytes = N;					\
   3040       break;						\
   3041     case BUILT_IN_ATOMIC_LOAD_ ## N:			\
   3042       pvalid_models = load_models;			\
   3043       sucs_arg = 1;					\
   3044       /* FALLTHROUGH */					\
   3045     case BUILT_IN_ATOMIC_STORE_ ## N:			\
   3046       if (!pvalid_models)				\
   3047 	pvalid_models = store_models;			\
   3048       /* FALLTHROUGH */					\
   3049     case BUILT_IN_ATOMIC_ADD_FETCH_ ## N:		\
   3050     case BUILT_IN_ATOMIC_SUB_FETCH_ ## N:		\
   3051     case BUILT_IN_ATOMIC_AND_FETCH_ ## N:		\
   3052     case BUILT_IN_ATOMIC_NAND_FETCH_ ## N:		\
   3053     case BUILT_IN_ATOMIC_XOR_FETCH_ ## N:		\
   3054     case BUILT_IN_ATOMIC_OR_FETCH_ ## N:		\
   3055     case BUILT_IN_ATOMIC_FETCH_ADD_ ## N:		\
   3056     case BUILT_IN_ATOMIC_FETCH_SUB_ ## N:		\
   3057     case BUILT_IN_ATOMIC_FETCH_AND_ ## N:		\
   3058     case BUILT_IN_ATOMIC_FETCH_NAND_ ## N:		\
   3059     case BUILT_IN_ATOMIC_FETCH_OR_ ## N:		\
   3060     case BUILT_IN_ATOMIC_FETCH_XOR_ ## N:		\
   3061 	bytes = N;					\
   3062 	if (sucs_arg == UINT_MAX)			\
   3063 	  sucs_arg = 2;					\
   3064 	if (!pvalid_models)				\
   3065 	  pvalid_models = all_models;			\
   3066 	break;						\
   3067     case BUILT_IN_ATOMIC_EXCHANGE_ ## N:		\
   3068 	bytes = N;					\
   3069 	sucs_arg = 3;					\
   3070 	pvalid_models = xchg_models;			\
   3071 	break;						\
   3072     case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_ ## N:	\
   3073 	bytes = N;					\
   3074 	sucs_arg = 4;					\
   3075 	fail_arg = 5;					\
   3076 	pvalid_models = all_models;			\
   3077 	arg2 = 1
   3078 
   3079     case BUILTIN_ACCESS_SIZE_FNSPEC (1);
   3080       break;
   3081     case BUILTIN_ACCESS_SIZE_FNSPEC (2);
   3082       break;
   3083     case BUILTIN_ACCESS_SIZE_FNSPEC (4);
   3084       break;
   3085     case BUILTIN_ACCESS_SIZE_FNSPEC (8);
   3086       break;
   3087     case BUILTIN_ACCESS_SIZE_FNSPEC (16);
   3088       break;
   3089 
   3090     case BUILT_IN_ATOMIC_CLEAR:
   3091       sucs_arg = 1;
   3092       pvalid_models = flag_clr_models;
   3093       break;
   3094 
   3095     default:
   3096       return false;
   3097     }
   3098 
   3099   unsigned nargs = gimple_call_num_args (stmt);
   3100   if (sucs_arg < nargs)
   3101     {
   3102       tree ord_sucs = gimple_call_arg (stmt, sucs_arg);
   3103       tree ord_fail = NULL_TREE;
   3104       if (fail_arg < nargs)
   3105 	ord_fail = gimple_call_arg (stmt, fail_arg);
   3106       check_atomic_memmodel (stmt, ord_sucs, ord_fail, pvalid_models);
   3107     }
   3108 
   3109   if (!bytes)
   3110     return true;
   3111 
   3112   tree size = build_int_cstu (sizetype, bytes);
   3113   tree dst = gimple_call_arg (stmt, 0);
   3114   check_memop_access (stmt, dst, NULL_TREE, size);
   3115 
   3116   if (arg2 != UINT_MAX)
   3117     {
   3118       tree dst = gimple_call_arg (stmt, arg2);
   3119       check_memop_access (stmt, dst, NULL_TREE, size);
   3120     }
   3121 
   3122   return true;
   3123 }
   3124 
   3125 /* Check call STMT to a built-in function for invalid accesses.  Return
   3126    true if a call has been handled.  */
   3127 
   3128 bool
   3129 pass_waccess::check_builtin (gcall *stmt)
   3130 {
   3131   tree callee = gimple_call_fndecl (stmt);
   3132   if (!callee)
   3133     return false;
   3134 
   3135   switch (DECL_FUNCTION_CODE (callee))
   3136     {
   3137     case BUILT_IN_ALLOCA:
   3138     case BUILT_IN_ALLOCA_WITH_ALIGN:
   3139     case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
   3140       check_alloca (stmt);
   3141       return true;
   3142 
   3143     case BUILT_IN_EXECL:
   3144     case BUILT_IN_EXECLE:
   3145     case BUILT_IN_EXECLP:
   3146     case BUILT_IN_EXECV:
   3147     case BUILT_IN_EXECVE:
   3148     case BUILT_IN_EXECVP:
   3149       check_read_access (stmt, call_arg (stmt, 0));
   3150       return true;
   3151 
   3152     case BUILT_IN_FREE:
   3153     case BUILT_IN_REALLOC:
   3154       if (!m_early_checks_p)
   3155 	{
   3156 	  tree arg = call_arg (stmt, 0);
   3157 	  if (TREE_CODE (arg) == SSA_NAME)
   3158 	    check_pointer_uses (stmt, arg);
   3159 	}
   3160       return true;
   3161 
   3162     case BUILT_IN_GETTEXT:
   3163     case BUILT_IN_PUTS:
   3164     case BUILT_IN_PUTS_UNLOCKED:
   3165     case BUILT_IN_STRDUP:
   3166       check_read_access (stmt, call_arg (stmt, 0));
   3167       return true;
   3168 
   3169     case BUILT_IN_INDEX:
   3170     case BUILT_IN_RINDEX:
   3171     case BUILT_IN_STRCHR:
   3172     case BUILT_IN_STRRCHR:
   3173     case BUILT_IN_STRLEN:
   3174       check_read_access (stmt, call_arg (stmt, 0));
   3175       return true;
   3176 
   3177     case BUILT_IN_FPUTS:
   3178     case BUILT_IN_FPUTS_UNLOCKED:
   3179       check_read_access (stmt, call_arg (stmt, 0));
   3180       return true;
   3181 
   3182     case BUILT_IN_STRNDUP:
   3183     case BUILT_IN_STRNLEN:
   3184       {
   3185 	tree str = call_arg (stmt, 0);
   3186 	tree len = call_arg (stmt, 1);
   3187 	check_read_access (stmt, str, len);
   3188 	return true;
   3189       }
   3190 
   3191     case BUILT_IN_STRCAT:
   3192       check_strcat (stmt);
   3193       return true;
   3194 
   3195     case BUILT_IN_STRNCAT:
   3196       check_strncat (stmt);
   3197       return true;
   3198 
   3199     case BUILT_IN_STPCPY:
   3200     case BUILT_IN_STRCPY:
   3201       check_stxcpy (stmt);
   3202       return true;
   3203 
   3204     case BUILT_IN_STPNCPY:
   3205     case BUILT_IN_STRNCPY:
   3206       check_stxncpy (stmt);
   3207       return true;
   3208 
   3209     case BUILT_IN_STRCASECMP:
   3210     case BUILT_IN_STRCMP:
   3211     case BUILT_IN_STRPBRK:
   3212     case BUILT_IN_STRSPN:
   3213     case BUILT_IN_STRCSPN:
   3214     case BUILT_IN_STRSTR:
   3215       check_read_access (stmt, call_arg (stmt, 0));
   3216       check_read_access (stmt, call_arg (stmt, 1));
   3217       return true;
   3218 
   3219     case BUILT_IN_STRNCASECMP:
   3220     case BUILT_IN_STRNCMP:
   3221       check_strncmp (stmt);
   3222       return true;
   3223 
   3224     case BUILT_IN_MEMCMP:
   3225       {
   3226 	tree a1 = call_arg (stmt, 0);
   3227 	tree a2 = call_arg (stmt, 1);
   3228 	tree len = call_arg (stmt, 2);
   3229 	check_read_access (stmt, a1, len, 0);
   3230 	check_read_access (stmt, a2, len, 0);
   3231 	return true;
   3232       }
   3233 
   3234     case BUILT_IN_MEMCPY:
   3235     case BUILT_IN_MEMPCPY:
   3236     case BUILT_IN_MEMMOVE:
   3237       {
   3238 	tree dst = call_arg (stmt, 0);
   3239 	tree src = call_arg (stmt, 1);
   3240 	tree len = call_arg (stmt, 2);
   3241 	check_memop_access (stmt, dst, src, len);
   3242 	return true;
   3243       }
   3244 
   3245     case BUILT_IN_MEMCHR:
   3246       {
   3247 	tree src = call_arg (stmt, 0);
   3248 	tree len = call_arg (stmt, 2);
   3249 	check_read_access (stmt, src, len, 0);
   3250 	return true;
   3251       }
   3252 
   3253     case BUILT_IN_MEMSET:
   3254       {
   3255 	tree dst = call_arg (stmt, 0);
   3256 	tree len = call_arg (stmt, 2);
   3257 	check_memop_access (stmt, dst, NULL_TREE, len);
   3258 	return true;
   3259       }
   3260 
   3261     default:
   3262       if (check_atomic_builtin (stmt))
   3263 	return true;
   3264       break;
   3265     }
   3266 
   3267   return false;
   3268 }
   3269 
   3270 /* Returns the type of the argument ARGNO to function with type FNTYPE
   3271    or null when the type cannot be determined or no such argument exists.  */
   3272 
   3273 static tree
   3274 fntype_argno_type (tree fntype, unsigned argno)
   3275 {
   3276   if (!prototype_p (fntype))
   3277     return NULL_TREE;
   3278 
   3279   tree argtype;
   3280   function_args_iterator it;
   3281   FOREACH_FUNCTION_ARGS (fntype, argtype, it)
   3282     if (argno-- == 0)
   3283       return argtype;
   3284 
   3285   return NULL_TREE;
   3286 }
   3287 
   3288 /* Helper to append the "human readable" attribute access specification
   3289    described by ACCESS to the array ATTRSTR with size STRSIZE.  Used in
   3290    diagnostics.  */
   3291 
   3292 static inline void
   3293 append_attrname (const std::pair<int, attr_access> &access,
   3294 		 char *attrstr, size_t strsize)
   3295 {
   3296   if (access.second.internal_p)
   3297     return;
   3298 
   3299   tree str = access.second.to_external_string ();
   3300   gcc_assert (strsize >= (size_t) TREE_STRING_LENGTH (str));
   3301   strcpy (attrstr, TREE_STRING_POINTER (str));
   3302 }
   3303 
   3304 /* Iterate over attribute access read-only, read-write, and write-only
   3305    arguments and diagnose past-the-end accesses and related problems
   3306    in the function call EXP.  */
   3307 
   3308 void
   3309 pass_waccess::maybe_check_access_sizes (rdwr_map *rwm, tree fndecl, tree fntype,
   3310 					gimple *stmt)
   3311 {
   3312   if (warning_suppressed_p (stmt, OPT_Wnonnull)
   3313       || warning_suppressed_p (stmt, OPT_Wstringop_overflow_))
   3314     return;
   3315 
   3316   auto_diagnostic_group adg;
   3317 
   3318   /* Set if a warning has been issued for any argument (used to decide
   3319      whether to emit an informational note at the end).  */
   3320   opt_code opt_warned = no_warning;
   3321 
   3322   /* A string describing the attributes that the warnings issued by this
   3323      function apply to.  Used to print one informational note per function
   3324      call, rather than one per warning.  That reduces clutter.  */
   3325   char attrstr[80];
   3326   attrstr[0] = 0;
   3327 
   3328   for (rdwr_map::iterator it = rwm->begin (); it != rwm->end (); ++it)
   3329     {
   3330       std::pair<int, attr_access> access = *it;
   3331 
   3332       /* Get the function call arguments corresponding to the attribute's
   3333 	 positional arguments.  When both arguments have been specified
   3334 	 there will be two entries in *RWM, one for each.  They are
   3335 	 cross-referenced by their respective argument numbers in
   3336 	 ACCESS.PTRARG and ACCESS.SIZARG.  */
   3337       const int ptridx = access.second.ptrarg;
   3338       const int sizidx = access.second.sizarg;
   3339 
   3340       gcc_assert (ptridx != -1);
   3341       gcc_assert (access.first == ptridx || access.first == sizidx);
   3342 
   3343       /* The pointer is set to null for the entry corresponding to
   3344 	 the size argument.  Skip it.  It's handled when the entry
   3345 	 corresponding to the pointer argument comes up.  */
   3346       if (!access.second.ptr)
   3347 	continue;
   3348 
   3349       tree ptrtype = fntype_argno_type (fntype, ptridx);
   3350       if (!ptrtype)
   3351 	/* A function with a prototype was redeclared without one and
   3352 	   the prototype has been lost.  See pr102759.  Avoid dealing
   3353 	   with this pathological case.  */
   3354 	return;
   3355 
   3356       tree argtype = TREE_TYPE (ptrtype);
   3357 
   3358       /* The size of the access by the call in elements.  */
   3359       tree access_nelts;
   3360       if (sizidx == -1)
   3361 	{
   3362 	  /* If only the pointer attribute operand was specified and
   3363 	     not size, set SIZE to the greater of MINSIZE or size of
   3364 	     one element of the pointed to type to detect smaller
   3365 	     objects (null pointers are diagnosed in this case only
   3366 	     if the pointer is also declared with attribute nonnull.  */
   3367 	  if (access.second.minsize
   3368 	      && access.second.minsize != HOST_WIDE_INT_M1U)
   3369 	    access_nelts = build_int_cstu (sizetype, access.second.minsize);
   3370 	  else if (VOID_TYPE_P (argtype) && access.second.mode == access_none)
   3371 	    /* Treat access mode none on a void* argument as expecting
   3372 	       as little as zero bytes.  */
   3373 	    access_nelts = size_zero_node;
   3374 	  else
   3375 	    access_nelts = size_one_node;
   3376 	}
   3377       else
   3378 	access_nelts = rwm->get (sizidx)->size;
   3379 
   3380       /* Format the value or range to avoid an explosion of messages.  */
   3381       char sizstr[80];
   3382       tree sizrng[2] = { size_zero_node, build_all_ones_cst (sizetype) };
   3383       if (get_size_range (m_ptr_qry.rvals, access_nelts, stmt, sizrng, 1))
   3384 	{
   3385 	  char *s0 = print_generic_expr_to_str (sizrng[0]);
   3386 	  if (tree_int_cst_equal (sizrng[0], sizrng[1]))
   3387 	    {
   3388 	      gcc_checking_assert (strlen (s0) < sizeof sizstr);
   3389 	      strcpy (sizstr, s0);
   3390 	    }
   3391 	  else
   3392 	    {
   3393 	      char *s1 = print_generic_expr_to_str (sizrng[1]);
   3394 	      gcc_checking_assert (strlen (s0) + strlen (s1)
   3395 				   < sizeof sizstr - 4);
   3396 	      sprintf (sizstr, "[%.37s, %.37s]", s0, s1);
   3397 	      free (s1);
   3398 	    }
   3399 	  free (s0);
   3400 	}
   3401       else
   3402 	*sizstr = '\0';
   3403 
   3404       /* Set if a warning has been issued for the current argument.  */
   3405       opt_code arg_warned = no_warning;
   3406       location_t loc = get_location (stmt);
   3407       tree ptr = access.second.ptr;
   3408       if (*sizstr
   3409 	  && tree_int_cst_sgn (sizrng[0]) < 0
   3410 	  && tree_int_cst_sgn (sizrng[1]) < 0)
   3411 	{
   3412 	  /* Warn about negative sizes.  */
   3413 	  if (access.second.internal_p)
   3414 	    {
   3415 	      const std::string argtypestr
   3416 		= access.second.array_as_string (ptrtype);
   3417 
   3418 	      if (warning_at (loc, OPT_Wstringop_overflow_,
   3419 			      "bound argument %i value %s is "
   3420 			      "negative for a variable length array "
   3421 			      "argument %i of type %s",
   3422 			      sizidx + 1, sizstr,
   3423 			      ptridx + 1, argtypestr.c_str ()))
   3424 		arg_warned = OPT_Wstringop_overflow_;
   3425 	    }
   3426 	  else if (warning_at (loc, OPT_Wstringop_overflow_,
   3427 			       "argument %i value %s is negative",
   3428 			       sizidx + 1, sizstr))
   3429 	    arg_warned = OPT_Wstringop_overflow_;
   3430 
   3431 	  if (arg_warned != no_warning)
   3432 	    {
   3433 	      append_attrname (access, attrstr, sizeof attrstr);
   3434 	      /* Remember a warning has been issued and avoid warning
   3435 		 again below for the same attribute.  */
   3436 	      opt_warned = arg_warned;
   3437 	      continue;
   3438 	    }
   3439 	}
   3440 
   3441       /* The size of the access by the call in bytes.  */
   3442       tree access_size = NULL_TREE;
   3443       if (tree_int_cst_sgn (sizrng[0]) >= 0)
   3444 	{
   3445 	  if (COMPLETE_TYPE_P (argtype))
   3446 	    {
   3447 	      /* Multiply ACCESS_SIZE by the size of the type the pointer
   3448 		 argument points to.  If it's incomplete the size is used
   3449 		 as is.  */
   3450 	      if (tree argsize = TYPE_SIZE_UNIT (argtype))
   3451 		if (TREE_CODE (argsize) == INTEGER_CST)
   3452 		  {
   3453 		    const int prec = TYPE_PRECISION (sizetype);
   3454 		    wide_int minsize = wi::to_wide (sizrng[0], prec);
   3455 		    minsize *= wi::to_wide (argsize, prec);
   3456 		    access_size = wide_int_to_tree (sizetype, minsize);
   3457 		  }
   3458 	    }
   3459 	  else
   3460 	    access_size = access_nelts;
   3461 	}
   3462 
   3463       if (integer_zerop (ptr))
   3464 	{
   3465 	  if (sizidx >= 0 && tree_int_cst_sgn (sizrng[0]) > 0)
   3466 	    {
   3467 	      /* Warn about null pointers with positive sizes.  This is
   3468 		 different from also declaring the pointer argument with
   3469 		 attribute nonnull when the function accepts null pointers
   3470 		 only when the corresponding size is zero.  */
   3471 	      if (access.second.internal_p)
   3472 		{
   3473 		  const std::string argtypestr
   3474 		    = access.second.array_as_string (ptrtype);
   3475 
   3476 		  if (warning_at (loc, OPT_Wnonnull,
   3477 				  "argument %i of variable length "
   3478 				  "array %s is null but "
   3479 				  "the corresponding bound argument "
   3480 				  "%i value is %s",
   3481 				  ptridx + 1, argtypestr.c_str (),
   3482 				  sizidx + 1, sizstr))
   3483 		    arg_warned = OPT_Wnonnull;
   3484 		}
   3485 	      else if (warning_at (loc, OPT_Wnonnull,
   3486 				   "argument %i is null but "
   3487 				   "the corresponding size argument "
   3488 				   "%i value is %s",
   3489 				   ptridx + 1, sizidx + 1, sizstr))
   3490 		arg_warned = OPT_Wnonnull;
   3491 	    }
   3492 	  else if (access_size && access.second.static_p)
   3493 	    {
   3494 	      /* Warn about null pointers for [static N] array arguments
   3495 		 but do not warn for ordinary (i.e., nonstatic) arrays.  */
   3496 	      if (warning_at (loc, OPT_Wnonnull,
   3497 			      "argument %i to %<%T[static %E]%> "
   3498 			      "is null where non-null expected",
   3499 			      ptridx + 1, argtype, access_nelts))
   3500 		arg_warned = OPT_Wnonnull;
   3501 	    }
   3502 
   3503 	  if (arg_warned != no_warning)
   3504 	    {
   3505 	      append_attrname (access, attrstr, sizeof attrstr);
   3506 	      /* Remember a warning has been issued and avoid warning
   3507 		 again below for the same attribute.  */
   3508 	      opt_warned = OPT_Wnonnull;
   3509 	      continue;
   3510 	    }
   3511 	}
   3512 
   3513       access_data data (m_ptr_qry.rvals, stmt, access.second.mode,
   3514 			NULL_TREE, false, NULL_TREE, false);
   3515       access_ref* const pobj = (access.second.mode == access_write_only
   3516 				? &data.dst : &data.src);
   3517       tree objsize = compute_objsize (ptr, stmt, 1, pobj, &m_ptr_qry);
   3518 
   3519       /* The size of the destination or source object.  */
   3520       tree dstsize = NULL_TREE, srcsize = NULL_TREE;
   3521       if (access.second.mode == access_read_only
   3522 	  || access.second.mode == access_none)
   3523 	{
   3524 	  /* For a read-only argument there is no destination.  For
   3525 	     no access, set the source as well and differentiate via
   3526 	     the access flag below.  */
   3527 	  srcsize = objsize;
   3528 	  if (access.second.mode == access_read_only
   3529 	      || access.second.mode == access_none)
   3530 	    {
   3531 	      /* For a read-only attribute there is no destination so
   3532 		 clear OBJSIZE.  This emits "reading N bytes" kind of
   3533 		 diagnostics instead of the "writing N bytes" kind,
   3534 		 unless MODE is none.  */
   3535 	      objsize = NULL_TREE;
   3536 	    }
   3537 	}
   3538       else
   3539 	dstsize = objsize;
   3540 
   3541       /* Clear the no-warning bit in case it was set by check_access
   3542 	 in a prior iteration so that accesses via different arguments
   3543 	 are diagnosed.  */
   3544       suppress_warning (stmt, OPT_Wstringop_overflow_, false);
   3545       access_mode mode = data.mode;
   3546       if (mode == access_deferred)
   3547 	mode = TYPE_READONLY (argtype) ? access_read_only : access_read_write;
   3548       check_access (stmt, access_size, /*maxread=*/ NULL_TREE, srcsize,
   3549 		    dstsize, mode, &data, m_ptr_qry.rvals);
   3550 
   3551       if (warning_suppressed_p (stmt, OPT_Wstringop_overflow_))
   3552 	opt_warned = OPT_Wstringop_overflow_;
   3553       if (opt_warned != no_warning)
   3554 	{
   3555 	  if (access.second.internal_p)
   3556 	    {
   3557 	      unsigned HOST_WIDE_INT nelts =
   3558 		access_nelts ? access.second.minsize : HOST_WIDE_INT_M1U;
   3559 	      tree arrtype = build_printable_array_type (argtype, nelts);
   3560 	      inform (loc, "referencing argument %u of type %qT",
   3561 		      ptridx + 1, arrtype);
   3562 	    }
   3563 	  else
   3564 	    /* If check_access issued a warning above, append the relevant
   3565 	       attribute to the string.  */
   3566 	    append_attrname (access, attrstr, sizeof attrstr);
   3567 	}
   3568     }
   3569 
   3570   if (*attrstr)
   3571     {
   3572       if (fndecl)
   3573 	inform (get_location (fndecl),
   3574 		"in a call to function %qD declared with attribute %qs",
   3575 		fndecl, attrstr);
   3576       else
   3577 	inform (get_location (stmt),
   3578 		"in a call with type %qT and attribute %qs",
   3579 		fntype, attrstr);
   3580     }
   3581   else if (opt_warned != no_warning)
   3582     {
   3583       if (fndecl)
   3584 	inform (get_location (fndecl),
   3585 		"in a call to function %qD", fndecl);
   3586       else
   3587 	inform (get_location (stmt),
   3588 		"in a call with type %qT", fntype);
   3589     }
   3590 
   3591   /* Set the bit in case it was cleared and not set above.  */
   3592   if (opt_warned != no_warning)
   3593     suppress_warning (stmt, opt_warned);
   3594 }
   3595 
   3596 /* Check call STMT to an ordinary (non-built-in) function for invalid
   3597    accesses.  Return true if a call has been handled.  */
   3598 
   3599 bool
   3600 pass_waccess::check_call_access (gcall *stmt)
   3601 {
   3602   tree fntype = gimple_call_fntype (stmt);
   3603   if (!fntype)
   3604     return false;
   3605 
   3606   tree fntypeattrs = TYPE_ATTRIBUTES (fntype);
   3607   if (!fntypeattrs)
   3608     return false;
   3609 
   3610   /* Map of attribute access specifications for function arguments.  */
   3611   rdwr_map rdwr_idx;
   3612   init_attr_rdwr_indices (&rdwr_idx, fntypeattrs);
   3613 
   3614   unsigned nargs = call_nargs (stmt);
   3615   for (unsigned i = 0; i != nargs; ++i)
   3616     {
   3617       tree arg = call_arg (stmt, i);
   3618 
   3619       /* Save the actual argument that corresponds to the access attribute
   3620 	 operand for later processing.  */
   3621       if (attr_access *access = rdwr_idx.get (i))
   3622 	{
   3623 	  if (POINTER_TYPE_P (TREE_TYPE (arg)))
   3624 	    {
   3625 	      access->ptr = arg;
   3626 	      /* A nonnull ACCESS->SIZE contains VLA bounds.  */
   3627 	    }
   3628 	  else
   3629 	    {
   3630 	      access->size = arg;
   3631 	      gcc_assert (access->ptr == NULL_TREE);
   3632 	    }
   3633 	}
   3634     }
   3635 
   3636   /* Check attribute access arguments.  */
   3637   tree fndecl = gimple_call_fndecl (stmt);
   3638   maybe_check_access_sizes (&rdwr_idx, fndecl, fntype, stmt);
   3639 
   3640   check_alloc_size_call (stmt);
   3641   return true;
   3642 }
   3643 
   3644 /* Check arguments in a call STMT for attribute nonstring.  */
   3645 
   3646 static void
   3647 check_nonstring_args (gcall *stmt)
   3648 {
   3649   tree fndecl = gimple_call_fndecl (stmt);
   3650 
   3651   /* Detect passing non-string arguments to functions expecting
   3652      nul-terminated strings.  */
   3653   maybe_warn_nonstring_arg (fndecl, stmt);
   3654 }
   3655 
   3656 /* Issue a warning if a deallocation function such as free, realloc,
   3657    or C++ operator delete is called with an argument not returned by
   3658    a matching allocation function such as malloc or the corresponding
   3659    form of C++ operator new.  */
   3660 
   3661 void
   3662 pass_waccess::maybe_check_dealloc_call (gcall *call)
   3663 {
   3664   tree fndecl = gimple_call_fndecl (call);
   3665   if (!fndecl)
   3666     return;
   3667 
   3668   unsigned argno = fndecl_dealloc_argno (fndecl);
   3669   if ((unsigned) call_nargs (call) <= argno)
   3670     return;
   3671 
   3672   tree ptr = gimple_call_arg (call, argno);
   3673   if (integer_zerop (ptr))
   3674     return;
   3675 
   3676   access_ref aref;
   3677   if (!compute_objsize (ptr, call, 0, &aref, &m_ptr_qry))
   3678     return;
   3679 
   3680   tree ref = aref.ref;
   3681   if (integer_zerop (ref))
   3682     return;
   3683 
   3684   tree dealloc_decl = fndecl;
   3685   location_t loc = gimple_location (call);
   3686 
   3687   if (DECL_P (ref) || EXPR_P (ref))
   3688     {
   3689       /* Diagnose freeing a declared object.  */
   3690       if (aref.ref_declared ()
   3691 	  && warning_at (loc, OPT_Wfree_nonheap_object,
   3692 			 "%qD called on unallocated object %qD",
   3693 			 dealloc_decl, ref))
   3694 	{
   3695 	  inform (get_location (ref), "declared here");
   3696 	  return;
   3697 	}
   3698 
   3699       /* Diagnose freeing a pointer that includes a positive offset.
   3700 	 Such a pointer cannot refer to the beginning of an allocated
   3701 	 object.  A negative offset may refer to it.  */
   3702       if (aref.sizrng[0] != aref.sizrng[1]
   3703 	  && warn_dealloc_offset (loc, call, aref))
   3704 	return;
   3705     }
   3706   else if (CONSTANT_CLASS_P (ref))
   3707     {
   3708       if (warning_at (loc, OPT_Wfree_nonheap_object,
   3709 		      "%qD called on a pointer to an unallocated "
   3710 		      "object %qE", dealloc_decl, ref))
   3711 	{
   3712 	  if (TREE_CODE (ptr) == SSA_NAME)
   3713 	    {
   3714 	      gimple *def_stmt = SSA_NAME_DEF_STMT (ptr);
   3715 	      if (is_gimple_assign (def_stmt))
   3716 		{
   3717 		  location_t loc = gimple_location (def_stmt);
   3718 		  inform (loc, "assigned here");
   3719 		}
   3720 	    }
   3721 	  return;
   3722 	}
   3723     }
   3724   else if (TREE_CODE (ref) == SSA_NAME)
   3725     {
   3726       /* Also warn if the pointer argument refers to the result
   3727 	 of an allocation call like alloca or VLA.  */
   3728       gimple *def_stmt = SSA_NAME_DEF_STMT (ref);
   3729       if (!def_stmt)
   3730 	return;
   3731 
   3732       if (is_gimple_call (def_stmt))
   3733 	{
   3734 	  bool warned = false;
   3735 	  if (gimple_call_alloc_p (def_stmt))
   3736 	    {
   3737 	      if (matching_alloc_calls_p (def_stmt, dealloc_decl))
   3738 		{
   3739 		  if (warn_dealloc_offset (loc, call, aref))
   3740 		    return;
   3741 		}
   3742 	      else
   3743 		{
   3744 		  tree alloc_decl = gimple_call_fndecl (def_stmt);
   3745 		  const opt_code opt =
   3746 		    (DECL_IS_OPERATOR_NEW_P (alloc_decl)
   3747 		     || DECL_IS_OPERATOR_DELETE_P (dealloc_decl)
   3748 		     ? OPT_Wmismatched_new_delete
   3749 		     : OPT_Wmismatched_dealloc);
   3750 		  warned = warning_at (loc, opt,
   3751 				       "%qD called on pointer returned "
   3752 				       "from a mismatched allocation "
   3753 				       "function", dealloc_decl);
   3754 		}
   3755 	    }
   3756 	  else if (gimple_call_builtin_p (def_stmt, BUILT_IN_ALLOCA)
   3757 		   || gimple_call_builtin_p (def_stmt,
   3758 					     BUILT_IN_ALLOCA_WITH_ALIGN))
   3759 	    warned = warning_at (loc, OPT_Wfree_nonheap_object,
   3760 				 "%qD called on pointer to "
   3761 				 "an unallocated object",
   3762 				 dealloc_decl);
   3763 	  else if (warn_dealloc_offset (loc, call, aref))
   3764 	    return;
   3765 
   3766 	  if (warned)
   3767 	    {
   3768 	      tree fndecl = gimple_call_fndecl (def_stmt);
   3769 	      inform (gimple_location (def_stmt),
   3770 		      "returned from %qD", fndecl);
   3771 	      return;
   3772 	    }
   3773 	}
   3774       else if (gimple_nop_p (def_stmt))
   3775 	{
   3776 	  ref = SSA_NAME_VAR (ref);
   3777 	  /* Diagnose freeing a pointer that includes a positive offset.  */
   3778 	  if (TREE_CODE (ref) == PARM_DECL
   3779 	      && !aref.deref
   3780 	      && aref.sizrng[0] != aref.sizrng[1]
   3781 	      && aref.offrng[0] > 0 && aref.offrng[1] > 0
   3782 	      && warn_dealloc_offset (loc, call, aref))
   3783 	    return;
   3784 	}
   3785     }
   3786 }
   3787 
   3788 /* Return true if either USE_STMT's basic block (that of a pointer's use)
   3789    is dominated by INVAL_STMT's (that of a pointer's invalidating statement,
   3790    which is either a clobber or a deallocation call), or if they're in
   3791    the same block, USE_STMT follows INVAL_STMT.  */
   3792 
   3793 bool
   3794 pass_waccess::use_after_inval_p (gimple *inval_stmt, gimple *use_stmt,
   3795 				 bool last_block /* = false */)
   3796 {
   3797   tree clobvar =
   3798     gimple_clobber_p (inval_stmt) ? gimple_assign_lhs (inval_stmt) : NULL_TREE;
   3799 
   3800   basic_block inval_bb = gimple_bb (inval_stmt);
   3801   basic_block use_bb = gimple_bb (use_stmt);
   3802 
   3803   if (!inval_bb || !use_bb)
   3804     return false;
   3805 
   3806   if (inval_bb != use_bb)
   3807     {
   3808       if (dominated_by_p (CDI_DOMINATORS, use_bb, inval_bb))
   3809 	return true;
   3810 
   3811       if (!clobvar || !last_block)
   3812 	return false;
   3813 
   3814       /* Proceed only when looking for uses of dangling pointers.  */
   3815       auto gsi = gsi_for_stmt (use_stmt);
   3816 
   3817       /* A use statement in the last basic block in a function or one that
   3818 	 falls through to it is after any other prior clobber of the used
   3819 	 variable unless it's followed by a clobber of the same variable. */
   3820       basic_block bb = use_bb;
   3821       while (bb != inval_bb
   3822 	     && single_succ_p (bb)
   3823 	     && !(single_succ_edge (bb)->flags
   3824 		  & (EDGE_EH | EDGE_ABNORMAL | EDGE_DFS_BACK)))
   3825 	{
   3826 	  for (; !gsi_end_p (gsi); gsi_next_nondebug (&gsi))
   3827 	    {
   3828 	      gimple *stmt = gsi_stmt (gsi);
   3829 	      if (gimple_clobber_p (stmt))
   3830 		{
   3831 		  if (clobvar == gimple_assign_lhs (stmt))
   3832 		    /* The use is followed by a clobber.  */
   3833 		    return false;
   3834 		}
   3835 	    }
   3836 
   3837 	  bb = single_succ (bb);
   3838 	  gsi = gsi_start_bb (bb);
   3839 	}
   3840 
   3841       /* The use is one of a dangling pointer if a clobber of the variable
   3842 	 [the pointer points to] has not been found before the function exit
   3843 	 point.  */
   3844       return bb == EXIT_BLOCK_PTR_FOR_FN (cfun);
   3845     }
   3846 
   3847   if (bitmap_set_bit (m_bb_uids_set, inval_bb->index))
   3848     /* The first time this basic block is visited assign increasing ids
   3849        to consecutive statements in it.  Use the ids to determine which
   3850        precedes which.  This avoids the linear traversal on subsequent
   3851        visits to the same block.  */
   3852     for (auto si = gsi_start_bb (inval_bb); !gsi_end_p (si);
   3853 	 gsi_next_nondebug (&si))
   3854       {
   3855 	gimple *stmt = gsi_stmt (si);
   3856 	unsigned uid = inc_gimple_stmt_max_uid (m_func);
   3857 	gimple_set_uid (stmt, uid);
   3858       }
   3859 
   3860   return gimple_uid (inval_stmt) < gimple_uid (use_stmt);
   3861 }
   3862 
   3863 /* Issue a warning for the USE_STMT of pointer or reference REF rendered
   3864    invalid by INVAL_STMT.  REF may be null when it's been optimized away.
   3865    When nonnull, INVAL_STMT is the deallocation function that rendered
   3866    the pointer or reference dangling.  Otherwise, VAR is the auto variable
   3867    (including an unnamed temporary such as a compound literal) whose
   3868    lifetime's rended it dangling.  MAYBE is true to issue the "maybe"
   3869    kind of warning.  EQUALITY is true when the pointer is used in
   3870    an equality expression.  */
   3871 
   3872 void
   3873 pass_waccess::warn_invalid_pointer (tree ref, gimple *use_stmt,
   3874 				    gimple *inval_stmt, tree var,
   3875 				    bool maybe, bool equality /* = false */)
   3876 {
   3877   /* Avoid printing the unhelpful "<unknown>" in the diagnostics.  */
   3878   if (ref && TREE_CODE (ref) == SSA_NAME)
   3879     {
   3880       tree var = SSA_NAME_VAR (ref);
   3881       if (!var)
   3882 	ref = NULL_TREE;
   3883       /* Don't warn for cases like when a cdtor returns 'this' on ARM.  */
   3884       else if (warning_suppressed_p (var, OPT_Wuse_after_free))
   3885 	return;
   3886       else if (DECL_ARTIFICIAL (var))
   3887 	ref = NULL_TREE;
   3888     }
   3889 
   3890   location_t use_loc = gimple_location (use_stmt);
   3891   if (use_loc == UNKNOWN_LOCATION)
   3892     {
   3893       use_loc = m_func->function_end_locus;
   3894       if (!ref)
   3895 	/* Avoid issuing a warning with no context other than
   3896 	   the function.  That would make it difficult to debug
   3897 	   in any but very simple cases.  */
   3898 	return;
   3899     }
   3900 
   3901   if (is_gimple_call (inval_stmt))
   3902     {
   3903       if ((equality && warn_use_after_free < 3)
   3904 	  || (maybe && warn_use_after_free < 2)
   3905 	  || warning_suppressed_p (use_stmt, OPT_Wuse_after_free))
   3906 	return;
   3907 
   3908       const tree inval_decl = gimple_call_fndecl (inval_stmt);
   3909 
   3910       if ((ref && warning_at (use_loc, OPT_Wuse_after_free,
   3911 			      (maybe
   3912 			       ? G_("pointer %qE may be used after %qD")
   3913 			       : G_("pointer %qE used after %qD")),
   3914 			      ref, inval_decl))
   3915 	  || (!ref && warning_at (use_loc, OPT_Wuse_after_free,
   3916 			      (maybe
   3917 			       ? G_("pointer may be used after %qD")
   3918 			       : G_("pointer used after %qD")),
   3919 				  inval_decl)))
   3920 	{
   3921 	  location_t loc = gimple_location (inval_stmt);
   3922 	  inform (loc, "call to %qD here", inval_decl);
   3923 	  suppress_warning (use_stmt, OPT_Wuse_after_free);
   3924 	}
   3925       return;
   3926     }
   3927 
   3928   if (equality
   3929       || (maybe && warn_dangling_pointer < 2)
   3930       || warning_suppressed_p (use_stmt, OPT_Wdangling_pointer_))
   3931     return;
   3932 
   3933   if (DECL_NAME (var))
   3934     {
   3935       if ((ref
   3936 	   && warning_at (use_loc, OPT_Wdangling_pointer_,
   3937 			  (maybe
   3938 			   ? G_("dangling pointer %qE to %qD may be used")
   3939 			   : G_("using dangling pointer %qE to %qD")),
   3940 			  ref, var))
   3941 	  || (!ref
   3942 	      && warning_at (use_loc, OPT_Wdangling_pointer_,
   3943 			     (maybe
   3944 			      ? G_("dangling pointer to %qD may be used")
   3945 			      : G_("using a dangling pointer to %qD")),
   3946 			     var)))
   3947 	inform (DECL_SOURCE_LOCATION (var),
   3948 		"%qD declared here", var);
   3949       suppress_warning (use_stmt, OPT_Wdangling_pointer_);
   3950       return;
   3951     }
   3952 
   3953   if ((ref
   3954        && warning_at (use_loc, OPT_Wdangling_pointer_,
   3955 		      (maybe
   3956 		       ? G_("dangling pointer %qE to an unnamed temporary "
   3957 			    "may be used")
   3958 		       : G_("using dangling pointer %qE to an unnamed "
   3959 			    "temporary")),
   3960 		      ref))
   3961       || (!ref
   3962 	  && warning_at (use_loc, OPT_Wdangling_pointer_,
   3963 			 (maybe
   3964 			  ? G_("dangling pointer to an unnamed temporary "
   3965 			       "may be used")
   3966 			  : G_("using a dangling pointer to an unnamed "
   3967 			       "temporary")))))
   3968     {
   3969       inform (DECL_SOURCE_LOCATION (var),
   3970 	      "unnamed temporary defined here");
   3971       suppress_warning (use_stmt, OPT_Wdangling_pointer_);
   3972     }
   3973 }
   3974 
   3975 /* If STMT is a call to either the standard realloc or to a user-defined
   3976    reallocation function returns its LHS and set *PTR to the reallocated
   3977    pointer.  Otherwise return null.  */
   3978 
   3979 static tree
   3980 get_realloc_lhs (gimple *stmt, tree *ptr)
   3981 {
   3982   if (gimple_call_builtin_p (stmt, BUILT_IN_REALLOC))
   3983     {
   3984       *ptr = gimple_call_arg (stmt, 0);
   3985       return gimple_call_lhs (stmt);
   3986     }
   3987 
   3988   gcall *call = dyn_cast<gcall *>(stmt);
   3989   if (!call)
   3990     return NULL_TREE;
   3991 
   3992   tree fnattr = NULL_TREE;
   3993   tree fndecl = gimple_call_fndecl (call);
   3994   if (fndecl)
   3995     fnattr = DECL_ATTRIBUTES (fndecl);
   3996   else
   3997     {
   3998       tree fntype = gimple_call_fntype (stmt);
   3999       if (!fntype)
   4000 	return NULL_TREE;
   4001       fnattr = TYPE_ATTRIBUTES (fntype);
   4002     }
   4003 
   4004   if (!fnattr)
   4005     return NULL_TREE;
   4006 
   4007   for (tree ats = fnattr;  (ats = lookup_attribute ("*dealloc", ats));
   4008        ats = TREE_CHAIN (ats))
   4009     {
   4010       tree args = TREE_VALUE (ats);
   4011       if (!args)
   4012 	continue;
   4013 
   4014       tree alloc = TREE_VALUE (args);
   4015       if (!alloc)
   4016 	continue;
   4017 
   4018       if (alloc == DECL_NAME (fndecl))
   4019 	{
   4020 	  unsigned argno = 0;
   4021 	  if (tree index = TREE_CHAIN (args))
   4022 	    argno = TREE_INT_CST_LOW (TREE_VALUE (index)) - 1;
   4023 	  *ptr = gimple_call_arg (stmt, argno);
   4024 	  return gimple_call_lhs (stmt);
   4025 	}
   4026     }
   4027 
   4028   return NULL_TREE;
   4029 }
   4030 
   4031 /* Warn if STMT is a call to a deallocation function that's not a match
   4032    for the REALLOC_STMT call.  Return true if warned.  */
   4033 
   4034 static bool
   4035 maybe_warn_mismatched_realloc (tree ptr, gimple *realloc_stmt, gimple *stmt)
   4036 {
   4037   if (!is_gimple_call (stmt))
   4038     return false;
   4039 
   4040   tree fndecl = gimple_call_fndecl (stmt);
   4041   if (!fndecl)
   4042     return false;
   4043 
   4044   unsigned argno = fndecl_dealloc_argno (fndecl);
   4045   if (call_nargs (stmt) <= argno)
   4046     return false;
   4047 
   4048   if (matching_alloc_calls_p (realloc_stmt, fndecl))
   4049     return false;
   4050 
   4051   /* Avoid printing the unhelpful "<unknown>" in the diagnostics.  */
   4052   if (ptr && TREE_CODE (ptr) == SSA_NAME
   4053       && (!SSA_NAME_VAR (ptr) || DECL_ARTIFICIAL (SSA_NAME_VAR (ptr))))
   4054     ptr = NULL_TREE;
   4055 
   4056   location_t loc = gimple_location (stmt);
   4057   tree realloc_decl = gimple_call_fndecl (realloc_stmt);
   4058   tree dealloc_decl = gimple_call_fndecl (stmt);
   4059   if (ptr && !warning_at (loc, OPT_Wmismatched_dealloc,
   4060 			  "%qD called on pointer %qE passed to mismatched "
   4061 			  "allocation function %qD",
   4062 			  dealloc_decl, ptr, realloc_decl))
   4063     return false;
   4064   if (!ptr && !warning_at (loc, OPT_Wmismatched_dealloc,
   4065 			   "%qD called on a pointer passed to mismatched "
   4066 			   "reallocation function %qD",
   4067 			   dealloc_decl, realloc_decl))
   4068     return false;
   4069 
   4070   inform (gimple_location (realloc_stmt),
   4071 	  "call to %qD", realloc_decl);
   4072   return true;
   4073 }
   4074 
   4075 /* Return true if P and Q point to the same object, and false if they
   4076    either don't or their relationship cannot be determined.  */
   4077 
   4078 static bool
   4079 pointers_related_p (gimple *stmt, tree p, tree q, pointer_query &qry,
   4080 		    auto_bitmap &visited)
   4081 {
   4082   if (!ptr_derefs_may_alias_p (p, q))
   4083     return false;
   4084 
   4085   /* TODO: Work harder to rule out relatedness.  */
   4086   access_ref pref, qref;
   4087   if (!qry.get_ref (p, stmt, &pref, 0)
   4088       || !qry.get_ref (q, stmt, &qref, 0))
   4089     /* GET_REF() only rarely fails.  When it does, it's likely because
   4090        it involves a self-referential PHI.  Return a conservative result.  */
   4091     return false;
   4092 
   4093   if (pref.ref == qref.ref)
   4094     return true;
   4095 
   4096   /* If either pointer is a PHI, iterate over all its operands and
   4097      return true if they're all related to the other pointer.  */
   4098   tree ptr = q;
   4099   unsigned version;
   4100   gphi *phi = pref.phi ();
   4101   if (phi)
   4102     version = SSA_NAME_VERSION (pref.ref);
   4103   else
   4104     {
   4105       phi = qref.phi ();
   4106       if (!phi)
   4107 	return false;
   4108 
   4109       ptr = p;
   4110       version = SSA_NAME_VERSION (qref.ref);
   4111     }
   4112 
   4113   if (!bitmap_set_bit (visited, version))
   4114     return true;
   4115 
   4116   unsigned nargs = gimple_phi_num_args (phi);
   4117   for (unsigned i = 0; i != nargs; ++i)
   4118     {
   4119       tree arg = gimple_phi_arg_def (phi, i);
   4120       if (!pointers_related_p (stmt, arg, ptr, qry, visited))
   4121 	return false;
   4122     }
   4123 
   4124   return true;
   4125 }
   4126 
   4127 /* Convenience wrapper for the above.  */
   4128 
   4129 static bool
   4130 pointers_related_p (gimple *stmt, tree p, tree q, pointer_query &qry)
   4131 {
   4132   auto_bitmap visited;
   4133   return pointers_related_p (stmt, p, q, qry, visited);
   4134 }
   4135 
   4136 /* For a STMT either a call to a deallocation function or a clobber, warn
   4137    for uses of the pointer PTR it was called with (including its copies
   4138    or others derived from it by pointer arithmetic).  If STMT is a clobber,
   4139    VAR is the decl of the clobbered variable.  When MAYBE is true use
   4140    a "maybe" form of diagnostic.  */
   4141 
   4142 void
   4143 pass_waccess::check_pointer_uses (gimple *stmt, tree ptr,
   4144 				  tree var /* = NULL_TREE */,
   4145 				  bool maybe /* = false */)
   4146 {
   4147   gcc_assert (TREE_CODE (ptr) == SSA_NAME);
   4148 
   4149   const bool check_dangling = !is_gimple_call (stmt);
   4150   basic_block stmt_bb = gimple_bb (stmt);
   4151 
   4152   /* If STMT is a reallocation function set to the reallocated pointer
   4153      and the LHS of the call, respectively.  */
   4154   tree realloc_ptr = NULL_TREE;
   4155   tree realloc_lhs = get_realloc_lhs (stmt, &realloc_ptr);
   4156 
   4157   auto_bitmap visited;
   4158 
   4159   auto_vec<tree> pointers;
   4160   pointers.safe_push (ptr);
   4161 
   4162   /* Starting with PTR, iterate over POINTERS added by the loop, and
   4163      either warn for their uses in basic blocks dominated by the STMT
   4164      or in statements that follow it in the same basic block, or add
   4165      them to POINTERS if they point into the same object as PTR (i.e.,
   4166      are obtained by pointer arithmetic on PTR).  */
   4167   for (unsigned i = 0; i != pointers.length (); ++i)
   4168     {
   4169       tree ptr = pointers[i];
   4170       if (!bitmap_set_bit (visited, SSA_NAME_VERSION (ptr)))
   4171 	/* Avoid revisiting the same pointer.  */
   4172 	continue;
   4173 
   4174       use_operand_p use_p;
   4175       imm_use_iterator iter;
   4176       FOR_EACH_IMM_USE_FAST (use_p, iter, ptr)
   4177 	{
   4178 	  gimple *use_stmt = USE_STMT (use_p);
   4179 	  if (use_stmt == stmt || is_gimple_debug (use_stmt))
   4180 	    continue;
   4181 
   4182 	  if (realloc_lhs)
   4183 	    {
   4184 	      /* Check to see if USE_STMT is a mismatched deallocation
   4185 		 call for the pointer passed to realloc.  That's a bug
   4186 		 regardless of the pointer's value and so warn.  */
   4187 	      if (maybe_warn_mismatched_realloc (*use_p->use, stmt, use_stmt))
   4188 		continue;
   4189 
   4190 	      /* Pointers passed to realloc that are used in basic blocks
   4191 		 where the realloc call is known to have failed are valid.
   4192 		 Ignore pointers that nothing is known about.  Those could
   4193 		 have escaped along with their nullness.  */
   4194 	      value_range vr;
   4195 	      if (m_ptr_qry.rvals->range_of_expr (vr, realloc_lhs, use_stmt))
   4196 		{
   4197 		  if (vr.zero_p ())
   4198 		    continue;
   4199 
   4200 		  if (!pointers_related_p (stmt, ptr, realloc_ptr, m_ptr_qry))
   4201 		    continue;
   4202 		}
   4203 	    }
   4204 
   4205 	  if (check_dangling
   4206 	      && gimple_code (use_stmt) == GIMPLE_RETURN)
   4207 	    /* Avoid interfering with -Wreturn-local-addr (which runs only
   4208 	       with optimization enabled so it won't diagnose cases that
   4209 	       would be caught here when optimization is disabled).  */
   4210 	    continue;
   4211 
   4212 	  bool equality = false;
   4213 	  if (is_gimple_assign (use_stmt))
   4214 	    {
   4215 	      tree_code code = gimple_assign_rhs_code (use_stmt);
   4216 	      equality = code == EQ_EXPR || code == NE_EXPR;
   4217 	    }
   4218 	  else if (gcond *cond = dyn_cast<gcond *>(use_stmt))
   4219 	    {
   4220 	      tree_code code = gimple_cond_code (cond);
   4221 	      equality = code == EQ_EXPR || code == NE_EXPR;
   4222 	    }
   4223 
   4224 	  /* Warn if USE_STMT is dominated by the deallocation STMT.
   4225 	     Otherwise, add the pointer to POINTERS so that the uses
   4226 	     of any other pointers derived from it can be checked.  */
   4227 	  if (use_after_inval_p (stmt, use_stmt, check_dangling))
   4228 	    {
   4229 	      if (gimple_code (use_stmt) == GIMPLE_PHI)
   4230 		{
   4231 		  /* Only add a PHI result to POINTERS if all its
   4232 		     operands are related to PTR, otherwise continue.  */
   4233 		  tree lhs = gimple_phi_result (use_stmt);
   4234 		  if (!pointers_related_p (stmt, lhs, ptr, m_ptr_qry))
   4235 		    continue;
   4236 
   4237 		  if (TREE_CODE (lhs) == SSA_NAME)
   4238 		    {
   4239 		      pointers.safe_push (lhs);
   4240 		      continue;
   4241 		    }
   4242 		}
   4243 
   4244 	      basic_block use_bb = gimple_bb (use_stmt);
   4245 	      bool this_maybe
   4246 		= (maybe
   4247 		   || !dominated_by_p (CDI_POST_DOMINATORS, stmt_bb, use_bb));
   4248 	      warn_invalid_pointer (*use_p->use, use_stmt, stmt, var,
   4249 				    this_maybe, equality);
   4250 	      continue;
   4251 	    }
   4252 
   4253 	  if (is_gimple_assign (use_stmt))
   4254 	    {
   4255 	      tree lhs = gimple_assign_lhs (use_stmt);
   4256 	      if (TREE_CODE (lhs) == SSA_NAME)
   4257 		{
   4258 		  tree_code rhs_code = gimple_assign_rhs_code (use_stmt);
   4259 		  if (rhs_code == POINTER_PLUS_EXPR || rhs_code == SSA_NAME)
   4260 		    pointers.safe_push (lhs);
   4261 		}
   4262 	      continue;
   4263 	    }
   4264 
   4265 	  if (gcall *call = dyn_cast <gcall *>(use_stmt))
   4266 	    {
   4267 	      if (gimple_call_return_arg (call) == ptr)
   4268 		if (tree lhs = gimple_call_lhs (call))
   4269 		  if (TREE_CODE (lhs) == SSA_NAME)
   4270 		    pointers.safe_push (lhs);
   4271 	      continue;
   4272 	    }
   4273 	}
   4274     }
   4275 }
   4276 
   4277 /* Check call STMT for invalid accesses.  */
   4278 
   4279 void
   4280 pass_waccess::check_call (gcall *stmt)
   4281 {
   4282   if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
   4283     check_builtin (stmt);
   4284 
   4285   /* .ASAN_MARK doesn't access any vars, only modifies shadow memory.  */
   4286   if (gimple_call_internal_p (stmt)
   4287       && gimple_call_internal_fn (stmt) == IFN_ASAN_MARK)
   4288     return;
   4289 
   4290   if (!m_early_checks_p)
   4291     if (tree callee = gimple_call_fndecl (stmt))
   4292       {
   4293 	/* Check for uses of the pointer passed to either a standard
   4294 	   or a user-defined deallocation function.  */
   4295 	unsigned argno = fndecl_dealloc_argno (callee);
   4296 	if (argno < (unsigned) call_nargs (stmt))
   4297 	  {
   4298 	    tree arg = call_arg (stmt, argno);
   4299 	    if (TREE_CODE (arg) == SSA_NAME)
   4300 	      check_pointer_uses (stmt, arg);
   4301 	  }
   4302       }
   4303 
   4304   check_call_access (stmt);
   4305   check_call_dangling (stmt);
   4306 
   4307   if (m_early_checks_p)
   4308     return;
   4309 
   4310   maybe_check_dealloc_call (stmt);
   4311   check_nonstring_args (stmt);
   4312 }
   4313 
   4314 /* Check non-call STMT for invalid accesses.  */
   4315 
   4316 void
   4317 pass_waccess::check_stmt (gimple *stmt)
   4318 {
   4319   if (m_check_dangling_p
   4320       && gimple_clobber_p (stmt, CLOBBER_EOL))
   4321     {
   4322       /* Ignore clobber statements in blocks with exceptional edges.  */
   4323       basic_block bb = gimple_bb (stmt);
   4324       edge e = EDGE_PRED (bb, 0);
   4325       if (e->flags & EDGE_EH)
   4326 	return;
   4327 
   4328       tree var = gimple_assign_lhs (stmt);
   4329       m_clobbers.put (var, stmt);
   4330       return;
   4331     }
   4332 
   4333   if (is_gimple_assign (stmt))
   4334     {
   4335       /* Clobbered unnamed temporaries such as compound literals can be
   4336 	 revived.  Check for an assignment to one and remove it from
   4337 	 M_CLOBBERS.  */
   4338       tree lhs = gimple_assign_lhs (stmt);
   4339       while (handled_component_p (lhs))
   4340 	lhs = TREE_OPERAND (lhs, 0);
   4341 
   4342       if (auto_var_p (lhs))
   4343 	m_clobbers.remove (lhs);
   4344       return;
   4345     }
   4346 
   4347   if (greturn *ret = dyn_cast <greturn *> (stmt))
   4348     {
   4349       if (optimize && flag_isolate_erroneous_paths_dereference)
   4350 	/* Avoid interfering with -Wreturn-local-addr (which runs only
   4351 	   with optimization enabled).  */
   4352 	return;
   4353 
   4354       tree arg = gimple_return_retval (ret);
   4355       if (!arg || TREE_CODE (arg) != ADDR_EXPR)
   4356 	return;
   4357 
   4358       arg = TREE_OPERAND (arg, 0);
   4359       while (handled_component_p (arg))
   4360 	arg = TREE_OPERAND (arg, 0);
   4361 
   4362       if (!auto_var_p (arg))
   4363 	return;
   4364 
   4365       gimple **pclobber = m_clobbers.get (arg);
   4366       if (!pclobber)
   4367 	return;
   4368 
   4369       if (!use_after_inval_p (*pclobber, stmt))
   4370 	return;
   4371 
   4372       warn_invalid_pointer (NULL_TREE, stmt, *pclobber, arg, false);
   4373     }
   4374 }
   4375 
   4376 /* Check basic block BB for invalid accesses.  */
   4377 
   4378 void
   4379 pass_waccess::check_block (basic_block bb)
   4380 {
   4381   /* Iterate over statements, looking for function calls.  */
   4382   for (auto si = gsi_start_bb (bb); !gsi_end_p (si);
   4383        gsi_next_nondebug (&si))
   4384     {
   4385       gimple *stmt = gsi_stmt (si);
   4386       if (gcall *call = dyn_cast <gcall *> (stmt))
   4387 	check_call (call);
   4388       else
   4389 	check_stmt (stmt);
   4390     }
   4391 }
   4392 
   4393 /* Return the argument that the call STMT to a built-in function returns
   4394    (including with an offset) or null if it doesn't.  */
   4395 
   4396 tree
   4397 pass_waccess::gimple_call_return_arg (gcall *call)
   4398 {
   4399   /* Check for attribute fn spec to see if the function returns one
   4400      of its arguments.  */
   4401   attr_fnspec fnspec = gimple_call_fnspec (call);
   4402   unsigned int argno;
   4403   if (!fnspec.returns_arg (&argno))
   4404     {
   4405       if (gimple_call_num_args (call) < 1)
   4406 	return NULL_TREE;
   4407 
   4408       if (!gimple_call_builtin_p (call, BUILT_IN_NORMAL))
   4409 	return NULL_TREE;
   4410 
   4411       tree fndecl = gimple_call_fndecl (call);
   4412       switch (DECL_FUNCTION_CODE (fndecl))
   4413 	{
   4414 	case BUILT_IN_MEMPCPY:
   4415 	case BUILT_IN_MEMPCPY_CHK:
   4416 	case BUILT_IN_MEMCHR:
   4417 	case BUILT_IN_STRCHR:
   4418 	case BUILT_IN_STRRCHR:
   4419 	case BUILT_IN_STRSTR:
   4420 	case BUILT_IN_STPCPY:
   4421 	case BUILT_IN_STPCPY_CHK:
   4422 	case BUILT_IN_STPNCPY:
   4423 	case BUILT_IN_STPNCPY_CHK:
   4424 	  argno = 0;
   4425 	  break;
   4426 
   4427 	default:
   4428 	  return NULL_TREE;
   4429 	}
   4430     }
   4431 
   4432   if (gimple_call_num_args (call) <= argno)
   4433     return NULL_TREE;
   4434 
   4435   return gimple_call_arg (call, argno);
   4436 }
   4437 
   4438 /* Check for and diagnose all uses of the dangling pointer VAR to the auto
   4439    object DECL whose lifetime has ended.  OBJREF is true when VAR denotes
   4440    an access to a DECL that may have been clobbered.  */
   4441 
   4442 void
   4443 pass_waccess::check_dangling_uses (tree var, tree decl, bool maybe /* = false */,
   4444 				   bool objref /* = false */)
   4445 {
   4446   if (!decl || !auto_var_p (decl))
   4447     return;
   4448 
   4449   gimple **pclob = m_clobbers.get (decl);
   4450   if (!pclob)
   4451     return;
   4452 
   4453   if (!objref)
   4454     {
   4455       check_pointer_uses (*pclob, var, decl, maybe);
   4456       return;
   4457     }
   4458 
   4459   gimple *use_stmt = SSA_NAME_DEF_STMT (var);
   4460   if (!use_after_inval_p (*pclob, use_stmt, true))
   4461     return;
   4462 
   4463   basic_block use_bb = gimple_bb (use_stmt);
   4464   basic_block clob_bb = gimple_bb (*pclob);
   4465   maybe = maybe || !dominated_by_p (CDI_POST_DOMINATORS, clob_bb, use_bb);
   4466   warn_invalid_pointer (var, use_stmt, *pclob, decl, maybe, false);
   4467 }
   4468 
   4469 /* Diagnose stores in BB and (recursively) its predecessors of the addresses
   4470    of local variables into nonlocal pointers that are left dangling after
   4471    the function returns.  BBS is a bitmap of basic blocks visited.  */
   4472 
   4473 void
   4474 pass_waccess::check_dangling_stores (basic_block bb,
   4475 				     hash_set<tree> &stores,
   4476 				     auto_bitmap &bbs)
   4477 {
   4478   if (!bitmap_set_bit (bbs, bb->index))
   4479     /* Avoid cycles. */
   4480     return;
   4481 
   4482   /* Iterate backwards over the statements looking for a store of
   4483      the address of a local variable into a nonlocal pointer.  */
   4484   for (auto gsi = gsi_last_nondebug_bb (bb); ; gsi_prev_nondebug (&gsi))
   4485     {
   4486       gimple *stmt = gsi_stmt (gsi);
   4487       if (!stmt)
   4488 	break;
   4489 
   4490       if (warning_suppressed_p (stmt, OPT_Wdangling_pointer_))
   4491 	continue;
   4492 
   4493       if (is_gimple_call (stmt)
   4494 	  && !(gimple_call_flags (stmt) & (ECF_CONST | ECF_PURE)))
   4495 	/* Avoid looking before nonconst, nonpure calls since those might
   4496 	   use the escaped locals.  */
   4497 	return;
   4498 
   4499       if (!is_gimple_assign (stmt) || gimple_clobber_p (stmt))
   4500 	continue;
   4501 
   4502       access_ref lhs_ref;
   4503       tree lhs = gimple_assign_lhs (stmt);
   4504       if (!m_ptr_qry.get_ref (lhs, stmt, &lhs_ref, 0))
   4505 	continue;
   4506 
   4507       if (auto_var_p (lhs_ref.ref))
   4508 	continue;
   4509 
   4510       if (DECL_P (lhs_ref.ref))
   4511 	{
   4512 	  if (!POINTER_TYPE_P (TREE_TYPE (lhs_ref.ref))
   4513 	      || lhs_ref.deref > 0)
   4514 	    continue;
   4515 	}
   4516       else if (TREE_CODE (lhs_ref.ref) == SSA_NAME)
   4517 	{
   4518 	  gimple *def_stmt = SSA_NAME_DEF_STMT (lhs_ref.ref);
   4519 	  if (!gimple_nop_p (def_stmt))
   4520 	    /* Avoid looking at or before stores into unknown objects.  */
   4521 	    return;
   4522 
   4523 	  tree var = SSA_NAME_VAR (lhs_ref.ref);
   4524 	  if (TREE_CODE (var) == PARM_DECL && DECL_BY_REFERENCE (var))
   4525 	    /* Avoid by-value arguments transformed into by-reference.  */
   4526 	    continue;
   4527 
   4528 	}
   4529       else if (TREE_CODE (lhs_ref.ref) == MEM_REF)
   4530 	{
   4531 	  tree arg = TREE_OPERAND (lhs_ref.ref, 0);
   4532 	  if (TREE_CODE (arg) == SSA_NAME)
   4533 	    {
   4534 	      gimple *def_stmt = SSA_NAME_DEF_STMT (arg);
   4535 	      if (!gimple_nop_p (def_stmt))
   4536 		return;
   4537 	    }
   4538 	}
   4539       else
   4540 	continue;
   4541 
   4542       if (stores.add (lhs_ref.ref))
   4543 	continue;
   4544 
   4545       /* FIXME: Handle stores of alloca() and VLA.  */
   4546       access_ref rhs_ref;
   4547       tree rhs = gimple_assign_rhs1 (stmt);
   4548       if (!m_ptr_qry.get_ref (rhs, stmt, &rhs_ref, 0)
   4549 	  || rhs_ref.deref != -1)
   4550 	continue;
   4551 
   4552       if (!auto_var_p (rhs_ref.ref))
   4553 	continue;
   4554 
   4555       location_t loc = gimple_location (stmt);
   4556       if (warning_at (loc, OPT_Wdangling_pointer_,
   4557 		      "storing the address of local variable %qD in %qE",
   4558 		      rhs_ref.ref, lhs))
   4559 	{
   4560 	  suppress_warning (stmt, OPT_Wdangling_pointer_);
   4561 
   4562 	  location_t loc = DECL_SOURCE_LOCATION (rhs_ref.ref);
   4563 	  inform (loc, "%qD declared here", rhs_ref.ref);
   4564 
   4565 	  if (DECL_P (lhs_ref.ref))
   4566 	    loc = DECL_SOURCE_LOCATION (lhs_ref.ref);
   4567 	  else if (EXPR_HAS_LOCATION (lhs_ref.ref))
   4568 	    loc = EXPR_LOCATION (lhs_ref.ref);
   4569 
   4570 	  if (loc != UNKNOWN_LOCATION)
   4571 	    inform (loc, "%qE declared here", lhs_ref.ref);
   4572 	}
   4573     }
   4574 
   4575   edge e;
   4576   edge_iterator ei;
   4577   FOR_EACH_EDGE (e, ei, bb->preds)
   4578     {
   4579       basic_block pred = e->src;
   4580       check_dangling_stores (pred, stores, bbs);
   4581     }
   4582 }
   4583 
   4584 /* Diagnose stores of the addresses of local variables into nonlocal
   4585    pointers that are left dangling after the function returns.  */
   4586 
   4587 void
   4588 pass_waccess::check_dangling_stores ()
   4589 {
   4590   auto_bitmap bbs;
   4591   hash_set<tree> stores;
   4592   check_dangling_stores (EXIT_BLOCK_PTR_FOR_FN (m_func), stores, bbs);
   4593 }
   4594 
   4595 /* Check for and diagnose uses of dangling pointers to auto objects
   4596    whose lifetime has ended.  */
   4597 
   4598 void
   4599 pass_waccess::check_dangling_uses ()
   4600 {
   4601   tree var;
   4602   unsigned i;
   4603   FOR_EACH_SSA_NAME (i, var, m_func)
   4604     {
   4605       /* For each SSA_NAME pointer VAR find the object it points to.
   4606 	 If the object is a clobbered local variable, check to see
   4607 	 if any of VAR's uses (or those of other pointers derived
   4608 	 from VAR) happens after the clobber.  If so, warn.  */
   4609 
   4610       gimple *def_stmt = SSA_NAME_DEF_STMT (var);
   4611       if (is_gimple_assign (def_stmt))
   4612 	{
   4613 	  tree rhs = gimple_assign_rhs1 (def_stmt);
   4614 	  if (TREE_CODE (rhs) == ADDR_EXPR)
   4615 	    {
   4616 	      if (!POINTER_TYPE_P (TREE_TYPE (var)))
   4617 		continue;
   4618 	      check_dangling_uses (var, TREE_OPERAND (rhs, 0));
   4619 	    }
   4620 	  else
   4621 	    {
   4622 	      /* For other expressions, check the base DECL to see
   4623 		 if it's been clobbered, most likely as a result of
   4624 		 inlining a reference to it.  */
   4625 	      tree decl = get_base_address (rhs);
   4626 	      if (DECL_P (decl))
   4627 		check_dangling_uses (var, decl, false, true);
   4628 	    }
   4629 	}
   4630       else if (POINTER_TYPE_P (TREE_TYPE (var)))
   4631 	{
   4632 	  if (gcall *call = dyn_cast<gcall *>(def_stmt))
   4633 	    {
   4634 	      if (tree arg = gimple_call_return_arg (call))
   4635 		{
   4636 		  access_ref aref;
   4637 		  if (m_ptr_qry.get_ref (arg, call, &aref, 0)
   4638 		      && aref.deref < 0)
   4639 		    check_dangling_uses (var, aref.ref);
   4640 		}
   4641 	    }
   4642 	  else if (gphi *phi = dyn_cast <gphi *>(def_stmt))
   4643 	    {
   4644 	      unsigned nargs = gimple_phi_num_args (phi);
   4645 	      for (unsigned i = 0; i != nargs; ++i)
   4646 		{
   4647 		  access_ref aref;
   4648 		  tree arg = gimple_phi_arg_def (phi, i);
   4649 		  if (m_ptr_qry.get_ref (arg, phi, &aref, 0)
   4650 		      && aref.deref < 0)
   4651 		    check_dangling_uses (var, aref.ref, true);
   4652 		}
   4653 	    }
   4654 	}
   4655     }
   4656 }
   4657 
   4658 /* Check CALL arguments for dangling pointers (those that have been
   4659    clobbered) and warn if found.  */
   4660 
   4661 void
   4662 pass_waccess::check_call_dangling (gcall *call)
   4663 {
   4664   unsigned nargs = gimple_call_num_args (call);
   4665   for (unsigned i = 0; i != nargs; ++i)
   4666     {
   4667       tree arg = gimple_call_arg (call, i);
   4668       if (TREE_CODE (arg) != ADDR_EXPR)
   4669 	continue;
   4670 
   4671       arg = TREE_OPERAND (arg, 0);
   4672       if (!DECL_P (arg))
   4673 	continue;
   4674 
   4675       gimple **pclobber = m_clobbers.get (arg);
   4676       if (!pclobber)
   4677 	continue;
   4678 
   4679       if (!use_after_inval_p (*pclobber, call))
   4680 	continue;
   4681 
   4682       warn_invalid_pointer (NULL_TREE, call, *pclobber, arg, false);
   4683     }
   4684 }
   4685 
   4686 /* Check function FUN for invalid accesses.  */
   4687 
   4688 unsigned
   4689 pass_waccess::execute (function *fun)
   4690 {
   4691   calculate_dominance_info (CDI_DOMINATORS);
   4692   calculate_dominance_info (CDI_POST_DOMINATORS);
   4693 
   4694   /* Set or clear EDGE_DFS_BACK bits on back edges.  */
   4695   mark_dfs_back_edges (fun);
   4696 
   4697   /* Create a new ranger instance and associate it with FUN.  */
   4698   m_ptr_qry.rvals = enable_ranger (fun);
   4699   m_func = fun;
   4700 
   4701   /* Check for dangling pointers in the earliest run of the pass.
   4702      The latest point -Wdangling-pointer should run is just before
   4703      loop unrolling which introduces uses after clobbers.  Most cases
   4704      can be detected without optimization; cases where the address of
   4705      the local variable is passed to and then returned from a user-
   4706      defined function before its lifetime ends and the returned pointer
   4707      becomes dangling depend on inlining.  */
   4708   m_check_dangling_p = m_early_checks_p;
   4709 
   4710   auto_bitmap bb_uids_set (&bitmap_default_obstack);
   4711   m_bb_uids_set = bb_uids_set;
   4712 
   4713   set_gimple_stmt_max_uid (m_func, 0);
   4714 
   4715   basic_block bb;
   4716   FOR_EACH_BB_FN (bb, fun)
   4717     check_block (bb);
   4718 
   4719   if (m_check_dangling_p)
   4720     {
   4721       check_dangling_uses ();
   4722       check_dangling_stores ();
   4723     }
   4724 
   4725   if (dump_file)
   4726     m_ptr_qry.dump (dump_file, (dump_flags & TDF_DETAILS) != 0);
   4727 
   4728   m_ptr_qry.flush_cache ();
   4729 
   4730   /* Release the ranger instance and replace it with a global ranger.
   4731      Also reset the pointer since calling disable_ranger() deletes it.  */
   4732   disable_ranger (fun);
   4733   m_ptr_qry.rvals = NULL;
   4734 
   4735   m_clobbers.empty ();
   4736   m_bb_uids_set = NULL;
   4737 
   4738   free_dominance_info (CDI_POST_DOMINATORS);
   4739   free_dominance_info (CDI_DOMINATORS);
   4740   return 0;
   4741 }
   4742 
   4743 }   // namespace
   4744 
   4745 /* Return a new instance of the pass.  */
   4746 
   4747 gimple_opt_pass *
   4748 make_pass_warn_access (gcc::context *ctxt)
   4749 {
   4750   return new pass_waccess (ctxt);
   4751 }
   4752