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