1  /* { dg-do run } */
       2  /* { dg-options "-O2 -fdump-tree-strlen -fdump-tree-optimized" } */
       3  
       4  #include "strlenopt.h"
       5  
       6  char buf[64];
       7  
       8  __attribute__((noinline, noclone)) size_t
       9  foo (void)
      10  {
      11    char *p = memcpy (buf, "abcdefgh", 9);
      12    /* This store can be optimized away as... */
      13    *p = '\0';
      14    /* ... the following strcat can be optimized into memcpy,
      15       which overwrites that '\0'.  */
      16    strcat (p, "ijk");
      17    /* This should be optimized into return 3.  */
      18    return strlen (p);
      19  }
      20  
      21  __attribute__((noinline, noclone)) size_t
      22  bar (char *p)
      23  {
      24    char *r = strchr (p, '\0');
      25    /* This store shouldn't be optimized away, because we
      26       want to crash if p is e.g. a string literal.  */
      27    *r = '\0';
      28    /* This strlen can be optimized into 0.  */
      29    return strlen (r);
      30  }
      31  
      32  int
      33  main ()
      34  {
      35    char *volatile p = buf;
      36    if (foo () != 3 || memcmp (buf, "ijk\0efgh\0", 10) != 0)
      37      abort ();
      38    if (bar (p) != 0 || memcmp (buf, "ijk\0efgh\0", 10) != 0)
      39      abort ();
      40    return 0;
      41  }
      42  
      43  /* { dg-final { scan-tree-dump-times "strlen \\(" 1 "strlen1" } } */
      44  /* { dg-final { scan-tree-dump-times "memcpy \\(" 2 "strlen1" } } */
      45  /* { dg-final { scan-tree-dump-times "strcpy \\(" 0 "strlen1" } } */
      46  /* { dg-final { scan-tree-dump-times "strcat \\(" 0 "strlen1" } } */
      47  /* { dg-final { scan-tree-dump-times "strchr \\(" 0 "strlen1" } } */
      48  /* { dg-final { scan-tree-dump-times "stpcpy \\(" 0 "strlen1" } } */
      49  /* { dg-final { scan-tree-dump-times "\\*r_\[0-9\]* = 0;" 1 "strlen1" } } */
      50  /* { dg-final { scan-tree-dump-times "return 3;" 1 "optimized" } } */
      51  /* { dg-final { scan-tree-dump-times "return 0;" 2 "optimized" } } */