]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/sanopt.c
ztest.c (test_large): Pass unsigned long *, not size_t *, to zlib uncompress function.
[thirdparty/gcc.git] / gcc / sanopt.c
CommitLineData
06cefae9 1/* Optimize and expand sanitizer functions.
cbe34bb5 2 Copyright (C) 2014-2017 Free Software Foundation, Inc.
06cefae9
MP
3 Contributed by Marek Polacek <polacek@redhat.com>
4
5This file is part of GCC.
6
7GCC is free software; you can redistribute it and/or modify it under
8the terms of the GNU General Public License as published by the Free
9Software Foundation; either version 3, or (at your option) any later
10version.
11
12GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or
14FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15for more details.
16
17You should have received a copy of the GNU General Public License
18along with GCC; see the file COPYING3. If not see
19<http://www.gnu.org/licenses/>. */
20
21#include "config.h"
22#include "system.h"
23#include "coretypes.h"
c7131fb2 24#include "backend.h"
06cefae9 25#include "tree.h"
c7131fb2 26#include "gimple.h"
2f75d6eb 27#include "ssa.h"
957060b5 28#include "tree-pass.h"
957060b5
AM
29#include "tree-ssa-operands.h"
30#include "gimple-pretty-print.h"
c7131fb2 31#include "fold-const.h"
06cefae9 32#include "gimple-iterator.h"
314e6352
ML
33#include "stringpool.h"
34#include "attribs.h"
06cefae9 35#include "asan.h"
06cefae9
MP
36#include "ubsan.h"
37#include "params.h"
d6a818c5 38#include "tree-hash-traits.h"
94087e88
JJ
39#include "gimple-ssa.h"
40#include "tree-phinodes.h"
41#include "ssa-iterators.h"
da402967
ML
42#include "gimplify.h"
43#include "gimple-iterator.h"
44#include "gimple-walk.h"
45#include "cfghooks.h"
46#include "tree-dfa.h"
47#include "tree-ssa.h"
06cefae9 48
06cefae9
MP
49/* This is used to carry information about basic blocks. It is
50 attached to the AUX field of the standard CFG block. */
51
52struct sanopt_info
53{
ab9a4330
JJ
54 /* True if this BB might call (directly or indirectly) free/munmap
55 or similar operation. */
56 bool has_freeing_call_p;
57
58 /* True if HAS_FREEING_CALL_P flag has been computed. */
59 bool has_freeing_call_computed_p;
60
61 /* True if there is a block with HAS_FREEING_CALL_P flag set
62 on any path between an immediate dominator of BB, denoted
63 imm(BB), and BB. */
64 bool imm_dom_path_with_freeing_call_p;
65
66 /* True if IMM_DOM_PATH_WITH_FREEING_CALL_P has been computed. */
67 bool imm_dom_path_with_freeing_call_computed_p;
68
69 /* Number of possibly freeing calls encountered in this bb
70 (so far). */
71 uint64_t freeing_call_events;
72
73 /* True if BB is currently being visited during computation
74 of IMM_DOM_PATH_WITH_FREEING_CALL_P flag. */
75 bool being_visited_p;
76
77 /* True if this BB has been visited in the dominator walk. */
06cefae9
MP
78 bool visited_p;
79};
80
e28f2090
YG
81/* If T has a single definition of form T = T2, return T2. */
82
83static tree
84maybe_get_single_definition (tree t)
85{
86 if (TREE_CODE (t) == SSA_NAME)
87 {
355fe088 88 gimple *g = SSA_NAME_DEF_STMT (t);
e28f2090
YG
89 if (gimple_assign_single_p (g))
90 return gimple_assign_rhs1 (g);
91 }
92 return NULL_TREE;
93}
94
35228ac7
JJ
95/* Tree triplet for vptr_check_map. */
96struct sanopt_tree_triplet
97{
98 tree t1, t2, t3;
99};
100
101/* Traits class for tree triplet hash maps below. */
102
9654754b 103struct sanopt_tree_triplet_hash : typed_noop_remove <sanopt_tree_triplet>
35228ac7 104{
9654754b
RS
105 typedef sanopt_tree_triplet value_type;
106 typedef sanopt_tree_triplet compare_type;
107
35228ac7
JJ
108 static inline hashval_t
109 hash (const sanopt_tree_triplet &ref)
110 {
111 inchash::hash hstate (0);
112 inchash::add_expr (ref.t1, hstate);
113 inchash::add_expr (ref.t2, hstate);
114 inchash::add_expr (ref.t3, hstate);
115 return hstate.end ();
116 }
117
118 static inline bool
9654754b 119 equal (const sanopt_tree_triplet &ref1, const sanopt_tree_triplet &ref2)
35228ac7
JJ
120 {
121 return operand_equal_p (ref1.t1, ref2.t1, 0)
122 && operand_equal_p (ref1.t2, ref2.t2, 0)
123 && operand_equal_p (ref1.t3, ref2.t3, 0);
124 }
125
35228ac7 126 static inline void
9654754b 127 mark_deleted (sanopt_tree_triplet &ref)
35228ac7 128 {
9654754b 129 ref.t1 = reinterpret_cast<tree> (1);
35228ac7
JJ
130 }
131
35228ac7 132 static inline void
9654754b 133 mark_empty (sanopt_tree_triplet &ref)
35228ac7 134 {
9654754b 135 ref.t1 = NULL;
35228ac7
JJ
136 }
137
35228ac7 138 static inline bool
9654754b 139 is_deleted (const sanopt_tree_triplet &ref)
35228ac7 140 {
9654754b 141 return ref.t1 == (void *) 1;
35228ac7
JJ
142 }
143
35228ac7 144 static inline bool
9654754b 145 is_empty (const sanopt_tree_triplet &ref)
35228ac7 146 {
9654754b 147 return ref.t1 == NULL;
35228ac7
JJ
148 }
149};
150
06cefae9
MP
151/* This is used to carry various hash maps and variables used
152 in sanopt_optimize_walker. */
153
154struct sanopt_ctx
155{
156 /* This map maps a pointer (the first argument of UBSAN_NULL) to
157 a vector of UBSAN_NULL call statements that check this pointer. */
355fe088 158 hash_map<tree, auto_vec<gimple *> > null_check_map;
06cefae9 159
ab9a4330
JJ
160 /* This map maps a pointer (the second argument of ASAN_CHECK) to
161 a vector of ASAN_CHECK call statements that check the access. */
355fe088 162 hash_map<tree_operand_hash, auto_vec<gimple *> > asan_check_map;
35228ac7
JJ
163
164 /* This map maps a tree triplet (the first, second and fourth argument
165 of UBSAN_VPTR) to a vector of UBSAN_VPTR call statements that check
166 that virtual table pointer. */
355fe088 167 hash_map<sanopt_tree_triplet_hash, auto_vec<gimple *> > vptr_check_map;
ab9a4330 168
06cefae9
MP
169 /* Number of IFN_ASAN_CHECK statements. */
170 int asan_num_accesses;
06cefae9 171
2f75d6eb
ML
172 /* True when the current functions constains an ASAN_MARK. */
173 bool contains_asan_mark;
174};
06cefae9 175
ab9a4330
JJ
176/* Return true if there might be any call to free/munmap operation
177 on any path in between DOM (which should be imm(BB)) and BB. */
178
179static bool
180imm_dom_path_with_freeing_call (basic_block bb, basic_block dom)
181{
182 sanopt_info *info = (sanopt_info *) bb->aux;
183 edge e;
184 edge_iterator ei;
185
186 if (info->imm_dom_path_with_freeing_call_computed_p)
187 return info->imm_dom_path_with_freeing_call_p;
188
189 info->being_visited_p = true;
190
191 FOR_EACH_EDGE (e, ei, bb->preds)
192 {
193 sanopt_info *pred_info = (sanopt_info *) e->src->aux;
194
195 if (e->src == dom)
196 continue;
197
198 if ((pred_info->imm_dom_path_with_freeing_call_computed_p
199 && pred_info->imm_dom_path_with_freeing_call_p)
200 || (pred_info->has_freeing_call_computed_p
201 && pred_info->has_freeing_call_p))
202 {
203 info->imm_dom_path_with_freeing_call_computed_p = true;
204 info->imm_dom_path_with_freeing_call_p = true;
205 info->being_visited_p = false;
206 return true;
207 }
208 }
209
210 FOR_EACH_EDGE (e, ei, bb->preds)
211 {
212 sanopt_info *pred_info = (sanopt_info *) e->src->aux;
213
214 if (e->src == dom)
215 continue;
216
217 if (pred_info->has_freeing_call_computed_p)
218 continue;
219
220 gimple_stmt_iterator gsi;
221 for (gsi = gsi_start_bb (e->src); !gsi_end_p (gsi); gsi_next (&gsi))
222 {
355fe088 223 gimple *stmt = gsi_stmt (gsi);
8e104951 224 gasm *asm_stmt;
ab9a4330 225
8e104951
ML
226 if ((is_gimple_call (stmt) && !nonfreeing_call_p (stmt))
227 || ((asm_stmt = dyn_cast <gasm *> (stmt))
228 && (gimple_asm_clobbers_memory_p (asm_stmt)
229 || gimple_asm_volatile_p (asm_stmt))))
ab9a4330
JJ
230 {
231 pred_info->has_freeing_call_p = true;
232 break;
233 }
234 }
235
236 pred_info->has_freeing_call_computed_p = true;
237 if (pred_info->has_freeing_call_p)
238 {
239 info->imm_dom_path_with_freeing_call_computed_p = true;
240 info->imm_dom_path_with_freeing_call_p = true;
241 info->being_visited_p = false;
242 return true;
243 }
244 }
245
246 FOR_EACH_EDGE (e, ei, bb->preds)
247 {
248 if (e->src == dom)
249 continue;
250
251 basic_block src;
252 for (src = e->src; src != dom; )
253 {
254 sanopt_info *pred_info = (sanopt_info *) src->aux;
255 if (pred_info->being_visited_p)
256 break;
257 basic_block imm = get_immediate_dominator (CDI_DOMINATORS, src);
258 if (imm_dom_path_with_freeing_call (src, imm))
259 {
260 info->imm_dom_path_with_freeing_call_computed_p = true;
261 info->imm_dom_path_with_freeing_call_p = true;
262 info->being_visited_p = false;
263 return true;
264 }
265 src = imm;
266 }
267 }
268
269 info->imm_dom_path_with_freeing_call_computed_p = true;
270 info->imm_dom_path_with_freeing_call_p = false;
271 info->being_visited_p = false;
272 return false;
273}
274
e28f2090
YG
275/* Get the first dominating check from the list of stored checks.
276 Non-dominating checks are silently dropped. */
277
355fe088
TS
278static gimple *
279maybe_get_dominating_check (auto_vec<gimple *> &v)
e28f2090
YG
280{
281 for (; !v.is_empty (); v.pop ())
282 {
355fe088 283 gimple *g = v.last ();
e28f2090
YG
284 sanopt_info *si = (sanopt_info *) gimple_bb (g)->aux;
285 if (!si->visited_p)
286 /* At this point we shouldn't have any statements
287 that aren't dominating the current BB. */
288 return g;
289 }
290 return NULL;
291}
292
ab9a4330
JJ
293/* Optimize away redundant UBSAN_NULL calls. */
294
295static bool
355fe088 296maybe_optimize_ubsan_null_ifn (struct sanopt_ctx *ctx, gimple *stmt)
ab9a4330
JJ
297{
298 gcc_assert (gimple_call_num_args (stmt) == 3);
299 tree ptr = gimple_call_arg (stmt, 0);
300 tree cur_align = gimple_call_arg (stmt, 2);
301 gcc_assert (TREE_CODE (cur_align) == INTEGER_CST);
302 bool remove = false;
303
355fe088
TS
304 auto_vec<gimple *> &v = ctx->null_check_map.get_or_insert (ptr);
305 gimple *g = maybe_get_dominating_check (v);
e28f2090 306 if (!g)
ab9a4330
JJ
307 {
308 /* For this PTR we don't have any UBSAN_NULL stmts recorded, so there's
309 nothing to optimize yet. */
310 v.safe_push (stmt);
311 return false;
312 }
313
314 /* We already have recorded a UBSAN_NULL check for this pointer. Perhaps we
315 can drop this one. But only if this check doesn't specify stricter
316 alignment. */
ab9a4330 317
e28f2090
YG
318 tree align = gimple_call_arg (g, 2);
319 int kind = tree_to_shwi (gimple_call_arg (g, 1));
320 /* If this is a NULL pointer check where we had segv anyway, we can
321 remove it. */
322 if (integer_zerop (align)
323 && (kind == UBSAN_LOAD_OF
324 || kind == UBSAN_STORE_OF
325 || kind == UBSAN_MEMBER_ACCESS))
326 remove = true;
327 /* Otherwise remove the check in non-recovering mode, or if the
328 stmts have same location. */
329 else if (integer_zerop (align))
330 remove = (flag_sanitize_recover & SANITIZE_NULL) == 0
331 || flag_sanitize_undefined_trap_on_error
332 || gimple_location (g) == gimple_location (stmt);
333 else if (tree_int_cst_le (cur_align, align))
334 remove = (flag_sanitize_recover & SANITIZE_ALIGNMENT) == 0
335 || flag_sanitize_undefined_trap_on_error
336 || gimple_location (g) == gimple_location (stmt);
337
338 if (!remove && gimple_bb (g) == gimple_bb (stmt)
339 && tree_int_cst_compare (cur_align, align) == 0)
340 v.pop ();
ab9a4330
JJ
341
342 if (!remove)
343 v.safe_push (stmt);
344 return remove;
345}
346
35228ac7
JJ
347/* Optimize away redundant UBSAN_VPTR calls. The second argument
348 is the value loaded from the virtual table, so rely on FRE to find out
349 when we can actually optimize. */
350
351static bool
355fe088 352maybe_optimize_ubsan_vptr_ifn (struct sanopt_ctx *ctx, gimple *stmt)
35228ac7
JJ
353{
354 gcc_assert (gimple_call_num_args (stmt) == 5);
355 sanopt_tree_triplet triplet;
356 triplet.t1 = gimple_call_arg (stmt, 0);
357 triplet.t2 = gimple_call_arg (stmt, 1);
358 triplet.t3 = gimple_call_arg (stmt, 3);
359
355fe088
TS
360 auto_vec<gimple *> &v = ctx->vptr_check_map.get_or_insert (triplet);
361 gimple *g = maybe_get_dominating_check (v);
35228ac7
JJ
362 if (!g)
363 {
364 /* For this PTR we don't have any UBSAN_VPTR stmts recorded, so there's
365 nothing to optimize yet. */
366 v.safe_push (stmt);
367 return false;
368 }
369
370 return true;
371}
372
e28f2090
YG
373/* Returns TRUE if ASan check of length LEN in block BB can be removed
374 if preceded by checks in V. */
ab9a4330
JJ
375
376static bool
355fe088 377can_remove_asan_check (auto_vec<gimple *> &v, tree len, basic_block bb)
ab9a4330 378{
ab9a4330 379 unsigned int i;
355fe088
TS
380 gimple *g;
381 gimple *to_pop = NULL;
ab9a4330
JJ
382 bool remove = false;
383 basic_block last_bb = bb;
384 bool cleanup = false;
385
386 FOR_EACH_VEC_ELT_REVERSE (v, i, g)
387 {
388 basic_block gbb = gimple_bb (g);
389 sanopt_info *si = (sanopt_info *) gbb->aux;
390 if (gimple_uid (g) < si->freeing_call_events)
391 {
392 /* If there is a potentially freeing call after g in gbb, we should
393 remove it from the vector, can't use in optimization. */
394 cleanup = true;
395 continue;
396 }
397
ab9a4330 398 tree glen = gimple_call_arg (g, 2);
e28f2090
YG
399 gcc_assert (TREE_CODE (glen) == INTEGER_CST);
400
ab9a4330
JJ
401 /* If we've checked only smaller length than we want to check now,
402 we can't remove the current stmt. If g is in the same basic block,
403 we want to remove it though, as the current stmt is better. */
404 if (tree_int_cst_lt (glen, len))
405 {
406 if (gbb == bb)
407 {
408 to_pop = g;
409 cleanup = true;
410 }
411 continue;
412 }
413
414 while (last_bb != gbb)
415 {
416 /* Paths from last_bb to bb have been checked before.
417 gbb is necessarily a dominator of last_bb, but not necessarily
418 immediate dominator. */
419 if (((sanopt_info *) last_bb->aux)->freeing_call_events)
420 break;
421
422 basic_block imm = get_immediate_dominator (CDI_DOMINATORS, last_bb);
423 gcc_assert (imm);
424 if (imm_dom_path_with_freeing_call (last_bb, imm))
425 break;
426
427 last_bb = imm;
428 }
429 if (last_bb == gbb)
430 remove = true;
431 break;
432 }
433
434 if (cleanup)
435 {
436 unsigned int j = 0, l = v.length ();
437 for (i = 0; i < l; i++)
438 if (v[i] != to_pop
439 && (gimple_uid (v[i])
440 == ((sanopt_info *)
441 gimple_bb (v[i])->aux)->freeing_call_events))
442 {
443 if (i != j)
444 v[j] = v[i];
445 j++;
446 }
447 v.truncate (j);
448 }
449
e28f2090
YG
450 return remove;
451}
452
453/* Optimize away redundant ASAN_CHECK calls. */
454
455static bool
355fe088 456maybe_optimize_asan_check_ifn (struct sanopt_ctx *ctx, gimple *stmt)
e28f2090
YG
457{
458 gcc_assert (gimple_call_num_args (stmt) == 4);
459 tree ptr = gimple_call_arg (stmt, 1);
460 tree len = gimple_call_arg (stmt, 2);
461 basic_block bb = gimple_bb (stmt);
462 sanopt_info *info = (sanopt_info *) bb->aux;
463
464 if (TREE_CODE (len) != INTEGER_CST)
465 return false;
466 if (integer_zerop (len))
467 return false;
468
469 gimple_set_uid (stmt, info->freeing_call_events);
470
355fe088 471 auto_vec<gimple *> *ptr_checks = &ctx->asan_check_map.get_or_insert (ptr);
e28f2090
YG
472
473 tree base_addr = maybe_get_single_definition (ptr);
355fe088 474 auto_vec<gimple *> *base_checks = NULL;
e28f2090
YG
475 if (base_addr)
476 {
477 base_checks = &ctx->asan_check_map.get_or_insert (base_addr);
478 /* Original pointer might have been invalidated. */
479 ptr_checks = ctx->asan_check_map.get (ptr);
480 }
481
355fe088
TS
482 gimple *g = maybe_get_dominating_check (*ptr_checks);
483 gimple *g2 = NULL;
e28f2090 484
06dd2ace 485 if (base_checks)
e28f2090 486 /* Try with base address as well. */
06dd2ace 487 g2 = maybe_get_dominating_check (*base_checks);
e28f2090 488
06dd2ace 489 if (g == NULL && g2 == NULL)
e28f2090
YG
490 {
491 /* For this PTR we don't have any ASAN_CHECK stmts recorded, so there's
492 nothing to optimize yet. */
493 ptr_checks->safe_push (stmt);
494 if (base_checks)
495 base_checks->safe_push (stmt);
496 return false;
497 }
498
499 bool remove = false;
500
501 if (ptr_checks)
502 remove = can_remove_asan_check (*ptr_checks, len, bb);
503
504 if (!remove && base_checks)
505 /* Try with base address as well. */
506 remove = can_remove_asan_check (*base_checks, len, bb);
507
ab9a4330 508 if (!remove)
e28f2090
YG
509 {
510 ptr_checks->safe_push (stmt);
511 if (base_checks)
512 base_checks->safe_push (stmt);
513 }
514
ab9a4330
JJ
515 return remove;
516}
517
518/* Try to optimize away redundant UBSAN_NULL and ASAN_CHECK calls.
519
06cefae9 520 We walk blocks in the CFG via a depth first search of the dominator
ab9a4330
JJ
521 tree; we push unique UBSAN_NULL or ASAN_CHECK statements into a vector
522 in the NULL_CHECK_MAP or ASAN_CHECK_MAP hash maps as we enter the
523 blocks. When leaving a block, we mark the block as visited; then
524 when checking the statements in the vector, we ignore statements that
525 are coming from already visited blocks, because these cannot dominate
526 anything anymore. CTX is a sanopt context. */
06cefae9
MP
527
528static void
529sanopt_optimize_walker (basic_block bb, struct sanopt_ctx *ctx)
530{
531 basic_block son;
532 gimple_stmt_iterator gsi;
ab9a4330 533 sanopt_info *info = (sanopt_info *) bb->aux;
e28f2090 534 bool asan_check_optimize = (flag_sanitize & SANITIZE_ADDRESS) != 0;
06cefae9
MP
535
536 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
537 {
355fe088 538 gimple *stmt = gsi_stmt (gsi);
06cefae9
MP
539 bool remove = false;
540
ab9a4330
JJ
541 if (!is_gimple_call (stmt))
542 {
543 /* Handle asm volatile or asm with "memory" clobber
544 the same as potentionally freeing call. */
538dd0b7
DM
545 gasm *asm_stmt = dyn_cast <gasm *> (stmt);
546 if (asm_stmt
ab9a4330 547 && asan_check_optimize
538dd0b7
DM
548 && (gimple_asm_clobbers_memory_p (asm_stmt)
549 || gimple_asm_volatile_p (asm_stmt)))
ab9a4330
JJ
550 info->freeing_call_events++;
551 gsi_next (&gsi);
552 continue;
553 }
554
555 if (asan_check_optimize && !nonfreeing_call_p (stmt))
556 info->freeing_call_events++;
557
94087e88
JJ
558 /* If __asan_before_dynamic_init ("module"); is followed by
559 __asan_after_dynamic_init (); without intervening memory loads/stores,
560 there is nothing to guard, so optimize both away. */
561 if (asan_check_optimize
562 && gimple_call_builtin_p (stmt, BUILT_IN_ASAN_BEFORE_DYNAMIC_INIT))
563 {
564 use_operand_p use;
565 gimple *use_stmt;
566 if (single_imm_use (gimple_vdef (stmt), &use, &use_stmt))
567 {
568 if (is_gimple_call (use_stmt)
569 && gimple_call_builtin_p (use_stmt,
570 BUILT_IN_ASAN_AFTER_DYNAMIC_INIT))
571 {
572 unlink_stmt_vdef (use_stmt);
573 gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
574 gsi_remove (&gsi2, true);
575 remove = true;
576 }
577 }
578 }
579
ab9a4330 580 if (gimple_call_internal_p (stmt))
06cefae9
MP
581 switch (gimple_call_internal_fn (stmt))
582 {
583 case IFN_UBSAN_NULL:
ab9a4330
JJ
584 remove = maybe_optimize_ubsan_null_ifn (ctx, stmt);
585 break;
35228ac7
JJ
586 case IFN_UBSAN_VPTR:
587 remove = maybe_optimize_ubsan_vptr_ifn (ctx, stmt);
588 break;
06cefae9 589 case IFN_ASAN_CHECK:
ab9a4330
JJ
590 if (asan_check_optimize)
591 remove = maybe_optimize_asan_check_ifn (ctx, stmt);
592 if (!remove)
593 ctx->asan_num_accesses++;
06cefae9 594 break;
2f75d6eb
ML
595 case IFN_ASAN_MARK:
596 ctx->contains_asan_mark = true;
597 break;
06cefae9
MP
598 default:
599 break;
600 }
601
ab9a4330
JJ
602 if (remove)
603 {
604 /* Drop this check. */
605 if (dump_file && (dump_flags & TDF_DETAILS))
606 {
607 fprintf (dump_file, "Optimizing out\n ");
608 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
609 fprintf (dump_file, "\n");
610 }
611 unlink_stmt_vdef (stmt);
612 gsi_remove (&gsi, true);
613 }
614 else
06cefae9
MP
615 gsi_next (&gsi);
616 }
617
ab9a4330
JJ
618 if (asan_check_optimize)
619 {
620 info->has_freeing_call_p = info->freeing_call_events != 0;
621 info->has_freeing_call_computed_p = true;
622 }
623
06cefae9
MP
624 for (son = first_dom_son (CDI_DOMINATORS, bb);
625 son;
626 son = next_dom_son (CDI_DOMINATORS, son))
627 sanopt_optimize_walker (son, ctx);
628
629 /* We're leaving this BB, so mark it to that effect. */
06cefae9
MP
630 info->visited_p = true;
631}
632
633/* Try to remove redundant sanitizer checks in function FUN. */
634
635static int
2f75d6eb 636sanopt_optimize (function *fun, bool *contains_asan_mark)
06cefae9
MP
637{
638 struct sanopt_ctx ctx;
639 ctx.asan_num_accesses = 0;
2f75d6eb 640 ctx.contains_asan_mark = false;
06cefae9
MP
641
642 /* Set up block info for each basic block. */
643 alloc_aux_for_blocks (sizeof (sanopt_info));
644
645 /* We're going to do a dominator walk, so ensure that we have
646 dominance information. */
647 calculate_dominance_info (CDI_DOMINATORS);
648
649 /* Recursively walk the dominator tree optimizing away
650 redundant checks. */
651 sanopt_optimize_walker (ENTRY_BLOCK_PTR_FOR_FN (fun), &ctx);
652
653 free_aux_for_blocks ();
654
2f75d6eb 655 *contains_asan_mark = ctx.contains_asan_mark;
06cefae9
MP
656 return ctx.asan_num_accesses;
657}
658
659/* Perform optimization of sanitize functions. */
660
17795822
TS
661namespace {
662
663const pass_data pass_data_sanopt =
06cefae9
MP
664{
665 GIMPLE_PASS, /* type */
666 "sanopt", /* name */
667 OPTGROUP_NONE, /* optinfo_flags */
668 TV_NONE, /* tv_id */
669 ( PROP_ssa | PROP_cfg | PROP_gimple_leh ), /* properties_required */
670 0, /* properties_provided */
671 0, /* properties_destroyed */
672 0, /* todo_flags_start */
673 TODO_update_ssa, /* todo_flags_finish */
674};
675
17795822 676class pass_sanopt : public gimple_opt_pass
06cefae9
MP
677{
678public:
679 pass_sanopt (gcc::context *ctxt)
680 : gimple_opt_pass (pass_data_sanopt, ctxt)
681 {}
682
683 /* opt_pass methods: */
684 virtual bool gate (function *) { return flag_sanitize; }
685 virtual unsigned int execute (function *);
686
687}; // class pass_sanopt
688
2f75d6eb
ML
689/* Sanitize all ASAN_MARK unpoison calls that are not reachable by a BB
690 that contains an ASAN_MARK poison. All these ASAN_MARK unpoison call
691 can be removed as all variables are unpoisoned in a function prologue. */
692
693static void
694sanitize_asan_mark_unpoison (void)
695{
696 /* 1) Find all BBs that contain an ASAN_MARK poison call. */
697 auto_sbitmap with_poison (last_basic_block_for_fn (cfun) + 1);
698 bitmap_clear (with_poison);
699 basic_block bb;
700
701 FOR_EACH_BB_FN (bb, cfun)
702 {
703 if (bitmap_bit_p (with_poison, bb->index))
704 continue;
705
706 gimple_stmt_iterator gsi;
707 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
708 {
709 gimple *stmt = gsi_stmt (gsi);
710 if (asan_mark_p (stmt, ASAN_MARK_POISON))
711 {
712 bitmap_set_bit (with_poison, bb->index);
713 break;
714 }
715 }
716 }
717
718 auto_sbitmap poisoned (last_basic_block_for_fn (cfun) + 1);
719 bitmap_clear (poisoned);
720 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
721 bitmap_copy (worklist, with_poison);
722
723 /* 2) Propagate the information to all reachable blocks. */
724 while (!bitmap_empty_p (worklist))
725 {
726 unsigned i = bitmap_first_set_bit (worklist);
727 bitmap_clear_bit (worklist, i);
728 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
729 gcc_assert (bb);
730
731 edge e;
732 edge_iterator ei;
733 FOR_EACH_EDGE (e, ei, bb->succs)
734 if (!bitmap_bit_p (poisoned, e->dest->index))
735 {
736 bitmap_set_bit (poisoned, e->dest->index);
737 bitmap_set_bit (worklist, e->dest->index);
738 }
739 }
740
741 /* 3) Iterate all BBs not included in POISONED BBs and remove unpoison
742 ASAN_MARK preceding an ASAN_MARK poison (which can still happen). */
743 FOR_EACH_BB_FN (bb, cfun)
744 {
745 if (bitmap_bit_p (poisoned, bb->index))
746 continue;
747
748 gimple_stmt_iterator gsi;
749 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
750 {
2f75d6eb
ML
751 gimple *stmt = gsi_stmt (gsi);
752 if (gimple_call_internal_p (stmt, IFN_ASAN_MARK))
753 {
754 if (asan_mark_p (stmt, ASAN_MARK_POISON))
755 break;
756 else
757 {
758 if (dump_file)
759 fprintf (dump_file, "Removing ASAN_MARK unpoison\n");
760 unlink_stmt_vdef (stmt);
761 release_defs (stmt);
762 gsi_remove (&gsi, true);
8ccaace8 763 continue;
2f75d6eb
ML
764 }
765 }
766
8ccaace8 767 gsi_next (&gsi);
2f75d6eb
ML
768 }
769 }
770}
771
772/* Return true when STMT is either ASAN_CHECK call or a call of a function
773 that can contain an ASAN_CHECK. */
774
775static bool
776maybe_contains_asan_check (gimple *stmt)
777{
778 if (is_gimple_call (stmt))
779 {
780 if (gimple_call_internal_p (stmt, IFN_ASAN_MARK))
781 return false;
782 else
783 return !(gimple_call_flags (stmt) & ECF_CONST);
784 }
785 else if (is_a<gasm *> (stmt))
786 return true;
787
788 return false;
789}
790
791/* Sanitize all ASAN_MARK poison calls that are not followed by an ASAN_CHECK
792 call. These calls can be removed. */
793
794static void
795sanitize_asan_mark_poison (void)
796{
797 /* 1) Find all BBs that possibly contain an ASAN_CHECK. */
798 auto_sbitmap with_check (last_basic_block_for_fn (cfun) + 1);
799 bitmap_clear (with_check);
800 basic_block bb;
801
802 FOR_EACH_BB_FN (bb, cfun)
803 {
804 gimple_stmt_iterator gsi;
805 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
806 {
807 gimple *stmt = gsi_stmt (gsi);
808 if (maybe_contains_asan_check (stmt))
809 {
810 bitmap_set_bit (with_check, bb->index);
811 break;
812 }
813 }
814 }
815
816 auto_sbitmap can_reach_check (last_basic_block_for_fn (cfun) + 1);
817 bitmap_clear (can_reach_check);
818 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
819 bitmap_copy (worklist, with_check);
820
821 /* 2) Propagate the information to all definitions blocks. */
822 while (!bitmap_empty_p (worklist))
823 {
824 unsigned i = bitmap_first_set_bit (worklist);
825 bitmap_clear_bit (worklist, i);
826 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
827 gcc_assert (bb);
828
829 edge e;
830 edge_iterator ei;
831 FOR_EACH_EDGE (e, ei, bb->preds)
832 if (!bitmap_bit_p (can_reach_check, e->src->index))
833 {
834 bitmap_set_bit (can_reach_check, e->src->index);
835 bitmap_set_bit (worklist, e->src->index);
836 }
837 }
838
839 /* 3) Iterate all BBs not included in CAN_REACH_CHECK BBs and remove poison
840 ASAN_MARK not followed by a call to function having an ASAN_CHECK. */
841 FOR_EACH_BB_FN (bb, cfun)
842 {
843 if (bitmap_bit_p (can_reach_check, bb->index))
844 continue;
845
846 gimple_stmt_iterator gsi;
847 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi);)
848 {
2f75d6eb
ML
849 gimple *stmt = gsi_stmt (gsi);
850 if (maybe_contains_asan_check (stmt))
851 break;
852 else if (asan_mark_p (stmt, ASAN_MARK_POISON))
853 {
854 if (dump_file)
855 fprintf (dump_file, "Removing ASAN_MARK poison\n");
856 unlink_stmt_vdef (stmt);
857 release_defs (stmt);
8ccaace8
JJ
858 gimple_stmt_iterator gsi2 = gsi;
859 gsi_prev (&gsi);
860 gsi_remove (&gsi2, true);
861 continue;
2f75d6eb
ML
862 }
863
8ccaace8 864 gsi_prev (&gsi);
2f75d6eb
ML
865 }
866 }
867}
868
da402967
ML
869/* Rewrite all usages of tree OP which is a PARM_DECL with a VAR_DECL
870 that is it's DECL_VALUE_EXPR. */
871
872static tree
873rewrite_usage_of_param (tree *op, int *walk_subtrees, void *)
874{
875 if (TREE_CODE (*op) == PARM_DECL && DECL_HAS_VALUE_EXPR_P (*op))
876 {
877 *op = DECL_VALUE_EXPR (*op);
878 *walk_subtrees = 0;
879 }
880
881 return NULL;
882}
883
884/* For a given function FUN, rewrite all addressable parameters so that
885 a new automatic variable is introduced. Right after function entry
886 a parameter is assigned to the variable. */
887
888static void
889sanitize_rewrite_addressable_params (function *fun)
890{
891 gimple *g;
892 gimple_seq stmts = NULL;
893 bool has_any_addressable_param = false;
894 auto_vec<tree> clear_value_expr_list;
895
896 for (tree arg = DECL_ARGUMENTS (current_function_decl);
897 arg; arg = DECL_CHAIN (arg))
898 {
70affe6a
ML
899 tree type = TREE_TYPE (arg);
900 if (TREE_ADDRESSABLE (arg) && !TREE_ADDRESSABLE (type)
901 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST)
da402967
ML
902 {
903 TREE_ADDRESSABLE (arg) = 0;
904 /* The parameter is no longer addressable. */
da402967
ML
905 has_any_addressable_param = true;
906
907 /* Create a new automatic variable. */
908 tree var = build_decl (DECL_SOURCE_LOCATION (arg),
909 VAR_DECL, DECL_NAME (arg), type);
910 TREE_ADDRESSABLE (var) = 1;
7c819e8a 911 DECL_IGNORED_P (var) = 1;
da402967
ML
912
913 gimple_add_tmp_var (var);
914
915 if (dump_file)
916 fprintf (dump_file,
917 "Rewriting parameter whose address is taken: %s\n",
918 IDENTIFIER_POINTER (DECL_NAME (arg)));
919
920 gcc_assert (!DECL_HAS_VALUE_EXPR_P (arg));
da402967
ML
921
922 SET_DECL_PT_UID (var, DECL_PT_UID (arg));
923
924 /* Assign value of parameter to newly created variable. */
925 if ((TREE_CODE (type) == COMPLEX_TYPE
926 || TREE_CODE (type) == VECTOR_TYPE))
927 {
928 /* We need to create a SSA name that will be used for the
929 assignment. */
930 DECL_GIMPLE_REG_P (arg) = 1;
931 tree tmp = get_or_create_ssa_default_def (cfun, arg);
932 g = gimple_build_assign (var, tmp);
933 gimple_set_location (g, DECL_SOURCE_LOCATION (arg));
934 gimple_seq_add_stmt (&stmts, g);
935 }
936 else
937 {
938 g = gimple_build_assign (var, arg);
939 gimple_set_location (g, DECL_SOURCE_LOCATION (arg));
940 gimple_seq_add_stmt (&stmts, g);
941 }
942
943 if (target_for_debug_bind (arg))
944 {
945 g = gimple_build_debug_bind (arg, var, NULL);
946 gimple_seq_add_stmt (&stmts, g);
947 clear_value_expr_list.safe_push (arg);
948 }
6d7649f8
ML
949
950 DECL_HAS_VALUE_EXPR_P (arg) = 1;
951 SET_DECL_VALUE_EXPR (arg, var);
da402967
ML
952 }
953 }
954
955 if (!has_any_addressable_param)
956 return;
957
958 /* Replace all usages of PARM_DECLs with the newly
959 created variable VAR. */
960 basic_block bb;
961 FOR_EACH_BB_FN (bb, fun)
962 {
963 gimple_stmt_iterator gsi;
964 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
965 {
966 gimple *stmt = gsi_stmt (gsi);
967 gimple_stmt_iterator it = gsi_for_stmt (stmt);
968 walk_gimple_stmt (&it, NULL, rewrite_usage_of_param, NULL);
969 }
970 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
971 {
972 gphi *phi = dyn_cast<gphi *> (gsi_stmt (gsi));
973 for (unsigned i = 0; i < gimple_phi_num_args (phi); ++i)
974 {
975 hash_set<tree> visited_nodes;
976 walk_tree (gimple_phi_arg_def_ptr (phi, i),
977 rewrite_usage_of_param, NULL, &visited_nodes);
978 }
979 }
980 }
981
982 /* Unset value expr for parameters for which we created debug bind
983 expressions. */
984 unsigned i;
985 tree arg;
986 FOR_EACH_VEC_ELT (clear_value_expr_list, i, arg)
987 {
988 DECL_HAS_VALUE_EXPR_P (arg) = 0;
989 SET_DECL_VALUE_EXPR (arg, NULL_TREE);
990 }
991
992 /* Insert default assignments at the beginning of a function. */
993 basic_block entry_bb = ENTRY_BLOCK_PTR_FOR_FN (fun);
994 entry_bb = split_edge (single_succ_edge (entry_bb));
995
996 gimple_stmt_iterator gsi = gsi_start_bb (entry_bb);
997 gsi_insert_seq_before (&gsi, stmts, GSI_NEW_STMT);
998}
999
06cefae9
MP
1000unsigned int
1001pass_sanopt::execute (function *fun)
1002{
1003 basic_block bb;
1004 int asan_num_accesses = 0;
2f75d6eb 1005 bool contains_asan_mark = false;
06cefae9
MP
1006
1007 /* Try to remove redundant checks. */
1008 if (optimize
ab9a4330 1009 && (flag_sanitize
35228ac7
JJ
1010 & (SANITIZE_NULL | SANITIZE_ALIGNMENT
1011 | SANITIZE_ADDRESS | SANITIZE_VPTR)))
2f75d6eb 1012 asan_num_accesses = sanopt_optimize (fun, &contains_asan_mark);
06cefae9
MP
1013 else if (flag_sanitize & SANITIZE_ADDRESS)
1014 {
1015 gimple_stmt_iterator gsi;
1016 FOR_EACH_BB_FN (bb, fun)
1017 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1018 {
355fe088 1019 gimple *stmt = gsi_stmt (gsi);
8e4284d0 1020 if (gimple_call_internal_p (stmt, IFN_ASAN_CHECK))
06cefae9 1021 ++asan_num_accesses;
2f75d6eb
ML
1022 else if (gimple_call_internal_p (stmt, IFN_ASAN_MARK))
1023 contains_asan_mark = true;
06cefae9
MP
1024 }
1025 }
1026
2f75d6eb
ML
1027 if (contains_asan_mark)
1028 {
1029 sanitize_asan_mark_unpoison ();
1030 sanitize_asan_mark_poison ();
1031 }
1032
da402967
ML
1033 if (asan_sanitize_stack_p ())
1034 sanitize_rewrite_addressable_params (fun);
1035
06cefae9
MP
1036 bool use_calls = ASAN_INSTRUMENTATION_WITH_CALL_THRESHOLD < INT_MAX
1037 && asan_num_accesses >= ASAN_INSTRUMENTATION_WITH_CALL_THRESHOLD;
1038
c7775327
ML
1039 hash_map<tree, tree> shadow_vars_mapping;
1040 bool need_commit_edge_insert = false;
06cefae9
MP
1041 FOR_EACH_BB_FN (bb, fun)
1042 {
1043 gimple_stmt_iterator gsi;
1044 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
1045 {
355fe088 1046 gimple *stmt = gsi_stmt (gsi);
06cefae9
MP
1047 bool no_next = false;
1048
1049 if (!is_gimple_call (stmt))
1050 {
1051 gsi_next (&gsi);
1052 continue;
1053 }
1054
1055 if (gimple_call_internal_p (stmt))
1056 {
1057 enum internal_fn ifn = gimple_call_internal_fn (stmt);
1058 switch (ifn)
1059 {
1060 case IFN_UBSAN_NULL:
1061 no_next = ubsan_expand_null_ifn (&gsi);
1062 break;
1063 case IFN_UBSAN_BOUNDS:
1064 no_next = ubsan_expand_bounds_ifn (&gsi);
1065 break;
1066 case IFN_UBSAN_OBJECT_SIZE:
1067 no_next = ubsan_expand_objsize_ifn (&gsi);
1068 break;
c9b39a49
JJ
1069 case IFN_UBSAN_PTR:
1070 no_next = ubsan_expand_ptr_ifn (&gsi);
1071 break;
35228ac7
JJ
1072 case IFN_UBSAN_VPTR:
1073 no_next = ubsan_expand_vptr_ifn (&gsi);
1074 break;
06cefae9
MP
1075 case IFN_ASAN_CHECK:
1076 no_next = asan_expand_check_ifn (&gsi, use_calls);
1077 break;
6dc4a604
ML
1078 case IFN_ASAN_MARK:
1079 no_next = asan_expand_mark_ifn (&gsi);
1080 break;
c7775327
ML
1081 case IFN_ASAN_POISON:
1082 no_next = asan_expand_poison_ifn (&gsi,
1083 &need_commit_edge_insert,
1084 shadow_vars_mapping);
1085 break;
06cefae9
MP
1086 default:
1087 break;
1088 }
1089 }
4088b790
MP
1090 else if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
1091 {
1092 tree callee = gimple_call_fndecl (stmt);
1093 switch (DECL_FUNCTION_CODE (callee))
1094 {
1095 case BUILT_IN_UNREACHABLE:
45b2222a 1096 if (sanitize_flags_p (SANITIZE_UNREACHABLE))
4088b790
MP
1097 no_next = ubsan_instrument_unreachable (&gsi);
1098 break;
1099 default:
1100 break;
1101 }
1102 }
06cefae9
MP
1103
1104 if (dump_file && (dump_flags & TDF_DETAILS))
1105 {
1106 fprintf (dump_file, "Expanded\n ");
1107 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1108 fprintf (dump_file, "\n");
1109 }
1110
1111 if (!no_next)
1112 gsi_next (&gsi);
1113 }
1114 }
c7775327
ML
1115
1116 if (need_commit_edge_insert)
1117 gsi_commit_edge_inserts ();
1118
06cefae9
MP
1119 return 0;
1120}
1121
17795822
TS
1122} // anon namespace
1123
06cefae9
MP
1124gimple_opt_pass *
1125make_pass_sanopt (gcc::context *ctxt)
1126{
1127 return new pass_sanopt (ctxt);
1128}