[doc][13/14] Document AArch64 target attributes and pragmas
[official-gcc.git] / gcc / gimple-ssa-isolate-paths.c
blob7d3758ce5abbe4d2ea406491b6bb461d85aa3b87
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 "alias.h"
26 #include "backend.h"
27 #include "cfghooks.h"
28 #include "tree.h"
29 #include "gimple.h"
30 #include "hard-reg-set.h"
31 #include "ssa.h"
32 #include "options.h"
33 #include "fold-const.h"
34 #include "flags.h"
35 #include "internal-fn.h"
36 #include "gimple-iterator.h"
37 #include "gimple-walk.h"
38 #include "tree-ssa.h"
39 #include "cfgloop.h"
40 #include "tree-pass.h"
41 #include "tree-cfg.h"
42 #include "diagnostic-core.h"
43 #include "intl.h"
46 static bool cfg_altered;
48 /* Callback for walk_stmt_load_store_ops.
50 Return TRUE if OP will dereference the tree stored in DATA, FALSE
51 otherwise.
53 This routine only makes a superficial check for a dereference. Thus,
54 it must only be used if it is safe to return a false negative. */
55 static bool
56 check_loadstore (gimple stmt, tree op, tree, void *data)
58 if ((TREE_CODE (op) == MEM_REF || TREE_CODE (op) == TARGET_MEM_REF)
59 && operand_equal_p (TREE_OPERAND (op, 0), (tree)data, 0))
61 TREE_THIS_VOLATILE (op) = 1;
62 TREE_SIDE_EFFECTS (op) = 1;
63 update_stmt (stmt);
64 return true;
66 return false;
69 /* Insert a trap after SI and remove SI and all statements after the trap. */
71 static void
72 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator *si_p, tree op)
74 /* We want the NULL pointer dereference to actually occur so that
75 code that wishes to catch the signal can do so.
77 If the dereference is a load, then there's nothing to do as the
78 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
80 If the dereference is a store and we can easily transform the RHS,
81 then simplify the RHS to enable more DCE. Note that we require the
82 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
83 gimple stmt = gsi_stmt (*si_p);
84 if (walk_stmt_load_store_ops (stmt, (void *)op, NULL, check_loadstore)
85 && is_gimple_assign (stmt)
86 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
88 /* We just need to turn the RHS into zero converted to the proper
89 type. */
90 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
91 gimple_assign_set_rhs_code (stmt, INTEGER_CST);
92 gimple_assign_set_rhs1 (stmt, fold_convert (type, integer_zero_node));
93 update_stmt (stmt);
96 gcall *new_stmt
97 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP), 0);
98 gimple_seq seq = NULL;
99 gimple_seq_add_stmt (&seq, new_stmt);
101 /* If we had a NULL pointer dereference, then we want to insert the
102 __builtin_trap after the statement, for the other cases we want
103 to insert before the statement. */
104 if (walk_stmt_load_store_ops (stmt, (void *)op,
105 check_loadstore,
106 check_loadstore))
108 gsi_insert_after (si_p, seq, GSI_NEW_STMT);
109 if (stmt_ends_bb_p (stmt))
111 split_block (gimple_bb (stmt), stmt);
112 return;
115 else
116 gsi_insert_before (si_p, seq, GSI_NEW_STMT);
118 /* We must remove statements from the end of the block so that we
119 never reference a released SSA_NAME. */
120 basic_block bb = gimple_bb (gsi_stmt (*si_p));
121 for (gimple_stmt_iterator si = gsi_last_bb (bb);
122 gsi_stmt (si) != gsi_stmt (*si_p);
123 si = gsi_last_bb (bb))
125 stmt = gsi_stmt (si);
126 unlink_stmt_vdef (stmt);
127 gsi_remove (&si, true);
128 release_defs (stmt);
132 /* BB when reached via incoming edge E will exhibit undefined behaviour
133 at STMT. Isolate and optimize the path which exhibits undefined
134 behaviour.
136 Isolation is simple. Duplicate BB and redirect E to BB'.
138 Optimization is simple as well. Replace STMT in BB' with an
139 unconditional trap and remove all outgoing edges from BB'.
141 If RET_ZERO, do not trap, only return NULL.
143 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
145 Return BB'. */
147 basic_block
148 isolate_path (basic_block bb, basic_block duplicate,
149 edge e, gimple stmt, tree op, bool ret_zero)
151 gimple_stmt_iterator si, si2;
152 edge_iterator ei;
153 edge e2;
155 /* First duplicate BB if we have not done so already and remove all
156 the duplicate's outgoing edges as duplicate is going to unconditionally
157 trap. Removing the outgoing edges is both an optimization and ensures
158 we don't need to do any PHI node updates. */
159 if (!duplicate)
161 duplicate = duplicate_block (bb, NULL, NULL);
162 if (!ret_zero)
163 for (ei = ei_start (duplicate->succs); (e2 = ei_safe_edge (ei)); )
164 remove_edge (e2);
167 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
168 e2 = redirect_edge_and_branch (e, duplicate);
169 if (e2)
170 flush_pending_stmts (e2);
173 /* There may be more than one statement in DUPLICATE which exhibits
174 undefined behaviour. Ultimately we want the first such statement in
175 DUPLCIATE so that we're able to delete as much code as possible.
177 So each time we discover undefined behaviour in DUPLICATE, search for
178 the statement which triggers undefined behaviour. If found, then
179 transform the statement into a trap and delete everything after the
180 statement. If not found, then this particular instance was subsumed by
181 an earlier instance of undefined behaviour and there's nothing to do.
183 This is made more complicated by the fact that we have STMT, which is in
184 BB rather than in DUPLICATE. So we set up two iterators, one for each
185 block and walk forward looking for STMT in BB, advancing each iterator at
186 each step.
188 When we find STMT the second iterator should point to STMT's equivalent in
189 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
190 nothing to do.
192 Ignore labels and debug statements. */
193 si = gsi_start_nondebug_after_labels_bb (bb);
194 si2 = gsi_start_nondebug_after_labels_bb (duplicate);
195 while (!gsi_end_p (si) && !gsi_end_p (si2) && gsi_stmt (si) != stmt)
197 gsi_next_nondebug (&si);
198 gsi_next_nondebug (&si2);
201 /* This would be an indicator that we never found STMT in BB, which should
202 never happen. */
203 gcc_assert (!gsi_end_p (si));
205 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
206 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
207 before SI2 and remove SI2 and all trailing statements. */
208 if (!gsi_end_p (si2))
210 if (ret_zero)
212 greturn *ret = as_a <greturn *> (gsi_stmt (si2));
213 tree zero = build_zero_cst (TREE_TYPE (gimple_return_retval (ret)));
214 gimple_return_set_retval (ret, zero);
215 update_stmt (ret);
217 else
218 insert_trap_and_remove_trailing_statements (&si2, op);
221 return duplicate;
224 /* Look for PHI nodes which feed statements in the same block where
225 the value of the PHI node implies the statement is erroneous.
227 For example, a NULL PHI arg value which then feeds a pointer
228 dereference.
230 When found isolate and optimize the path associated with the PHI
231 argument feeding the erroneous statement. */
232 static void
233 find_implicit_erroneous_behaviour (void)
235 basic_block bb;
237 FOR_EACH_BB_FN (bb, cfun)
239 gphi_iterator si;
241 /* Out of an abundance of caution, do not isolate paths to a
242 block where the block has any abnormal outgoing edges.
244 We might be able to relax this in the future. We have to detect
245 when we have to split the block with the NULL dereference and
246 the trap we insert. We have to preserve abnormal edges out
247 of the isolated block which in turn means updating PHIs at
248 the targets of those abnormal outgoing edges. */
249 if (has_abnormal_or_eh_outgoing_edge_p (bb))
250 continue;
252 /* First look for a PHI which sets a pointer to NULL and which
253 is then dereferenced within BB. This is somewhat overly
254 conservative, but probably catches most of the interesting
255 cases. */
256 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
258 gphi *phi = si.phi ();
259 tree lhs = gimple_phi_result (phi);
261 /* If the result is not a pointer, then there is no need to
262 examine the arguments. */
263 if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
264 continue;
266 /* PHI produces a pointer result. See if any of the PHI's
267 arguments are NULL.
269 When we remove an edge, we want to reprocess the current
270 index, hence the ugly way we update I for each iteration. */
271 basic_block duplicate = NULL;
272 for (unsigned i = 0, next_i = 0;
273 i < gimple_phi_num_args (phi);
274 i = next_i)
276 tree op = gimple_phi_arg_def (phi, i);
277 edge e = gimple_phi_arg_edge (phi, i);
278 imm_use_iterator iter;
279 gimple use_stmt;
281 next_i = i + 1;
283 if (TREE_CODE (op) == ADDR_EXPR)
285 tree valbase = get_base_address (TREE_OPERAND (op, 0));
286 if ((TREE_CODE (valbase) == VAR_DECL
287 && !is_global_var (valbase))
288 || TREE_CODE (valbase) == PARM_DECL)
290 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
292 greturn *return_stmt
293 = dyn_cast <greturn *> (use_stmt);
294 if (!return_stmt)
295 continue;
297 if (gimple_return_retval (return_stmt) != lhs)
298 continue;
300 if (warning_at (gimple_location (use_stmt),
301 OPT_Wreturn_local_addr,
302 "function may return address "
303 "of local variable"))
304 inform (DECL_SOURCE_LOCATION(valbase),
305 "declared here");
307 if (gimple_bb (use_stmt) == bb)
309 duplicate = isolate_path (bb, duplicate, e,
310 use_stmt, lhs, true);
312 /* When we remove an incoming edge, we need to
313 reprocess the Ith element. */
314 next_i = i;
315 cfg_altered = true;
321 if (!integer_zerop (op))
322 continue;
324 /* We've got a NULL PHI argument. Now see if the
325 PHI's result is dereferenced within BB. */
326 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
328 /* We only care about uses in BB. Catching cases in
329 in other blocks would require more complex path
330 isolation code. */
331 if (gimple_bb (use_stmt) != bb)
332 continue;
334 if (infer_nonnull_range (use_stmt, lhs,
335 flag_isolate_erroneous_paths_dereference,
336 flag_isolate_erroneous_paths_attribute))
339 duplicate = isolate_path (bb, duplicate, e,
340 use_stmt, lhs, false);
342 /* When we remove an incoming edge, we need to
343 reprocess the Ith element. */
344 next_i = i;
345 cfg_altered = true;
353 /* Look for statements which exhibit erroneous behaviour. For example
354 a NULL pointer dereference.
356 When found, optimize the block containing the erroneous behaviour. */
357 static void
358 find_explicit_erroneous_behaviour (void)
360 basic_block bb;
362 FOR_EACH_BB_FN (bb, cfun)
364 gimple_stmt_iterator si;
366 /* Out of an abundance of caution, do not isolate paths to a
367 block where the block has any abnormal outgoing edges.
369 We might be able to relax this in the future. We have to detect
370 when we have to split the block with the NULL dereference and
371 the trap we insert. We have to preserve abnormal edges out
372 of the isolated block which in turn means updating PHIs at
373 the targets of those abnormal outgoing edges. */
374 if (has_abnormal_or_eh_outgoing_edge_p (bb))
375 continue;
377 /* Now look at the statements in the block and see if any of
378 them explicitly dereference a NULL pointer. This happens
379 because of jump threading and constant propagation. */
380 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
382 gimple stmt = gsi_stmt (si);
384 /* By passing null_pointer_node, we can use infer_nonnull_range
385 to detect explicit NULL pointer dereferences and other uses
386 where a non-NULL value is required. */
387 if (infer_nonnull_range (stmt, null_pointer_node,
388 flag_isolate_erroneous_paths_dereference,
389 flag_isolate_erroneous_paths_attribute))
391 insert_trap_and_remove_trailing_statements (&si,
392 null_pointer_node);
394 /* And finally, remove all outgoing edges from BB. */
395 edge e;
396 for (edge_iterator ei = ei_start (bb->succs);
397 (e = ei_safe_edge (ei)); )
398 remove_edge (e);
400 /* Ignore any more operands on this statement and
401 continue the statement iterator (which should
402 terminate its loop immediately. */
403 cfg_altered = true;
404 break;
407 /* Detect returning the address of a local variable. This only
408 becomes undefined behavior if the result is used, so we do not
409 insert a trap and only return NULL instead. */
410 if (greturn *return_stmt = dyn_cast <greturn *> (stmt))
412 tree val = gimple_return_retval (return_stmt);
413 if (val && TREE_CODE (val) == ADDR_EXPR)
415 tree valbase = get_base_address (TREE_OPERAND (val, 0));
416 if ((TREE_CODE (valbase) == VAR_DECL
417 && !is_global_var (valbase))
418 || TREE_CODE (valbase) == PARM_DECL)
420 /* We only need it for this particular case. */
421 calculate_dominance_info (CDI_POST_DOMINATORS);
422 const char* msg;
423 bool always_executed = dominated_by_p
424 (CDI_POST_DOMINATORS,
425 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)), bb);
426 if (always_executed)
427 msg = N_("function returns address of local variable");
428 else
429 msg = N_("function may return address of "
430 "local variable");
432 if (warning_at (gimple_location (stmt),
433 OPT_Wreturn_local_addr, msg))
434 inform (DECL_SOURCE_LOCATION(valbase), "declared here");
435 tree zero = build_zero_cst (TREE_TYPE (val));
436 gimple_return_set_retval (return_stmt, zero);
437 update_stmt (stmt);
445 /* Search the function for statements which, if executed, would cause
446 the program to fault such as a dereference of a NULL pointer.
448 Such a program can't be valid if such a statement was to execute
449 according to ISO standards.
451 We detect explicit NULL pointer dereferences as well as those implied
452 by a PHI argument having a NULL value which unconditionally flows into
453 a dereference in the same block as the PHI.
455 In the former case we replace the offending statement with an
456 unconditional trap and eliminate the outgoing edges from the statement's
457 basic block. This may expose secondary optimization opportunities.
459 In the latter case, we isolate the path(s) with the NULL PHI
460 feeding the dereference. We can then replace the offending statement
461 and eliminate the outgoing edges in the duplicate. Again, this may
462 expose secondary optimization opportunities.
464 A warning for both cases may be advisable as well.
466 Other statically detectable violations of the ISO standard could be
467 handled in a similar way, such as out-of-bounds array indexing. */
469 static unsigned int
470 gimple_ssa_isolate_erroneous_paths (void)
472 initialize_original_copy_tables ();
474 /* Search all the blocks for edges which, if traversed, will
475 result in undefined behaviour. */
476 cfg_altered = false;
478 /* First handle cases where traversal of a particular edge
479 triggers undefined behaviour. These cases require creating
480 duplicate blocks and thus new SSA_NAMEs.
482 We want that process complete prior to the phase where we start
483 removing edges from the CFG. Edge removal may ultimately result in
484 removal of PHI nodes and thus releasing SSA_NAMEs back to the
485 name manager.
487 If the two processes run in parallel we could release an SSA_NAME
488 back to the manager but we could still have dangling references
489 to the released SSA_NAME in unreachable blocks.
490 that any released names not have dangling references in the IL. */
491 find_implicit_erroneous_behaviour ();
492 find_explicit_erroneous_behaviour ();
494 free_original_copy_tables ();
496 /* We scramble the CFG and loop structures a bit, clean up
497 appropriately. We really should incrementally update the
498 loop structures, in theory it shouldn't be that hard. */
499 free_dominance_info (CDI_POST_DOMINATORS);
500 if (cfg_altered)
502 free_dominance_info (CDI_DOMINATORS);
503 loops_state_set (LOOPS_NEED_FIXUP);
504 return TODO_cleanup_cfg | TODO_update_ssa;
506 return 0;
509 namespace {
510 const pass_data pass_data_isolate_erroneous_paths =
512 GIMPLE_PASS, /* type */
513 "isolate-paths", /* name */
514 OPTGROUP_NONE, /* optinfo_flags */
515 TV_ISOLATE_ERRONEOUS_PATHS, /* tv_id */
516 ( PROP_cfg | PROP_ssa ), /* properties_required */
517 0, /* properties_provided */
518 0, /* properties_destroyed */
519 0, /* todo_flags_start */
520 0, /* todo_flags_finish */
523 class pass_isolate_erroneous_paths : public gimple_opt_pass
525 public:
526 pass_isolate_erroneous_paths (gcc::context *ctxt)
527 : gimple_opt_pass (pass_data_isolate_erroneous_paths, ctxt)
530 /* opt_pass methods: */
531 opt_pass * clone () { return new pass_isolate_erroneous_paths (m_ctxt); }
532 virtual bool gate (function *)
534 /* If we do not have a suitable builtin function for the trap statement,
535 then do not perform the optimization. */
536 return (flag_isolate_erroneous_paths_dereference != 0
537 || flag_isolate_erroneous_paths_attribute != 0);
540 virtual unsigned int execute (function *)
542 return gimple_ssa_isolate_erroneous_paths ();
545 }; // class pass_isolate_erroneous_paths
548 gimple_opt_pass *
549 make_pass_isolate_erroneous_paths (gcc::context *ctxt)
551 return new pass_isolate_erroneous_paths (ctxt);