gcc/cp/ChangeLog:
[official-gcc.git] / gcc / sanopt.c
blobb7740741d43a68d03ffa4f36f886c53c669f7305
1 /* Optimize and expand sanitizer functions.
2 Copyright (C) 2014-2017 Free Software Foundation, Inc.
3 Contributed by Marek Polacek <polacek@redhat.com>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "ssa.h"
28 #include "tree-pass.h"
29 #include "tree-ssa-operands.h"
30 #include "gimple-pretty-print.h"
31 #include "fold-const.h"
32 #include "gimple-iterator.h"
33 #include "asan.h"
34 #include "ubsan.h"
35 #include "params.h"
36 #include "tree-hash-traits.h"
37 #include "gimple-ssa.h"
38 #include "tree-phinodes.h"
39 #include "ssa-iterators.h"
40 #include "gimplify.h"
41 #include "gimple-iterator.h"
42 #include "gimple-walk.h"
43 #include "cfghooks.h"
44 #include "tree-dfa.h"
45 #include "tree-ssa.h"
47 /* This is used to carry information about basic blocks. It is
48 attached to the AUX field of the standard CFG block. */
50 struct sanopt_info
52 /* True if this BB might call (directly or indirectly) free/munmap
53 or similar operation. */
54 bool has_freeing_call_p;
56 /* True if HAS_FREEING_CALL_P flag has been computed. */
57 bool has_freeing_call_computed_p;
59 /* True if there is a block with HAS_FREEING_CALL_P flag set
60 on any path between an immediate dominator of BB, denoted
61 imm(BB), and BB. */
62 bool imm_dom_path_with_freeing_call_p;
64 /* True if IMM_DOM_PATH_WITH_FREEING_CALL_P has been computed. */
65 bool imm_dom_path_with_freeing_call_computed_p;
67 /* Number of possibly freeing calls encountered in this bb
68 (so far). */
69 uint64_t freeing_call_events;
71 /* True if BB is currently being visited during computation
72 of IMM_DOM_PATH_WITH_FREEING_CALL_P flag. */
73 bool being_visited_p;
75 /* True if this BB has been visited in the dominator walk. */
76 bool visited_p;
79 /* If T has a single definition of form T = T2, return T2. */
81 static tree
82 maybe_get_single_definition (tree t)
84 if (TREE_CODE (t) == SSA_NAME)
86 gimple *g = SSA_NAME_DEF_STMT (t);
87 if (gimple_assign_single_p (g))
88 return gimple_assign_rhs1 (g);
90 return NULL_TREE;
93 /* Tree triplet for vptr_check_map. */
94 struct sanopt_tree_triplet
96 tree t1, t2, t3;
99 /* Traits class for tree triplet hash maps below. */
101 struct sanopt_tree_triplet_hash : typed_noop_remove <sanopt_tree_triplet>
103 typedef sanopt_tree_triplet value_type;
104 typedef sanopt_tree_triplet compare_type;
106 static inline hashval_t
107 hash (const sanopt_tree_triplet &ref)
109 inchash::hash hstate (0);
110 inchash::add_expr (ref.t1, hstate);
111 inchash::add_expr (ref.t2, hstate);
112 inchash::add_expr (ref.t3, hstate);
113 return hstate.end ();
116 static inline bool
117 equal (const sanopt_tree_triplet &ref1, const sanopt_tree_triplet &ref2)
119 return operand_equal_p (ref1.t1, ref2.t1, 0)
120 && operand_equal_p (ref1.t2, ref2.t2, 0)
121 && operand_equal_p (ref1.t3, ref2.t3, 0);
124 static inline void
125 mark_deleted (sanopt_tree_triplet &ref)
127 ref.t1 = reinterpret_cast<tree> (1);
130 static inline void
131 mark_empty (sanopt_tree_triplet &ref)
133 ref.t1 = NULL;
136 static inline bool
137 is_deleted (const sanopt_tree_triplet &ref)
139 return ref.t1 == (void *) 1;
142 static inline bool
143 is_empty (const sanopt_tree_triplet &ref)
145 return ref.t1 == NULL;
149 /* This is used to carry various hash maps and variables used
150 in sanopt_optimize_walker. */
152 struct sanopt_ctx
154 /* This map maps a pointer (the first argument of UBSAN_NULL) to
155 a vector of UBSAN_NULL call statements that check this pointer. */
156 hash_map<tree, auto_vec<gimple *> > null_check_map;
158 /* This map maps a pointer (the second argument of ASAN_CHECK) to
159 a vector of ASAN_CHECK call statements that check the access. */
160 hash_map<tree_operand_hash, auto_vec<gimple *> > asan_check_map;
162 /* This map maps a tree triplet (the first, second and fourth argument
163 of UBSAN_VPTR) to a vector of UBSAN_VPTR call statements that check
164 that virtual table pointer. */
165 hash_map<sanopt_tree_triplet_hash, auto_vec<gimple *> > vptr_check_map;
167 /* Number of IFN_ASAN_CHECK statements. */
168 int asan_num_accesses;
170 /* True when the current functions constains an ASAN_MARK. */
171 bool contains_asan_mark;
174 /* Return true if there might be any call to free/munmap operation
175 on any path in between DOM (which should be imm(BB)) and BB. */
177 static bool
178 imm_dom_path_with_freeing_call (basic_block bb, basic_block dom)
180 sanopt_info *info = (sanopt_info *) bb->aux;
181 edge e;
182 edge_iterator ei;
184 if (info->imm_dom_path_with_freeing_call_computed_p)
185 return info->imm_dom_path_with_freeing_call_p;
187 info->being_visited_p = true;
189 FOR_EACH_EDGE (e, ei, bb->preds)
191 sanopt_info *pred_info = (sanopt_info *) e->src->aux;
193 if (e->src == dom)
194 continue;
196 if ((pred_info->imm_dom_path_with_freeing_call_computed_p
197 && pred_info->imm_dom_path_with_freeing_call_p)
198 || (pred_info->has_freeing_call_computed_p
199 && pred_info->has_freeing_call_p))
201 info->imm_dom_path_with_freeing_call_computed_p = true;
202 info->imm_dom_path_with_freeing_call_p = true;
203 info->being_visited_p = false;
204 return true;
208 FOR_EACH_EDGE (e, ei, bb->preds)
210 sanopt_info *pred_info = (sanopt_info *) e->src->aux;
212 if (e->src == dom)
213 continue;
215 if (pred_info->has_freeing_call_computed_p)
216 continue;
218 gimple_stmt_iterator gsi;
219 for (gsi = gsi_start_bb (e->src); !gsi_end_p (gsi); gsi_next (&gsi))
221 gimple *stmt = gsi_stmt (gsi);
222 gasm *asm_stmt;
224 if ((is_gimple_call (stmt) && !nonfreeing_call_p (stmt))
225 || ((asm_stmt = dyn_cast <gasm *> (stmt))
226 && (gimple_asm_clobbers_memory_p (asm_stmt)
227 || gimple_asm_volatile_p (asm_stmt))))
229 pred_info->has_freeing_call_p = true;
230 break;
234 pred_info->has_freeing_call_computed_p = true;
235 if (pred_info->has_freeing_call_p)
237 info->imm_dom_path_with_freeing_call_computed_p = true;
238 info->imm_dom_path_with_freeing_call_p = true;
239 info->being_visited_p = false;
240 return true;
244 FOR_EACH_EDGE (e, ei, bb->preds)
246 if (e->src == dom)
247 continue;
249 basic_block src;
250 for (src = e->src; src != dom; )
252 sanopt_info *pred_info = (sanopt_info *) src->aux;
253 if (pred_info->being_visited_p)
254 break;
255 basic_block imm = get_immediate_dominator (CDI_DOMINATORS, src);
256 if (imm_dom_path_with_freeing_call (src, imm))
258 info->imm_dom_path_with_freeing_call_computed_p = true;
259 info->imm_dom_path_with_freeing_call_p = true;
260 info->being_visited_p = false;
261 return true;
263 src = imm;
267 info->imm_dom_path_with_freeing_call_computed_p = true;
268 info->imm_dom_path_with_freeing_call_p = false;
269 info->being_visited_p = false;
270 return false;
273 /* Get the first dominating check from the list of stored checks.
274 Non-dominating checks are silently dropped. */
276 static gimple *
277 maybe_get_dominating_check (auto_vec<gimple *> &v)
279 for (; !v.is_empty (); v.pop ())
281 gimple *g = v.last ();
282 sanopt_info *si = (sanopt_info *) gimple_bb (g)->aux;
283 if (!si->visited_p)
284 /* At this point we shouldn't have any statements
285 that aren't dominating the current BB. */
286 return g;
288 return NULL;
291 /* Optimize away redundant UBSAN_NULL calls. */
293 static bool
294 maybe_optimize_ubsan_null_ifn (struct sanopt_ctx *ctx, gimple *stmt)
296 gcc_assert (gimple_call_num_args (stmt) == 3);
297 tree ptr = gimple_call_arg (stmt, 0);
298 tree cur_align = gimple_call_arg (stmt, 2);
299 gcc_assert (TREE_CODE (cur_align) == INTEGER_CST);
300 bool remove = false;
302 auto_vec<gimple *> &v = ctx->null_check_map.get_or_insert (ptr);
303 gimple *g = maybe_get_dominating_check (v);
304 if (!g)
306 /* For this PTR we don't have any UBSAN_NULL stmts recorded, so there's
307 nothing to optimize yet. */
308 v.safe_push (stmt);
309 return false;
312 /* We already have recorded a UBSAN_NULL check for this pointer. Perhaps we
313 can drop this one. But only if this check doesn't specify stricter
314 alignment. */
316 tree align = gimple_call_arg (g, 2);
317 int kind = tree_to_shwi (gimple_call_arg (g, 1));
318 /* If this is a NULL pointer check where we had segv anyway, we can
319 remove it. */
320 if (integer_zerop (align)
321 && (kind == UBSAN_LOAD_OF
322 || kind == UBSAN_STORE_OF
323 || kind == UBSAN_MEMBER_ACCESS))
324 remove = true;
325 /* Otherwise remove the check in non-recovering mode, or if the
326 stmts have same location. */
327 else if (integer_zerop (align))
328 remove = (flag_sanitize_recover & SANITIZE_NULL) == 0
329 || flag_sanitize_undefined_trap_on_error
330 || gimple_location (g) == gimple_location (stmt);
331 else if (tree_int_cst_le (cur_align, align))
332 remove = (flag_sanitize_recover & SANITIZE_ALIGNMENT) == 0
333 || flag_sanitize_undefined_trap_on_error
334 || gimple_location (g) == gimple_location (stmt);
336 if (!remove && gimple_bb (g) == gimple_bb (stmt)
337 && tree_int_cst_compare (cur_align, align) == 0)
338 v.pop ();
340 if (!remove)
341 v.safe_push (stmt);
342 return remove;
345 /* Optimize away redundant UBSAN_VPTR calls. The second argument
346 is the value loaded from the virtual table, so rely on FRE to find out
347 when we can actually optimize. */
349 static bool
350 maybe_optimize_ubsan_vptr_ifn (struct sanopt_ctx *ctx, gimple *stmt)
352 gcc_assert (gimple_call_num_args (stmt) == 5);
353 sanopt_tree_triplet triplet;
354 triplet.t1 = gimple_call_arg (stmt, 0);
355 triplet.t2 = gimple_call_arg (stmt, 1);
356 triplet.t3 = gimple_call_arg (stmt, 3);
358 auto_vec<gimple *> &v = ctx->vptr_check_map.get_or_insert (triplet);
359 gimple *g = maybe_get_dominating_check (v);
360 if (!g)
362 /* For this PTR we don't have any UBSAN_VPTR stmts recorded, so there's
363 nothing to optimize yet. */
364 v.safe_push (stmt);
365 return false;
368 return true;
371 /* Returns TRUE if ASan check of length LEN in block BB can be removed
372 if preceded by checks in V. */
374 static bool
375 can_remove_asan_check (auto_vec<gimple *> &v, tree len, basic_block bb)
377 unsigned int i;
378 gimple *g;
379 gimple *to_pop = NULL;
380 bool remove = false;
381 basic_block last_bb = bb;
382 bool cleanup = false;
384 FOR_EACH_VEC_ELT_REVERSE (v, i, g)
386 basic_block gbb = gimple_bb (g);
387 sanopt_info *si = (sanopt_info *) gbb->aux;
388 if (gimple_uid (g) < si->freeing_call_events)
390 /* If there is a potentially freeing call after g in gbb, we should
391 remove it from the vector, can't use in optimization. */
392 cleanup = true;
393 continue;
396 tree glen = gimple_call_arg (g, 2);
397 gcc_assert (TREE_CODE (glen) == INTEGER_CST);
399 /* If we've checked only smaller length than we want to check now,
400 we can't remove the current stmt. If g is in the same basic block,
401 we want to remove it though, as the current stmt is better. */
402 if (tree_int_cst_lt (glen, len))
404 if (gbb == bb)
406 to_pop = g;
407 cleanup = true;
409 continue;
412 while (last_bb != gbb)
414 /* Paths from last_bb to bb have been checked before.
415 gbb is necessarily a dominator of last_bb, but not necessarily
416 immediate dominator. */
417 if (((sanopt_info *) last_bb->aux)->freeing_call_events)
418 break;
420 basic_block imm = get_immediate_dominator (CDI_DOMINATORS, last_bb);
421 gcc_assert (imm);
422 if (imm_dom_path_with_freeing_call (last_bb, imm))
423 break;
425 last_bb = imm;
427 if (last_bb == gbb)
428 remove = true;
429 break;
432 if (cleanup)
434 unsigned int j = 0, l = v.length ();
435 for (i = 0; i < l; i++)
436 if (v[i] != to_pop
437 && (gimple_uid (v[i])
438 == ((sanopt_info *)
439 gimple_bb (v[i])->aux)->freeing_call_events))
441 if (i != j)
442 v[j] = v[i];
443 j++;
445 v.truncate (j);
448 return remove;
451 /* Optimize away redundant ASAN_CHECK calls. */
453 static bool
454 maybe_optimize_asan_check_ifn (struct sanopt_ctx *ctx, gimple *stmt)
456 gcc_assert (gimple_call_num_args (stmt) == 4);
457 tree ptr = gimple_call_arg (stmt, 1);
458 tree len = gimple_call_arg (stmt, 2);
459 basic_block bb = gimple_bb (stmt);
460 sanopt_info *info = (sanopt_info *) bb->aux;
462 if (TREE_CODE (len) != INTEGER_CST)
463 return false;
464 if (integer_zerop (len))
465 return false;
467 gimple_set_uid (stmt, info->freeing_call_events);
469 auto_vec<gimple *> *ptr_checks = &ctx->asan_check_map.get_or_insert (ptr);
471 tree base_addr = maybe_get_single_definition (ptr);
472 auto_vec<gimple *> *base_checks = NULL;
473 if (base_addr)
475 base_checks = &ctx->asan_check_map.get_or_insert (base_addr);
476 /* Original pointer might have been invalidated. */
477 ptr_checks = ctx->asan_check_map.get (ptr);
480 gimple *g = maybe_get_dominating_check (*ptr_checks);
481 gimple *g2 = NULL;
483 if (base_checks)
484 /* Try with base address as well. */
485 g2 = maybe_get_dominating_check (*base_checks);
487 if (g == NULL && g2 == NULL)
489 /* For this PTR we don't have any ASAN_CHECK stmts recorded, so there's
490 nothing to optimize yet. */
491 ptr_checks->safe_push (stmt);
492 if (base_checks)
493 base_checks->safe_push (stmt);
494 return false;
497 bool remove = false;
499 if (ptr_checks)
500 remove = can_remove_asan_check (*ptr_checks, len, bb);
502 if (!remove && base_checks)
503 /* Try with base address as well. */
504 remove = can_remove_asan_check (*base_checks, len, bb);
506 if (!remove)
508 ptr_checks->safe_push (stmt);
509 if (base_checks)
510 base_checks->safe_push (stmt);
513 return remove;
516 /* Try to optimize away redundant UBSAN_NULL and ASAN_CHECK calls.
518 We walk blocks in the CFG via a depth first search of the dominator
519 tree; we push unique UBSAN_NULL or ASAN_CHECK statements into a vector
520 in the NULL_CHECK_MAP or ASAN_CHECK_MAP hash maps as we enter the
521 blocks. When leaving a block, we mark the block as visited; then
522 when checking the statements in the vector, we ignore statements that
523 are coming from already visited blocks, because these cannot dominate
524 anything anymore. CTX is a sanopt context. */
526 static void
527 sanopt_optimize_walker (basic_block bb, struct sanopt_ctx *ctx)
529 basic_block son;
530 gimple_stmt_iterator gsi;
531 sanopt_info *info = (sanopt_info *) bb->aux;
532 bool asan_check_optimize = (flag_sanitize & SANITIZE_ADDRESS) != 0;
534 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
536 gimple *stmt = gsi_stmt (gsi);
537 bool remove = false;
539 if (!is_gimple_call (stmt))
541 /* Handle asm volatile or asm with "memory" clobber
542 the same as potentionally freeing call. */
543 gasm *asm_stmt = dyn_cast <gasm *> (stmt);
544 if (asm_stmt
545 && asan_check_optimize
546 && (gimple_asm_clobbers_memory_p (asm_stmt)
547 || gimple_asm_volatile_p (asm_stmt)))
548 info->freeing_call_events++;
549 gsi_next (&gsi);
550 continue;
553 if (asan_check_optimize && !nonfreeing_call_p (stmt))
554 info->freeing_call_events++;
556 /* If __asan_before_dynamic_init ("module"); is followed by
557 __asan_after_dynamic_init (); without intervening memory loads/stores,
558 there is nothing to guard, so optimize both away. */
559 if (asan_check_optimize
560 && gimple_call_builtin_p (stmt, BUILT_IN_ASAN_BEFORE_DYNAMIC_INIT))
562 use_operand_p use;
563 gimple *use_stmt;
564 if (single_imm_use (gimple_vdef (stmt), &use, &use_stmt))
566 if (is_gimple_call (use_stmt)
567 && gimple_call_builtin_p (use_stmt,
568 BUILT_IN_ASAN_AFTER_DYNAMIC_INIT))
570 unlink_stmt_vdef (use_stmt);
571 gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
572 gsi_remove (&gsi2, true);
573 remove = true;
578 if (gimple_call_internal_p (stmt))
579 switch (gimple_call_internal_fn (stmt))
581 case IFN_UBSAN_NULL:
582 remove = maybe_optimize_ubsan_null_ifn (ctx, stmt);
583 break;
584 case IFN_UBSAN_VPTR:
585 remove = maybe_optimize_ubsan_vptr_ifn (ctx, stmt);
586 break;
587 case IFN_ASAN_CHECK:
588 if (asan_check_optimize)
589 remove = maybe_optimize_asan_check_ifn (ctx, stmt);
590 if (!remove)
591 ctx->asan_num_accesses++;
592 break;
593 case IFN_ASAN_MARK:
594 ctx->contains_asan_mark = true;
595 break;
596 default:
597 break;
600 if (remove)
602 /* Drop this check. */
603 if (dump_file && (dump_flags & TDF_DETAILS))
605 fprintf (dump_file, "Optimizing out\n ");
606 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
607 fprintf (dump_file, "\n");
609 unlink_stmt_vdef (stmt);
610 gsi_remove (&gsi, true);
612 else
613 gsi_next (&gsi);
616 if (asan_check_optimize)
618 info->has_freeing_call_p = info->freeing_call_events != 0;
619 info->has_freeing_call_computed_p = true;
622 for (son = first_dom_son (CDI_DOMINATORS, bb);
623 son;
624 son = next_dom_son (CDI_DOMINATORS, son))
625 sanopt_optimize_walker (son, ctx);
627 /* We're leaving this BB, so mark it to that effect. */
628 info->visited_p = true;
631 /* Try to remove redundant sanitizer checks in function FUN. */
633 static int
634 sanopt_optimize (function *fun, bool *contains_asan_mark)
636 struct sanopt_ctx ctx;
637 ctx.asan_num_accesses = 0;
638 ctx.contains_asan_mark = false;
640 /* Set up block info for each basic block. */
641 alloc_aux_for_blocks (sizeof (sanopt_info));
643 /* We're going to do a dominator walk, so ensure that we have
644 dominance information. */
645 calculate_dominance_info (CDI_DOMINATORS);
647 /* Recursively walk the dominator tree optimizing away
648 redundant checks. */
649 sanopt_optimize_walker (ENTRY_BLOCK_PTR_FOR_FN (fun), &ctx);
651 free_aux_for_blocks ();
653 *contains_asan_mark = ctx.contains_asan_mark;
654 return ctx.asan_num_accesses;
657 /* Perform optimization of sanitize functions. */
659 namespace {
661 const pass_data pass_data_sanopt =
663 GIMPLE_PASS, /* type */
664 "sanopt", /* name */
665 OPTGROUP_NONE, /* optinfo_flags */
666 TV_NONE, /* tv_id */
667 ( PROP_ssa | PROP_cfg | PROP_gimple_leh ), /* properties_required */
668 0, /* properties_provided */
669 0, /* properties_destroyed */
670 0, /* todo_flags_start */
671 TODO_update_ssa, /* todo_flags_finish */
674 class pass_sanopt : public gimple_opt_pass
676 public:
677 pass_sanopt (gcc::context *ctxt)
678 : gimple_opt_pass (pass_data_sanopt, ctxt)
681 /* opt_pass methods: */
682 virtual bool gate (function *) { return flag_sanitize; }
683 virtual unsigned int execute (function *);
685 }; // class pass_sanopt
687 /* Sanitize all ASAN_MARK unpoison calls that are not reachable by a BB
688 that contains an ASAN_MARK poison. All these ASAN_MARK unpoison call
689 can be removed as all variables are unpoisoned in a function prologue. */
691 static void
692 sanitize_asan_mark_unpoison (void)
694 /* 1) Find all BBs that contain an ASAN_MARK poison call. */
695 auto_sbitmap with_poison (last_basic_block_for_fn (cfun) + 1);
696 bitmap_clear (with_poison);
697 basic_block bb;
699 FOR_EACH_BB_FN (bb, cfun)
701 if (bitmap_bit_p (with_poison, bb->index))
702 continue;
704 gimple_stmt_iterator gsi;
705 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
707 gimple *stmt = gsi_stmt (gsi);
708 if (asan_mark_p (stmt, ASAN_MARK_POISON))
710 bitmap_set_bit (with_poison, bb->index);
711 break;
716 auto_sbitmap poisoned (last_basic_block_for_fn (cfun) + 1);
717 bitmap_clear (poisoned);
718 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
719 bitmap_copy (worklist, with_poison);
721 /* 2) Propagate the information to all reachable blocks. */
722 while (!bitmap_empty_p (worklist))
724 unsigned i = bitmap_first_set_bit (worklist);
725 bitmap_clear_bit (worklist, i);
726 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
727 gcc_assert (bb);
729 edge e;
730 edge_iterator ei;
731 FOR_EACH_EDGE (e, ei, bb->succs)
732 if (!bitmap_bit_p (poisoned, e->dest->index))
734 bitmap_set_bit (poisoned, e->dest->index);
735 bitmap_set_bit (worklist, e->dest->index);
739 /* 3) Iterate all BBs not included in POISONED BBs and remove unpoison
740 ASAN_MARK preceding an ASAN_MARK poison (which can still happen). */
741 FOR_EACH_BB_FN (bb, cfun)
743 if (bitmap_bit_p (poisoned, bb->index))
744 continue;
746 gimple_stmt_iterator gsi;
747 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
749 gimple *stmt = gsi_stmt (gsi);
750 if (gimple_call_internal_p (stmt, IFN_ASAN_MARK))
752 if (asan_mark_p (stmt, ASAN_MARK_POISON))
753 break;
754 else
756 if (dump_file)
757 fprintf (dump_file, "Removing ASAN_MARK unpoison\n");
758 unlink_stmt_vdef (stmt);
759 release_defs (stmt);
760 gsi_remove (&gsi, true);
761 continue;
765 gsi_next (&gsi);
770 /* Return true when STMT is either ASAN_CHECK call or a call of a function
771 that can contain an ASAN_CHECK. */
773 static bool
774 maybe_contains_asan_check (gimple *stmt)
776 if (is_gimple_call (stmt))
778 if (gimple_call_internal_p (stmt, IFN_ASAN_MARK))
779 return false;
780 else
781 return !(gimple_call_flags (stmt) & ECF_CONST);
783 else if (is_a<gasm *> (stmt))
784 return true;
786 return false;
789 /* Sanitize all ASAN_MARK poison calls that are not followed by an ASAN_CHECK
790 call. These calls can be removed. */
792 static void
793 sanitize_asan_mark_poison (void)
795 /* 1) Find all BBs that possibly contain an ASAN_CHECK. */
796 auto_sbitmap with_check (last_basic_block_for_fn (cfun) + 1);
797 bitmap_clear (with_check);
798 basic_block bb;
800 FOR_EACH_BB_FN (bb, cfun)
802 gimple_stmt_iterator gsi;
803 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
805 gimple *stmt = gsi_stmt (gsi);
806 if (maybe_contains_asan_check (stmt))
808 bitmap_set_bit (with_check, bb->index);
809 break;
814 auto_sbitmap can_reach_check (last_basic_block_for_fn (cfun) + 1);
815 bitmap_clear (can_reach_check);
816 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
817 bitmap_copy (worklist, with_check);
819 /* 2) Propagate the information to all definitions blocks. */
820 while (!bitmap_empty_p (worklist))
822 unsigned i = bitmap_first_set_bit (worklist);
823 bitmap_clear_bit (worklist, i);
824 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
825 gcc_assert (bb);
827 edge e;
828 edge_iterator ei;
829 FOR_EACH_EDGE (e, ei, bb->preds)
830 if (!bitmap_bit_p (can_reach_check, e->src->index))
832 bitmap_set_bit (can_reach_check, e->src->index);
833 bitmap_set_bit (worklist, e->src->index);
837 /* 3) Iterate all BBs not included in CAN_REACH_CHECK BBs and remove poison
838 ASAN_MARK not followed by a call to function having an ASAN_CHECK. */
839 FOR_EACH_BB_FN (bb, cfun)
841 if (bitmap_bit_p (can_reach_check, bb->index))
842 continue;
844 gimple_stmt_iterator gsi;
845 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi);)
847 gimple *stmt = gsi_stmt (gsi);
848 if (maybe_contains_asan_check (stmt))
849 break;
850 else if (asan_mark_p (stmt, ASAN_MARK_POISON))
852 if (dump_file)
853 fprintf (dump_file, "Removing ASAN_MARK poison\n");
854 unlink_stmt_vdef (stmt);
855 release_defs (stmt);
856 gimple_stmt_iterator gsi2 = gsi;
857 gsi_prev (&gsi);
858 gsi_remove (&gsi2, true);
859 continue;
862 gsi_prev (&gsi);
867 /* Rewrite all usages of tree OP which is a PARM_DECL with a VAR_DECL
868 that is it's DECL_VALUE_EXPR. */
870 static tree
871 rewrite_usage_of_param (tree *op, int *walk_subtrees, void *)
873 if (TREE_CODE (*op) == PARM_DECL && DECL_HAS_VALUE_EXPR_P (*op))
875 *op = DECL_VALUE_EXPR (*op);
876 *walk_subtrees = 0;
879 return NULL;
882 /* For a given function FUN, rewrite all addressable parameters so that
883 a new automatic variable is introduced. Right after function entry
884 a parameter is assigned to the variable. */
886 static void
887 sanitize_rewrite_addressable_params (function *fun)
889 gimple *g;
890 gimple_seq stmts = NULL;
891 bool has_any_addressable_param = false;
892 auto_vec<tree> clear_value_expr_list;
894 for (tree arg = DECL_ARGUMENTS (current_function_decl);
895 arg; arg = DECL_CHAIN (arg))
897 if (TREE_ADDRESSABLE (arg) && !TREE_ADDRESSABLE (TREE_TYPE (arg)))
899 TREE_ADDRESSABLE (arg) = 0;
900 /* The parameter is no longer addressable. */
901 tree type = TREE_TYPE (arg);
902 has_any_addressable_param = true;
904 /* Create a new automatic variable. */
905 tree var = build_decl (DECL_SOURCE_LOCATION (arg),
906 VAR_DECL, DECL_NAME (arg), type);
907 TREE_ADDRESSABLE (var) = 1;
908 DECL_IGNORED_P (var) = 1;
910 gimple_add_tmp_var (var);
912 if (dump_file)
913 fprintf (dump_file,
914 "Rewriting parameter whose address is taken: %s\n",
915 IDENTIFIER_POINTER (DECL_NAME (arg)));
917 gcc_assert (!DECL_HAS_VALUE_EXPR_P (arg));
918 DECL_HAS_VALUE_EXPR_P (arg) = 1;
919 SET_DECL_VALUE_EXPR (arg, var);
921 SET_DECL_PT_UID (var, DECL_PT_UID (arg));
923 /* Assign value of parameter to newly created variable. */
924 if ((TREE_CODE (type) == COMPLEX_TYPE
925 || TREE_CODE (type) == VECTOR_TYPE))
927 /* We need to create a SSA name that will be used for the
928 assignment. */
929 DECL_GIMPLE_REG_P (arg) = 1;
930 tree tmp = get_or_create_ssa_default_def (cfun, arg);
931 g = gimple_build_assign (var, tmp);
932 gimple_set_location (g, DECL_SOURCE_LOCATION (arg));
933 gimple_seq_add_stmt (&stmts, g);
935 else
937 g = gimple_build_assign (var, arg);
938 gimple_set_location (g, DECL_SOURCE_LOCATION (arg));
939 gimple_seq_add_stmt (&stmts, g);
942 if (target_for_debug_bind (arg))
944 g = gimple_build_debug_bind (arg, var, NULL);
945 gimple_seq_add_stmt (&stmts, g);
946 clear_value_expr_list.safe_push (arg);
951 if (!has_any_addressable_param)
952 return;
954 /* Replace all usages of PARM_DECLs with the newly
955 created variable VAR. */
956 basic_block bb;
957 FOR_EACH_BB_FN (bb, fun)
959 gimple_stmt_iterator gsi;
960 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
962 gimple *stmt = gsi_stmt (gsi);
963 gimple_stmt_iterator it = gsi_for_stmt (stmt);
964 walk_gimple_stmt (&it, NULL, rewrite_usage_of_param, NULL);
966 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
968 gphi *phi = dyn_cast<gphi *> (gsi_stmt (gsi));
969 for (unsigned i = 0; i < gimple_phi_num_args (phi); ++i)
971 hash_set<tree> visited_nodes;
972 walk_tree (gimple_phi_arg_def_ptr (phi, i),
973 rewrite_usage_of_param, NULL, &visited_nodes);
978 /* Unset value expr for parameters for which we created debug bind
979 expressions. */
980 unsigned i;
981 tree arg;
982 FOR_EACH_VEC_ELT (clear_value_expr_list, i, arg)
984 DECL_HAS_VALUE_EXPR_P (arg) = 0;
985 SET_DECL_VALUE_EXPR (arg, NULL_TREE);
988 /* Insert default assignments at the beginning of a function. */
989 basic_block entry_bb = ENTRY_BLOCK_PTR_FOR_FN (fun);
990 entry_bb = split_edge (single_succ_edge (entry_bb));
992 gimple_stmt_iterator gsi = gsi_start_bb (entry_bb);
993 gsi_insert_seq_before (&gsi, stmts, GSI_NEW_STMT);
996 unsigned int
997 pass_sanopt::execute (function *fun)
999 basic_block bb;
1000 int asan_num_accesses = 0;
1001 bool contains_asan_mark = false;
1003 /* Try to remove redundant checks. */
1004 if (optimize
1005 && (flag_sanitize
1006 & (SANITIZE_NULL | SANITIZE_ALIGNMENT
1007 | SANITIZE_ADDRESS | SANITIZE_VPTR)))
1008 asan_num_accesses = sanopt_optimize (fun, &contains_asan_mark);
1009 else if (flag_sanitize & SANITIZE_ADDRESS)
1011 gimple_stmt_iterator gsi;
1012 FOR_EACH_BB_FN (bb, fun)
1013 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1015 gimple *stmt = gsi_stmt (gsi);
1016 if (gimple_call_internal_p (stmt, IFN_ASAN_CHECK))
1017 ++asan_num_accesses;
1018 else if (gimple_call_internal_p (stmt, IFN_ASAN_MARK))
1019 contains_asan_mark = true;
1023 if (contains_asan_mark)
1025 sanitize_asan_mark_unpoison ();
1026 sanitize_asan_mark_poison ();
1029 if (asan_sanitize_stack_p ())
1030 sanitize_rewrite_addressable_params (fun);
1032 bool use_calls = ASAN_INSTRUMENTATION_WITH_CALL_THRESHOLD < INT_MAX
1033 && asan_num_accesses >= ASAN_INSTRUMENTATION_WITH_CALL_THRESHOLD;
1035 hash_map<tree, tree> shadow_vars_mapping;
1036 bool need_commit_edge_insert = false;
1037 FOR_EACH_BB_FN (bb, fun)
1039 gimple_stmt_iterator gsi;
1040 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
1042 gimple *stmt = gsi_stmt (gsi);
1043 bool no_next = false;
1045 if (!is_gimple_call (stmt))
1047 gsi_next (&gsi);
1048 continue;
1051 if (gimple_call_internal_p (stmt))
1053 enum internal_fn ifn = gimple_call_internal_fn (stmt);
1054 switch (ifn)
1056 case IFN_UBSAN_NULL:
1057 no_next = ubsan_expand_null_ifn (&gsi);
1058 break;
1059 case IFN_UBSAN_BOUNDS:
1060 no_next = ubsan_expand_bounds_ifn (&gsi);
1061 break;
1062 case IFN_UBSAN_OBJECT_SIZE:
1063 no_next = ubsan_expand_objsize_ifn (&gsi);
1064 break;
1065 case IFN_UBSAN_VPTR:
1066 no_next = ubsan_expand_vptr_ifn (&gsi);
1067 break;
1068 case IFN_ASAN_CHECK:
1069 no_next = asan_expand_check_ifn (&gsi, use_calls);
1070 break;
1071 case IFN_ASAN_MARK:
1072 no_next = asan_expand_mark_ifn (&gsi);
1073 break;
1074 case IFN_ASAN_POISON:
1075 no_next = asan_expand_poison_ifn (&gsi,
1076 &need_commit_edge_insert,
1077 shadow_vars_mapping);
1078 break;
1079 default:
1080 break;
1083 else if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
1085 tree callee = gimple_call_fndecl (stmt);
1086 switch (DECL_FUNCTION_CODE (callee))
1088 case BUILT_IN_UNREACHABLE:
1089 if (sanitize_flags_p (SANITIZE_UNREACHABLE))
1090 no_next = ubsan_instrument_unreachable (&gsi);
1091 break;
1092 default:
1093 break;
1097 if (dump_file && (dump_flags & TDF_DETAILS))
1099 fprintf (dump_file, "Expanded\n ");
1100 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1101 fprintf (dump_file, "\n");
1104 if (!no_next)
1105 gsi_next (&gsi);
1109 if (need_commit_edge_insert)
1110 gsi_commit_edge_inserts ();
1112 return 0;
1115 } // anon namespace
1117 gimple_opt_pass *
1118 make_pass_sanopt (gcc::context *ctxt)
1120 return new pass_sanopt (ctxt);