]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-ssa-dce.cc
libstdc++: fix C header include guards
[thirdparty/gcc.git] / gcc / tree-ssa-dce.cc
1 /* Dead code elimination pass for the GNU compiler.
2 Copyright (C) 2002-2024 Free Software Foundation, Inc.
3 Contributed by Ben Elliston <bje@redhat.com>
4 and Andrew MacLeod <amacleod@redhat.com>
5 Adapted to use control dependence by Steven Bosscher, SUSE Labs.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 3, or (at your option) any
12 later version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
22
23 /* Dead code elimination.
24
25 References:
26
27 Building an Optimizing Compiler,
28 Robert Morgan, Butterworth-Heinemann, 1998, Section 8.9.
29
30 Advanced Compiler Design and Implementation,
31 Steven Muchnick, Morgan Kaufmann, 1997, Section 18.10.
32
33 Dead-code elimination is the removal of statements which have no
34 impact on the program's output. "Dead statements" have no impact
35 on the program's output, while "necessary statements" may have
36 impact on the output.
37
38 The algorithm consists of three phases:
39 1. Marking as necessary all statements known to be necessary,
40 e.g. most function calls, writing a value to memory, etc;
41 2. Propagating necessary statements, e.g., the statements
42 giving values to operands in necessary statements; and
43 3. Removing dead statements. */
44
45 #include "config.h"
46 #include "system.h"
47 #include "coretypes.h"
48 #include "backend.h"
49 #include "rtl.h"
50 #include "tree.h"
51 #include "gimple.h"
52 #include "cfghooks.h"
53 #include "tree-pass.h"
54 #include "ssa.h"
55 #include "gimple-pretty-print.h"
56 #include "fold-const.h"
57 #include "calls.h"
58 #include "cfganal.h"
59 #include "tree-eh.h"
60 #include "gimplify.h"
61 #include "gimple-iterator.h"
62 #include "tree-cfg.h"
63 #include "tree-ssa-loop-niter.h"
64 #include "tree-into-ssa.h"
65 #include "tree-dfa.h"
66 #include "cfgloop.h"
67 #include "tree-scalar-evolution.h"
68 #include "tree-ssa-propagate.h"
69 #include "gimple-fold.h"
70 #include "tree-ssa.h"
71
72 static struct stmt_stats
73 {
74 int total;
75 int total_phis;
76 int removed;
77 int removed_phis;
78 } stats;
79
80 #define STMT_NECESSARY GF_PLF_1
81
82 static vec<gimple *> worklist;
83
84 /* Vector indicating an SSA name has already been processed and marked
85 as necessary. */
86 static sbitmap processed;
87
88 /* Vector indicating that the last statement of a basic block has already
89 been marked as necessary. */
90 static sbitmap last_stmt_necessary;
91
92 /* Vector indicating that BB contains statements that are live. */
93 static sbitmap bb_contains_live_stmts;
94
95 /* Before we can determine whether a control branch is dead, we need to
96 compute which blocks are control dependent on which edges.
97
98 We expect each block to be control dependent on very few edges so we
99 use a bitmap for each block recording its edges. An array holds the
100 bitmap. The Ith bit in the bitmap is set if that block is dependent
101 on the Ith edge. */
102 static control_dependences *cd;
103
104 /* Vector indicating that a basic block has already had all the edges
105 processed that it is control dependent on. */
106 static sbitmap visited_control_parents;
107
108 /* TRUE if this pass alters the CFG (by removing control statements).
109 FALSE otherwise.
110
111 If this pass alters the CFG, then it will arrange for the dominators
112 to be recomputed. */
113 static bool cfg_altered;
114
115 /* When non-NULL holds map from basic block index into the postorder. */
116 static int *bb_postorder;
117
118
119 /* True if we should treat any stmt with a vdef as necessary. */
120
121 static inline bool
122 keep_all_vdefs_p ()
123 {
124 return optimize_debug;
125 }
126
127 /* 1 if CALLEE is the function __cxa_atexit.
128 2 if CALLEE is the function __aeabi_atexit.
129 0 otherwise. */
130
131 static inline int
132 is_cxa_atexit (const_tree callee)
133 {
134 if (callee != NULL_TREE
135 && strcmp (IDENTIFIER_POINTER (DECL_NAME (callee)), "__cxa_atexit") == 0)
136 return 1;
137 if (callee != NULL_TREE
138 && strcmp (IDENTIFIER_POINTER (DECL_NAME (callee)), "__aeabi_atexit") == 0)
139 return 2;
140 return 0;
141 }
142
143 /* True if STMT is a call to __cxa_atexit (or __aeabi_atexit)
144 and the function argument to that call is a const or pure
145 non-looping function decl. */
146
147 static inline bool
148 is_removable_cxa_atexit_call (gimple *stmt)
149 {
150 tree callee = gimple_call_fndecl (stmt);
151 int functype = is_cxa_atexit (callee);
152 if (!functype)
153 return false;
154 if (gimple_call_num_args (stmt) != 3)
155 return false;
156
157 /* The function argument is the 1st argument for __cxa_atexit
158 or the 2nd argument for __eabi_atexit. */
159 tree arg = gimple_call_arg (stmt, functype == 2 ? 1 : 0);
160 if (TREE_CODE (arg) != ADDR_EXPR)
161 return false;
162 arg = TREE_OPERAND (arg, 0);
163 if (TREE_CODE (arg) != FUNCTION_DECL)
164 return false;
165 int flags = flags_from_decl_or_type (arg);
166
167 /* If the function is noreturn then it cannot be removed. */
168 if (flags & ECF_NORETURN)
169 return false;
170
171 /* The function needs to be const or pure and non looping. */
172 return (flags & (ECF_CONST|ECF_PURE))
173 && !(flags & ECF_LOOPING_CONST_OR_PURE);
174 }
175
176 /* If STMT is not already marked necessary, mark it, and add it to the
177 worklist if ADD_TO_WORKLIST is true. */
178
179 static inline void
180 mark_stmt_necessary (gimple *stmt, bool add_to_worklist)
181 {
182 gcc_assert (stmt);
183
184 if (gimple_plf (stmt, STMT_NECESSARY))
185 return;
186
187 if (dump_file && (dump_flags & TDF_DETAILS))
188 {
189 fprintf (dump_file, "Marking useful stmt: ");
190 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
191 fprintf (dump_file, "\n");
192 }
193
194 gimple_set_plf (stmt, STMT_NECESSARY, true);
195 if (add_to_worklist)
196 worklist.safe_push (stmt);
197 if (add_to_worklist && bb_contains_live_stmts && !is_gimple_debug (stmt))
198 bitmap_set_bit (bb_contains_live_stmts, gimple_bb (stmt)->index);
199 }
200
201
202 /* Mark the statement defining operand OP as necessary. */
203
204 static inline void
205 mark_operand_necessary (tree op)
206 {
207 gimple *stmt;
208 int ver;
209
210 gcc_assert (op);
211
212 ver = SSA_NAME_VERSION (op);
213 if (bitmap_bit_p (processed, ver))
214 {
215 stmt = SSA_NAME_DEF_STMT (op);
216 gcc_assert (gimple_nop_p (stmt)
217 || gimple_plf (stmt, STMT_NECESSARY));
218 return;
219 }
220 bitmap_set_bit (processed, ver);
221
222 stmt = SSA_NAME_DEF_STMT (op);
223 gcc_assert (stmt);
224
225 if (gimple_plf (stmt, STMT_NECESSARY) || gimple_nop_p (stmt))
226 return;
227
228 if (dump_file && (dump_flags & TDF_DETAILS))
229 {
230 fprintf (dump_file, "marking necessary through ");
231 print_generic_expr (dump_file, op);
232 fprintf (dump_file, " stmt ");
233 print_gimple_stmt (dump_file, stmt, 0);
234 }
235
236 gimple_set_plf (stmt, STMT_NECESSARY, true);
237 if (bb_contains_live_stmts)
238 bitmap_set_bit (bb_contains_live_stmts, gimple_bb (stmt)->index);
239 worklist.safe_push (stmt);
240 }
241
242
243 /* Mark STMT as necessary if it obviously is. Add it to the worklist if
244 it can make other statements necessary.
245
246 If AGGRESSIVE is false, control statements are conservatively marked as
247 necessary. */
248
249 static void
250 mark_stmt_if_obviously_necessary (gimple *stmt, bool aggressive)
251 {
252 /* Statements that are implicitly live. Most function calls, asm
253 and return statements are required. Labels and GIMPLE_BIND nodes
254 are kept because they are control flow, and we have no way of
255 knowing whether they can be removed. DCE can eliminate all the
256 other statements in a block, and CFG can then remove the block
257 and labels. */
258 switch (gimple_code (stmt))
259 {
260 case GIMPLE_PREDICT:
261 case GIMPLE_LABEL:
262 mark_stmt_necessary (stmt, false);
263 return;
264
265 case GIMPLE_ASM:
266 case GIMPLE_RESX:
267 case GIMPLE_RETURN:
268 mark_stmt_necessary (stmt, true);
269 return;
270
271 case GIMPLE_CALL:
272 {
273 /* Never elide a noreturn call we pruned control-flow for. */
274 if ((gimple_call_flags (stmt) & ECF_NORETURN)
275 && gimple_call_ctrl_altering_p (stmt))
276 {
277 mark_stmt_necessary (stmt, true);
278 return;
279 }
280
281 tree callee = gimple_call_fndecl (stmt);
282 if (callee != NULL_TREE
283 && fndecl_built_in_p (callee, BUILT_IN_NORMAL))
284 switch (DECL_FUNCTION_CODE (callee))
285 {
286 case BUILT_IN_MALLOC:
287 case BUILT_IN_ALIGNED_ALLOC:
288 case BUILT_IN_CALLOC:
289 CASE_BUILT_IN_ALLOCA:
290 case BUILT_IN_STRDUP:
291 case BUILT_IN_STRNDUP:
292 case BUILT_IN_GOMP_ALLOC:
293 return;
294
295 default:;
296 }
297
298 if (callee != NULL_TREE
299 && flag_allocation_dce
300 && DECL_IS_REPLACEABLE_OPERATOR_NEW_P (callee))
301 return;
302
303 /* For __cxa_atexit calls, don't mark as necessary right away. */
304 if (is_removable_cxa_atexit_call (stmt))
305 return;
306
307 /* IFN_GOACC_LOOP calls are necessary in that they are used to
308 represent parameter (i.e. step, bound) of a lowered OpenACC
309 partitioned loop. But this kind of partitioned loop might not
310 survive from aggressive loop removal for it has loop exit and
311 is assumed to be finite. Therefore, we need to explicitly mark
312 these calls. (An example is libgomp.oacc-c-c++-common/pr84955.c) */
313 if (gimple_call_internal_p (stmt, IFN_GOACC_LOOP))
314 {
315 mark_stmt_necessary (stmt, true);
316 return;
317 }
318 break;
319 }
320
321 case GIMPLE_DEBUG:
322 /* Debug temps without a value are not useful. ??? If we could
323 easily locate the debug temp bind stmt for a use thereof,
324 would could refrain from marking all debug temps here, and
325 mark them only if they're used. */
326 if (gimple_debug_nonbind_marker_p (stmt)
327 || !gimple_debug_bind_p (stmt)
328 || gimple_debug_bind_has_value_p (stmt)
329 || TREE_CODE (gimple_debug_bind_get_var (stmt)) != DEBUG_EXPR_DECL)
330 mark_stmt_necessary (stmt, false);
331 return;
332
333 case GIMPLE_GOTO:
334 gcc_assert (!simple_goto_p (stmt));
335 mark_stmt_necessary (stmt, true);
336 return;
337
338 case GIMPLE_COND:
339 gcc_assert (EDGE_COUNT (gimple_bb (stmt)->succs) == 2);
340 /* Fall through. */
341
342 case GIMPLE_SWITCH:
343 if (! aggressive)
344 mark_stmt_necessary (stmt, true);
345 break;
346
347 case GIMPLE_ASSIGN:
348 /* Mark indirect CLOBBERs to be lazily removed if their SSA operands
349 do not prevail. That also makes control flow leading to them
350 not necessary in aggressive mode. */
351 if (gimple_clobber_p (stmt) && !zero_ssa_operands (stmt, SSA_OP_USE))
352 return;
353 break;
354
355 default:
356 break;
357 }
358
359 /* If the statement has volatile operands, it needs to be preserved.
360 Same for statements that can alter control flow in unpredictable
361 ways. */
362 if (gimple_has_side_effects (stmt) || is_ctrl_altering_stmt (stmt))
363 {
364 mark_stmt_necessary (stmt, true);
365 return;
366 }
367
368 /* If a statement could throw, it can be deemed necessary unless we
369 are allowed to remove dead EH. Test this after checking for
370 new/delete operators since we always elide their EH. */
371 if (!cfun->can_delete_dead_exceptions
372 && stmt_could_throw_p (cfun, stmt))
373 {
374 mark_stmt_necessary (stmt, true);
375 return;
376 }
377
378 if ((gimple_vdef (stmt) && keep_all_vdefs_p ())
379 || stmt_may_clobber_global_p (stmt, false))
380 {
381 mark_stmt_necessary (stmt, true);
382 return;
383 }
384
385 return;
386 }
387
388
389 /* Mark the last statement of BB as necessary. */
390
391 static bool
392 mark_last_stmt_necessary (basic_block bb)
393 {
394 if (!bitmap_set_bit (last_stmt_necessary, bb->index))
395 return true;
396
397 bitmap_set_bit (bb_contains_live_stmts, bb->index);
398
399 /* We actually mark the statement only if it is a control statement. */
400 gimple *stmt = *gsi_last_bb (bb);
401 if (stmt && is_ctrl_stmt (stmt))
402 {
403 mark_stmt_necessary (stmt, true);
404 return true;
405 }
406 return false;
407 }
408
409
410 /* Mark control dependent edges of BB as necessary. We have to do this only
411 once for each basic block so we set the appropriate bit after we're done.
412
413 When IGNORE_SELF is true, ignore BB in the list of control dependences. */
414
415 static void
416 mark_control_dependent_edges_necessary (basic_block bb, bool ignore_self)
417 {
418 bitmap_iterator bi;
419 unsigned edge_number;
420 bool skipped = false;
421
422 gcc_assert (bb != EXIT_BLOCK_PTR_FOR_FN (cfun));
423
424 if (bb == ENTRY_BLOCK_PTR_FOR_FN (cfun))
425 return;
426
427 EXECUTE_IF_SET_IN_BITMAP (cd->get_edges_dependent_on (bb->index),
428 0, edge_number, bi)
429 {
430 basic_block cd_bb = cd->get_edge_src (edge_number);
431
432 if (ignore_self && cd_bb == bb)
433 {
434 skipped = true;
435 continue;
436 }
437
438 if (!mark_last_stmt_necessary (cd_bb))
439 mark_control_dependent_edges_necessary (cd_bb, false);
440 }
441
442 if (!skipped)
443 bitmap_set_bit (visited_control_parents, bb->index);
444 }
445
446
447 /* Find obviously necessary statements. These are things like most function
448 calls, and stores to file level variables.
449
450 If EL is NULL, control statements are conservatively marked as
451 necessary. Otherwise it contains the list of edges used by control
452 dependence analysis. */
453
454 static void
455 find_obviously_necessary_stmts (bool aggressive)
456 {
457 basic_block bb;
458 gimple_stmt_iterator gsi;
459 edge e;
460 gimple *phi, *stmt;
461 int flags;
462
463 FOR_EACH_BB_FN (bb, cfun)
464 {
465 /* PHI nodes are never inherently necessary. */
466 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
467 {
468 phi = gsi_stmt (gsi);
469 gimple_set_plf (phi, STMT_NECESSARY, false);
470 }
471
472 /* Check all statements in the block. */
473 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
474 {
475 stmt = gsi_stmt (gsi);
476 gimple_set_plf (stmt, STMT_NECESSARY, false);
477 mark_stmt_if_obviously_necessary (stmt, aggressive);
478 }
479 }
480
481 /* Pure and const functions are finite and thus have no infinite loops in
482 them. */
483 flags = flags_from_decl_or_type (current_function_decl);
484 if ((flags & (ECF_CONST|ECF_PURE)) && !(flags & ECF_LOOPING_CONST_OR_PURE))
485 return;
486
487 /* Prevent the empty possibly infinite loops from being removed. This is
488 needed to make the logic in remove_dead_stmt work to identify the
489 correct edge to keep when removing a controlling condition. */
490 if (aggressive)
491 {
492 if (mark_irreducible_loops ())
493 FOR_EACH_BB_FN (bb, cfun)
494 {
495 edge_iterator ei;
496 FOR_EACH_EDGE (e, ei, bb->succs)
497 if ((e->flags & EDGE_DFS_BACK)
498 && (e->flags & EDGE_IRREDUCIBLE_LOOP))
499 {
500 if (dump_file)
501 fprintf (dump_file, "Marking back edge of irreducible "
502 "loop %i->%i\n", e->src->index, e->dest->index);
503 mark_control_dependent_edges_necessary (e->dest, false);
504 }
505 }
506
507 for (auto loop : loops_list (cfun, 0))
508 /* For loops without an exit do not mark any condition. */
509 if (loop->exits->next->e && !finite_loop_p (loop))
510 {
511 if (dump_file)
512 fprintf (dump_file, "cannot prove finiteness of loop %i\n",
513 loop->num);
514 mark_control_dependent_edges_necessary (loop->latch, false);
515 }
516 }
517 }
518
519
520 /* Return true if REF is based on an aliased base, otherwise false. */
521
522 static bool
523 ref_may_be_aliased (tree ref)
524 {
525 if (TREE_CODE (ref) == WITH_SIZE_EXPR)
526 ref = TREE_OPERAND (ref, 0);
527 while (handled_component_p (ref))
528 ref = TREE_OPERAND (ref, 0);
529 if ((TREE_CODE (ref) == MEM_REF || TREE_CODE (ref) == TARGET_MEM_REF)
530 && TREE_CODE (TREE_OPERAND (ref, 0)) == ADDR_EXPR)
531 ref = TREE_OPERAND (TREE_OPERAND (ref, 0), 0);
532 return !(DECL_P (ref)
533 && !may_be_aliased (ref));
534 }
535
536 static bitmap visited = NULL;
537 static unsigned int longest_chain = 0;
538 static unsigned int total_chain = 0;
539 static unsigned int nr_walks = 0;
540 static bool chain_ovfl = false;
541
542 /* Worker for the walker that marks reaching definitions of REF,
543 which is based on a non-aliased decl, necessary. It returns
544 true whenever the defining statement of the current VDEF is
545 a kill for REF, as no dominating may-defs are necessary for REF
546 anymore. DATA points to the basic-block that contains the
547 stmt that refers to REF. */
548
549 static bool
550 mark_aliased_reaching_defs_necessary_1 (ao_ref *ref, tree vdef, void *data)
551 {
552 gimple *def_stmt = SSA_NAME_DEF_STMT (vdef);
553
554 /* All stmts we visit are necessary. */
555 if (! gimple_clobber_p (def_stmt))
556 mark_operand_necessary (vdef);
557
558 /* If the stmt lhs kills ref, then we can stop walking. */
559 if (gimple_has_lhs (def_stmt)
560 && TREE_CODE (gimple_get_lhs (def_stmt)) != SSA_NAME
561 /* The assignment is not necessarily carried out if it can throw
562 and we can catch it in the current function where we could inspect
563 the previous value.
564 ??? We only need to care about the RHS throwing. For aggregate
565 assignments or similar calls and non-call exceptions the LHS
566 might throw as well. */
567 && !stmt_can_throw_internal (cfun, def_stmt))
568 {
569 tree base, lhs = gimple_get_lhs (def_stmt);
570 poly_int64 size, offset, max_size;
571 bool reverse;
572 ao_ref_base (ref);
573 base
574 = get_ref_base_and_extent (lhs, &offset, &size, &max_size, &reverse);
575 /* We can get MEM[symbol: sZ, index: D.8862_1] here,
576 so base == refd->base does not always hold. */
577 if (base == ref->base)
578 {
579 /* For a must-alias check we need to be able to constrain
580 the accesses properly. */
581 if (known_eq (size, max_size)
582 && known_subrange_p (ref->offset, ref->max_size, offset, size))
583 return true;
584 /* Or they need to be exactly the same. */
585 else if (ref->ref
586 /* Make sure there is no induction variable involved
587 in the references (gcc.c-torture/execute/pr42142.c).
588 The simplest way is to check if the kill dominates
589 the use. */
590 /* But when both are in the same block we cannot
591 easily tell whether we came from a backedge
592 unless we decide to compute stmt UIDs
593 (see PR58246). */
594 && (basic_block) data != gimple_bb (def_stmt)
595 && dominated_by_p (CDI_DOMINATORS, (basic_block) data,
596 gimple_bb (def_stmt))
597 && operand_equal_p (ref->ref, lhs, 0))
598 return true;
599 }
600 }
601
602 /* Otherwise keep walking. */
603 return false;
604 }
605
606 static void
607 mark_aliased_reaching_defs_necessary (gimple *stmt, tree ref)
608 {
609 /* Should have been caught before calling this function. */
610 gcc_checking_assert (!keep_all_vdefs_p ());
611
612 unsigned int chain;
613 ao_ref refd;
614 gcc_assert (!chain_ovfl);
615 ao_ref_init (&refd, ref);
616 chain = walk_aliased_vdefs (&refd, gimple_vuse (stmt),
617 mark_aliased_reaching_defs_necessary_1,
618 gimple_bb (stmt), NULL);
619 if (chain > longest_chain)
620 longest_chain = chain;
621 total_chain += chain;
622 nr_walks++;
623 }
624
625 /* Worker for the walker that marks reaching definitions of REF, which
626 is not based on a non-aliased decl. For simplicity we need to end
627 up marking all may-defs necessary that are not based on a non-aliased
628 decl. The only job of this walker is to skip may-defs based on
629 a non-aliased decl. */
630
631 static bool
632 mark_all_reaching_defs_necessary_1 (ao_ref *ref ATTRIBUTE_UNUSED,
633 tree vdef, void *data ATTRIBUTE_UNUSED)
634 {
635 gimple *def_stmt = SSA_NAME_DEF_STMT (vdef);
636
637 /* We have to skip already visited (and thus necessary) statements
638 to make the chaining work after we dropped back to simple mode. */
639 if (chain_ovfl
640 && bitmap_bit_p (processed, SSA_NAME_VERSION (vdef)))
641 {
642 gcc_assert (gimple_nop_p (def_stmt)
643 || gimple_plf (def_stmt, STMT_NECESSARY));
644 return false;
645 }
646
647 /* We want to skip stores to non-aliased variables. */
648 if (!chain_ovfl
649 && gimple_assign_single_p (def_stmt))
650 {
651 tree lhs = gimple_assign_lhs (def_stmt);
652 if (!ref_may_be_aliased (lhs))
653 return false;
654 }
655
656 /* We want to skip statments that do not constitute stores but have
657 a virtual definition. */
658 if (gcall *call = dyn_cast <gcall *> (def_stmt))
659 {
660 tree callee = gimple_call_fndecl (call);
661 if (callee != NULL_TREE
662 && fndecl_built_in_p (callee, BUILT_IN_NORMAL))
663 switch (DECL_FUNCTION_CODE (callee))
664 {
665 case BUILT_IN_MALLOC:
666 case BUILT_IN_ALIGNED_ALLOC:
667 case BUILT_IN_CALLOC:
668 CASE_BUILT_IN_ALLOCA:
669 case BUILT_IN_FREE:
670 case BUILT_IN_GOMP_ALLOC:
671 case BUILT_IN_GOMP_FREE:
672 return false;
673
674 default:;
675 }
676
677 if (callee != NULL_TREE
678 && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (callee)
679 || DECL_IS_OPERATOR_DELETE_P (callee))
680 && gimple_call_from_new_or_delete (call))
681 return false;
682 if (is_removable_cxa_atexit_call (call))
683 return false;
684 }
685
686 if (! gimple_clobber_p (def_stmt))
687 mark_operand_necessary (vdef);
688
689 return false;
690 }
691
692 static void
693 mark_all_reaching_defs_necessary (gimple *stmt)
694 {
695 /* Should have been caught before calling this function. */
696 gcc_checking_assert (!keep_all_vdefs_p ());
697 walk_aliased_vdefs (NULL, gimple_vuse (stmt),
698 mark_all_reaching_defs_necessary_1, NULL, &visited);
699 }
700
701 /* Return true for PHI nodes with one or identical arguments
702 can be removed. */
703 static bool
704 degenerate_phi_p (gimple *phi)
705 {
706 unsigned int i;
707 tree op = gimple_phi_arg_def (phi, 0);
708 for (i = 1; i < gimple_phi_num_args (phi); i++)
709 if (gimple_phi_arg_def (phi, i) != op)
710 return false;
711 return true;
712 }
713
714 /* Return that NEW_CALL and DELETE_CALL are a valid pair of new
715 and delete operators. */
716
717 static bool
718 valid_new_delete_pair_p (gimple *new_call, gimple *delete_call)
719 {
720 tree new_asm = DECL_ASSEMBLER_NAME (gimple_call_fndecl (new_call));
721 tree delete_asm = DECL_ASSEMBLER_NAME (gimple_call_fndecl (delete_call));
722 return valid_new_delete_pair_p (new_asm, delete_asm);
723 }
724
725 /* Propagate necessity using the operands of necessary statements.
726 Process the uses on each statement in the worklist, and add all
727 feeding statements which contribute to the calculation of this
728 value to the worklist.
729
730 In conservative mode, EL is NULL. */
731
732 static void
733 propagate_necessity (bool aggressive)
734 {
735 gimple *stmt;
736
737 if (dump_file && (dump_flags & TDF_DETAILS))
738 fprintf (dump_file, "\nProcessing worklist:\n");
739
740 while (worklist.length () > 0)
741 {
742 /* Take STMT from worklist. */
743 stmt = worklist.pop ();
744
745 if (dump_file && (dump_flags & TDF_DETAILS))
746 {
747 fprintf (dump_file, "processing: ");
748 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
749 fprintf (dump_file, "\n");
750 }
751
752 if (aggressive)
753 {
754 /* Mark the last statement of the basic blocks on which the block
755 containing STMT is control dependent, but only if we haven't
756 already done so. */
757 basic_block bb = gimple_bb (stmt);
758 if (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun)
759 && !bitmap_bit_p (visited_control_parents, bb->index))
760 mark_control_dependent_edges_necessary (bb, false);
761 }
762
763 if (gimple_code (stmt) == GIMPLE_PHI
764 /* We do not process virtual PHI nodes nor do we track their
765 necessity. */
766 && !virtual_operand_p (gimple_phi_result (stmt)))
767 {
768 /* PHI nodes are somewhat special in that each PHI alternative has
769 data and control dependencies. All the statements feeding the
770 PHI node's arguments are always necessary. In aggressive mode,
771 we also consider the control dependent edges leading to the
772 predecessor block associated with each PHI alternative as
773 necessary. */
774 gphi *phi = as_a <gphi *> (stmt);
775 size_t k;
776
777 for (k = 0; k < gimple_phi_num_args (stmt); k++)
778 {
779 tree arg = PHI_ARG_DEF (stmt, k);
780 if (TREE_CODE (arg) == SSA_NAME)
781 mark_operand_necessary (arg);
782 }
783
784 /* For PHI operands it matters from where the control flow arrives
785 to the BB. Consider the following example:
786
787 a=exp1;
788 b=exp2;
789 if (test)
790 ;
791 else
792 ;
793 c=PHI(a,b)
794
795 We need to mark control dependence of the empty basic blocks, since they
796 contains computation of PHI operands.
797
798 Doing so is too restrictive in the case the predecestor block is in
799 the loop. Consider:
800
801 if (b)
802 {
803 int i;
804 for (i = 0; i<1000; ++i)
805 ;
806 j = 0;
807 }
808 return j;
809
810 There is PHI for J in the BB containing return statement.
811 In this case the control dependence of predecestor block (that is
812 within the empty loop) also contains the block determining number
813 of iterations of the block that would prevent removing of empty
814 loop in this case.
815
816 This scenario can be avoided by splitting critical edges.
817 To save the critical edge splitting pass we identify how the control
818 dependence would look like if the edge was split.
819
820 Consider the modified CFG created from current CFG by splitting
821 edge B->C. In the postdominance tree of modified CFG, C' is
822 always child of C. There are two cases how chlids of C' can look
823 like:
824
825 1) C' is leaf
826
827 In this case the only basic block C' is control dependent on is B.
828
829 2) C' has single child that is B
830
831 In this case control dependence of C' is same as control
832 dependence of B in original CFG except for block B itself.
833 (since C' postdominate B in modified CFG)
834
835 Now how to decide what case happens? There are two basic options:
836
837 a) C postdominate B. Then C immediately postdominate B and
838 case 2 happens iff there is no other way from B to C except
839 the edge B->C.
840
841 There is other way from B to C iff there is succesor of B that
842 is not postdominated by B. Testing this condition is somewhat
843 expensive, because we need to iterate all succesors of B.
844 We are safe to assume that this does not happen: we will mark B
845 as needed when processing the other path from B to C that is
846 conrol dependent on B and marking control dependencies of B
847 itself is harmless because they will be processed anyway after
848 processing control statement in B.
849
850 b) C does not postdominate B. Always case 1 happens since there is
851 path from C to exit that does not go through B and thus also C'. */
852
853 if (aggressive && !degenerate_phi_p (stmt))
854 {
855 for (k = 0; k < gimple_phi_num_args (stmt); k++)
856 {
857 basic_block arg_bb = gimple_phi_arg_edge (phi, k)->src;
858
859 if (gimple_bb (stmt)
860 != get_immediate_dominator (CDI_POST_DOMINATORS, arg_bb))
861 {
862 if (!mark_last_stmt_necessary (arg_bb))
863 mark_control_dependent_edges_necessary (arg_bb, false);
864 }
865 else if (arg_bb != ENTRY_BLOCK_PTR_FOR_FN (cfun)
866 && !bitmap_bit_p (visited_control_parents,
867 arg_bb->index))
868 mark_control_dependent_edges_necessary (arg_bb, true);
869 }
870 }
871 }
872 else
873 {
874 /* Propagate through the operands. Examine all the USE, VUSE and
875 VDEF operands in this statement. Mark all the statements
876 which feed this statement's uses as necessary. */
877 ssa_op_iter iter;
878 tree use;
879
880 /* If this is a call to free which is directly fed by an
881 allocation function do not mark that necessary through
882 processing the argument. */
883 bool is_delete_operator
884 = (is_gimple_call (stmt)
885 && gimple_call_from_new_or_delete (as_a <gcall *> (stmt))
886 && gimple_call_operator_delete_p (as_a <gcall *> (stmt)));
887 if (is_delete_operator
888 || gimple_call_builtin_p (stmt, BUILT_IN_FREE)
889 || gimple_call_builtin_p (stmt, BUILT_IN_GOMP_FREE))
890 {
891 tree ptr = gimple_call_arg (stmt, 0);
892 gcall *def_stmt;
893 tree def_callee;
894 /* If the pointer we free is defined by an allocation
895 function do not add the call to the worklist. */
896 if (TREE_CODE (ptr) == SSA_NAME
897 && (def_stmt = dyn_cast <gcall *> (SSA_NAME_DEF_STMT (ptr)))
898 && (def_callee = gimple_call_fndecl (def_stmt))
899 && ((DECL_BUILT_IN_CLASS (def_callee) == BUILT_IN_NORMAL
900 && (DECL_FUNCTION_CODE (def_callee) == BUILT_IN_ALIGNED_ALLOC
901 || DECL_FUNCTION_CODE (def_callee) == BUILT_IN_MALLOC
902 || DECL_FUNCTION_CODE (def_callee) == BUILT_IN_CALLOC
903 || DECL_FUNCTION_CODE (def_callee) == BUILT_IN_GOMP_ALLOC))
904 || (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (def_callee)
905 && gimple_call_from_new_or_delete (def_stmt))))
906 {
907 if (is_delete_operator
908 && !valid_new_delete_pair_p (def_stmt, stmt))
909 mark_operand_necessary (gimple_call_arg (stmt, 0));
910
911 /* Delete operators can have alignment and (or) size
912 as next arguments. When being a SSA_NAME, they
913 must be marked as necessary. Similarly GOMP_free. */
914 if (gimple_call_num_args (stmt) >= 2)
915 for (unsigned i = 1; i < gimple_call_num_args (stmt);
916 i++)
917 {
918 tree arg = gimple_call_arg (stmt, i);
919 if (TREE_CODE (arg) == SSA_NAME)
920 mark_operand_necessary (arg);
921 }
922
923 continue;
924 }
925 }
926
927 FOR_EACH_SSA_TREE_OPERAND (use, stmt, iter, SSA_OP_USE)
928 mark_operand_necessary (use);
929
930 use = gimple_vuse (stmt);
931 if (!use)
932 continue;
933
934 /* No need to search for vdefs if we intrinsicly keep them all. */
935 if (keep_all_vdefs_p ())
936 continue;
937
938 /* If we dropped to simple mode make all immediately
939 reachable definitions necessary. */
940 if (chain_ovfl)
941 {
942 mark_all_reaching_defs_necessary (stmt);
943 continue;
944 }
945
946 /* For statements that may load from memory (have a VUSE) we
947 have to mark all reaching (may-)definitions as necessary.
948 We partition this task into two cases:
949 1) explicit loads based on decls that are not aliased
950 2) implicit loads (like calls) and explicit loads not
951 based on decls that are not aliased (like indirect
952 references or loads from globals)
953 For 1) we mark all reaching may-defs as necessary, stopping
954 at dominating kills. For 2) we want to mark all dominating
955 references necessary, but non-aliased ones which we handle
956 in 1). By keeping a global visited bitmap for references
957 we walk for 2) we avoid quadratic behavior for those. */
958
959 if (gcall *call = dyn_cast <gcall *> (stmt))
960 {
961 tree callee = gimple_call_fndecl (call);
962 unsigned i;
963
964 /* Calls to functions that are merely acting as barriers
965 or that only store to memory do not make any previous
966 stores necessary. */
967 if (callee != NULL_TREE
968 && DECL_BUILT_IN_CLASS (callee) == BUILT_IN_NORMAL
969 && (DECL_FUNCTION_CODE (callee) == BUILT_IN_MEMSET
970 || DECL_FUNCTION_CODE (callee) == BUILT_IN_MEMSET_CHK
971 || DECL_FUNCTION_CODE (callee) == BUILT_IN_MALLOC
972 || DECL_FUNCTION_CODE (callee) == BUILT_IN_ALIGNED_ALLOC
973 || DECL_FUNCTION_CODE (callee) == BUILT_IN_CALLOC
974 || DECL_FUNCTION_CODE (callee) == BUILT_IN_FREE
975 || DECL_FUNCTION_CODE (callee) == BUILT_IN_VA_END
976 || ALLOCA_FUNCTION_CODE_P (DECL_FUNCTION_CODE (callee))
977 || DECL_FUNCTION_CODE (callee) == BUILT_IN_STACK_SAVE
978 || DECL_FUNCTION_CODE (callee) == BUILT_IN_STACK_RESTORE
979 || DECL_FUNCTION_CODE (callee) == BUILT_IN_ASSUME_ALIGNED))
980 continue;
981
982 if (callee != NULL_TREE
983 && (DECL_IS_REPLACEABLE_OPERATOR_NEW_P (callee)
984 || DECL_IS_OPERATOR_DELETE_P (callee))
985 && gimple_call_from_new_or_delete (call))
986 continue;
987
988 if (is_removable_cxa_atexit_call (call))
989 continue;
990
991 /* Calls implicitly load from memory, their arguments
992 in addition may explicitly perform memory loads. */
993 mark_all_reaching_defs_necessary (call);
994 for (i = 0; i < gimple_call_num_args (call); ++i)
995 {
996 tree arg = gimple_call_arg (call, i);
997 if (TREE_CODE (arg) == SSA_NAME
998 || is_gimple_min_invariant (arg))
999 continue;
1000 if (TREE_CODE (arg) == WITH_SIZE_EXPR)
1001 arg = TREE_OPERAND (arg, 0);
1002 if (!ref_may_be_aliased (arg))
1003 mark_aliased_reaching_defs_necessary (call, arg);
1004 }
1005 }
1006 else if (gimple_assign_single_p (stmt))
1007 {
1008 tree rhs;
1009 /* If this is a load mark things necessary. */
1010 rhs = gimple_assign_rhs1 (stmt);
1011 if (TREE_CODE (rhs) != SSA_NAME
1012 && !is_gimple_min_invariant (rhs)
1013 && TREE_CODE (rhs) != CONSTRUCTOR)
1014 {
1015 if (!ref_may_be_aliased (rhs))
1016 mark_aliased_reaching_defs_necessary (stmt, rhs);
1017 else
1018 mark_all_reaching_defs_necessary (stmt);
1019 }
1020 }
1021 else if (greturn *return_stmt = dyn_cast <greturn *> (stmt))
1022 {
1023 tree rhs = gimple_return_retval (return_stmt);
1024 /* A return statement may perform a load. */
1025 if (rhs
1026 && TREE_CODE (rhs) != SSA_NAME
1027 && !is_gimple_min_invariant (rhs)
1028 && TREE_CODE (rhs) != CONSTRUCTOR)
1029 {
1030 if (!ref_may_be_aliased (rhs))
1031 mark_aliased_reaching_defs_necessary (stmt, rhs);
1032 else
1033 mark_all_reaching_defs_necessary (stmt);
1034 }
1035 }
1036 else if (gasm *asm_stmt = dyn_cast <gasm *> (stmt))
1037 {
1038 unsigned i;
1039 mark_all_reaching_defs_necessary (stmt);
1040 /* Inputs may perform loads. */
1041 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
1042 {
1043 tree op = TREE_VALUE (gimple_asm_input_op (asm_stmt, i));
1044 if (TREE_CODE (op) != SSA_NAME
1045 && !is_gimple_min_invariant (op)
1046 && TREE_CODE (op) != CONSTRUCTOR
1047 && !ref_may_be_aliased (op))
1048 mark_aliased_reaching_defs_necessary (stmt, op);
1049 }
1050 }
1051 else if (gimple_code (stmt) == GIMPLE_TRANSACTION)
1052 {
1053 /* The beginning of a transaction is a memory barrier. */
1054 /* ??? If we were really cool, we'd only be a barrier
1055 for the memories touched within the transaction. */
1056 mark_all_reaching_defs_necessary (stmt);
1057 }
1058 else
1059 gcc_unreachable ();
1060
1061 /* If we over-used our alias oracle budget drop to simple
1062 mode. The cost metric allows quadratic behavior
1063 (number of uses times number of may-defs queries) up to
1064 a constant maximal number of queries and after that falls back to
1065 super-linear complexity. */
1066 if (/* Constant but quadratic for small functions. */
1067 total_chain > 128 * 128
1068 /* Linear in the number of may-defs. */
1069 && total_chain > 32 * longest_chain
1070 /* Linear in the number of uses. */
1071 && total_chain > nr_walks * 32)
1072 {
1073 chain_ovfl = true;
1074 if (visited)
1075 bitmap_clear (visited);
1076 }
1077 }
1078 }
1079 }
1080
1081 /* Remove dead PHI nodes from block BB. */
1082
1083 static bool
1084 remove_dead_phis (basic_block bb)
1085 {
1086 bool something_changed = false;
1087 gphi *phi;
1088 gphi_iterator gsi;
1089
1090 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);)
1091 {
1092 stats.total_phis++;
1093 phi = gsi.phi ();
1094
1095 /* We do not track necessity of virtual PHI nodes. Instead do
1096 very simple dead PHI removal here. */
1097 if (virtual_operand_p (gimple_phi_result (phi)))
1098 {
1099 /* Virtual PHI nodes with one or identical arguments
1100 can be removed. */
1101 if (!loops_state_satisfies_p (LOOP_CLOSED_SSA)
1102 && degenerate_phi_p (phi))
1103 {
1104 tree vdef = gimple_phi_result (phi);
1105 tree vuse = gimple_phi_arg_def (phi, 0);
1106
1107 use_operand_p use_p;
1108 imm_use_iterator iter;
1109 gimple *use_stmt;
1110 FOR_EACH_IMM_USE_STMT (use_stmt, iter, vdef)
1111 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
1112 SET_USE (use_p, vuse);
1113 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vdef)
1114 && TREE_CODE (vuse) == SSA_NAME)
1115 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (vuse) = 1;
1116 }
1117 else
1118 gimple_set_plf (phi, STMT_NECESSARY, true);
1119 }
1120
1121 if (!gimple_plf (phi, STMT_NECESSARY))
1122 {
1123 something_changed = true;
1124 if (dump_file && (dump_flags & TDF_DETAILS))
1125 {
1126 fprintf (dump_file, "Deleting : ");
1127 print_gimple_stmt (dump_file, phi, 0, TDF_SLIM);
1128 fprintf (dump_file, "\n");
1129 }
1130
1131 remove_phi_node (&gsi, true);
1132 stats.removed_phis++;
1133 continue;
1134 }
1135
1136 gsi_next (&gsi);
1137 }
1138 return something_changed;
1139 }
1140
1141
1142 /* Remove dead statement pointed to by iterator I. Receives the basic block BB
1143 containing I so that we don't have to look it up. */
1144
1145 static void
1146 remove_dead_stmt (gimple_stmt_iterator *i, basic_block bb,
1147 vec<edge> &to_remove_edges)
1148 {
1149 gimple *stmt = gsi_stmt (*i);
1150
1151 if (dump_file && (dump_flags & TDF_DETAILS))
1152 {
1153 fprintf (dump_file, "Deleting : ");
1154 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1155 fprintf (dump_file, "\n");
1156 }
1157
1158 stats.removed++;
1159
1160 /* If we have determined that a conditional branch statement contributes
1161 nothing to the program, then we not only remove it, but we need to update
1162 the CFG. We can chose any of edges out of BB as long as we are sure to not
1163 close infinite loops. This is done by always choosing the edge closer to
1164 exit in inverted_rev_post_order_compute order. */
1165 if (is_ctrl_stmt (stmt))
1166 {
1167 edge_iterator ei;
1168 edge e = NULL, e2;
1169
1170 /* See if there is only one non-abnormal edge. */
1171 if (single_succ_p (bb))
1172 e = single_succ_edge (bb);
1173 /* Otherwise chose one that is closer to bb with live statement in it.
1174 To be able to chose one, we compute inverted post order starting from
1175 all BBs with live statements. */
1176 if (!e)
1177 {
1178 if (!bb_postorder)
1179 {
1180 int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
1181 int n = inverted_rev_post_order_compute (cfun, rpo,
1182 &bb_contains_live_stmts);
1183 bb_postorder = XNEWVEC (int, last_basic_block_for_fn (cfun));
1184 for (int i = 0; i < n; ++i)
1185 bb_postorder[rpo[i]] = i;
1186 free (rpo);
1187 }
1188 FOR_EACH_EDGE (e2, ei, bb->succs)
1189 if (!e || e2->dest == EXIT_BLOCK_PTR_FOR_FN (cfun)
1190 || bb_postorder [e->dest->index]
1191 >= bb_postorder [e2->dest->index])
1192 e = e2;
1193 }
1194 gcc_assert (e);
1195 e->probability = profile_probability::always ();
1196
1197 /* The edge is no longer associated with a conditional, so it does
1198 not have TRUE/FALSE flags.
1199 We are also safe to drop EH/ABNORMAL flags and turn them into
1200 normal control flow, because we know that all the destinations (including
1201 those odd edges) are equivalent for program execution. */
1202 e->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE | EDGE_EH | EDGE_ABNORMAL);
1203
1204 /* The lone outgoing edge from BB will be a fallthru edge. */
1205 e->flags |= EDGE_FALLTHRU;
1206
1207 /* Remove the remaining outgoing edges. */
1208 FOR_EACH_EDGE (e2, ei, bb->succs)
1209 if (e != e2)
1210 {
1211 /* If we made a BB unconditionally exit a loop or removed
1212 an entry into an irreducible region, then this transform
1213 alters the set of BBs in the loop. Schedule a fixup. */
1214 if (loop_exit_edge_p (bb->loop_father, e)
1215 || (e2->dest->flags & BB_IRREDUCIBLE_LOOP))
1216 loops_state_set (LOOPS_NEED_FIXUP);
1217 to_remove_edges.safe_push (e2);
1218 }
1219 }
1220
1221 /* If this is a store into a variable that is being optimized away,
1222 add a debug bind stmt if possible. */
1223 if (MAY_HAVE_DEBUG_BIND_STMTS
1224 && gimple_assign_single_p (stmt)
1225 && is_gimple_val (gimple_assign_rhs1 (stmt)))
1226 {
1227 tree lhs = gimple_assign_lhs (stmt);
1228 if ((VAR_P (lhs) || TREE_CODE (lhs) == PARM_DECL)
1229 && !DECL_IGNORED_P (lhs)
1230 && is_gimple_reg_type (TREE_TYPE (lhs))
1231 && !is_global_var (lhs)
1232 && !DECL_HAS_VALUE_EXPR_P (lhs))
1233 {
1234 tree rhs = gimple_assign_rhs1 (stmt);
1235 gdebug *note
1236 = gimple_build_debug_bind (lhs, unshare_expr (rhs), stmt);
1237 gsi_insert_after (i, note, GSI_SAME_STMT);
1238 }
1239 }
1240
1241 unlink_stmt_vdef (stmt);
1242 gsi_remove (i, true);
1243 release_defs (stmt);
1244 }
1245
1246 /* Helper for maybe_optimize_arith_overflow. Find in *TP if there are any
1247 uses of data (SSA_NAME) other than REALPART_EXPR referencing it. */
1248
1249 static tree
1250 find_non_realpart_uses (tree *tp, int *walk_subtrees, void *data)
1251 {
1252 if (TYPE_P (*tp) || TREE_CODE (*tp) == REALPART_EXPR)
1253 *walk_subtrees = 0;
1254 if (*tp == (tree) data)
1255 return *tp;
1256 return NULL_TREE;
1257 }
1258
1259 /* If the IMAGPART_EXPR of the {ADD,SUB,MUL}_OVERFLOW result is never used,
1260 but REALPART_EXPR is, optimize the {ADD,SUB,MUL}_OVERFLOW internal calls
1261 into plain unsigned {PLUS,MINUS,MULT}_EXPR, and if needed reset debug
1262 uses. */
1263
1264 static void
1265 maybe_optimize_arith_overflow (gimple_stmt_iterator *gsi,
1266 enum tree_code subcode)
1267 {
1268 gimple *stmt = gsi_stmt (*gsi);
1269 tree lhs = gimple_call_lhs (stmt);
1270
1271 if (lhs == NULL || TREE_CODE (lhs) != SSA_NAME)
1272 return;
1273
1274 imm_use_iterator imm_iter;
1275 use_operand_p use_p;
1276 bool has_debug_uses = false;
1277 bool has_realpart_uses = false;
1278 bool has_other_uses = false;
1279 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, lhs)
1280 {
1281 gimple *use_stmt = USE_STMT (use_p);
1282 if (is_gimple_debug (use_stmt))
1283 has_debug_uses = true;
1284 else if (is_gimple_assign (use_stmt)
1285 && gimple_assign_rhs_code (use_stmt) == REALPART_EXPR
1286 && TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) == lhs)
1287 has_realpart_uses = true;
1288 else
1289 {
1290 has_other_uses = true;
1291 break;
1292 }
1293 }
1294
1295 if (!has_realpart_uses || has_other_uses)
1296 return;
1297
1298 tree arg0 = gimple_call_arg (stmt, 0);
1299 tree arg1 = gimple_call_arg (stmt, 1);
1300 location_t loc = gimple_location (stmt);
1301 tree type = TREE_TYPE (TREE_TYPE (lhs));
1302 tree utype = unsigned_type_for (type);
1303 tree result = fold_build2_loc (loc, subcode, utype,
1304 fold_convert_loc (loc, utype, arg0),
1305 fold_convert_loc (loc, utype, arg1));
1306 result = fold_convert_loc (loc, type, result);
1307
1308 if (has_debug_uses)
1309 {
1310 gimple *use_stmt;
1311 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, lhs)
1312 {
1313 if (!gimple_debug_bind_p (use_stmt))
1314 continue;
1315 tree v = gimple_debug_bind_get_value (use_stmt);
1316 if (walk_tree (&v, find_non_realpart_uses, lhs, NULL))
1317 {
1318 gimple_debug_bind_reset_value (use_stmt);
1319 update_stmt (use_stmt);
1320 }
1321 }
1322 }
1323
1324 if (TREE_CODE (result) == INTEGER_CST && TREE_OVERFLOW (result))
1325 result = drop_tree_overflow (result);
1326 tree overflow = build_zero_cst (type);
1327 tree ctype = build_complex_type (type);
1328 if (TREE_CODE (result) == INTEGER_CST)
1329 result = build_complex (ctype, result, overflow);
1330 else
1331 result = build2_loc (gimple_location (stmt), COMPLEX_EXPR,
1332 ctype, result, overflow);
1333
1334 if (dump_file && (dump_flags & TDF_DETAILS))
1335 {
1336 fprintf (dump_file, "Transforming call: ");
1337 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1338 fprintf (dump_file, "because the overflow result is never used into: ");
1339 print_generic_stmt (dump_file, result, TDF_SLIM);
1340 fprintf (dump_file, "\n");
1341 }
1342
1343 gimplify_and_update_call_from_tree (gsi, result);
1344 }
1345
1346 /* Returns whether the control parents of BB are preserved. */
1347
1348 static bool
1349 control_parents_preserved_p (basic_block bb)
1350 {
1351 /* If we marked the control parents from BB they are preserved. */
1352 if (bitmap_bit_p (visited_control_parents, bb->index))
1353 return true;
1354
1355 /* But they can also end up being marked from elsewhere. */
1356 bitmap_iterator bi;
1357 unsigned edge_number;
1358 EXECUTE_IF_SET_IN_BITMAP (cd->get_edges_dependent_on (bb->index),
1359 0, edge_number, bi)
1360 {
1361 basic_block cd_bb = cd->get_edge_src (edge_number);
1362 if (cd_bb != bb
1363 && !bitmap_bit_p (last_stmt_necessary, cd_bb->index))
1364 return false;
1365 }
1366 /* And cache the result. */
1367 bitmap_set_bit (visited_control_parents, bb->index);
1368 return true;
1369 }
1370
1371 /* Eliminate unnecessary statements. Any instruction not marked as necessary
1372 contributes nothing to the program, and can be deleted. */
1373
1374 static bool
1375 eliminate_unnecessary_stmts (bool aggressive)
1376 {
1377 bool something_changed = false;
1378 basic_block bb;
1379 gimple_stmt_iterator gsi, psi;
1380 gimple *stmt;
1381 tree call;
1382 auto_vec<edge> to_remove_edges;
1383
1384 if (dump_file && (dump_flags & TDF_DETAILS))
1385 fprintf (dump_file, "\nEliminating unnecessary statements:\n");
1386
1387 bool had_setjmp = cfun->calls_setjmp;
1388 clear_special_calls ();
1389
1390 /* Walking basic blocks and statements in reverse order avoids
1391 releasing SSA names before any other DEFs that refer to them are
1392 released. This helps avoid loss of debug information, as we get
1393 a chance to propagate all RHSs of removed SSAs into debug uses,
1394 rather than only the latest ones. E.g., consider:
1395
1396 x_3 = y_1 + z_2;
1397 a_5 = x_3 - b_4;
1398 # DEBUG a => a_5
1399
1400 If we were to release x_3 before a_5, when we reached a_5 and
1401 tried to substitute it into the debug stmt, we'd see x_3 there,
1402 but x_3's DEF, type, etc would have already been disconnected.
1403 By going backwards, the debug stmt first changes to:
1404
1405 # DEBUG a => x_3 - b_4
1406
1407 and then to:
1408
1409 # DEBUG a => y_1 + z_2 - b_4
1410
1411 as desired. */
1412 gcc_assert (dom_info_available_p (CDI_DOMINATORS));
1413 auto_vec<basic_block> h;
1414 h = get_all_dominated_blocks (CDI_DOMINATORS,
1415 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
1416
1417 while (h.length ())
1418 {
1419 bb = h.pop ();
1420
1421 /* Remove dead statements. */
1422 auto_bitmap debug_seen;
1423 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi = psi)
1424 {
1425 stmt = gsi_stmt (gsi);
1426
1427 psi = gsi;
1428 gsi_prev (&psi);
1429
1430 stats.total++;
1431
1432 /* We can mark a call to free as not necessary if the
1433 defining statement of its argument is not necessary
1434 (and thus is getting removed). */
1435 if (gimple_plf (stmt, STMT_NECESSARY)
1436 && (gimple_call_builtin_p (stmt, BUILT_IN_FREE)
1437 || (is_gimple_call (stmt)
1438 && gimple_call_from_new_or_delete (as_a <gcall *> (stmt))
1439 && gimple_call_operator_delete_p (as_a <gcall *> (stmt)))))
1440 {
1441 tree ptr = gimple_call_arg (stmt, 0);
1442 if (TREE_CODE (ptr) == SSA_NAME)
1443 {
1444 gimple *def_stmt = SSA_NAME_DEF_STMT (ptr);
1445 if (!gimple_nop_p (def_stmt)
1446 && !gimple_plf (def_stmt, STMT_NECESSARY))
1447 gimple_set_plf (stmt, STMT_NECESSARY, false);
1448 }
1449 }
1450
1451 /* If GSI is not necessary then remove it. */
1452 if (!gimple_plf (stmt, STMT_NECESSARY))
1453 {
1454 /* Keep clobbers that we can keep live live. */
1455 if (gimple_clobber_p (stmt))
1456 {
1457 ssa_op_iter iter;
1458 use_operand_p use_p;
1459 bool dead = false;
1460 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
1461 {
1462 tree name = USE_FROM_PTR (use_p);
1463 if (!SSA_NAME_IS_DEFAULT_DEF (name)
1464 && !bitmap_bit_p (processed, SSA_NAME_VERSION (name)))
1465 {
1466 dead = true;
1467 break;
1468 }
1469 }
1470 if (!dead
1471 /* When doing CD-DCE we have to ensure all controls
1472 of the stmt are still live. */
1473 && (!aggressive || control_parents_preserved_p (bb)))
1474 {
1475 bitmap_clear (debug_seen);
1476 continue;
1477 }
1478 }
1479 if (!is_gimple_debug (stmt))
1480 something_changed = true;
1481 remove_dead_stmt (&gsi, bb, to_remove_edges);
1482 continue;
1483 }
1484 else if (is_gimple_call (stmt))
1485 {
1486 tree name = gimple_call_lhs (stmt);
1487
1488 notice_special_calls (as_a <gcall *> (stmt));
1489
1490 /* When LHS of var = call (); is dead, simplify it into
1491 call (); saving one operand. */
1492 if (name
1493 && TREE_CODE (name) == SSA_NAME
1494 && !bitmap_bit_p (processed, SSA_NAME_VERSION (name))
1495 /* Avoid doing so for allocation calls which we
1496 did not mark as necessary, it will confuse the
1497 special logic we apply to malloc/free pair removal. */
1498 && (!(call = gimple_call_fndecl (stmt))
1499 || ((DECL_BUILT_IN_CLASS (call) != BUILT_IN_NORMAL
1500 || (DECL_FUNCTION_CODE (call) != BUILT_IN_ALIGNED_ALLOC
1501 && DECL_FUNCTION_CODE (call) != BUILT_IN_MALLOC
1502 && DECL_FUNCTION_CODE (call) != BUILT_IN_CALLOC
1503 && !ALLOCA_FUNCTION_CODE_P
1504 (DECL_FUNCTION_CODE (call))))
1505 && !DECL_IS_REPLACEABLE_OPERATOR_NEW_P (call))))
1506 {
1507 something_changed = true;
1508 if (dump_file && (dump_flags & TDF_DETAILS))
1509 {
1510 fprintf (dump_file, "Deleting LHS of call: ");
1511 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
1512 fprintf (dump_file, "\n");
1513 }
1514
1515 gimple_call_set_lhs (stmt, NULL_TREE);
1516 maybe_clean_or_replace_eh_stmt (stmt, stmt);
1517 update_stmt (stmt);
1518 release_ssa_name (name);
1519
1520 /* GOMP_SIMD_LANE (unless three argument) or ASAN_POISON
1521 without lhs is not needed. */
1522 if (gimple_call_internal_p (stmt))
1523 switch (gimple_call_internal_fn (stmt))
1524 {
1525 case IFN_GOMP_SIMD_LANE:
1526 if (gimple_call_num_args (stmt) >= 3
1527 && !integer_nonzerop (gimple_call_arg (stmt, 2)))
1528 break;
1529 /* FALLTHRU */
1530 case IFN_ASAN_POISON:
1531 remove_dead_stmt (&gsi, bb, to_remove_edges);
1532 break;
1533 default:
1534 break;
1535 }
1536 }
1537 else if (gimple_call_internal_p (stmt))
1538 switch (gimple_call_internal_fn (stmt))
1539 {
1540 case IFN_ADD_OVERFLOW:
1541 maybe_optimize_arith_overflow (&gsi, PLUS_EXPR);
1542 break;
1543 case IFN_SUB_OVERFLOW:
1544 maybe_optimize_arith_overflow (&gsi, MINUS_EXPR);
1545 break;
1546 case IFN_MUL_OVERFLOW:
1547 maybe_optimize_arith_overflow (&gsi, MULT_EXPR);
1548 break;
1549 case IFN_UADDC:
1550 if (integer_zerop (gimple_call_arg (stmt, 2)))
1551 maybe_optimize_arith_overflow (&gsi, PLUS_EXPR);
1552 break;
1553 case IFN_USUBC:
1554 if (integer_zerop (gimple_call_arg (stmt, 2)))
1555 maybe_optimize_arith_overflow (&gsi, MINUS_EXPR);
1556 break;
1557 default:
1558 break;
1559 }
1560 }
1561 else if (gimple_debug_bind_p (stmt))
1562 {
1563 /* We are only keeping the last debug-bind of a
1564 non-DEBUG_EXPR_DECL variable in a series of
1565 debug-bind stmts. */
1566 tree var = gimple_debug_bind_get_var (stmt);
1567 if (TREE_CODE (var) != DEBUG_EXPR_DECL
1568 && !bitmap_set_bit (debug_seen, DECL_UID (var)))
1569 remove_dead_stmt (&gsi, bb, to_remove_edges);
1570 continue;
1571 }
1572 bitmap_clear (debug_seen);
1573 }
1574
1575 /* Remove dead PHI nodes. */
1576 something_changed |= remove_dead_phis (bb);
1577 }
1578
1579 /* First remove queued edges. */
1580 if (!to_remove_edges.is_empty ())
1581 {
1582 /* Remove edges. We've delayed this to not get bogus debug stmts
1583 during PHI node removal. */
1584 for (unsigned i = 0; i < to_remove_edges.length (); ++i)
1585 remove_edge (to_remove_edges[i]);
1586 cfg_altered = true;
1587 }
1588 /* When we cleared calls_setjmp we can purge all abnormal edges. Do so.
1589 ??? We'd like to assert that setjmp calls do not pop out of nothing
1590 but we currently lack a per-stmt way of noting whether a call was
1591 recognized as returns-twice (or rather receives-control). */
1592 if (!cfun->calls_setjmp && had_setjmp)
1593 {
1594 /* Make sure we only remove the edges, not dominated blocks. Using
1595 gimple_purge_dead_abnormal_call_edges would do that and we
1596 cannot free dominators yet. */
1597 FOR_EACH_BB_FN (bb, cfun)
1598 if (gcall *stmt = safe_dyn_cast <gcall *> (*gsi_last_bb (bb)))
1599 if (!stmt_can_make_abnormal_goto (stmt))
1600 {
1601 edge_iterator ei;
1602 edge e;
1603 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
1604 {
1605 if (e->flags & EDGE_ABNORMAL)
1606 {
1607 if (e->flags & EDGE_FALLTHRU)
1608 e->flags &= ~EDGE_ABNORMAL;
1609 else
1610 remove_edge (e);
1611 cfg_altered = true;
1612 }
1613 else
1614 ei_next (&ei);
1615 }
1616 }
1617 }
1618
1619 /* Now remove the unreachable blocks. */
1620 if (cfg_altered)
1621 {
1622 basic_block prev_bb;
1623
1624 find_unreachable_blocks ();
1625
1626 /* Delete all unreachable basic blocks in reverse dominator order. */
1627 for (bb = EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb;
1628 bb != ENTRY_BLOCK_PTR_FOR_FN (cfun); bb = prev_bb)
1629 {
1630 prev_bb = bb->prev_bb;
1631
1632 if ((bb_contains_live_stmts
1633 && !bitmap_bit_p (bb_contains_live_stmts, bb->index))
1634 || !(bb->flags & BB_REACHABLE))
1635 {
1636 /* Since we don't track liveness of virtual PHI nodes, it is
1637 possible that we rendered some PHI nodes unreachable while
1638 they are still in use. Mark them for renaming. */
1639 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1640 gsi_next (&gsi))
1641 if (virtual_operand_p (gimple_phi_result (gsi.phi ())))
1642 {
1643 bool found = false;
1644 imm_use_iterator iter;
1645
1646 FOR_EACH_IMM_USE_STMT (stmt, iter,
1647 gimple_phi_result (gsi.phi ()))
1648 {
1649 if (!(gimple_bb (stmt)->flags & BB_REACHABLE))
1650 continue;
1651 if (gimple_code (stmt) == GIMPLE_PHI
1652 || gimple_plf (stmt, STMT_NECESSARY))
1653 {
1654 found = true;
1655 break;
1656 }
1657 }
1658 if (found)
1659 mark_virtual_phi_result_for_renaming (gsi.phi ());
1660 }
1661
1662 if (!(bb->flags & BB_REACHABLE))
1663 {
1664 /* Speed up the removal of blocks that don't
1665 dominate others. Walking backwards, this should
1666 be the common case. ??? Do we need to recompute
1667 dominators because of cfg_altered? */
1668 if (!first_dom_son (CDI_DOMINATORS, bb))
1669 delete_basic_block (bb);
1670 else
1671 {
1672 h = get_all_dominated_blocks (CDI_DOMINATORS, bb);
1673
1674 while (h.length ())
1675 {
1676 bb = h.pop ();
1677 prev_bb = bb->prev_bb;
1678 /* Rearrangements to the CFG may have failed
1679 to update the dominators tree, so that
1680 formerly-dominated blocks are now
1681 otherwise reachable. */
1682 if (!!(bb->flags & BB_REACHABLE))
1683 continue;
1684 delete_basic_block (bb);
1685 }
1686
1687 h.release ();
1688 }
1689 }
1690 }
1691 }
1692 }
1693
1694 if (bb_postorder)
1695 free (bb_postorder);
1696 bb_postorder = NULL;
1697
1698 return something_changed;
1699 }
1700
1701
1702 /* Print out removed statement statistics. */
1703
1704 static void
1705 print_stats (void)
1706 {
1707 float percg;
1708
1709 percg = ((float) stats.removed / (float) stats.total) * 100;
1710 fprintf (dump_file, "Removed %d of %d statements (%d%%)\n",
1711 stats.removed, stats.total, (int) percg);
1712
1713 if (stats.total_phis == 0)
1714 percg = 0;
1715 else
1716 percg = ((float) stats.removed_phis / (float) stats.total_phis) * 100;
1717
1718 fprintf (dump_file, "Removed %d of %d PHI nodes (%d%%)\n",
1719 stats.removed_phis, stats.total_phis, (int) percg);
1720 }
1721
1722 /* Initialization for this pass. Set up the used data structures. */
1723
1724 static void
1725 tree_dce_init (bool aggressive)
1726 {
1727 memset ((void *) &stats, 0, sizeof (stats));
1728
1729 if (aggressive)
1730 {
1731 last_stmt_necessary = sbitmap_alloc (last_basic_block_for_fn (cfun));
1732 bitmap_clear (last_stmt_necessary);
1733 bb_contains_live_stmts = sbitmap_alloc (last_basic_block_for_fn (cfun));
1734 bitmap_clear (bb_contains_live_stmts);
1735 }
1736
1737 processed = sbitmap_alloc (num_ssa_names + 1);
1738 bitmap_clear (processed);
1739
1740 worklist.create (64);
1741 cfg_altered = false;
1742 }
1743
1744 /* Cleanup after this pass. */
1745
1746 static void
1747 tree_dce_done (bool aggressive)
1748 {
1749 if (aggressive)
1750 {
1751 delete cd;
1752 sbitmap_free (visited_control_parents);
1753 sbitmap_free (last_stmt_necessary);
1754 sbitmap_free (bb_contains_live_stmts);
1755 bb_contains_live_stmts = NULL;
1756 }
1757
1758 sbitmap_free (processed);
1759
1760 worklist.release ();
1761 }
1762
1763 /* Sort PHI argument values for make_forwarders_with_degenerate_phis. */
1764
1765 static int
1766 sort_phi_args (const void *a_, const void *b_)
1767 {
1768 auto *a = (const std::pair<edge, hashval_t> *) a_;
1769 auto *b = (const std::pair<edge, hashval_t> *) b_;
1770 hashval_t ha = a->second;
1771 hashval_t hb = b->second;
1772 if (ha < hb)
1773 return -1;
1774 else if (ha > hb)
1775 return 1;
1776 else if (a->first->dest_idx < b->first->dest_idx)
1777 return -1;
1778 else if (a->first->dest_idx > b->first->dest_idx)
1779 return 1;
1780 else
1781 return 0;
1782 }
1783
1784 /* Look for a non-virtual PHIs and make a forwarder block when all PHIs
1785 have the same argument on a set of edges. This is to not consider
1786 control dependences of individual edges for same values but only for
1787 the common set. */
1788
1789 static unsigned
1790 make_forwarders_with_degenerate_phis (function *fn)
1791 {
1792 unsigned todo = 0;
1793
1794 basic_block bb;
1795 FOR_EACH_BB_FN (bb, fn)
1796 {
1797 /* Only PHIs with three or more arguments have opportunities. */
1798 if (EDGE_COUNT (bb->preds) < 3)
1799 continue;
1800 /* Do not touch loop headers or blocks with abnormal predecessors.
1801 ??? This is to avoid creating valid loops here, see PR103458.
1802 We might want to improve things to either explicitely add those
1803 loops or at least consider blocks with no backedges. */
1804 if (bb->loop_father->header == bb
1805 || bb_has_abnormal_pred (bb))
1806 continue;
1807
1808 /* Take one PHI node as template to look for identical
1809 arguments. Build a vector of candidates forming sets
1810 of argument edges with equal values. Note optimality
1811 depends on the particular choice of the template PHI
1812 since equal arguments are unordered leaving other PHIs
1813 with more than one set of equal arguments within this
1814 argument range unsorted. We'd have to break ties by
1815 looking at other PHI nodes. */
1816 gphi_iterator gsi = gsi_start_nonvirtual_phis (bb);
1817 if (gsi_end_p (gsi))
1818 continue;
1819 gphi *phi = gsi.phi ();
1820 auto_vec<std::pair<edge, hashval_t>, 8> args;
1821 bool need_resort = false;
1822 for (unsigned i = 0; i < gimple_phi_num_args (phi); ++i)
1823 {
1824 edge e = gimple_phi_arg_edge (phi, i);
1825 /* Skip abnormal edges since we cannot redirect them. */
1826 if (e->flags & EDGE_ABNORMAL)
1827 continue;
1828 /* Skip loop exit edges when we are in loop-closed SSA form
1829 since the forwarder we'd create does not have a PHI node. */
1830 if (loops_state_satisfies_p (LOOP_CLOSED_SSA)
1831 && loop_exit_edge_p (e->src->loop_father, e))
1832 continue;
1833
1834 tree arg = gimple_phi_arg_def (phi, i);
1835 if (!CONSTANT_CLASS_P (arg) && TREE_CODE (arg) != SSA_NAME)
1836 need_resort = true;
1837 args.safe_push (std::make_pair (e, iterative_hash_expr (arg, 0)));
1838 }
1839 if (args.length () < 2)
1840 continue;
1841 args.qsort (sort_phi_args);
1842 /* The above sorting can be different between -g and -g0, as e.g. decls
1843 can have different uids (-g could have bigger gaps in between them).
1844 So, only use that to determine which args are equal, then change
1845 second from hash value to smallest dest_idx of the edges which have
1846 equal argument and sort again. If all the phi arguments are
1847 constants or SSA_NAME, there is no need for the second sort, the hash
1848 values are stable in that case. */
1849 hashval_t hash = args[0].second;
1850 args[0].second = args[0].first->dest_idx;
1851 bool any_equal = false;
1852 for (unsigned i = 1; i < args.length (); ++i)
1853 if (hash == args[i].second
1854 && operand_equal_p (PHI_ARG_DEF_FROM_EDGE (phi, args[i - 1].first),
1855 PHI_ARG_DEF_FROM_EDGE (phi, args[i].first)))
1856 {
1857 args[i].second = args[i - 1].second;
1858 any_equal = true;
1859 }
1860 else
1861 {
1862 hash = args[i].second;
1863 args[i].second = args[i].first->dest_idx;
1864 }
1865 if (!any_equal)
1866 continue;
1867 if (need_resort)
1868 args.qsort (sort_phi_args);
1869
1870 /* From the candidates vector now verify true candidates for
1871 forwarders and create them. */
1872 gphi *vphi = get_virtual_phi (bb);
1873 unsigned start = 0;
1874 while (start < args.length () - 1)
1875 {
1876 unsigned i;
1877 for (i = start + 1; i < args.length (); ++i)
1878 if (args[start].second != args[i].second)
1879 break;
1880 /* args[start]..args[i-1] are equal. */
1881 if (start != i - 1)
1882 {
1883 /* Check all PHI nodes for argument equality. */
1884 bool equal = true;
1885 gphi_iterator gsi2 = gsi;
1886 gsi_next (&gsi2);
1887 for (; !gsi_end_p (gsi2); gsi_next (&gsi2))
1888 {
1889 gphi *phi2 = gsi2.phi ();
1890 if (virtual_operand_p (gimple_phi_result (phi2)))
1891 continue;
1892 tree start_arg
1893 = PHI_ARG_DEF_FROM_EDGE (phi2, args[start].first);
1894 for (unsigned j = start + 1; j < i; ++j)
1895 {
1896 if (!operand_equal_p (start_arg,
1897 PHI_ARG_DEF_FROM_EDGE
1898 (phi2, args[j].first)))
1899 {
1900 /* Another PHI might have a shorter set of
1901 equivalent args. Go for that. */
1902 i = j;
1903 if (j == start + 1)
1904 equal = false;
1905 break;
1906 }
1907 }
1908 if (!equal)
1909 break;
1910 }
1911 if (equal)
1912 {
1913 /* If we are asked to forward all edges the block
1914 has all degenerate PHIs. Do nothing in that case. */
1915 if (start == 0
1916 && i == args.length ()
1917 && args.length () == gimple_phi_num_args (phi))
1918 break;
1919 /* Instead of using make_forwarder_block we are
1920 rolling our own variant knowing that the forwarder
1921 does not need PHI nodes apart from eventually
1922 a virtual one. */
1923 auto_vec<tree, 8> vphi_args;
1924 if (vphi)
1925 {
1926 vphi_args.reserve_exact (i - start);
1927 for (unsigned j = start; j < i; ++j)
1928 vphi_args.quick_push
1929 (PHI_ARG_DEF_FROM_EDGE (vphi, args[j].first));
1930 }
1931 free_dominance_info (fn, CDI_DOMINATORS);
1932 basic_block forwarder = split_edge (args[start].first);
1933 profile_count count = profile_count::zero ();
1934 for (unsigned j = start + 1; j < i; ++j)
1935 {
1936 edge e = args[j].first;
1937 redirect_edge_and_branch_force (e, forwarder);
1938 redirect_edge_var_map_clear (e);
1939 count += e->count ();
1940 }
1941 forwarder->count = count;
1942 if (vphi)
1943 {
1944 tree def = copy_ssa_name (vphi_args[0]);
1945 gphi *vphi_copy = create_phi_node (def, forwarder);
1946 for (unsigned j = start; j < i; ++j)
1947 add_phi_arg (vphi_copy, vphi_args[j - start],
1948 args[j].first, UNKNOWN_LOCATION);
1949 SET_PHI_ARG_DEF
1950 (vphi, single_succ_edge (forwarder)->dest_idx, def);
1951 }
1952 todo |= TODO_cleanup_cfg;
1953 }
1954 }
1955 /* Continue searching for more opportunities. */
1956 start = i;
1957 }
1958 }
1959 return todo;
1960 }
1961
1962 /* Main routine to eliminate dead code.
1963
1964 AGGRESSIVE controls the aggressiveness of the algorithm.
1965 In conservative mode, we ignore control dependence and simply declare
1966 all but the most trivially dead branches necessary. This mode is fast.
1967 In aggressive mode, control dependences are taken into account, which
1968 results in more dead code elimination, but at the cost of some time.
1969
1970 FIXME: Aggressive mode before PRE doesn't work currently because
1971 the dominance info is not invalidated after DCE1. This is
1972 not an issue right now because we only run aggressive DCE
1973 as the last tree SSA pass, but keep this in mind when you
1974 start experimenting with pass ordering. */
1975
1976 static unsigned int
1977 perform_tree_ssa_dce (bool aggressive)
1978 {
1979 bool something_changed = 0;
1980 unsigned todo = 0;
1981
1982 /* Preheaders are needed for SCEV to work.
1983 Simple lateches and recorded exits improve chances that loop will
1984 proved to be finite in testcases such as in loop-15.c and loop-24.c */
1985 bool in_loop_pipeline = scev_initialized_p ();
1986 if (aggressive && ! in_loop_pipeline)
1987 {
1988 loop_optimizer_init (LOOPS_NORMAL
1989 | LOOPS_HAVE_RECORDED_EXITS);
1990 scev_initialize ();
1991 }
1992
1993 if (aggressive)
1994 todo |= make_forwarders_with_degenerate_phis (cfun);
1995
1996 calculate_dominance_info (CDI_DOMINATORS);
1997
1998 tree_dce_init (aggressive);
1999
2000 if (aggressive)
2001 {
2002 /* Compute control dependence. */
2003 calculate_dominance_info (CDI_POST_DOMINATORS);
2004 cd = new control_dependences ();
2005
2006 visited_control_parents =
2007 sbitmap_alloc (last_basic_block_for_fn (cfun));
2008 bitmap_clear (visited_control_parents);
2009
2010 mark_dfs_back_edges ();
2011 }
2012
2013 find_obviously_necessary_stmts (aggressive);
2014
2015 if (aggressive && ! in_loop_pipeline)
2016 {
2017 scev_finalize ();
2018 loop_optimizer_finalize ();
2019 }
2020
2021 longest_chain = 0;
2022 total_chain = 0;
2023 nr_walks = 0;
2024 chain_ovfl = false;
2025 visited = BITMAP_ALLOC (NULL);
2026 propagate_necessity (aggressive);
2027 BITMAP_FREE (visited);
2028
2029 something_changed |= eliminate_unnecessary_stmts (aggressive);
2030 something_changed |= cfg_altered;
2031
2032 /* We do not update postdominators, so free them unconditionally. */
2033 free_dominance_info (CDI_POST_DOMINATORS);
2034
2035 /* If we removed paths in the CFG, then we need to update
2036 dominators as well. I haven't investigated the possibility
2037 of incrementally updating dominators. */
2038 if (cfg_altered)
2039 free_dominance_info (CDI_DOMINATORS);
2040
2041 statistics_counter_event (cfun, "Statements deleted", stats.removed);
2042 statistics_counter_event (cfun, "PHI nodes deleted", stats.removed_phis);
2043
2044 /* Debugging dumps. */
2045 if (dump_file && (dump_flags & (TDF_STATS|TDF_DETAILS)))
2046 print_stats ();
2047
2048 tree_dce_done (aggressive);
2049
2050 if (something_changed)
2051 {
2052 free_numbers_of_iterations_estimates (cfun);
2053 if (in_loop_pipeline)
2054 scev_reset ();
2055 todo |= TODO_update_ssa | TODO_cleanup_cfg;
2056 }
2057 return todo;
2058 }
2059
2060 /* Pass entry points. */
2061 static unsigned int
2062 tree_ssa_dce (void)
2063 {
2064 return perform_tree_ssa_dce (/*aggressive=*/false);
2065 }
2066
2067 static unsigned int
2068 tree_ssa_cd_dce (void)
2069 {
2070 return perform_tree_ssa_dce (/*aggressive=*/optimize >= 2);
2071 }
2072
2073 namespace {
2074
2075 const pass_data pass_data_dce =
2076 {
2077 GIMPLE_PASS, /* type */
2078 "dce", /* name */
2079 OPTGROUP_NONE, /* optinfo_flags */
2080 TV_TREE_DCE, /* tv_id */
2081 ( PROP_cfg | PROP_ssa ), /* properties_required */
2082 0, /* properties_provided */
2083 0, /* properties_destroyed */
2084 0, /* todo_flags_start */
2085 0, /* todo_flags_finish */
2086 };
2087
2088 class pass_dce : public gimple_opt_pass
2089 {
2090 public:
2091 pass_dce (gcc::context *ctxt)
2092 : gimple_opt_pass (pass_data_dce, ctxt), update_address_taken_p (false)
2093 {}
2094
2095 /* opt_pass methods: */
2096 opt_pass * clone () final override { return new pass_dce (m_ctxt); }
2097 void set_pass_param (unsigned n, bool param) final override
2098 {
2099 gcc_assert (n == 0);
2100 update_address_taken_p = param;
2101 }
2102 bool gate (function *) final override { return flag_tree_dce != 0; }
2103 unsigned int execute (function *) final override
2104 {
2105 return (tree_ssa_dce ()
2106 | (update_address_taken_p ? TODO_update_address_taken : 0));
2107 }
2108
2109 private:
2110 bool update_address_taken_p;
2111 }; // class pass_dce
2112
2113 } // anon namespace
2114
2115 gimple_opt_pass *
2116 make_pass_dce (gcc::context *ctxt)
2117 {
2118 return new pass_dce (ctxt);
2119 }
2120
2121 namespace {
2122
2123 const pass_data pass_data_cd_dce =
2124 {
2125 GIMPLE_PASS, /* type */
2126 "cddce", /* name */
2127 OPTGROUP_NONE, /* optinfo_flags */
2128 TV_TREE_CD_DCE, /* tv_id */
2129 ( PROP_cfg | PROP_ssa ), /* properties_required */
2130 0, /* properties_provided */
2131 0, /* properties_destroyed */
2132 0, /* todo_flags_start */
2133 0, /* todo_flags_finish */
2134 };
2135
2136 class pass_cd_dce : public gimple_opt_pass
2137 {
2138 public:
2139 pass_cd_dce (gcc::context *ctxt)
2140 : gimple_opt_pass (pass_data_cd_dce, ctxt), update_address_taken_p (false)
2141 {}
2142
2143 /* opt_pass methods: */
2144 opt_pass * clone () final override { return new pass_cd_dce (m_ctxt); }
2145 void set_pass_param (unsigned n, bool param) final override
2146 {
2147 gcc_assert (n == 0);
2148 update_address_taken_p = param;
2149 }
2150 bool gate (function *) final override { return flag_tree_dce != 0; }
2151 unsigned int execute (function *) final override
2152 {
2153 return (tree_ssa_cd_dce ()
2154 | (update_address_taken_p ? TODO_update_address_taken : 0));
2155 }
2156
2157 private:
2158 bool update_address_taken_p;
2159 }; // class pass_cd_dce
2160
2161 } // anon namespace
2162
2163 gimple_opt_pass *
2164 make_pass_cd_dce (gcc::context *ctxt)
2165 {
2166 return new pass_cd_dce (ctxt);
2167 }
2168
2169
2170 /* A cheap DCE interface. WORKLIST is a list of possibly dead stmts and
2171 is consumed by this function. The function has linear complexity in
2172 the number of dead stmts with a constant factor like the average SSA
2173 use operands number. */
2174
2175 void
2176 simple_dce_from_worklist (bitmap worklist, bitmap need_eh_cleanup)
2177 {
2178 int phiremoved = 0;
2179 int stmtremoved = 0;
2180 while (! bitmap_empty_p (worklist))
2181 {
2182 /* Pop item. */
2183 unsigned i = bitmap_clear_first_set_bit (worklist);
2184
2185 tree def = ssa_name (i);
2186 /* Removed by somebody else or still in use.
2187 Note use in itself for a phi node is not counted as still in use. */
2188 if (!def)
2189 continue;
2190 if (!has_zero_uses (def))
2191 {
2192 gimple *def_stmt = SSA_NAME_DEF_STMT (def);
2193
2194 if (gimple_code (def_stmt) != GIMPLE_PHI)
2195 continue;
2196
2197 gimple *use_stmt;
2198 imm_use_iterator use_iter;
2199 bool canremove = true;
2200
2201 FOR_EACH_IMM_USE_STMT (use_stmt, use_iter, def)
2202 {
2203 /* Ignore debug statements. */
2204 if (is_gimple_debug (use_stmt))
2205 continue;
2206 if (use_stmt != def_stmt)
2207 {
2208 canremove = false;
2209 break;
2210 }
2211 }
2212 if (!canremove)
2213 continue;
2214 }
2215
2216 gimple *t = SSA_NAME_DEF_STMT (def);
2217 if (gimple_has_side_effects (t))
2218 continue;
2219
2220 /* The defining statement needs to be defining only this name.
2221 ASM is the only statement that can define more than one
2222 name. */
2223 if (is_a<gasm *>(t)
2224 && !single_ssa_def_operand (t, SSA_OP_ALL_DEFS))
2225 continue;
2226
2227 /* Don't remove statements that are needed for non-call
2228 eh to work. */
2229 if (stmt_unremovable_because_of_non_call_eh_p (cfun, t))
2230 continue;
2231
2232 /* Tell the caller that we removed a statement that might
2233 throw so it could cleanup the cfg for that block. */
2234 if (need_eh_cleanup && stmt_could_throw_p (cfun, t))
2235 bitmap_set_bit (need_eh_cleanup, gimple_bb (t)->index);
2236
2237 /* Add uses to the worklist. */
2238 ssa_op_iter iter;
2239 use_operand_p use_p;
2240 FOR_EACH_PHI_OR_STMT_USE (use_p, t, iter, SSA_OP_USE)
2241 {
2242 tree use = USE_FROM_PTR (use_p);
2243 if (TREE_CODE (use) == SSA_NAME
2244 && ! SSA_NAME_IS_DEFAULT_DEF (use))
2245 bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
2246 }
2247
2248 /* Remove stmt. */
2249 if (dump_file && (dump_flags & TDF_DETAILS))
2250 {
2251 fprintf (dump_file, "Removing dead stmt:");
2252 print_gimple_stmt (dump_file, t, 0);
2253 }
2254 gimple_stmt_iterator gsi = gsi_for_stmt (t);
2255 if (gimple_code (t) == GIMPLE_PHI)
2256 {
2257 remove_phi_node (&gsi, true);
2258 phiremoved++;
2259 }
2260 else
2261 {
2262 unlink_stmt_vdef (t);
2263 gsi_remove (&gsi, true);
2264 release_defs (t);
2265 stmtremoved++;
2266 }
2267 }
2268 statistics_counter_event (cfun, "PHIs removed",
2269 phiremoved);
2270 statistics_counter_event (cfun, "Statements removed",
2271 stmtremoved);
2272 }