1 /* PR tree-optimization/79376 - wrong lower bound with %s and non-constant
2    strings in -Wformat-overflow
3    { dg-do compile }
4    { dg-options "-O2 -fdump-tree-optimized" } */
5 
6 #define CAT(s, n)   s ## n
7 #define FAIL(line)  CAT (failure_on_line_, line)
8 
9 /* Emit a call to a function named failure_on_line_NNN when EXPR is false.  */
10 #define ASSERT(expr)				\
11   do {						\
12     extern void FAIL (__LINE__)(void);		\
13     if (!(expr)) FAIL (__LINE__)();		\
14   } while (0)
15 
16 #define KEEP(line)  CAT (keep_call_on_line_, line)
17 
18 /* Emit a call to a function named keep_call_on_line_NNN when EXPR is true.
19    Used to verify that the expression need not be the only one that holds.  */
20 #define ASSERT_MAYBE(expr)			\
21   do {						\
22     extern void KEEP (__LINE__)(void);		\
23     if (expr) KEEP (__LINE__)();		\
24   } while (0)
25 
26 struct Arrays
27 {
28   char a1[1];
29   char a2[2];
30   char a3[3];
31   char a4[4];
32   char a5[5];
33   char ax[];
34 };
35 
test_arrays(int i,struct Arrays * a)36 void test_arrays (int i, struct Arrays *a)
37 {
38   {
39     const char *s = i < 0 ? a->a3 : a->a1;
40 
41     int n = __builtin_snprintf (0, 0, "%-s", s);
42 
43     ASSERT (0 <= n && n < 3);
44 
45     ASSERT_MAYBE (0 == n);
46     ASSERT_MAYBE (1 == n);
47     ASSERT_MAYBE (2 == n);
48   }
49 
50   {
51     const char *s = i < 0 ? a->a3 : a->a5;
52 
53     int n = __builtin_snprintf (0, 0, "%-s", s);
54 
55     ASSERT (0 <= n && n < 5);
56 
57     ASSERT_MAYBE (0 == n);
58     ASSERT_MAYBE (1 == n);
59     ASSERT_MAYBE (2 == n);
60     ASSERT_MAYBE (3 == n);
61     ASSERT_MAYBE (4 == n);
62   }
63 }
64 
test_string_and_array(int i,struct Arrays * a)65 void test_string_and_array (int i, struct Arrays *a)
66 {
67   {
68     const char *s = i < 0 ? a->a3 : "1";
69 
70     int n = __builtin_snprintf (0, 0, "%-s", s);
71 
72     ASSERT (0 <= n && n < 3);
73 
74     ASSERT_MAYBE (0 == n);
75     ASSERT_MAYBE (1 == n);
76     ASSERT_MAYBE (2 == n);
77   }
78 
79   {
80     const char *s = i < 0 ? "12" : a->a5;
81 
82     int n = __builtin_snprintf (0, 0, "%-s", s);
83 
84     ASSERT (0 <= n && n < 5);
85 
86     ASSERT_MAYBE (0 == n);
87     ASSERT_MAYBE (1 == n);
88     ASSERT_MAYBE (2 == n);
89     ASSERT_MAYBE (3 == n);
90     ASSERT_MAYBE (4 == n);
91   }
92 
93   {
94     const char *s = i < 0 ? a->a4 : 0 < i ? "12" : a->a5;
95 
96     int n = __builtin_snprintf (0, 0, "%-s", s);
97 
98     ASSERT (0 <= n && n < 5);
99 
100     ASSERT_MAYBE (0 == n);
101     ASSERT_MAYBE (1 == n);
102     ASSERT_MAYBE (2 == n);
103     ASSERT_MAYBE (3 == n);
104     ASSERT_MAYBE (4 == n);
105   }
106 }
107 
108 /* { dg-final { scan-tree-dump-not "failure_on_line" "optimized"} }
109    { dg-final { scan-tree-dump-times "keep_call_on_line" 21 "optimized"} } */
110