2015-06-11 Paul Thomas <pault@gcc.gnu.org>
[official-gcc.git] / gcc / gimple-ssa-isolate-paths.c
bloba4626be9cac322a64def3684add55775912cbe6c
1 /* Detect paths through the CFG which can never be executed in a conforming
2 program and isolate them.
4 Copyright (C) 2013-2015 Free Software Foundation, Inc.
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "input.h"
26 #include "alias.h"
27 #include "symtab.h"
28 #include "options.h"
29 #include "tree.h"
30 #include "fold-const.h"
31 #include "flags.h"
32 #include "predict.h"
33 #include "tm.h"
34 #include "hard-reg-set.h"
35 #include "input.h"
36 #include "function.h"
37 #include "dominance.h"
38 #include "cfg.h"
39 #include "basic-block.h"
40 #include "tree-ssa-alias.h"
41 #include "internal-fn.h"
42 #include "gimple-expr.h"
43 #include "is-a.h"
44 #include "gimple.h"
45 #include "gimple-iterator.h"
46 #include "gimple-walk.h"
47 #include "tree-ssa.h"
48 #include "stringpool.h"
49 #include "tree-ssanames.h"
50 #include "gimple-ssa.h"
51 #include "tree-ssa-operands.h"
52 #include "tree-phinodes.h"
53 #include "ssa-iterators.h"
54 #include "cfgloop.h"
55 #include "tree-pass.h"
56 #include "tree-cfg.h"
57 #include "diagnostic-core.h"
58 #include "intl.h"
61 static bool cfg_altered;
63 /* Callback for walk_stmt_load_store_ops.
65 Return TRUE if OP will dereference the tree stored in DATA, FALSE
66 otherwise.
68 This routine only makes a superficial check for a dereference. Thus,
69 it must only be used if it is safe to return a false negative. */
70 static bool
71 check_loadstore (gimple stmt, tree op, tree, void *data)
73 if ((TREE_CODE (op) == MEM_REF || TREE_CODE (op) == TARGET_MEM_REF)
74 && operand_equal_p (TREE_OPERAND (op, 0), (tree)data, 0))
76 TREE_THIS_VOLATILE (op) = 1;
77 TREE_SIDE_EFFECTS (op) = 1;
78 update_stmt (stmt);
79 return true;
81 return false;
84 /* Insert a trap after SI and remove SI and all statements after the trap. */
86 static void
87 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator *si_p, tree op)
89 /* We want the NULL pointer dereference to actually occur so that
90 code that wishes to catch the signal can do so.
92 If the dereference is a load, then there's nothing to do as the
93 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
95 If the dereference is a store and we can easily transform the RHS,
96 then simplify the RHS to enable more DCE. Note that we require the
97 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
98 gimple stmt = gsi_stmt (*si_p);
99 if (walk_stmt_load_store_ops (stmt, (void *)op, NULL, check_loadstore)
100 && is_gimple_assign (stmt)
101 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
103 /* We just need to turn the RHS into zero converted to the proper
104 type. */
105 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
106 gimple_assign_set_rhs_code (stmt, INTEGER_CST);
107 gimple_assign_set_rhs1 (stmt, fold_convert (type, integer_zero_node));
108 update_stmt (stmt);
111 gcall *new_stmt
112 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP), 0);
113 gimple_seq seq = NULL;
114 gimple_seq_add_stmt (&seq, new_stmt);
116 /* If we had a NULL pointer dereference, then we want to insert the
117 __builtin_trap after the statement, for the other cases we want
118 to insert before the statement. */
119 if (walk_stmt_load_store_ops (stmt, (void *)op,
120 check_loadstore,
121 check_loadstore))
122 gsi_insert_after (si_p, seq, GSI_NEW_STMT);
123 else
124 gsi_insert_before (si_p, seq, GSI_NEW_STMT);
126 /* We must remove statements from the end of the block so that we
127 never reference a released SSA_NAME. */
128 basic_block bb = gimple_bb (gsi_stmt (*si_p));
129 for (gimple_stmt_iterator si = gsi_last_bb (bb);
130 gsi_stmt (si) != gsi_stmt (*si_p);
131 si = gsi_last_bb (bb))
133 stmt = gsi_stmt (si);
134 unlink_stmt_vdef (stmt);
135 gsi_remove (&si, true);
136 release_defs (stmt);
140 /* BB when reached via incoming edge E will exhibit undefined behaviour
141 at STMT. Isolate and optimize the path which exhibits undefined
142 behaviour.
144 Isolation is simple. Duplicate BB and redirect E to BB'.
146 Optimization is simple as well. Replace STMT in BB' with an
147 unconditional trap and remove all outgoing edges from BB'.
149 If RET_ZERO, do not trap, only return NULL.
151 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
153 Return BB'. */
155 basic_block
156 isolate_path (basic_block bb, basic_block duplicate,
157 edge e, gimple stmt, tree op, bool ret_zero)
159 gimple_stmt_iterator si, si2;
160 edge_iterator ei;
161 edge e2;
163 /* First duplicate BB if we have not done so already and remove all
164 the duplicate's outgoing edges as duplicate is going to unconditionally
165 trap. Removing the outgoing edges is both an optimization and ensures
166 we don't need to do any PHI node updates. */
167 if (!duplicate)
169 duplicate = duplicate_block (bb, NULL, NULL);
170 if (!ret_zero)
171 for (ei = ei_start (duplicate->succs); (e2 = ei_safe_edge (ei)); )
172 remove_edge (e2);
175 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
176 e2 = redirect_edge_and_branch (e, duplicate);
177 if (e2)
178 flush_pending_stmts (e2);
181 /* There may be more than one statement in DUPLICATE which exhibits
182 undefined behaviour. Ultimately we want the first such statement in
183 DUPLCIATE so that we're able to delete as much code as possible.
185 So each time we discover undefined behaviour in DUPLICATE, search for
186 the statement which triggers undefined behaviour. If found, then
187 transform the statement into a trap and delete everything after the
188 statement. If not found, then this particular instance was subsumed by
189 an earlier instance of undefined behaviour and there's nothing to do.
191 This is made more complicated by the fact that we have STMT, which is in
192 BB rather than in DUPLICATE. So we set up two iterators, one for each
193 block and walk forward looking for STMT in BB, advancing each iterator at
194 each step.
196 When we find STMT the second iterator should point to STMT's equivalent in
197 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
198 nothing to do.
200 Ignore labels and debug statements. */
201 si = gsi_start_nondebug_after_labels_bb (bb);
202 si2 = gsi_start_nondebug_after_labels_bb (duplicate);
203 while (!gsi_end_p (si) && !gsi_end_p (si2) && gsi_stmt (si) != stmt)
205 gsi_next_nondebug (&si);
206 gsi_next_nondebug (&si2);
209 /* This would be an indicator that we never found STMT in BB, which should
210 never happen. */
211 gcc_assert (!gsi_end_p (si));
213 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
214 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
215 before SI2 and remove SI2 and all trailing statements. */
216 if (!gsi_end_p (si2))
218 if (ret_zero)
220 greturn *ret = as_a <greturn *> (gsi_stmt (si2));
221 tree zero = build_zero_cst (TREE_TYPE (gimple_return_retval (ret)));
222 gimple_return_set_retval (ret, zero);
223 update_stmt (ret);
225 else
226 insert_trap_and_remove_trailing_statements (&si2, op);
229 return duplicate;
232 /* Look for PHI nodes which feed statements in the same block where
233 the value of the PHI node implies the statement is erroneous.
235 For example, a NULL PHI arg value which then feeds a pointer
236 dereference.
238 When found isolate and optimize the path associated with the PHI
239 argument feeding the erroneous statement. */
240 static void
241 find_implicit_erroneous_behaviour (void)
243 basic_block bb;
245 FOR_EACH_BB_FN (bb, cfun)
247 gphi_iterator si;
249 /* Out of an abundance of caution, do not isolate paths to a
250 block where the block has any abnormal outgoing edges.
252 We might be able to relax this in the future. We have to detect
253 when we have to split the block with the NULL dereference and
254 the trap we insert. We have to preserve abnormal edges out
255 of the isolated block which in turn means updating PHIs at
256 the targets of those abnormal outgoing edges. */
257 if (has_abnormal_or_eh_outgoing_edge_p (bb))
258 continue;
260 /* First look for a PHI which sets a pointer to NULL and which
261 is then dereferenced within BB. This is somewhat overly
262 conservative, but probably catches most of the interesting
263 cases. */
264 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
266 gphi *phi = si.phi ();
267 tree lhs = gimple_phi_result (phi);
269 /* If the result is not a pointer, then there is no need to
270 examine the arguments. */
271 if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
272 continue;
274 /* PHI produces a pointer result. See if any of the PHI's
275 arguments are NULL.
277 When we remove an edge, we want to reprocess the current
278 index, hence the ugly way we update I for each iteration. */
279 basic_block duplicate = NULL;
280 for (unsigned i = 0, next_i = 0;
281 i < gimple_phi_num_args (phi);
282 i = next_i)
284 tree op = gimple_phi_arg_def (phi, i);
285 edge e = gimple_phi_arg_edge (phi, i);
286 imm_use_iterator iter;
287 gimple use_stmt;
289 next_i = i + 1;
291 if (TREE_CODE (op) == ADDR_EXPR)
293 tree valbase = get_base_address (TREE_OPERAND (op, 0));
294 if ((TREE_CODE (valbase) == VAR_DECL
295 && !is_global_var (valbase))
296 || TREE_CODE (valbase) == PARM_DECL)
298 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
300 greturn *return_stmt
301 = dyn_cast <greturn *> (use_stmt);
302 if (!return_stmt)
303 continue;
305 if (gimple_return_retval (return_stmt) != lhs)
306 continue;
308 if (warning_at (gimple_location (use_stmt),
309 OPT_Wreturn_local_addr,
310 "function may return address "
311 "of local variable"))
312 inform (DECL_SOURCE_LOCATION(valbase),
313 "declared here");
315 if (gimple_bb (use_stmt) == bb)
317 duplicate = isolate_path (bb, duplicate, e,
318 use_stmt, lhs, true);
320 /* When we remove an incoming edge, we need to
321 reprocess the Ith element. */
322 next_i = i;
323 cfg_altered = true;
329 if (!integer_zerop (op))
330 continue;
332 /* We've got a NULL PHI argument. Now see if the
333 PHI's result is dereferenced within BB. */
334 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
336 /* We only care about uses in BB. Catching cases in
337 in other blocks would require more complex path
338 isolation code. */
339 if (gimple_bb (use_stmt) != bb)
340 continue;
342 if (infer_nonnull_range (use_stmt, lhs,
343 flag_isolate_erroneous_paths_dereference,
344 flag_isolate_erroneous_paths_attribute))
347 duplicate = isolate_path (bb, duplicate, e,
348 use_stmt, lhs, false);
350 /* When we remove an incoming edge, we need to
351 reprocess the Ith element. */
352 next_i = i;
353 cfg_altered = true;
361 /* Look for statements which exhibit erroneous behaviour. For example
362 a NULL pointer dereference.
364 When found, optimize the block containing the erroneous behaviour. */
365 static void
366 find_explicit_erroneous_behaviour (void)
368 basic_block bb;
370 FOR_EACH_BB_FN (bb, cfun)
372 gimple_stmt_iterator si;
374 /* Out of an abundance of caution, do not isolate paths to a
375 block where the block has any abnormal outgoing edges.
377 We might be able to relax this in the future. We have to detect
378 when we have to split the block with the NULL dereference and
379 the trap we insert. We have to preserve abnormal edges out
380 of the isolated block which in turn means updating PHIs at
381 the targets of those abnormal outgoing edges. */
382 if (has_abnormal_or_eh_outgoing_edge_p (bb))
383 continue;
385 /* Now look at the statements in the block and see if any of
386 them explicitly dereference a NULL pointer. This happens
387 because of jump threading and constant propagation. */
388 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
390 gimple stmt = gsi_stmt (si);
392 /* By passing null_pointer_node, we can use infer_nonnull_range
393 to detect explicit NULL pointer dereferences and other uses
394 where a non-NULL value is required. */
395 if (infer_nonnull_range (stmt, null_pointer_node,
396 flag_isolate_erroneous_paths_dereference,
397 flag_isolate_erroneous_paths_attribute))
399 insert_trap_and_remove_trailing_statements (&si,
400 null_pointer_node);
402 /* And finally, remove all outgoing edges from BB. */
403 edge e;
404 for (edge_iterator ei = ei_start (bb->succs);
405 (e = ei_safe_edge (ei)); )
406 remove_edge (e);
408 /* Ignore any more operands on this statement and
409 continue the statement iterator (which should
410 terminate its loop immediately. */
411 cfg_altered = true;
412 break;
415 /* Detect returning the address of a local variable. This only
416 becomes undefined behavior if the result is used, so we do not
417 insert a trap and only return NULL instead. */
418 if (greturn *return_stmt = dyn_cast <greturn *> (stmt))
420 tree val = gimple_return_retval (return_stmt);
421 if (val && TREE_CODE (val) == ADDR_EXPR)
423 tree valbase = get_base_address (TREE_OPERAND (val, 0));
424 if ((TREE_CODE (valbase) == VAR_DECL
425 && !is_global_var (valbase))
426 || TREE_CODE (valbase) == PARM_DECL)
428 /* We only need it for this particular case. */
429 calculate_dominance_info (CDI_POST_DOMINATORS);
430 const char* msg;
431 bool always_executed = dominated_by_p
432 (CDI_POST_DOMINATORS,
433 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)), bb);
434 if (always_executed)
435 msg = N_("function returns address of local variable");
436 else
437 msg = N_("function may return address of "
438 "local variable");
440 if (warning_at (gimple_location (stmt),
441 OPT_Wreturn_local_addr, msg))
442 inform (DECL_SOURCE_LOCATION(valbase), "declared here");
443 tree zero = build_zero_cst (TREE_TYPE (val));
444 gimple_return_set_retval (return_stmt, zero);
445 update_stmt (stmt);
453 /* Search the function for statements which, if executed, would cause
454 the program to fault such as a dereference of a NULL pointer.
456 Such a program can't be valid if such a statement was to execute
457 according to ISO standards.
459 We detect explicit NULL pointer dereferences as well as those implied
460 by a PHI argument having a NULL value which unconditionally flows into
461 a dereference in the same block as the PHI.
463 In the former case we replace the offending statement with an
464 unconditional trap and eliminate the outgoing edges from the statement's
465 basic block. This may expose secondary optimization opportunities.
467 In the latter case, we isolate the path(s) with the NULL PHI
468 feeding the dereference. We can then replace the offending statement
469 and eliminate the outgoing edges in the duplicate. Again, this may
470 expose secondary optimization opportunities.
472 A warning for both cases may be advisable as well.
474 Other statically detectable violations of the ISO standard could be
475 handled in a similar way, such as out-of-bounds array indexing. */
477 static unsigned int
478 gimple_ssa_isolate_erroneous_paths (void)
480 initialize_original_copy_tables ();
482 /* Search all the blocks for edges which, if traversed, will
483 result in undefined behaviour. */
484 cfg_altered = false;
486 /* First handle cases where traversal of a particular edge
487 triggers undefined behaviour. These cases require creating
488 duplicate blocks and thus new SSA_NAMEs.
490 We want that process complete prior to the phase where we start
491 removing edges from the CFG. Edge removal may ultimately result in
492 removal of PHI nodes and thus releasing SSA_NAMEs back to the
493 name manager.
495 If the two processes run in parallel we could release an SSA_NAME
496 back to the manager but we could still have dangling references
497 to the released SSA_NAME in unreachable blocks.
498 that any released names not have dangling references in the IL. */
499 find_implicit_erroneous_behaviour ();
500 find_explicit_erroneous_behaviour ();
502 free_original_copy_tables ();
504 /* We scramble the CFG and loop structures a bit, clean up
505 appropriately. We really should incrementally update the
506 loop structures, in theory it shouldn't be that hard. */
507 if (cfg_altered)
509 free_dominance_info (CDI_DOMINATORS);
510 free_dominance_info (CDI_POST_DOMINATORS);
511 loops_state_set (LOOPS_NEED_FIXUP);
512 return TODO_cleanup_cfg | TODO_update_ssa;
514 return 0;
517 namespace {
518 const pass_data pass_data_isolate_erroneous_paths =
520 GIMPLE_PASS, /* type */
521 "isolate-paths", /* name */
522 OPTGROUP_NONE, /* optinfo_flags */
523 TV_ISOLATE_ERRONEOUS_PATHS, /* tv_id */
524 ( PROP_cfg | PROP_ssa ), /* properties_required */
525 0, /* properties_provided */
526 0, /* properties_destroyed */
527 0, /* todo_flags_start */
528 0, /* todo_flags_finish */
531 class pass_isolate_erroneous_paths : public gimple_opt_pass
533 public:
534 pass_isolate_erroneous_paths (gcc::context *ctxt)
535 : gimple_opt_pass (pass_data_isolate_erroneous_paths, ctxt)
538 /* opt_pass methods: */
539 opt_pass * clone () { return new pass_isolate_erroneous_paths (m_ctxt); }
540 virtual bool gate (function *)
542 /* If we do not have a suitable builtin function for the trap statement,
543 then do not perform the optimization. */
544 return (flag_isolate_erroneous_paths_dereference != 0
545 || flag_isolate_erroneous_paths_attribute != 0);
548 virtual unsigned int execute (function *)
550 return gimple_ssa_isolate_erroneous_paths ();
553 }; // class pass_isolate_erroneous_paths
556 gimple_opt_pass *
557 make_pass_isolate_erroneous_paths (gcc::context *ctxt)
559 return new pass_isolate_erroneous_paths (ctxt);