1 /* Detect paths through the CFG which can never be executed in a conforming
2 program and isolate them.
4 Copyright (C) 2013-2014 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)
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/>. */
24 #include "coretypes.h"
33 #include "hard-reg-set.h"
36 #include "dominance.h"
38 #include "basic-block.h"
39 #include "tree-ssa-alias.h"
40 #include "internal-fn.h"
41 #include "gimple-expr.h"
44 #include "gimple-iterator.h"
45 #include "gimple-walk.h"
47 #include "stringpool.h"
48 #include "tree-ssanames.h"
49 #include "gimple-ssa.h"
50 #include "tree-ssa-operands.h"
51 #include "tree-phinodes.h"
52 #include "ssa-iterators.h"
54 #include "tree-pass.h"
56 #include "diagnostic-core.h"
60 static bool cfg_altered
;
62 /* Callback for walk_stmt_load_store_ops.
64 Return TRUE if OP will dereference the tree stored in DATA, FALSE
67 This routine only makes a superficial check for a dereference. Thus,
68 it must only be used if it is safe to return a false negative. */
70 check_loadstore (gimple stmt
, tree op
, tree
, void *data
)
72 if ((TREE_CODE (op
) == MEM_REF
|| TREE_CODE (op
) == TARGET_MEM_REF
)
73 && operand_equal_p (TREE_OPERAND (op
, 0), (tree
)data
, 0))
75 TREE_THIS_VOLATILE (op
) = 1;
76 TREE_SIDE_EFFECTS (op
) = 1;
83 /* Insert a trap after SI and remove SI and all statements after the trap. */
86 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator
*si_p
, tree op
)
88 /* We want the NULL pointer dereference to actually occur so that
89 code that wishes to catch the signal can do so.
91 If the dereference is a load, then there's nothing to do as the
92 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
94 If the dereference is a store and we can easily transform the RHS,
95 then simplify the RHS to enable more DCE. Note that we require the
96 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
97 gimple stmt
= gsi_stmt (*si_p
);
98 if (walk_stmt_load_store_ops (stmt
, (void *)op
, NULL
, check_loadstore
)
99 && is_gimple_assign (stmt
)
100 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt
))))
102 /* We just need to turn the RHS into zero converted to the proper
104 tree type
= TREE_TYPE (gimple_assign_lhs (stmt
));
105 gimple_assign_set_rhs_code (stmt
, INTEGER_CST
);
106 gimple_assign_set_rhs1 (stmt
, fold_convert (type
, integer_zero_node
));
111 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP
), 0);
112 gimple_seq seq
= NULL
;
113 gimple_seq_add_stmt (&seq
, new_stmt
);
115 /* If we had a NULL pointer dereference, then we want to insert the
116 __builtin_trap after the statement, for the other cases we want
117 to insert before the statement. */
118 if (walk_stmt_load_store_ops (stmt
, (void *)op
,
121 gsi_insert_after (si_p
, seq
, GSI_NEW_STMT
);
123 gsi_insert_before (si_p
, seq
, GSI_NEW_STMT
);
125 /* We must remove statements from the end of the block so that we
126 never reference a released SSA_NAME. */
127 basic_block bb
= gimple_bb (gsi_stmt (*si_p
));
128 for (gimple_stmt_iterator si
= gsi_last_bb (bb
);
129 gsi_stmt (si
) != gsi_stmt (*si_p
);
130 si
= gsi_last_bb (bb
))
132 stmt
= gsi_stmt (si
);
133 unlink_stmt_vdef (stmt
);
134 gsi_remove (&si
, true);
139 /* BB when reached via incoming edge E will exhibit undefined behaviour
140 at STMT. Isolate and optimize the path which exhibits undefined
143 Isolation is simple. Duplicate BB and redirect E to BB'.
145 Optimization is simple as well. Replace STMT in BB' with an
146 unconditional trap and remove all outgoing edges from BB'.
148 If RET_ZERO, do not trap, only return NULL.
150 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
155 isolate_path (basic_block bb
, basic_block duplicate
,
156 edge e
, gimple stmt
, tree op
, bool ret_zero
)
158 gimple_stmt_iterator si
, si2
;
162 /* First duplicate BB if we have not done so already and remove all
163 the duplicate's outgoing edges as duplicate is going to unconditionally
164 trap. Removing the outgoing edges is both an optimization and ensures
165 we don't need to do any PHI node updates. */
168 duplicate
= duplicate_block (bb
, NULL
, NULL
);
170 for (ei
= ei_start (duplicate
->succs
); (e2
= ei_safe_edge (ei
)); )
174 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
175 e2
= redirect_edge_and_branch (e
, duplicate
);
177 flush_pending_stmts (e2
);
180 /* There may be more than one statement in DUPLICATE which exhibits
181 undefined behaviour. Ultimately we want the first such statement in
182 DUPLCIATE so that we're able to delete as much code as possible.
184 So each time we discover undefined behaviour in DUPLICATE, search for
185 the statement which triggers undefined behaviour. If found, then
186 transform the statement into a trap and delete everything after the
187 statement. If not found, then this particular instance was subsumed by
188 an earlier instance of undefined behaviour and there's nothing to do.
190 This is made more complicated by the fact that we have STMT, which is in
191 BB rather than in DUPLICATE. So we set up two iterators, one for each
192 block and walk forward looking for STMT in BB, advancing each iterator at
195 When we find STMT the second iterator should point to STMT's equivalent in
196 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
199 Ignore labels and debug statements. */
200 si
= gsi_start_nondebug_after_labels_bb (bb
);
201 si2
= gsi_start_nondebug_after_labels_bb (duplicate
);
202 while (!gsi_end_p (si
) && !gsi_end_p (si2
) && gsi_stmt (si
) != stmt
)
204 gsi_next_nondebug (&si
);
205 gsi_next_nondebug (&si2
);
208 /* This would be an indicator that we never found STMT in BB, which should
210 gcc_assert (!gsi_end_p (si
));
212 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
213 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
214 before SI2 and remove SI2 and all trailing statements. */
215 if (!gsi_end_p (si2
))
219 greturn
*ret
= as_a
<greturn
*> (gsi_stmt (si2
));
220 tree zero
= build_zero_cst (TREE_TYPE (gimple_return_retval (ret
)));
221 gimple_return_set_retval (ret
, zero
);
225 insert_trap_and_remove_trailing_statements (&si2
, op
);
231 /* Look for PHI nodes which feed statements in the same block where
232 the value of the PHI node implies the statement is erroneous.
234 For example, a NULL PHI arg value which then feeds a pointer
237 When found isolate and optimize the path associated with the PHI
238 argument feeding the erroneous statement. */
240 find_implicit_erroneous_behaviour (void)
244 FOR_EACH_BB_FN (bb
, cfun
)
248 /* Out of an abundance of caution, do not isolate paths to a
249 block where the block has any abnormal outgoing edges.
251 We might be able to relax this in the future. We have to detect
252 when we have to split the block with the NULL dereference and
253 the trap we insert. We have to preserve abnormal edges out
254 of the isolated block which in turn means updating PHIs at
255 the targets of those abnormal outgoing edges. */
256 if (has_abnormal_or_eh_outgoing_edge_p (bb
))
259 /* First look for a PHI which sets a pointer to NULL and which
260 is then dereferenced within BB. This is somewhat overly
261 conservative, but probably catches most of the interesting
263 for (si
= gsi_start_phis (bb
); !gsi_end_p (si
); gsi_next (&si
))
265 gphi
*phi
= si
.phi ();
266 tree lhs
= gimple_phi_result (phi
);
268 /* If the result is not a pointer, then there is no need to
269 examine the arguments. */
270 if (!POINTER_TYPE_P (TREE_TYPE (lhs
)))
273 /* PHI produces a pointer result. See if any of the PHI's
276 When we remove an edge, we want to reprocess the current
277 index, hence the ugly way we update I for each iteration. */
278 basic_block duplicate
= NULL
;
279 for (unsigned i
= 0, next_i
= 0;
280 i
< gimple_phi_num_args (phi
);
283 tree op
= gimple_phi_arg_def (phi
, i
);
284 edge e
= gimple_phi_arg_edge (phi
, i
);
285 imm_use_iterator iter
;
290 if (TREE_CODE (op
) == ADDR_EXPR
)
292 tree valbase
= get_base_address (TREE_OPERAND (op
, 0));
293 if ((TREE_CODE (valbase
) == VAR_DECL
294 && !is_global_var (valbase
))
295 || TREE_CODE (valbase
) == PARM_DECL
)
297 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
300 = dyn_cast
<greturn
*> (use_stmt
);
304 if (gimple_return_retval (return_stmt
) != lhs
)
307 if (warning_at (gimple_location (use_stmt
),
308 OPT_Wreturn_local_addr
,
309 "function may return address "
310 "of local variable"))
311 inform (DECL_SOURCE_LOCATION(valbase
),
314 if (gimple_bb (use_stmt
) == bb
)
316 duplicate
= isolate_path (bb
, duplicate
, e
,
317 use_stmt
, lhs
, true);
319 /* When we remove an incoming edge, we need to
320 reprocess the Ith element. */
328 if (!integer_zerop (op
))
331 /* We've got a NULL PHI argument. Now see if the
332 PHI's result is dereferenced within BB. */
333 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
335 /* We only care about uses in BB. Catching cases in
336 in other blocks would require more complex path
338 if (gimple_bb (use_stmt
) != bb
)
341 if (infer_nonnull_range (use_stmt
, lhs
,
342 flag_isolate_erroneous_paths_dereference
,
343 flag_isolate_erroneous_paths_attribute
))
346 duplicate
= isolate_path (bb
, duplicate
, e
,
347 use_stmt
, lhs
, false);
349 /* When we remove an incoming edge, we need to
350 reprocess the Ith element. */
360 /* Look for statements which exhibit erroneous behaviour. For example
361 a NULL pointer dereference.
363 When found, optimize the block containing the erroneous behaviour. */
365 find_explicit_erroneous_behaviour (void)
369 FOR_EACH_BB_FN (bb
, cfun
)
371 gimple_stmt_iterator si
;
373 /* Out of an abundance of caution, do not isolate paths to a
374 block where the block has any abnormal outgoing edges.
376 We might be able to relax this in the future. We have to detect
377 when we have to split the block with the NULL dereference and
378 the trap we insert. We have to preserve abnormal edges out
379 of the isolated block which in turn means updating PHIs at
380 the targets of those abnormal outgoing edges. */
381 if (has_abnormal_or_eh_outgoing_edge_p (bb
))
384 /* Now look at the statements in the block and see if any of
385 them explicitly dereference a NULL pointer. This happens
386 because of jump threading and constant propagation. */
387 for (si
= gsi_start_bb (bb
); !gsi_end_p (si
); gsi_next (&si
))
389 gimple stmt
= gsi_stmt (si
);
391 /* By passing null_pointer_node, we can use infer_nonnull_range
392 to detect explicit NULL pointer dereferences and other uses
393 where a non-NULL value is required. */
394 if (infer_nonnull_range (stmt
, null_pointer_node
,
395 flag_isolate_erroneous_paths_dereference
,
396 flag_isolate_erroneous_paths_attribute
))
398 insert_trap_and_remove_trailing_statements (&si
,
401 /* And finally, remove all outgoing edges from BB. */
403 for (edge_iterator ei
= ei_start (bb
->succs
);
404 (e
= ei_safe_edge (ei
)); )
407 /* Ignore any more operands on this statement and
408 continue the statement iterator (which should
409 terminate its loop immediately. */
414 /* Detect returning the address of a local variable. This only
415 becomes undefined behavior if the result is used, so we do not
416 insert a trap and only return NULL instead. */
417 if (greturn
*return_stmt
= dyn_cast
<greturn
*> (stmt
))
419 tree val
= gimple_return_retval (return_stmt
);
420 if (val
&& TREE_CODE (val
) == ADDR_EXPR
)
422 tree valbase
= get_base_address (TREE_OPERAND (val
, 0));
423 if ((TREE_CODE (valbase
) == VAR_DECL
424 && !is_global_var (valbase
))
425 || TREE_CODE (valbase
) == PARM_DECL
)
427 /* We only need it for this particular case. */
428 calculate_dominance_info (CDI_POST_DOMINATORS
);
430 bool always_executed
= dominated_by_p
431 (CDI_POST_DOMINATORS
,
432 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun
)), bb
);
434 msg
= N_("function returns address of local variable");
436 msg
= N_("function may return address of "
439 if (warning_at (gimple_location (stmt
),
440 OPT_Wreturn_local_addr
, msg
))
441 inform (DECL_SOURCE_LOCATION(valbase
), "declared here");
442 tree zero
= build_zero_cst (TREE_TYPE (val
));
443 gimple_return_set_retval (return_stmt
, zero
);
452 /* Search the function for statements which, if executed, would cause
453 the program to fault such as a dereference of a NULL pointer.
455 Such a program can't be valid if such a statement was to execute
456 according to ISO standards.
458 We detect explicit NULL pointer dereferences as well as those implied
459 by a PHI argument having a NULL value which unconditionally flows into
460 a dereference in the same block as the PHI.
462 In the former case we replace the offending statement with an
463 unconditional trap and eliminate the outgoing edges from the statement's
464 basic block. This may expose secondary optimization opportunities.
466 In the latter case, we isolate the path(s) with the NULL PHI
467 feeding the dereference. We can then replace the offending statement
468 and eliminate the outgoing edges in the duplicate. Again, this may
469 expose secondary optimization opportunities.
471 A warning for both cases may be advisable as well.
473 Other statically detectable violations of the ISO standard could be
474 handled in a similar way, such as out-of-bounds array indexing. */
477 gimple_ssa_isolate_erroneous_paths (void)
479 initialize_original_copy_tables ();
481 /* Search all the blocks for edges which, if traversed, will
482 result in undefined behaviour. */
485 /* First handle cases where traversal of a particular edge
486 triggers undefined behaviour. These cases require creating
487 duplicate blocks and thus new SSA_NAMEs.
489 We want that process complete prior to the phase where we start
490 removing edges from the CFG. Edge removal may ultimately result in
491 removal of PHI nodes and thus releasing SSA_NAMEs back to the
494 If the two processes run in parallel we could release an SSA_NAME
495 back to the manager but we could still have dangling references
496 to the released SSA_NAME in unreachable blocks.
497 that any released names not have dangling references in the IL. */
498 find_implicit_erroneous_behaviour ();
499 find_explicit_erroneous_behaviour ();
501 free_original_copy_tables ();
503 /* We scramble the CFG and loop structures a bit, clean up
504 appropriately. We really should incrementally update the
505 loop structures, in theory it shouldn't be that hard. */
508 free_dominance_info (CDI_DOMINATORS
);
509 free_dominance_info (CDI_POST_DOMINATORS
);
510 loops_state_set (LOOPS_NEED_FIXUP
);
511 return TODO_cleanup_cfg
| TODO_update_ssa
;
517 const pass_data pass_data_isolate_erroneous_paths
=
519 GIMPLE_PASS
, /* type */
520 "isolate-paths", /* name */
521 OPTGROUP_NONE
, /* optinfo_flags */
522 TV_ISOLATE_ERRONEOUS_PATHS
, /* tv_id */
523 ( PROP_cfg
| PROP_ssa
), /* properties_required */
524 0, /* properties_provided */
525 0, /* properties_destroyed */
526 0, /* todo_flags_start */
527 0, /* todo_flags_finish */
530 class pass_isolate_erroneous_paths
: public gimple_opt_pass
533 pass_isolate_erroneous_paths (gcc::context
*ctxt
)
534 : gimple_opt_pass (pass_data_isolate_erroneous_paths
, ctxt
)
537 /* opt_pass methods: */
538 opt_pass
* clone () { return new pass_isolate_erroneous_paths (m_ctxt
); }
539 virtual bool gate (function
*)
541 /* If we do not have a suitable builtin function for the trap statement,
542 then do not perform the optimization. */
543 return (flag_isolate_erroneous_paths_dereference
!= 0
544 || flag_isolate_erroneous_paths_attribute
!= 0);
547 virtual unsigned int execute (function
*)
549 return gimple_ssa_isolate_erroneous_paths ();
552 }; // class pass_isolate_erroneous_paths
556 make_pass_isolate_erroneous_paths (gcc::context
*ctxt
)
558 return new pass_isolate_erroneous_paths (ctxt
);