Introduce LABEL_REF_LABEL
[official-gcc.git] / gcc / gimple-ssa-isolate-paths.c
blob0b62915f55d5e066f40d879c69fa07726d7f8f84
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)
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 "tree.h"
26 #include "flags.h"
27 #include "basic-block.h"
28 #include "tree-ssa-alias.h"
29 #include "internal-fn.h"
30 #include "gimple-expr.h"
31 #include "is-a.h"
32 #include "gimple.h"
33 #include "gimple-iterator.h"
34 #include "gimple-walk.h"
35 #include "tree-ssa.h"
36 #include "stringpool.h"
37 #include "tree-ssanames.h"
38 #include "gimple-ssa.h"
39 #include "tree-ssa-operands.h"
40 #include "tree-phinodes.h"
41 #include "ssa-iterators.h"
42 #include "cfgloop.h"
43 #include "tree-pass.h"
44 #include "tree-cfg.h"
45 #include "diagnostic-core.h"
46 #include "intl.h"
49 static bool cfg_altered;
51 /* Callback for walk_stmt_load_store_ops.
53 Return TRUE if OP will dereference the tree stored in DATA, FALSE
54 otherwise.
56 This routine only makes a superficial check for a dereference. Thus,
57 it must only be used if it is safe to return a false negative. */
58 static bool
59 check_loadstore (gimple stmt, tree op, tree, void *data)
61 if ((TREE_CODE (op) == MEM_REF || TREE_CODE (op) == TARGET_MEM_REF)
62 && operand_equal_p (TREE_OPERAND (op, 0), (tree)data, 0))
64 TREE_THIS_VOLATILE (op) = 1;
65 TREE_SIDE_EFFECTS (op) = 1;
66 update_stmt (stmt);
67 return true;
69 return false;
72 /* Insert a trap after SI and remove SI and all statements after the trap. */
74 static void
75 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator *si_p, tree op)
77 /* We want the NULL pointer dereference to actually occur so that
78 code that wishes to catch the signal can do so.
80 If the dereference is a load, then there's nothing to do as the
81 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
83 If the dereference is a store and we can easily transform the RHS,
84 then simplify the RHS to enable more DCE. Note that we require the
85 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
86 gimple stmt = gsi_stmt (*si_p);
87 if (walk_stmt_load_store_ops (stmt, (void *)op, NULL, check_loadstore)
88 && is_gimple_assign (stmt)
89 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
91 /* We just need to turn the RHS into zero converted to the proper
92 type. */
93 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
94 gimple_assign_set_rhs_code (stmt, INTEGER_CST);
95 gimple_assign_set_rhs1 (stmt, fold_convert (type, integer_zero_node));
96 update_stmt (stmt);
99 gimple new_stmt
100 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP), 0);
101 gimple_seq seq = NULL;
102 gimple_seq_add_stmt (&seq, new_stmt);
104 /* If we had a NULL pointer dereference, then we want to insert the
105 __builtin_trap after the statement, for the other cases we want
106 to insert before the statement. */
107 if (walk_stmt_load_store_ops (stmt, (void *)op,
108 check_loadstore,
109 check_loadstore))
110 gsi_insert_after (si_p, seq, GSI_NEW_STMT);
111 else
112 gsi_insert_before (si_p, seq, GSI_NEW_STMT);
114 /* We must remove statements from the end of the block so that we
115 never reference a released SSA_NAME. */
116 basic_block bb = gimple_bb (gsi_stmt (*si_p));
117 for (gimple_stmt_iterator si = gsi_last_bb (bb);
118 gsi_stmt (si) != gsi_stmt (*si_p);
119 si = gsi_last_bb (bb))
121 stmt = gsi_stmt (si);
122 unlink_stmt_vdef (stmt);
123 gsi_remove (&si, true);
124 release_defs (stmt);
128 /* BB when reached via incoming edge E will exhibit undefined behaviour
129 at STMT. Isolate and optimize the path which exhibits undefined
130 behaviour.
132 Isolation is simple. Duplicate BB and redirect E to BB'.
134 Optimization is simple as well. Replace STMT in BB' with an
135 unconditional trap and remove all outgoing edges from BB'.
137 If RET_ZERO, do not trap, only return NULL.
139 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
141 Return BB'. */
143 basic_block
144 isolate_path (basic_block bb, basic_block duplicate,
145 edge e, gimple stmt, tree op, bool ret_zero)
147 gimple_stmt_iterator si, si2;
148 edge_iterator ei;
149 edge e2;
151 /* First duplicate BB if we have not done so already and remove all
152 the duplicate's outgoing edges as duplicate is going to unconditionally
153 trap. Removing the outgoing edges is both an optimization and ensures
154 we don't need to do any PHI node updates. */
155 if (!duplicate)
157 duplicate = duplicate_block (bb, NULL, NULL);
158 if (!ret_zero)
159 for (ei = ei_start (duplicate->succs); (e2 = ei_safe_edge (ei)); )
160 remove_edge (e2);
163 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
164 e2 = redirect_edge_and_branch (e, duplicate);
165 if (e2)
166 flush_pending_stmts (e2);
169 /* There may be more than one statement in DUPLICATE which exhibits
170 undefined behaviour. Ultimately we want the first such statement in
171 DUPLCIATE so that we're able to delete as much code as possible.
173 So each time we discover undefined behaviour in DUPLICATE, search for
174 the statement which triggers undefined behaviour. If found, then
175 transform the statement into a trap and delete everything after the
176 statement. If not found, then this particular instance was subsumed by
177 an earlier instance of undefined behaviour and there's nothing to do.
179 This is made more complicated by the fact that we have STMT, which is in
180 BB rather than in DUPLICATE. So we set up two iterators, one for each
181 block and walk forward looking for STMT in BB, advancing each iterator at
182 each step.
184 When we find STMT the second iterator should point to STMT's equivalent in
185 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
186 nothing to do.
188 Ignore labels and debug statements. */
189 si = gsi_start_nondebug_after_labels_bb (bb);
190 si2 = gsi_start_nondebug_after_labels_bb (duplicate);
191 while (!gsi_end_p (si) && !gsi_end_p (si2) && gsi_stmt (si) != stmt)
193 gsi_next_nondebug (&si);
194 gsi_next_nondebug (&si2);
197 /* This would be an indicator that we never found STMT in BB, which should
198 never happen. */
199 gcc_assert (!gsi_end_p (si));
201 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
202 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
203 before SI2 and remove SI2 and all trailing statements. */
204 if (!gsi_end_p (si2))
206 if (ret_zero)
208 gimple ret = gsi_stmt (si2);
209 tree zero = build_zero_cst (TREE_TYPE (gimple_return_retval (ret)));
210 gimple_return_set_retval (ret, zero);
211 update_stmt (ret);
213 else
214 insert_trap_and_remove_trailing_statements (&si2, op);
217 return duplicate;
220 /* Look for PHI nodes which feed statements in the same block where
221 the value of the PHI node implies the statement is erroneous.
223 For example, a NULL PHI arg value which then feeds a pointer
224 dereference.
226 When found isolate and optimize the path associated with the PHI
227 argument feeding the erroneous statement. */
228 static void
229 find_implicit_erroneous_behaviour (void)
231 basic_block bb;
233 FOR_EACH_BB_FN (bb, cfun)
235 gimple_stmt_iterator si;
237 /* Out of an abundance of caution, do not isolate paths to a
238 block where the block has any abnormal outgoing edges.
240 We might be able to relax this in the future. We have to detect
241 when we have to split the block with the NULL dereference and
242 the trap we insert. We have to preserve abnormal edges out
243 of the isolated block which in turn means updating PHIs at
244 the targets of those abnormal outgoing edges. */
245 if (has_abnormal_or_eh_outgoing_edge_p (bb))
246 continue;
248 /* First look for a PHI which sets a pointer to NULL and which
249 is then dereferenced within BB. This is somewhat overly
250 conservative, but probably catches most of the interesting
251 cases. */
252 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
254 gimple phi = gsi_stmt (si);
255 tree lhs = gimple_phi_result (phi);
257 /* If the result is not a pointer, then there is no need to
258 examine the arguments. */
259 if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
260 continue;
262 /* PHI produces a pointer result. See if any of the PHI's
263 arguments are NULL.
265 When we remove an edge, we want to reprocess the current
266 index, hence the ugly way we update I for each iteration. */
267 basic_block duplicate = NULL;
268 for (unsigned i = 0, next_i = 0;
269 i < gimple_phi_num_args (phi);
270 i = next_i)
272 tree op = gimple_phi_arg_def (phi, i);
273 edge e = gimple_phi_arg_edge (phi, i);
274 imm_use_iterator iter;
275 gimple use_stmt;
277 next_i = i + 1;
279 if (TREE_CODE (op) == ADDR_EXPR)
281 tree valbase = get_base_address (TREE_OPERAND (op, 0));
282 if ((TREE_CODE (valbase) == VAR_DECL
283 && !is_global_var (valbase))
284 || TREE_CODE (valbase) == PARM_DECL)
286 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
288 if (gimple_code (use_stmt) != GIMPLE_RETURN
289 || gimple_return_retval (use_stmt) != lhs)
290 continue;
292 if (warning_at (gimple_location (use_stmt),
293 OPT_Wreturn_local_addr,
294 "function may return address "
295 "of local variable"))
296 inform (DECL_SOURCE_LOCATION(valbase),
297 "declared here");
299 if (gimple_bb (use_stmt) == bb)
301 duplicate = isolate_path (bb, duplicate, e,
302 use_stmt, lhs, true);
304 /* When we remove an incoming edge, we need to
305 reprocess the Ith element. */
306 next_i = i;
307 cfg_altered = true;
313 if (!integer_zerop (op))
314 continue;
316 /* We've got a NULL PHI argument. Now see if the
317 PHI's result is dereferenced within BB. */
318 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
320 /* We only care about uses in BB. Catching cases in
321 in other blocks would require more complex path
322 isolation code. */
323 if (gimple_bb (use_stmt) != bb)
324 continue;
326 if (infer_nonnull_range (use_stmt, lhs,
327 flag_isolate_erroneous_paths_dereference,
328 flag_isolate_erroneous_paths_attribute))
331 duplicate = isolate_path (bb, duplicate, e,
332 use_stmt, lhs, false);
334 /* When we remove an incoming edge, we need to
335 reprocess the Ith element. */
336 next_i = i;
337 cfg_altered = true;
345 /* Look for statements which exhibit erroneous behaviour. For example
346 a NULL pointer dereference.
348 When found, optimize the block containing the erroneous behaviour. */
349 static void
350 find_explicit_erroneous_behaviour (void)
352 basic_block bb;
354 FOR_EACH_BB_FN (bb, cfun)
356 gimple_stmt_iterator si;
358 /* Out of an abundance of caution, do not isolate paths to a
359 block where the block has any abnormal outgoing edges.
361 We might be able to relax this in the future. We have to detect
362 when we have to split the block with the NULL dereference and
363 the trap we insert. We have to preserve abnormal edges out
364 of the isolated block which in turn means updating PHIs at
365 the targets of those abnormal outgoing edges. */
366 if (has_abnormal_or_eh_outgoing_edge_p (bb))
367 continue;
369 /* Now look at the statements in the block and see if any of
370 them explicitly dereference a NULL pointer. This happens
371 because of jump threading and constant propagation. */
372 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
374 gimple stmt = gsi_stmt (si);
376 /* By passing null_pointer_node, we can use infer_nonnull_range
377 to detect explicit NULL pointer dereferences and other uses
378 where a non-NULL value is required. */
379 if (infer_nonnull_range (stmt, null_pointer_node,
380 flag_isolate_erroneous_paths_dereference,
381 flag_isolate_erroneous_paths_attribute))
383 insert_trap_and_remove_trailing_statements (&si,
384 null_pointer_node);
386 /* And finally, remove all outgoing edges from BB. */
387 edge e;
388 for (edge_iterator ei = ei_start (bb->succs);
389 (e = ei_safe_edge (ei)); )
390 remove_edge (e);
392 /* Ignore any more operands on this statement and
393 continue the statement iterator (which should
394 terminate its loop immediately. */
395 cfg_altered = true;
396 break;
399 /* Detect returning the address of a local variable. This only
400 becomes undefined behavior if the result is used, so we do not
401 insert a trap and only return NULL instead. */
402 if (gimple_code (stmt) == GIMPLE_RETURN)
404 tree val = gimple_return_retval (stmt);
405 if (val && TREE_CODE (val) == ADDR_EXPR)
407 tree valbase = get_base_address (TREE_OPERAND (val, 0));
408 if ((TREE_CODE (valbase) == VAR_DECL
409 && !is_global_var (valbase))
410 || TREE_CODE (valbase) == PARM_DECL)
412 /* We only need it for this particular case. */
413 calculate_dominance_info (CDI_POST_DOMINATORS);
414 const char* msg;
415 bool always_executed = dominated_by_p
416 (CDI_POST_DOMINATORS,
417 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)), bb);
418 if (always_executed)
419 msg = N_("function returns address of local variable");
420 else
421 msg = N_("function may return address of "
422 "local variable");
424 if (warning_at (gimple_location (stmt),
425 OPT_Wreturn_local_addr, msg))
426 inform (DECL_SOURCE_LOCATION(valbase), "declared here");
427 tree zero = build_zero_cst (TREE_TYPE (val));
428 gimple_return_set_retval (stmt, zero);
429 update_stmt (stmt);
437 /* Search the function for statements which, if executed, would cause
438 the program to fault such as a dereference of a NULL pointer.
440 Such a program can't be valid if such a statement was to execute
441 according to ISO standards.
443 We detect explicit NULL pointer dereferences as well as those implied
444 by a PHI argument having a NULL value which unconditionally flows into
445 a dereference in the same block as the PHI.
447 In the former case we replace the offending statement with an
448 unconditional trap and eliminate the outgoing edges from the statement's
449 basic block. This may expose secondary optimization opportunities.
451 In the latter case, we isolate the path(s) with the NULL PHI
452 feeding the dereference. We can then replace the offending statement
453 and eliminate the outgoing edges in the duplicate. Again, this may
454 expose secondary optimization opportunities.
456 A warning for both cases may be advisable as well.
458 Other statically detectable violations of the ISO standard could be
459 handled in a similar way, such as out-of-bounds array indexing. */
461 static unsigned int
462 gimple_ssa_isolate_erroneous_paths (void)
464 initialize_original_copy_tables ();
466 /* Search all the blocks for edges which, if traversed, will
467 result in undefined behaviour. */
468 cfg_altered = false;
470 /* First handle cases where traversal of a particular edge
471 triggers undefined behaviour. These cases require creating
472 duplicate blocks and thus new SSA_NAMEs.
474 We want that process complete prior to the phase where we start
475 removing edges from the CFG. Edge removal may ultimately result in
476 removal of PHI nodes and thus releasing SSA_NAMEs back to the
477 name manager.
479 If the two processes run in parallel we could release an SSA_NAME
480 back to the manager but we could still have dangling references
481 to the released SSA_NAME in unreachable blocks.
482 that any released names not have dangling references in the IL. */
483 find_implicit_erroneous_behaviour ();
484 find_explicit_erroneous_behaviour ();
486 free_original_copy_tables ();
488 /* We scramble the CFG and loop structures a bit, clean up
489 appropriately. We really should incrementally update the
490 loop structures, in theory it shouldn't be that hard. */
491 if (cfg_altered)
493 free_dominance_info (CDI_DOMINATORS);
494 free_dominance_info (CDI_POST_DOMINATORS);
495 loops_state_set (LOOPS_NEED_FIXUP);
496 return TODO_cleanup_cfg | TODO_update_ssa;
498 return 0;
501 namespace {
502 const pass_data pass_data_isolate_erroneous_paths =
504 GIMPLE_PASS, /* type */
505 "isolate-paths", /* name */
506 OPTGROUP_NONE, /* optinfo_flags */
507 TV_ISOLATE_ERRONEOUS_PATHS, /* tv_id */
508 ( PROP_cfg | PROP_ssa ), /* properties_required */
509 0, /* properties_provided */
510 0, /* properties_destroyed */
511 0, /* todo_flags_start */
512 0, /* todo_flags_finish */
515 class pass_isolate_erroneous_paths : public gimple_opt_pass
517 public:
518 pass_isolate_erroneous_paths (gcc::context *ctxt)
519 : gimple_opt_pass (pass_data_isolate_erroneous_paths, ctxt)
522 /* opt_pass methods: */
523 opt_pass * clone () { return new pass_isolate_erroneous_paths (m_ctxt); }
524 virtual bool gate (function *)
526 /* If we do not have a suitable builtin function for the trap statement,
527 then do not perform the optimization. */
528 return (flag_isolate_erroneous_paths_dereference != 0
529 || flag_isolate_erroneous_paths_attribute != 0);
532 virtual unsigned int execute (function *)
534 return gimple_ssa_isolate_erroneous_paths ();
537 }; // class pass_isolate_erroneous_paths
540 gimple_opt_pass *
541 make_pass_isolate_erroneous_paths (gcc::context *ctxt)
543 return new pass_isolate_erroneous_paths (ctxt);