2015-03-04 Robert Dewar <dewar@adacore.com>
[official-gcc.git] / gcc / gimple-ssa-isolate-paths.c
blobde318f34831f4813001105cb0ad1072733b414ba
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 "hash-set.h"
26 #include "machmode.h"
27 #include "vec.h"
28 #include "double-int.h"
29 #include "input.h"
30 #include "alias.h"
31 #include "symtab.h"
32 #include "options.h"
33 #include "wide-int.h"
34 #include "inchash.h"
35 #include "tree.h"
36 #include "fold-const.h"
37 #include "flags.h"
38 #include "predict.h"
39 #include "tm.h"
40 #include "hard-reg-set.h"
41 #include "input.h"
42 #include "function.h"
43 #include "dominance.h"
44 #include "cfg.h"
45 #include "basic-block.h"
46 #include "tree-ssa-alias.h"
47 #include "internal-fn.h"
48 #include "gimple-expr.h"
49 #include "is-a.h"
50 #include "gimple.h"
51 #include "gimple-iterator.h"
52 #include "gimple-walk.h"
53 #include "tree-ssa.h"
54 #include "stringpool.h"
55 #include "tree-ssanames.h"
56 #include "gimple-ssa.h"
57 #include "tree-ssa-operands.h"
58 #include "tree-phinodes.h"
59 #include "ssa-iterators.h"
60 #include "cfgloop.h"
61 #include "tree-pass.h"
62 #include "tree-cfg.h"
63 #include "diagnostic-core.h"
64 #include "intl.h"
67 static bool cfg_altered;
69 /* Callback for walk_stmt_load_store_ops.
71 Return TRUE if OP will dereference the tree stored in DATA, FALSE
72 otherwise.
74 This routine only makes a superficial check for a dereference. Thus,
75 it must only be used if it is safe to return a false negative. */
76 static bool
77 check_loadstore (gimple stmt, tree op, tree, void *data)
79 if ((TREE_CODE (op) == MEM_REF || TREE_CODE (op) == TARGET_MEM_REF)
80 && operand_equal_p (TREE_OPERAND (op, 0), (tree)data, 0))
82 TREE_THIS_VOLATILE (op) = 1;
83 TREE_SIDE_EFFECTS (op) = 1;
84 update_stmt (stmt);
85 return true;
87 return false;
90 /* Insert a trap after SI and remove SI and all statements after the trap. */
92 static void
93 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator *si_p, tree op)
95 /* We want the NULL pointer dereference to actually occur so that
96 code that wishes to catch the signal can do so.
98 If the dereference is a load, then there's nothing to do as the
99 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
101 If the dereference is a store and we can easily transform the RHS,
102 then simplify the RHS to enable more DCE. Note that we require the
103 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
104 gimple stmt = gsi_stmt (*si_p);
105 if (walk_stmt_load_store_ops (stmt, (void *)op, NULL, check_loadstore)
106 && is_gimple_assign (stmt)
107 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
109 /* We just need to turn the RHS into zero converted to the proper
110 type. */
111 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
112 gimple_assign_set_rhs_code (stmt, INTEGER_CST);
113 gimple_assign_set_rhs1 (stmt, fold_convert (type, integer_zero_node));
114 update_stmt (stmt);
117 gcall *new_stmt
118 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP), 0);
119 gimple_seq seq = NULL;
120 gimple_seq_add_stmt (&seq, new_stmt);
122 /* If we had a NULL pointer dereference, then we want to insert the
123 __builtin_trap after the statement, for the other cases we want
124 to insert before the statement. */
125 if (walk_stmt_load_store_ops (stmt, (void *)op,
126 check_loadstore,
127 check_loadstore))
128 gsi_insert_after (si_p, seq, GSI_NEW_STMT);
129 else
130 gsi_insert_before (si_p, seq, GSI_NEW_STMT);
132 /* We must remove statements from the end of the block so that we
133 never reference a released SSA_NAME. */
134 basic_block bb = gimple_bb (gsi_stmt (*si_p));
135 for (gimple_stmt_iterator si = gsi_last_bb (bb);
136 gsi_stmt (si) != gsi_stmt (*si_p);
137 si = gsi_last_bb (bb))
139 stmt = gsi_stmt (si);
140 unlink_stmt_vdef (stmt);
141 gsi_remove (&si, true);
142 release_defs (stmt);
146 /* BB when reached via incoming edge E will exhibit undefined behaviour
147 at STMT. Isolate and optimize the path which exhibits undefined
148 behaviour.
150 Isolation is simple. Duplicate BB and redirect E to BB'.
152 Optimization is simple as well. Replace STMT in BB' with an
153 unconditional trap and remove all outgoing edges from BB'.
155 If RET_ZERO, do not trap, only return NULL.
157 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
159 Return BB'. */
161 basic_block
162 isolate_path (basic_block bb, basic_block duplicate,
163 edge e, gimple stmt, tree op, bool ret_zero)
165 gimple_stmt_iterator si, si2;
166 edge_iterator ei;
167 edge e2;
169 /* First duplicate BB if we have not done so already and remove all
170 the duplicate's outgoing edges as duplicate is going to unconditionally
171 trap. Removing the outgoing edges is both an optimization and ensures
172 we don't need to do any PHI node updates. */
173 if (!duplicate)
175 duplicate = duplicate_block (bb, NULL, NULL);
176 if (!ret_zero)
177 for (ei = ei_start (duplicate->succs); (e2 = ei_safe_edge (ei)); )
178 remove_edge (e2);
181 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
182 e2 = redirect_edge_and_branch (e, duplicate);
183 if (e2)
184 flush_pending_stmts (e2);
187 /* There may be more than one statement in DUPLICATE which exhibits
188 undefined behaviour. Ultimately we want the first such statement in
189 DUPLCIATE so that we're able to delete as much code as possible.
191 So each time we discover undefined behaviour in DUPLICATE, search for
192 the statement which triggers undefined behaviour. If found, then
193 transform the statement into a trap and delete everything after the
194 statement. If not found, then this particular instance was subsumed by
195 an earlier instance of undefined behaviour and there's nothing to do.
197 This is made more complicated by the fact that we have STMT, which is in
198 BB rather than in DUPLICATE. So we set up two iterators, one for each
199 block and walk forward looking for STMT in BB, advancing each iterator at
200 each step.
202 When we find STMT the second iterator should point to STMT's equivalent in
203 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
204 nothing to do.
206 Ignore labels and debug statements. */
207 si = gsi_start_nondebug_after_labels_bb (bb);
208 si2 = gsi_start_nondebug_after_labels_bb (duplicate);
209 while (!gsi_end_p (si) && !gsi_end_p (si2) && gsi_stmt (si) != stmt)
211 gsi_next_nondebug (&si);
212 gsi_next_nondebug (&si2);
215 /* This would be an indicator that we never found STMT in BB, which should
216 never happen. */
217 gcc_assert (!gsi_end_p (si));
219 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
220 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
221 before SI2 and remove SI2 and all trailing statements. */
222 if (!gsi_end_p (si2))
224 if (ret_zero)
226 greturn *ret = as_a <greturn *> (gsi_stmt (si2));
227 tree zero = build_zero_cst (TREE_TYPE (gimple_return_retval (ret)));
228 gimple_return_set_retval (ret, zero);
229 update_stmt (ret);
231 else
232 insert_trap_and_remove_trailing_statements (&si2, op);
235 return duplicate;
238 /* Look for PHI nodes which feed statements in the same block where
239 the value of the PHI node implies the statement is erroneous.
241 For example, a NULL PHI arg value which then feeds a pointer
242 dereference.
244 When found isolate and optimize the path associated with the PHI
245 argument feeding the erroneous statement. */
246 static void
247 find_implicit_erroneous_behaviour (void)
249 basic_block bb;
251 FOR_EACH_BB_FN (bb, cfun)
253 gphi_iterator si;
255 /* Out of an abundance of caution, do not isolate paths to a
256 block where the block has any abnormal outgoing edges.
258 We might be able to relax this in the future. We have to detect
259 when we have to split the block with the NULL dereference and
260 the trap we insert. We have to preserve abnormal edges out
261 of the isolated block which in turn means updating PHIs at
262 the targets of those abnormal outgoing edges. */
263 if (has_abnormal_or_eh_outgoing_edge_p (bb))
264 continue;
266 /* First look for a PHI which sets a pointer to NULL and which
267 is then dereferenced within BB. This is somewhat overly
268 conservative, but probably catches most of the interesting
269 cases. */
270 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
272 gphi *phi = si.phi ();
273 tree lhs = gimple_phi_result (phi);
275 /* If the result is not a pointer, then there is no need to
276 examine the arguments. */
277 if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
278 continue;
280 /* PHI produces a pointer result. See if any of the PHI's
281 arguments are NULL.
283 When we remove an edge, we want to reprocess the current
284 index, hence the ugly way we update I for each iteration. */
285 basic_block duplicate = NULL;
286 for (unsigned i = 0, next_i = 0;
287 i < gimple_phi_num_args (phi);
288 i = next_i)
290 tree op = gimple_phi_arg_def (phi, i);
291 edge e = gimple_phi_arg_edge (phi, i);
292 imm_use_iterator iter;
293 gimple use_stmt;
295 next_i = i + 1;
297 if (TREE_CODE (op) == ADDR_EXPR)
299 tree valbase = get_base_address (TREE_OPERAND (op, 0));
300 if ((TREE_CODE (valbase) == VAR_DECL
301 && !is_global_var (valbase))
302 || TREE_CODE (valbase) == PARM_DECL)
304 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
306 greturn *return_stmt
307 = dyn_cast <greturn *> (use_stmt);
308 if (!return_stmt)
309 continue;
311 if (gimple_return_retval (return_stmt) != lhs)
312 continue;
314 if (warning_at (gimple_location (use_stmt),
315 OPT_Wreturn_local_addr,
316 "function may return address "
317 "of local variable"))
318 inform (DECL_SOURCE_LOCATION(valbase),
319 "declared here");
321 if (gimple_bb (use_stmt) == bb)
323 duplicate = isolate_path (bb, duplicate, e,
324 use_stmt, lhs, true);
326 /* When we remove an incoming edge, we need to
327 reprocess the Ith element. */
328 next_i = i;
329 cfg_altered = true;
335 if (!integer_zerop (op))
336 continue;
338 /* We've got a NULL PHI argument. Now see if the
339 PHI's result is dereferenced within BB. */
340 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
342 /* We only care about uses in BB. Catching cases in
343 in other blocks would require more complex path
344 isolation code. */
345 if (gimple_bb (use_stmt) != bb)
346 continue;
348 if (infer_nonnull_range (use_stmt, lhs,
349 flag_isolate_erroneous_paths_dereference,
350 flag_isolate_erroneous_paths_attribute))
353 duplicate = isolate_path (bb, duplicate, e,
354 use_stmt, lhs, false);
356 /* When we remove an incoming edge, we need to
357 reprocess the Ith element. */
358 next_i = i;
359 cfg_altered = true;
367 /* Look for statements which exhibit erroneous behaviour. For example
368 a NULL pointer dereference.
370 When found, optimize the block containing the erroneous behaviour. */
371 static void
372 find_explicit_erroneous_behaviour (void)
374 basic_block bb;
376 FOR_EACH_BB_FN (bb, cfun)
378 gimple_stmt_iterator si;
380 /* Out of an abundance of caution, do not isolate paths to a
381 block where the block has any abnormal outgoing edges.
383 We might be able to relax this in the future. We have to detect
384 when we have to split the block with the NULL dereference and
385 the trap we insert. We have to preserve abnormal edges out
386 of the isolated block which in turn means updating PHIs at
387 the targets of those abnormal outgoing edges. */
388 if (has_abnormal_or_eh_outgoing_edge_p (bb))
389 continue;
391 /* Now look at the statements in the block and see if any of
392 them explicitly dereference a NULL pointer. This happens
393 because of jump threading and constant propagation. */
394 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
396 gimple stmt = gsi_stmt (si);
398 /* By passing null_pointer_node, we can use infer_nonnull_range
399 to detect explicit NULL pointer dereferences and other uses
400 where a non-NULL value is required. */
401 if (infer_nonnull_range (stmt, null_pointer_node,
402 flag_isolate_erroneous_paths_dereference,
403 flag_isolate_erroneous_paths_attribute))
405 insert_trap_and_remove_trailing_statements (&si,
406 null_pointer_node);
408 /* And finally, remove all outgoing edges from BB. */
409 edge e;
410 for (edge_iterator ei = ei_start (bb->succs);
411 (e = ei_safe_edge (ei)); )
412 remove_edge (e);
414 /* Ignore any more operands on this statement and
415 continue the statement iterator (which should
416 terminate its loop immediately. */
417 cfg_altered = true;
418 break;
421 /* Detect returning the address of a local variable. This only
422 becomes undefined behavior if the result is used, so we do not
423 insert a trap and only return NULL instead. */
424 if (greturn *return_stmt = dyn_cast <greturn *> (stmt))
426 tree val = gimple_return_retval (return_stmt);
427 if (val && TREE_CODE (val) == ADDR_EXPR)
429 tree valbase = get_base_address (TREE_OPERAND (val, 0));
430 if ((TREE_CODE (valbase) == VAR_DECL
431 && !is_global_var (valbase))
432 || TREE_CODE (valbase) == PARM_DECL)
434 /* We only need it for this particular case. */
435 calculate_dominance_info (CDI_POST_DOMINATORS);
436 const char* msg;
437 bool always_executed = dominated_by_p
438 (CDI_POST_DOMINATORS,
439 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)), bb);
440 if (always_executed)
441 msg = N_("function returns address of local variable");
442 else
443 msg = N_("function may return address of "
444 "local variable");
446 if (warning_at (gimple_location (stmt),
447 OPT_Wreturn_local_addr, msg))
448 inform (DECL_SOURCE_LOCATION(valbase), "declared here");
449 tree zero = build_zero_cst (TREE_TYPE (val));
450 gimple_return_set_retval (return_stmt, zero);
451 update_stmt (stmt);
459 /* Search the function for statements which, if executed, would cause
460 the program to fault such as a dereference of a NULL pointer.
462 Such a program can't be valid if such a statement was to execute
463 according to ISO standards.
465 We detect explicit NULL pointer dereferences as well as those implied
466 by a PHI argument having a NULL value which unconditionally flows into
467 a dereference in the same block as the PHI.
469 In the former case we replace the offending statement with an
470 unconditional trap and eliminate the outgoing edges from the statement's
471 basic block. This may expose secondary optimization opportunities.
473 In the latter case, we isolate the path(s) with the NULL PHI
474 feeding the dereference. We can then replace the offending statement
475 and eliminate the outgoing edges in the duplicate. Again, this may
476 expose secondary optimization opportunities.
478 A warning for both cases may be advisable as well.
480 Other statically detectable violations of the ISO standard could be
481 handled in a similar way, such as out-of-bounds array indexing. */
483 static unsigned int
484 gimple_ssa_isolate_erroneous_paths (void)
486 initialize_original_copy_tables ();
488 /* Search all the blocks for edges which, if traversed, will
489 result in undefined behaviour. */
490 cfg_altered = false;
492 /* First handle cases where traversal of a particular edge
493 triggers undefined behaviour. These cases require creating
494 duplicate blocks and thus new SSA_NAMEs.
496 We want that process complete prior to the phase where we start
497 removing edges from the CFG. Edge removal may ultimately result in
498 removal of PHI nodes and thus releasing SSA_NAMEs back to the
499 name manager.
501 If the two processes run in parallel we could release an SSA_NAME
502 back to the manager but we could still have dangling references
503 to the released SSA_NAME in unreachable blocks.
504 that any released names not have dangling references in the IL. */
505 find_implicit_erroneous_behaviour ();
506 find_explicit_erroneous_behaviour ();
508 free_original_copy_tables ();
510 /* We scramble the CFG and loop structures a bit, clean up
511 appropriately. We really should incrementally update the
512 loop structures, in theory it shouldn't be that hard. */
513 if (cfg_altered)
515 free_dominance_info (CDI_DOMINATORS);
516 free_dominance_info (CDI_POST_DOMINATORS);
517 loops_state_set (LOOPS_NEED_FIXUP);
518 return TODO_cleanup_cfg | TODO_update_ssa;
520 return 0;
523 namespace {
524 const pass_data pass_data_isolate_erroneous_paths =
526 GIMPLE_PASS, /* type */
527 "isolate-paths", /* name */
528 OPTGROUP_NONE, /* optinfo_flags */
529 TV_ISOLATE_ERRONEOUS_PATHS, /* tv_id */
530 ( PROP_cfg | PROP_ssa ), /* properties_required */
531 0, /* properties_provided */
532 0, /* properties_destroyed */
533 0, /* todo_flags_start */
534 0, /* todo_flags_finish */
537 class pass_isolate_erroneous_paths : public gimple_opt_pass
539 public:
540 pass_isolate_erroneous_paths (gcc::context *ctxt)
541 : gimple_opt_pass (pass_data_isolate_erroneous_paths, ctxt)
544 /* opt_pass methods: */
545 opt_pass * clone () { return new pass_isolate_erroneous_paths (m_ctxt); }
546 virtual bool gate (function *)
548 /* If we do not have a suitable builtin function for the trap statement,
549 then do not perform the optimization. */
550 return (flag_isolate_erroneous_paths_dereference != 0
551 || flag_isolate_erroneous_paths_attribute != 0);
554 virtual unsigned int execute (function *)
556 return gimple_ssa_isolate_erroneous_paths ();
559 }; // class pass_isolate_erroneous_paths
562 gimple_opt_pass *
563 make_pass_isolate_erroneous_paths (gcc::context *ctxt)
565 return new pass_isolate_erroneous_paths (ctxt);