gimple-ssa-isolate-paths.c (pass_isolate_erroneous_paths): Comment fix.
[gcc.git] / gcc / gimple-ssa-isolate-paths.c
1 /* Detect paths through the CFG which can never be executed in a conforming
2 program and isolate them.
3
4 Copyright (C) 2013
5 Free Software Foundation, Inc.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License 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 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "basic-block.h"
29 #include "gimple.h"
30 #include "tree-ssa.h"
31 #include "tree-ssanames.h"
32 #include "gimple-ssa.h"
33 #include "tree-ssa-operands.h"
34 #include "tree-phinodes.h"
35 #include "ssa-iterators.h"
36 #include "cfgloop.h"
37 #include "tree-pass.h"
38
39
40 static bool cfg_altered;
41
42 /* Callback for walk_stmt_load_store_ops.
43
44 Return TRUE if OP will dereference the tree stored in DATA, FALSE
45 otherwise.
46
47 This routine only makes a superficial check for a dereference. Thus,
48 it must only be used if it is safe to return a false negative. */
49 static bool
50 check_loadstore (gimple stmt ATTRIBUTE_UNUSED, tree op, void *data)
51 {
52 if ((TREE_CODE (op) == MEM_REF || TREE_CODE (op) == TARGET_MEM_REF)
53 && operand_equal_p (TREE_OPERAND (op, 0), (tree)data, 0))
54 {
55 TREE_THIS_VOLATILE (op) = 1;
56 TREE_SIDE_EFFECTS (op) = 1;
57 update_stmt (stmt);
58 return true;
59 }
60 return false;
61 }
62
63 /* Insert a trap after SI and remove SI and all statements after the trap. */
64
65 static void
66 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator *si_p, tree op)
67 {
68 /* We want the NULL pointer dereference to actually occur so that
69 code that wishes to catch the signal can do so.
70
71 If the dereference is a load, then there's nothing to do as the
72 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
73
74 If the dereference is a store and we can easily transform the RHS,
75 then simplify the RHS to enable more DCE. */
76 gimple stmt = gsi_stmt (*si_p);
77 if (walk_stmt_load_store_ops (stmt, (void *)op, NULL, check_loadstore)
78 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
79 {
80 /* We just need to turn the RHS into zero converted to the proper
81 type. */
82 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
83 gimple_assign_set_rhs_code (stmt, INTEGER_CST);
84 gimple_assign_set_rhs1 (stmt, fold_convert (type, integer_zero_node));
85 update_stmt (stmt);
86 }
87
88 gimple new_stmt
89 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP), 0);
90 gimple_seq seq = NULL;
91 gimple_seq_add_stmt (&seq, new_stmt);
92
93 /* If we had a NULL pointer dereference, then we want to insert the
94 __builtin_trap after the statement, for the other cases we want
95 to insert before the statement. */
96 if (walk_stmt_load_store_ops (stmt, (void *)op,
97 check_loadstore,
98 check_loadstore))
99 gsi_insert_after (si_p, seq, GSI_NEW_STMT);
100 else
101 gsi_insert_before (si_p, seq, GSI_NEW_STMT);
102
103 /* We must remove statements from the end of the block so that we
104 never reference a released SSA_NAME. */
105 basic_block bb = gimple_bb (gsi_stmt (*si_p));
106 for (gimple_stmt_iterator si = gsi_last_bb (bb);
107 gsi_stmt (si) != gsi_stmt (*si_p);
108 si = gsi_last_bb (bb))
109 {
110 stmt = gsi_stmt (si);
111 unlink_stmt_vdef (stmt);
112 gsi_remove (&si, true);
113 release_defs (stmt);
114 }
115 }
116
117 /* BB when reached via incoming edge E will exhibit undefined behaviour
118 at STMT. Isolate and optimize the path which exhibits undefined
119 behaviour.
120
121 Isolation is simple. Duplicate BB and redirect E to BB'.
122
123 Optimization is simple as well. Replace STMT in BB' with an
124 unconditional trap and remove all outgoing edges from BB'.
125
126 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
127
128 Return BB'. */
129
130 basic_block
131 isolate_path (basic_block bb, basic_block duplicate,
132 edge e, gimple stmt, tree op)
133 {
134 gimple_stmt_iterator si, si2;
135 edge_iterator ei;
136 edge e2;
137
138
139 /* First duplicate BB if we have not done so already and remove all
140 the duplicate's outgoing edges as duplicate is going to unconditionally
141 trap. Removing the outgoing edges is both an optimization and ensures
142 we don't need to do any PHI node updates. */
143 if (!duplicate)
144 {
145 duplicate = duplicate_block (bb, NULL, NULL);
146 for (ei = ei_start (duplicate->succs); (e2 = ei_safe_edge (ei)); )
147 remove_edge (e2);
148 }
149
150 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
151 e2 = redirect_edge_and_branch (e, duplicate);
152 if (e2)
153 flush_pending_stmts (e2);
154
155
156 /* There may be more than one statement in DUPLICATE which exhibits
157 undefined behaviour. Ultimately we want the first such statement in
158 DUPLCIATE so that we're able to delete as much code as possible.
159
160 So each time we discover undefined behaviour in DUPLICATE, search for
161 the statement which triggers undefined behaviour. If found, then
162 transform the statement into a trap and delete everything after the
163 statement. If not found, then this particular instance was subsumed by
164 an earlier instance of undefined behaviour and there's nothing to do.
165
166 This is made more complicated by the fact that we have STMT, which is in
167 BB rather than in DUPLICATE. So we set up two iterators, one for each
168 block and walk forward looking for STMT in BB, advancing each iterator at
169 each step.
170
171 When we find STMT the second iterator should point to STMT's equivalent in
172 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
173 nothing to do.
174
175 Ignore labels and debug statements. */
176 si = gsi_start_nondebug_after_labels_bb (bb);
177 si2 = gsi_start_nondebug_after_labels_bb (duplicate);
178 while (!gsi_end_p (si) && !gsi_end_p (si2) && gsi_stmt (si) != stmt)
179 {
180 gsi_next_nondebug (&si);
181 gsi_next_nondebug (&si2);
182 }
183
184 /* This would be an indicator that we never found STMT in BB, which should
185 never happen. */
186 gcc_assert (!gsi_end_p (si));
187
188 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
189 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
190 before SI2 and remove SI2 and all trailing statements. */
191 if (!gsi_end_p (si2))
192 insert_trap_and_remove_trailing_statements (&si2, op);
193
194 return duplicate;
195 }
196
197 /* Look for PHI nodes which feed statements in the same block where
198 the value of the PHI node implies the statement is erroneous.
199
200 For example, a NULL PHI arg value which then feeds a pointer
201 dereference.
202
203 When found isolate and optimize the path associated with the PHI
204 argument feeding the erroneous statement. */
205 static void
206 find_implicit_erroneous_behaviour (void)
207 {
208 basic_block bb;
209
210 FOR_EACH_BB (bb)
211 {
212 gimple_stmt_iterator si;
213
214 /* First look for a PHI which sets a pointer to NULL and which
215 is then dereferenced within BB. This is somewhat overly
216 conservative, but probably catches most of the interesting
217 cases. */
218 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
219 {
220 gimple phi = gsi_stmt (si);
221 tree lhs = gimple_phi_result (phi);
222
223 /* If the result is not a pointer, then there is no need to
224 examine the arguments. */
225 if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
226 continue;
227
228 /* PHI produces a pointer result. See if any of the PHI's
229 arguments are NULL.
230
231 When we remove an edge, we want to reprocess the current
232 index, hence the ugly way we update I for each iteration. */
233 basic_block duplicate = NULL;
234 for (unsigned i = 0, next_i = 0;
235 i < gimple_phi_num_args (phi);
236 i = next_i)
237 {
238 tree op = gimple_phi_arg_def (phi, i);
239
240 next_i = i + 1;
241
242 if (!integer_zerop (op))
243 continue;
244
245 edge e = gimple_phi_arg_edge (phi, i);
246 imm_use_iterator iter;
247 gimple use_stmt;
248
249 /* We've got a NULL PHI argument. Now see if the
250 PHI's result is dereferenced within BB. */
251 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
252 {
253 /* We only care about uses in BB. Catching cases in
254 in other blocks would require more complex path
255 isolation code. */
256 if (gimple_bb (use_stmt) != bb)
257 continue;
258
259 if (infer_nonnull_range (use_stmt, lhs))
260 {
261 duplicate = isolate_path (bb, duplicate,
262 e, use_stmt, lhs);
263
264 /* When we remove an incoming edge, we need to
265 reprocess the Ith element. */
266 next_i = i;
267 cfg_altered = true;
268 }
269 }
270 }
271 }
272 }
273 }
274
275 /* Look for statements which exhibit erroneous behaviour. For example
276 a NULL pointer dereference.
277
278 When found, optimize the block containing the erroneous behaviour. */
279 static void
280 find_explicit_erroneous_behaviour (void)
281 {
282 basic_block bb;
283
284 FOR_EACH_BB (bb)
285 {
286 gimple_stmt_iterator si;
287
288 /* Now look at the statements in the block and see if any of
289 them explicitly dereference a NULL pointer. This happens
290 because of jump threading and constant propagation. */
291 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
292 {
293 gimple stmt = gsi_stmt (si);
294
295 /* By passing null_pointer_node, we can use infer_nonnull_range
296 to detect explicit NULL pointer dereferences and other uses
297 where a non-NULL value is required. */
298 if (infer_nonnull_range (stmt, null_pointer_node))
299 {
300 insert_trap_and_remove_trailing_statements (&si,
301 null_pointer_node);
302
303 /* And finally, remove all outgoing edges from BB. */
304 edge e;
305 for (edge_iterator ei = ei_start (bb->succs);
306 (e = ei_safe_edge (ei)); )
307 remove_edge (e);
308
309 /* Ignore any more operands on this statement and
310 continue the statement iterator (which should
311 terminate its loop immediately. */
312 cfg_altered = true;
313 break;
314 }
315 }
316 }
317 }
318 /* Search the function for statements which, if executed, would cause
319 the program to fault such as a dereference of a NULL pointer.
320
321 Such a program can't be valid if such a statement was to execute
322 according to ISO standards.
323
324 We detect explicit NULL pointer dereferences as well as those implied
325 by a PHI argument having a NULL value which unconditionally flows into
326 a dereference in the same block as the PHI.
327
328 In the former case we replace the offending statement with an
329 unconditional trap and eliminate the outgoing edges from the statement's
330 basic block. This may expose secondary optimization opportunities.
331
332 In the latter case, we isolate the path(s) with the NULL PHI
333 feeding the dereference. We can then replace the offending statement
334 and eliminate the outgoing edges in the duplicate. Again, this may
335 expose secondary optimization opportunities.
336
337 A warning for both cases may be advisable as well.
338
339 Other statically detectable violations of the ISO standard could be
340 handled in a similar way, such as out-of-bounds array indexing. */
341
342 static unsigned int
343 gimple_ssa_isolate_erroneous_paths (void)
344 {
345 initialize_original_copy_tables ();
346
347 /* Search all the blocks for edges which, if traversed, will
348 result in undefined behaviour. */
349 cfg_altered = false;
350
351 /* First handle cases where traversal of a particular edge
352 triggers undefined behaviour. These cases require creating
353 duplicate blocks and thus new SSA_NAMEs.
354
355 We want that process complete prior to the phase where we start
356 removing edges from the CFG. Edge removal may ultimately result in
357 removal of PHI nodes and thus releasing SSA_NAMEs back to the
358 name manager.
359
360 If the two processes run in parallel we could release an SSA_NAME
361 back to the manager but we could still have dangling references
362 to the released SSA_NAME in unreachable blocks.
363 that any released names not have dangling references in the IL. */
364 find_implicit_erroneous_behaviour ();
365 find_explicit_erroneous_behaviour ();
366
367 free_original_copy_tables ();
368
369 /* We scramble the CFG and loop structures a bit, clean up
370 appropriately. We really should incrementally update the
371 loop structures, in theory it shouldn't be that hard. */
372 if (cfg_altered)
373 {
374 free_dominance_info (CDI_DOMINATORS);
375 free_dominance_info (CDI_POST_DOMINATORS);
376 loops_state_set (LOOPS_NEED_FIXUP);
377 return TODO_cleanup_cfg | TODO_update_ssa;
378 }
379 return 0;
380 }
381
382 static bool
383 gate_isolate_erroneous_paths (void)
384 {
385 /* If we do not have a suitable builtin function for the trap statement,
386 then do not perform the optimization. */
387 return (flag_isolate_erroneous_paths != 0);
388 }
389
390 namespace {
391 const pass_data pass_data_isolate_erroneous_paths =
392 {
393 GIMPLE_PASS, /* type */
394 "isolate-paths", /* name */
395 OPTGROUP_NONE, /* optinfo_flags */
396 true, /* has_gate */
397 true, /* has_execute */
398 TV_ISOLATE_ERRONEOUS_PATHS, /* tv_id */
399 ( PROP_cfg | PROP_ssa ), /* properties_required */
400 0, /* properties_provided */
401 0, /* properties_destroyed */
402 0, /* todo_flags_start */
403 TODO_verify_ssa, /* todo_flags_finish */
404 };
405
406 class pass_isolate_erroneous_paths : public gimple_opt_pass
407 {
408 public:
409 pass_isolate_erroneous_paths (gcc::context *ctxt)
410 : gimple_opt_pass (pass_data_isolate_erroneous_paths, ctxt)
411 {}
412
413 /* opt_pass methods: */
414 opt_pass * clone () { return new pass_isolate_erroneous_paths (m_ctxt); }
415 bool gate () { return gate_isolate_erroneous_paths (); }
416 unsigned int execute () { return gimple_ssa_isolate_erroneous_paths (); }
417
418 }; // class pass_isolate_erroneous_paths
419 }
420
421 gimple_opt_pass *
422 make_pass_isolate_erroneous_paths (gcc::context *ctxt)
423 {
424 return new pass_isolate_erroneous_paths (ctxt);
425 }