* tree-cfg.c (cleanup_tree_cfg): Pull a call to
[official-gcc.git] / gcc / tree-cfg.c
blob72f73784d6055289ad1c5c78398a9edf92aeff32
1 /* Control flow functions for trees.
2 Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING. If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "rtl.h"
28 #include "tm_p.h"
29 #include "hard-reg-set.h"
30 #include "basic-block.h"
31 #include "output.h"
32 #include "errors.h"
33 #include "flags.h"
34 #include "function.h"
35 #include "expr.h"
36 #include "ggc.h"
37 #include "langhooks.h"
38 #include "diagnostic.h"
39 #include "tree-flow.h"
40 #include "timevar.h"
41 #include "tree-dump.h"
42 #include "tree-pass.h"
43 #include "toplev.h"
44 #include "except.h"
45 #include "cfgloop.h"
46 #include "cfglayout.h"
48 /* This file contains functions for building the Control Flow Graph (CFG)
49 for a function tree. */
51 /* Local declarations. */
53 /* Initial capacity for the basic block array. */
54 static const int initial_cfg_capacity = 20;
56 /* Mapping of labels to their associated blocks. This can greatly speed up
57 building of the CFG in code with lots of gotos. */
58 static GTY(()) varray_type label_to_block_map;
60 /* CFG statistics. */
61 struct cfg_stats_d
63 long num_merged_labels;
66 static struct cfg_stats_d cfg_stats;
68 /* Nonzero if we found a computed goto while building basic blocks. */
69 static bool found_computed_goto;
71 /* Basic blocks and flowgraphs. */
72 static basic_block create_bb (void *, void *, basic_block);
73 static void create_block_annotation (basic_block);
74 static void free_blocks_annotations (void);
75 static void clear_blocks_annotations (void);
76 static void make_blocks (tree);
77 static void factor_computed_gotos (void);
79 /* Edges. */
80 static void make_edges (void);
81 static void make_ctrl_stmt_edges (basic_block);
82 static void make_exit_edges (basic_block);
83 static void make_cond_expr_edges (basic_block);
84 static void make_switch_expr_edges (basic_block);
85 static void make_goto_expr_edges (basic_block);
86 static edge tree_redirect_edge_and_branch (edge, basic_block);
87 static edge tree_try_redirect_by_replacing_jump (edge, basic_block);
88 static void split_critical_edges (void);
90 /* Various helpers. */
91 static inline bool stmt_starts_bb_p (tree, tree);
92 static int tree_verify_flow_info (void);
93 static void tree_make_forwarder_block (edge);
94 static bool thread_jumps (void);
95 static bool tree_forwarder_block_p (basic_block);
96 static void bsi_commit_edge_inserts_1 (edge e);
97 static void tree_cfg2vcg (FILE *);
99 /* Flowgraph optimization and cleanup. */
100 static void tree_merge_blocks (basic_block, basic_block);
101 static bool tree_can_merge_blocks_p (basic_block, basic_block);
102 static void remove_bb (basic_block);
103 static bool cleanup_control_flow (void);
104 static bool cleanup_control_expr_graph (basic_block, block_stmt_iterator);
105 static edge find_taken_edge_cond_expr (basic_block, tree);
106 static edge find_taken_edge_switch_expr (basic_block, tree);
107 static tree find_case_label_for_value (tree, tree);
108 static bool phi_alternatives_equal (basic_block, edge, edge);
111 /*---------------------------------------------------------------------------
112 Create basic blocks
113 ---------------------------------------------------------------------------*/
115 /* Entry point to the CFG builder for trees. TP points to the list of
116 statements to be added to the flowgraph. */
118 static void
119 build_tree_cfg (tree *tp)
121 /* Register specific tree functions. */
122 tree_register_cfg_hooks ();
124 /* Initialize rbi_pool. */
125 alloc_rbi_pool ();
127 /* Initialize the basic block array. */
128 init_flow ();
129 profile_status = PROFILE_ABSENT;
130 n_basic_blocks = 0;
131 last_basic_block = 0;
132 VARRAY_BB_INIT (basic_block_info, initial_cfg_capacity, "basic_block_info");
133 memset ((void *) &cfg_stats, 0, sizeof (cfg_stats));
135 /* Build a mapping of labels to their associated blocks. */
136 VARRAY_BB_INIT (label_to_block_map, initial_cfg_capacity,
137 "label to block map");
139 ENTRY_BLOCK_PTR->next_bb = EXIT_BLOCK_PTR;
140 EXIT_BLOCK_PTR->prev_bb = ENTRY_BLOCK_PTR;
142 found_computed_goto = 0;
143 make_blocks (*tp);
145 /* Computed gotos are hell to deal with, especially if there are
146 lots of them with a large number of destinations. So we factor
147 them to a common computed goto location before we build the
148 edge list. After we convert back to normal form, we will un-factor
149 the computed gotos since factoring introduces an unwanted jump. */
150 if (found_computed_goto)
151 factor_computed_gotos ();
153 /* Make sure there is always at least one block, even if its empty. */
154 if (n_basic_blocks == 0)
155 create_empty_bb (ENTRY_BLOCK_PTR);
157 create_block_annotation (ENTRY_BLOCK_PTR);
158 create_block_annotation (EXIT_BLOCK_PTR);
160 /* Adjust the size of the array. */
161 VARRAY_GROW (basic_block_info, n_basic_blocks);
163 /* To speed up statement iterator walks, we first purge dead labels. */
164 cleanup_dead_labels ();
166 /* Group case nodes to reduce the number of edges.
167 We do this after cleaning up dead labels because otherwise we miss
168 a lot of obvious case merging opportunities. */
169 group_case_labels ();
171 /* Create the edges of the flowgraph. */
172 make_edges ();
174 /* Debugging dumps. */
176 /* Write the flowgraph to a VCG file. */
178 int local_dump_flags;
179 FILE *dump_file = dump_begin (TDI_vcg, &local_dump_flags);
180 if (dump_file)
182 tree_cfg2vcg (dump_file);
183 dump_end (TDI_vcg, dump_file);
187 /* Dump a textual representation of the flowgraph. */
188 if (dump_file)
189 dump_tree_cfg (dump_file, dump_flags);
192 static void
193 execute_build_cfg (void)
195 build_tree_cfg (&DECL_SAVED_TREE (current_function_decl));
198 struct tree_opt_pass pass_build_cfg =
200 "cfg", /* name */
201 NULL, /* gate */
202 execute_build_cfg, /* execute */
203 NULL, /* sub */
204 NULL, /* next */
205 0, /* static_pass_number */
206 TV_TREE_CFG, /* tv_id */
207 PROP_gimple_leh, /* properties_required */
208 PROP_cfg, /* properties_provided */
209 0, /* properties_destroyed */
210 0, /* todo_flags_start */
211 TODO_verify_stmts, /* todo_flags_finish */
212 0 /* letter */
215 /* Search the CFG for any computed gotos. If found, factor them to a
216 common computed goto site. Also record the location of that site so
217 that we can un-factor the gotos after we have converted back to
218 normal form. */
220 static void
221 factor_computed_gotos (void)
223 basic_block bb;
224 tree factored_label_decl = NULL;
225 tree var = NULL;
226 tree factored_computed_goto_label = NULL;
227 tree factored_computed_goto = NULL;
229 /* We know there are one or more computed gotos in this function.
230 Examine the last statement in each basic block to see if the block
231 ends with a computed goto. */
233 FOR_EACH_BB (bb)
235 block_stmt_iterator bsi = bsi_last (bb);
236 tree last;
238 if (bsi_end_p (bsi))
239 continue;
240 last = bsi_stmt (bsi);
242 /* Ignore the computed goto we create when we factor the original
243 computed gotos. */
244 if (last == factored_computed_goto)
245 continue;
247 /* If the last statement is a computed goto, factor it. */
248 if (computed_goto_p (last))
250 tree assignment;
252 /* The first time we find a computed goto we need to create
253 the factored goto block and the variable each original
254 computed goto will use for their goto destination. */
255 if (! factored_computed_goto)
257 basic_block new_bb = create_empty_bb (bb);
258 block_stmt_iterator new_bsi = bsi_start (new_bb);
260 /* Create the destination of the factored goto. Each original
261 computed goto will put its desired destination into this
262 variable and jump to the label we create immediately
263 below. */
264 var = create_tmp_var (ptr_type_node, "gotovar");
266 /* Build a label for the new block which will contain the
267 factored computed goto. */
268 factored_label_decl = create_artificial_label ();
269 factored_computed_goto_label
270 = build1 (LABEL_EXPR, void_type_node, factored_label_decl);
271 bsi_insert_after (&new_bsi, factored_computed_goto_label,
272 BSI_NEW_STMT);
274 /* Build our new computed goto. */
275 factored_computed_goto = build1 (GOTO_EXPR, void_type_node, var);
276 bsi_insert_after (&new_bsi, factored_computed_goto,
277 BSI_NEW_STMT);
280 /* Copy the original computed goto's destination into VAR. */
281 assignment = build (MODIFY_EXPR, ptr_type_node,
282 var, GOTO_DESTINATION (last));
283 bsi_insert_before (&bsi, assignment, BSI_SAME_STMT);
285 /* And re-vector the computed goto to the new destination. */
286 GOTO_DESTINATION (last) = factored_label_decl;
292 /* Create annotations for a single basic block. */
294 static void
295 create_block_annotation (basic_block bb)
297 /* Verify that the tree_annotations field is clear. */
298 gcc_assert (!bb->tree_annotations);
299 bb->tree_annotations = ggc_alloc_cleared (sizeof (struct bb_ann_d));
303 /* Free the annotations for all the basic blocks. */
305 static void free_blocks_annotations (void)
307 clear_blocks_annotations ();
311 /* Clear the annotations for all the basic blocks. */
313 static void
314 clear_blocks_annotations (void)
316 basic_block bb;
318 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, NULL, next_bb)
319 bb->tree_annotations = NULL;
323 /* Build a flowgraph for the statement_list STMT_LIST. */
325 static void
326 make_blocks (tree stmt_list)
328 tree_stmt_iterator i = tsi_start (stmt_list);
329 tree stmt = NULL;
330 bool start_new_block = true;
331 bool first_stmt_of_list = true;
332 basic_block bb = ENTRY_BLOCK_PTR;
334 while (!tsi_end_p (i))
336 tree prev_stmt;
338 prev_stmt = stmt;
339 stmt = tsi_stmt (i);
341 /* If the statement starts a new basic block or if we have determined
342 in a previous pass that we need to create a new block for STMT, do
343 so now. */
344 if (start_new_block || stmt_starts_bb_p (stmt, prev_stmt))
346 if (!first_stmt_of_list)
347 stmt_list = tsi_split_statement_list_before (&i);
348 bb = create_basic_block (stmt_list, NULL, bb);
349 start_new_block = false;
352 /* Now add STMT to BB and create the subgraphs for special statement
353 codes. */
354 set_bb_for_stmt (stmt, bb);
356 if (computed_goto_p (stmt))
357 found_computed_goto = true;
359 /* If STMT is a basic block terminator, set START_NEW_BLOCK for the
360 next iteration. */
361 if (stmt_ends_bb_p (stmt))
362 start_new_block = true;
364 tsi_next (&i);
365 first_stmt_of_list = false;
370 /* Create and return a new empty basic block after bb AFTER. */
372 static basic_block
373 create_bb (void *h, void *e, basic_block after)
375 basic_block bb;
377 gcc_assert (!e);
379 /* Create and initialize a new basic block. */
380 bb = alloc_block ();
381 memset (bb, 0, sizeof (*bb));
383 bb->index = last_basic_block;
384 bb->flags = BB_NEW;
385 bb->stmt_list = h ? h : alloc_stmt_list ();
387 /* Add the new block to the linked list of blocks. */
388 link_block (bb, after);
390 /* Grow the basic block array if needed. */
391 if ((size_t) last_basic_block == VARRAY_SIZE (basic_block_info))
393 size_t new_size = last_basic_block + (last_basic_block + 3) / 4;
394 VARRAY_GROW (basic_block_info, new_size);
397 /* Add the newly created block to the array. */
398 BASIC_BLOCK (last_basic_block) = bb;
400 create_block_annotation (bb);
402 n_basic_blocks++;
403 last_basic_block++;
405 initialize_bb_rbi (bb);
406 return bb;
410 /*---------------------------------------------------------------------------
411 Edge creation
412 ---------------------------------------------------------------------------*/
414 /* Join all the blocks in the flowgraph. */
416 static void
417 make_edges (void)
419 basic_block bb;
421 /* Create an edge from entry to the first block with executable
422 statements in it. */
423 make_edge (ENTRY_BLOCK_PTR, BASIC_BLOCK (0), EDGE_FALLTHRU);
425 /* Traverse basic block array placing edges. */
426 FOR_EACH_BB (bb)
428 tree first = first_stmt (bb);
429 tree last = last_stmt (bb);
431 if (first)
433 /* Edges for statements that always alter flow control. */
434 if (is_ctrl_stmt (last))
435 make_ctrl_stmt_edges (bb);
437 /* Edges for statements that sometimes alter flow control. */
438 if (is_ctrl_altering_stmt (last))
439 make_exit_edges (bb);
442 /* Finally, if no edges were created above, this is a regular
443 basic block that only needs a fallthru edge. */
444 if (EDGE_COUNT (bb->succs) == 0)
445 make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
448 /* We do not care about fake edges, so remove any that the CFG
449 builder inserted for completeness. */
450 remove_fake_exit_edges ();
452 /* Clean up the graph and warn for unreachable code. */
453 cleanup_tree_cfg ();
457 /* Create edges for control statement at basic block BB. */
459 static void
460 make_ctrl_stmt_edges (basic_block bb)
462 tree last = last_stmt (bb);
464 gcc_assert (last);
465 switch (TREE_CODE (last))
467 case GOTO_EXPR:
468 make_goto_expr_edges (bb);
469 break;
471 case RETURN_EXPR:
472 make_edge (bb, EXIT_BLOCK_PTR, 0);
473 break;
475 case COND_EXPR:
476 make_cond_expr_edges (bb);
477 break;
479 case SWITCH_EXPR:
480 make_switch_expr_edges (bb);
481 break;
483 case RESX_EXPR:
484 make_eh_edges (last);
485 /* Yet another NORETURN hack. */
486 if (EDGE_COUNT (bb->succs) == 0)
487 make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
488 break;
490 default:
491 gcc_unreachable ();
496 /* Create exit edges for statements in block BB that alter the flow of
497 control. Statements that alter the control flow are 'goto', 'return'
498 and calls to non-returning functions. */
500 static void
501 make_exit_edges (basic_block bb)
503 tree last = last_stmt (bb), op;
505 gcc_assert (last);
506 switch (TREE_CODE (last))
508 case CALL_EXPR:
509 /* If this function receives a nonlocal goto, then we need to
510 make edges from this call site to all the nonlocal goto
511 handlers. */
512 if (TREE_SIDE_EFFECTS (last)
513 && current_function_has_nonlocal_label)
514 make_goto_expr_edges (bb);
516 /* If this statement has reachable exception handlers, then
517 create abnormal edges to them. */
518 make_eh_edges (last);
520 /* Some calls are known not to return. For such calls we create
521 a fake edge.
523 We really need to revamp how we build edges so that it's not
524 such a bloody pain to avoid creating edges for this case since
525 all we do is remove these edges when we're done building the
526 CFG. */
527 if (call_expr_flags (last) & (ECF_NORETURN | ECF_LONGJMP))
529 make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
530 return;
533 /* Don't forget the fall-thru edge. */
534 make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
535 break;
537 case MODIFY_EXPR:
538 /* A MODIFY_EXPR may have a CALL_EXPR on its RHS and the CALL_EXPR
539 may have an abnormal edge. Search the RHS for this case and
540 create any required edges. */
541 op = get_call_expr_in (last);
542 if (op && TREE_SIDE_EFFECTS (op)
543 && current_function_has_nonlocal_label)
544 make_goto_expr_edges (bb);
546 make_eh_edges (last);
547 make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
548 break;
550 default:
551 gcc_unreachable ();
556 /* Create the edges for a COND_EXPR starting at block BB.
557 At this point, both clauses must contain only simple gotos. */
559 static void
560 make_cond_expr_edges (basic_block bb)
562 tree entry = last_stmt (bb);
563 basic_block then_bb, else_bb;
564 tree then_label, else_label;
566 gcc_assert (entry);
567 gcc_assert (TREE_CODE (entry) == COND_EXPR);
569 /* Entry basic blocks for each component. */
570 then_label = GOTO_DESTINATION (COND_EXPR_THEN (entry));
571 else_label = GOTO_DESTINATION (COND_EXPR_ELSE (entry));
572 then_bb = label_to_block (then_label);
573 else_bb = label_to_block (else_label);
575 make_edge (bb, then_bb, EDGE_TRUE_VALUE);
576 make_edge (bb, else_bb, EDGE_FALSE_VALUE);
580 /* Create the edges for a SWITCH_EXPR starting at block BB.
581 At this point, the switch body has been lowered and the
582 SWITCH_LABELS filled in, so this is in effect a multi-way branch. */
584 static void
585 make_switch_expr_edges (basic_block bb)
587 tree entry = last_stmt (bb);
588 size_t i, n;
589 tree vec;
591 vec = SWITCH_LABELS (entry);
592 n = TREE_VEC_LENGTH (vec);
594 for (i = 0; i < n; ++i)
596 tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i));
597 basic_block label_bb = label_to_block (lab);
598 make_edge (bb, label_bb, 0);
603 /* Return the basic block holding label DEST. */
605 basic_block
606 label_to_block (tree dest)
608 int uid = LABEL_DECL_UID (dest);
610 /* We would die hard when faced by undefined label. Emit label to
611 very first basic block. This will hopefully make even the dataflow
612 and undefined variable warnings quite right. */
613 if ((errorcount || sorrycount) && uid < 0)
615 block_stmt_iterator bsi = bsi_start (BASIC_BLOCK (0));
616 tree stmt;
618 stmt = build1 (LABEL_EXPR, void_type_node, dest);
619 bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
620 uid = LABEL_DECL_UID (dest);
622 return VARRAY_BB (label_to_block_map, uid);
626 /* Create edges for a goto statement at block BB. */
628 static void
629 make_goto_expr_edges (basic_block bb)
631 tree goto_t, dest;
632 basic_block target_bb;
633 int for_call;
634 block_stmt_iterator last = bsi_last (bb);
636 goto_t = bsi_stmt (last);
638 /* If the last statement is not a GOTO (i.e., it is a RETURN_EXPR,
639 CALL_EXPR or MODIFY_EXPR), then the edge is an abnormal edge resulting
640 from a nonlocal goto. */
641 if (TREE_CODE (goto_t) != GOTO_EXPR)
643 dest = error_mark_node;
644 for_call = 1;
646 else
648 dest = GOTO_DESTINATION (goto_t);
649 for_call = 0;
651 /* A GOTO to a local label creates normal edges. */
652 if (simple_goto_p (goto_t))
654 edge e = make_edge (bb, label_to_block (dest), EDGE_FALLTHRU);
655 #ifdef USE_MAPPED_LOCATION
656 e->goto_locus = EXPR_LOCATION (goto_t);
657 #else
658 e->goto_locus = EXPR_LOCUS (goto_t);
659 #endif
660 bsi_remove (&last);
661 return;
664 /* Nothing more to do for nonlocal gotos. */
665 if (TREE_CODE (dest) == LABEL_DECL)
666 return;
668 /* Computed gotos remain. */
671 /* Look for the block starting with the destination label. In the
672 case of a computed goto, make an edge to any label block we find
673 in the CFG. */
674 FOR_EACH_BB (target_bb)
676 block_stmt_iterator bsi;
678 for (bsi = bsi_start (target_bb); !bsi_end_p (bsi); bsi_next (&bsi))
680 tree target = bsi_stmt (bsi);
682 if (TREE_CODE (target) != LABEL_EXPR)
683 break;
685 if (
686 /* Computed GOTOs. Make an edge to every label block that has
687 been marked as a potential target for a computed goto. */
688 (FORCED_LABEL (LABEL_EXPR_LABEL (target)) && for_call == 0)
689 /* Nonlocal GOTO target. Make an edge to every label block
690 that has been marked as a potential target for a nonlocal
691 goto. */
692 || (DECL_NONLOCAL (LABEL_EXPR_LABEL (target)) && for_call == 1))
694 make_edge (bb, target_bb, EDGE_ABNORMAL);
695 break;
700 /* Degenerate case of computed goto with no labels. */
701 if (!for_call && EDGE_COUNT (bb->succs) == 0)
702 make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
706 /*---------------------------------------------------------------------------
707 Flowgraph analysis
708 ---------------------------------------------------------------------------*/
710 /* Remove unreachable blocks and other miscellaneous clean up work. */
712 bool
713 cleanup_tree_cfg (void)
715 bool something_changed = true;
716 bool retval = false;
718 timevar_push (TV_TREE_CLEANUP_CFG);
720 retval = cleanup_control_flow ();
722 /* These two transformations can cascade, so we iterate on them until
723 nothing changes. */
724 while (something_changed)
726 something_changed = delete_unreachable_blocks ();
727 something_changed |= thread_jumps ();
728 retval |= something_changed;
731 #ifdef ENABLE_CHECKING
732 if (retval)
733 gcc_assert (!cleanup_control_flow ());
734 #endif
736 /* Merging the blocks creates no new opportunities for the other
737 optimizations, so do it here. */
738 merge_seq_blocks ();
740 compact_blocks ();
742 #ifdef ENABLE_CHECKING
743 verify_flow_info ();
744 #endif
745 timevar_pop (TV_TREE_CLEANUP_CFG);
746 return retval;
750 /* Cleanup useless labels in basic blocks. This is something we wish
751 to do early because it allows us to group case labels before creating
752 the edges for the CFG, and it speeds up block statement iterators in
753 all passes later on.
754 We only run this pass once, running it more than once is probably not
755 profitable. */
757 /* A map from basic block index to the leading label of that block. */
758 static tree *label_for_bb;
760 /* Callback for for_each_eh_region. Helper for cleanup_dead_labels. */
761 static void
762 update_eh_label (struct eh_region *region)
764 tree old_label = get_eh_region_tree_label (region);
765 if (old_label)
767 tree new_label;
768 basic_block bb = label_to_block (old_label);
770 /* ??? After optimizing, there may be EH regions with labels
771 that have already been removed from the function body, so
772 there is no basic block for them. */
773 if (! bb)
774 return;
776 new_label = label_for_bb[bb->index];
777 set_eh_region_tree_label (region, new_label);
781 /* Given LABEL return the first label in the same basic block. */
782 static tree
783 main_block_label (tree label)
785 basic_block bb = label_to_block (label);
787 /* label_to_block possibly inserted undefined label into the chain. */
788 if (!label_for_bb[bb->index])
789 label_for_bb[bb->index] = label;
790 return label_for_bb[bb->index];
793 /* Cleanup redundant labels. This is a three-steo process:
794 1) Find the leading label for each block.
795 2) Redirect all references to labels to the leading labels.
796 3) Cleanup all useless labels. */
798 void
799 cleanup_dead_labels (void)
801 basic_block bb;
802 label_for_bb = xcalloc (last_basic_block, sizeof (tree));
804 /* Find a suitable label for each block. We use the first user-defined
805 label is there is one, or otherwise just the first label we see. */
806 FOR_EACH_BB (bb)
808 block_stmt_iterator i;
810 for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
812 tree label, stmt = bsi_stmt (i);
814 if (TREE_CODE (stmt) != LABEL_EXPR)
815 break;
817 label = LABEL_EXPR_LABEL (stmt);
819 /* If we have not yet seen a label for the current block,
820 remember this one and see if there are more labels. */
821 if (! label_for_bb[bb->index])
823 label_for_bb[bb->index] = label;
824 continue;
827 /* If we did see a label for the current block already, but it
828 is an artificially created label, replace it if the current
829 label is a user defined label. */
830 if (! DECL_ARTIFICIAL (label)
831 && DECL_ARTIFICIAL (label_for_bb[bb->index]))
833 label_for_bb[bb->index] = label;
834 break;
839 /* Now redirect all jumps/branches to the selected label.
840 First do so for each block ending in a control statement. */
841 FOR_EACH_BB (bb)
843 tree stmt = last_stmt (bb);
844 if (!stmt)
845 continue;
847 switch (TREE_CODE (stmt))
849 case COND_EXPR:
851 tree true_branch, false_branch;
853 true_branch = COND_EXPR_THEN (stmt);
854 false_branch = COND_EXPR_ELSE (stmt);
856 GOTO_DESTINATION (true_branch)
857 = main_block_label (GOTO_DESTINATION (true_branch));
858 GOTO_DESTINATION (false_branch)
859 = main_block_label (GOTO_DESTINATION (false_branch));
861 break;
864 case SWITCH_EXPR:
866 size_t i;
867 tree vec = SWITCH_LABELS (stmt);
868 size_t n = TREE_VEC_LENGTH (vec);
870 /* Replace all destination labels. */
871 for (i = 0; i < n; ++i)
872 CASE_LABEL (TREE_VEC_ELT (vec, i))
873 = main_block_label (CASE_LABEL (TREE_VEC_ELT (vec, i)));
875 break;
878 /* We have to handle GOTO_EXPRs until they're removed, and we don't
879 remove them until after we've created the CFG edges. */
880 case GOTO_EXPR:
881 if (! computed_goto_p (stmt))
883 GOTO_DESTINATION (stmt)
884 = main_block_label (GOTO_DESTINATION (stmt));
885 break;
888 default:
889 break;
893 for_each_eh_region (update_eh_label);
895 /* Finally, purge dead labels. All user-defined labels and labels that
896 can be the target of non-local gotos are preserved. */
897 FOR_EACH_BB (bb)
899 block_stmt_iterator i;
900 tree label_for_this_bb = label_for_bb[bb->index];
902 if (! label_for_this_bb)
903 continue;
905 for (i = bsi_start (bb); !bsi_end_p (i); )
907 tree label, stmt = bsi_stmt (i);
909 if (TREE_CODE (stmt) != LABEL_EXPR)
910 break;
912 label = LABEL_EXPR_LABEL (stmt);
914 if (label == label_for_this_bb
915 || ! DECL_ARTIFICIAL (label)
916 || DECL_NONLOCAL (label))
917 bsi_next (&i);
918 else
919 bsi_remove (&i);
923 free (label_for_bb);
926 /* Look for blocks ending in a multiway branch (a SWITCH_EXPR in GIMPLE),
927 and scan the sorted vector of cases. Combine the ones jumping to the
928 same label.
929 Eg. three separate entries 1: 2: 3: become one entry 1..3: */
931 void
932 group_case_labels (void)
934 basic_block bb;
936 FOR_EACH_BB (bb)
938 tree stmt = last_stmt (bb);
939 if (stmt && TREE_CODE (stmt) == SWITCH_EXPR)
941 tree labels = SWITCH_LABELS (stmt);
942 int old_size = TREE_VEC_LENGTH (labels);
943 int i, j, new_size = old_size;
944 tree default_label = TREE_VEC_ELT (labels, old_size - 1);
946 /* Look for possible opportunities to merge cases.
947 Ignore the last element of the label vector because it
948 must be the default case. */
949 i = 0;
950 while (i < old_size - 2)
952 tree base_case, base_label, base_high, type;
953 base_case = TREE_VEC_ELT (labels, i);
955 gcc_assert (base_case);
956 base_label = CASE_LABEL (base_case);
958 /* Discard cases that have the same destination as the
959 default case. */
960 if (base_label == default_label)
962 TREE_VEC_ELT (labels, i) = NULL_TREE;
963 i++;
964 continue;
967 type = TREE_TYPE (CASE_LOW (base_case));
968 base_high = CASE_HIGH (base_case) ?
969 CASE_HIGH (base_case) : CASE_LOW (base_case);
971 /* Try to merge case labels. Break out when we reach the end
972 of the label vector or when we cannot merge the next case
973 label with the current one. */
974 while (i < old_size - 2)
976 tree merge_case = TREE_VEC_ELT (labels, ++i);
977 tree merge_label = CASE_LABEL (merge_case);
978 tree t = int_const_binop (PLUS_EXPR, base_high,
979 integer_one_node, 1);
981 /* Merge the cases if they jump to the same place,
982 and their ranges are consecutive. */
983 if (merge_label == base_label
984 && tree_int_cst_equal (CASE_LOW (merge_case), t))
986 base_high = CASE_HIGH (merge_case) ?
987 CASE_HIGH (merge_case) : CASE_LOW (merge_case);
988 CASE_HIGH (base_case) = base_high;
989 TREE_VEC_ELT (labels, i) = NULL_TREE;
990 new_size--;
992 else
993 break;
997 /* Compress the case labels in the label vector, and adjust the
998 length of the vector. */
999 for (i = 0, j = 0; i < new_size; i++)
1001 while (! TREE_VEC_ELT (labels, j))
1002 j++;
1003 TREE_VEC_ELT (labels, i) = TREE_VEC_ELT (labels, j++);
1005 TREE_VEC_LENGTH (labels) = new_size;
1010 /* Checks whether we can merge block B into block A. */
1012 static bool
1013 tree_can_merge_blocks_p (basic_block a, basic_block b)
1015 tree stmt;
1016 block_stmt_iterator bsi;
1018 if (EDGE_COUNT (a->succs) != 1)
1019 return false;
1021 if (EDGE_SUCC (a, 0)->flags & EDGE_ABNORMAL)
1022 return false;
1024 if (EDGE_SUCC (a, 0)->dest != b)
1025 return false;
1027 if (b == EXIT_BLOCK_PTR)
1028 return false;
1030 if (EDGE_COUNT (b->preds) > 1)
1031 return false;
1033 /* If A ends by a statement causing exceptions or something similar, we
1034 cannot merge the blocks. */
1035 stmt = last_stmt (a);
1036 if (stmt && stmt_ends_bb_p (stmt))
1037 return false;
1039 /* Do not allow a block with only a non-local label to be merged. */
1040 if (stmt && TREE_CODE (stmt) == LABEL_EXPR
1041 && DECL_NONLOCAL (LABEL_EXPR_LABEL (stmt)))
1042 return false;
1044 /* There may be no phi nodes at the start of b. Most of these degenerate
1045 phi nodes should be cleaned up by kill_redundant_phi_nodes. */
1046 if (phi_nodes (b))
1047 return false;
1049 /* Do not remove user labels. */
1050 for (bsi = bsi_start (b); !bsi_end_p (bsi); bsi_next (&bsi))
1052 stmt = bsi_stmt (bsi);
1053 if (TREE_CODE (stmt) != LABEL_EXPR)
1054 break;
1055 if (!DECL_ARTIFICIAL (LABEL_EXPR_LABEL (stmt)))
1056 return false;
1059 return true;
1063 /* Merge block B into block A. */
1065 static void
1066 tree_merge_blocks (basic_block a, basic_block b)
1068 block_stmt_iterator bsi;
1069 tree_stmt_iterator last;
1071 if (dump_file)
1072 fprintf (dump_file, "Merging blocks %d and %d\n", a->index, b->index);
1074 /* Ensure that B follows A. */
1075 move_block_after (b, a);
1077 gcc_assert (EDGE_SUCC (a, 0)->flags & EDGE_FALLTHRU);
1078 gcc_assert (!last_stmt (a) || !stmt_ends_bb_p (last_stmt (a)));
1080 /* Remove labels from B and set bb_for_stmt to A for other statements. */
1081 for (bsi = bsi_start (b); !bsi_end_p (bsi);)
1083 if (TREE_CODE (bsi_stmt (bsi)) == LABEL_EXPR)
1084 bsi_remove (&bsi);
1085 else
1087 set_bb_for_stmt (bsi_stmt (bsi), a);
1088 bsi_next (&bsi);
1092 /* Merge the chains. */
1093 last = tsi_last (a->stmt_list);
1094 tsi_link_after (&last, b->stmt_list, TSI_NEW_STMT);
1095 b->stmt_list = NULL;
1099 /* Walk the function tree removing unnecessary statements.
1101 * Empty statement nodes are removed
1103 * Unnecessary TRY_FINALLY and TRY_CATCH blocks are removed
1105 * Unnecessary COND_EXPRs are removed
1107 * Some unnecessary BIND_EXPRs are removed
1109 Clearly more work could be done. The trick is doing the analysis
1110 and removal fast enough to be a net improvement in compile times.
1112 Note that when we remove a control structure such as a COND_EXPR
1113 BIND_EXPR, or TRY block, we will need to repeat this optimization pass
1114 to ensure we eliminate all the useless code. */
1116 struct rus_data
1118 tree *last_goto;
1119 bool repeat;
1120 bool may_throw;
1121 bool may_branch;
1122 bool has_label;
1125 static void remove_useless_stmts_1 (tree *, struct rus_data *);
1127 static bool
1128 remove_useless_stmts_warn_notreached (tree stmt)
1130 if (EXPR_HAS_LOCATION (stmt))
1132 location_t loc = EXPR_LOCATION (stmt);
1133 warning ("%Hwill never be executed", &loc);
1134 return true;
1137 switch (TREE_CODE (stmt))
1139 case STATEMENT_LIST:
1141 tree_stmt_iterator i;
1142 for (i = tsi_start (stmt); !tsi_end_p (i); tsi_next (&i))
1143 if (remove_useless_stmts_warn_notreached (tsi_stmt (i)))
1144 return true;
1146 break;
1148 case COND_EXPR:
1149 if (remove_useless_stmts_warn_notreached (COND_EXPR_COND (stmt)))
1150 return true;
1151 if (remove_useless_stmts_warn_notreached (COND_EXPR_THEN (stmt)))
1152 return true;
1153 if (remove_useless_stmts_warn_notreached (COND_EXPR_ELSE (stmt)))
1154 return true;
1155 break;
1157 case TRY_FINALLY_EXPR:
1158 case TRY_CATCH_EXPR:
1159 if (remove_useless_stmts_warn_notreached (TREE_OPERAND (stmt, 0)))
1160 return true;
1161 if (remove_useless_stmts_warn_notreached (TREE_OPERAND (stmt, 1)))
1162 return true;
1163 break;
1165 case CATCH_EXPR:
1166 return remove_useless_stmts_warn_notreached (CATCH_BODY (stmt));
1167 case EH_FILTER_EXPR:
1168 return remove_useless_stmts_warn_notreached (EH_FILTER_FAILURE (stmt));
1169 case BIND_EXPR:
1170 return remove_useless_stmts_warn_notreached (BIND_EXPR_BLOCK (stmt));
1172 default:
1173 /* Not a live container. */
1174 break;
1177 return false;
1180 static void
1181 remove_useless_stmts_cond (tree *stmt_p, struct rus_data *data)
1183 tree then_clause, else_clause, cond;
1184 bool save_has_label, then_has_label, else_has_label;
1186 save_has_label = data->has_label;
1187 data->has_label = false;
1188 data->last_goto = NULL;
1190 remove_useless_stmts_1 (&COND_EXPR_THEN (*stmt_p), data);
1192 then_has_label = data->has_label;
1193 data->has_label = false;
1194 data->last_goto = NULL;
1196 remove_useless_stmts_1 (&COND_EXPR_ELSE (*stmt_p), data);
1198 else_has_label = data->has_label;
1199 data->has_label = save_has_label | then_has_label | else_has_label;
1201 fold_stmt (stmt_p);
1202 then_clause = COND_EXPR_THEN (*stmt_p);
1203 else_clause = COND_EXPR_ELSE (*stmt_p);
1204 cond = COND_EXPR_COND (*stmt_p);
1206 /* If neither arm does anything at all, we can remove the whole IF. */
1207 if (!TREE_SIDE_EFFECTS (then_clause) && !TREE_SIDE_EFFECTS (else_clause))
1209 *stmt_p = build_empty_stmt ();
1210 data->repeat = true;
1213 /* If there are no reachable statements in an arm, then we can
1214 zap the entire conditional. */
1215 else if (integer_nonzerop (cond) && !else_has_label)
1217 if (warn_notreached)
1218 remove_useless_stmts_warn_notreached (else_clause);
1219 *stmt_p = then_clause;
1220 data->repeat = true;
1222 else if (integer_zerop (cond) && !then_has_label)
1224 if (warn_notreached)
1225 remove_useless_stmts_warn_notreached (then_clause);
1226 *stmt_p = else_clause;
1227 data->repeat = true;
1230 /* Check a couple of simple things on then/else with single stmts. */
1231 else
1233 tree then_stmt = expr_only (then_clause);
1234 tree else_stmt = expr_only (else_clause);
1236 /* Notice branches to a common destination. */
1237 if (then_stmt && else_stmt
1238 && TREE_CODE (then_stmt) == GOTO_EXPR
1239 && TREE_CODE (else_stmt) == GOTO_EXPR
1240 && (GOTO_DESTINATION (then_stmt) == GOTO_DESTINATION (else_stmt)))
1242 *stmt_p = then_stmt;
1243 data->repeat = true;
1246 /* If the THEN/ELSE clause merely assigns a value to a variable or
1247 parameter which is already known to contain that value, then
1248 remove the useless THEN/ELSE clause. */
1249 else if (TREE_CODE (cond) == VAR_DECL || TREE_CODE (cond) == PARM_DECL)
1251 if (else_stmt
1252 && TREE_CODE (else_stmt) == MODIFY_EXPR
1253 && TREE_OPERAND (else_stmt, 0) == cond
1254 && integer_zerop (TREE_OPERAND (else_stmt, 1)))
1255 COND_EXPR_ELSE (*stmt_p) = alloc_stmt_list ();
1257 else if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
1258 && (TREE_CODE (TREE_OPERAND (cond, 0)) == VAR_DECL
1259 || TREE_CODE (TREE_OPERAND (cond, 0)) == PARM_DECL)
1260 && TREE_CONSTANT (TREE_OPERAND (cond, 1)))
1262 tree stmt = (TREE_CODE (cond) == EQ_EXPR
1263 ? then_stmt : else_stmt);
1264 tree *location = (TREE_CODE (cond) == EQ_EXPR
1265 ? &COND_EXPR_THEN (*stmt_p)
1266 : &COND_EXPR_ELSE (*stmt_p));
1268 if (stmt
1269 && TREE_CODE (stmt) == MODIFY_EXPR
1270 && TREE_OPERAND (stmt, 0) == TREE_OPERAND (cond, 0)
1271 && TREE_OPERAND (stmt, 1) == TREE_OPERAND (cond, 1))
1272 *location = alloc_stmt_list ();
1276 /* Protect GOTOs in the arm of COND_EXPRs from being removed. They
1277 would be re-introduced during lowering. */
1278 data->last_goto = NULL;
1282 static void
1283 remove_useless_stmts_tf (tree *stmt_p, struct rus_data *data)
1285 bool save_may_branch, save_may_throw;
1286 bool this_may_branch, this_may_throw;
1288 /* Collect may_branch and may_throw information for the body only. */
1289 save_may_branch = data->may_branch;
1290 save_may_throw = data->may_throw;
1291 data->may_branch = false;
1292 data->may_throw = false;
1293 data->last_goto = NULL;
1295 remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 0), data);
1297 this_may_branch = data->may_branch;
1298 this_may_throw = data->may_throw;
1299 data->may_branch |= save_may_branch;
1300 data->may_throw |= save_may_throw;
1301 data->last_goto = NULL;
1303 remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 1), data);
1305 /* If the body is empty, then we can emit the FINALLY block without
1306 the enclosing TRY_FINALLY_EXPR. */
1307 if (!TREE_SIDE_EFFECTS (TREE_OPERAND (*stmt_p, 0)))
1309 *stmt_p = TREE_OPERAND (*stmt_p, 1);
1310 data->repeat = true;
1313 /* If the handler is empty, then we can emit the TRY block without
1314 the enclosing TRY_FINALLY_EXPR. */
1315 else if (!TREE_SIDE_EFFECTS (TREE_OPERAND (*stmt_p, 1)))
1317 *stmt_p = TREE_OPERAND (*stmt_p, 0);
1318 data->repeat = true;
1321 /* If the body neither throws, nor branches, then we can safely
1322 string the TRY and FINALLY blocks together. */
1323 else if (!this_may_branch && !this_may_throw)
1325 tree stmt = *stmt_p;
1326 *stmt_p = TREE_OPERAND (stmt, 0);
1327 append_to_statement_list (TREE_OPERAND (stmt, 1), stmt_p);
1328 data->repeat = true;
1333 static void
1334 remove_useless_stmts_tc (tree *stmt_p, struct rus_data *data)
1336 bool save_may_throw, this_may_throw;
1337 tree_stmt_iterator i;
1338 tree stmt;
1340 /* Collect may_throw information for the body only. */
1341 save_may_throw = data->may_throw;
1342 data->may_throw = false;
1343 data->last_goto = NULL;
1345 remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 0), data);
1347 this_may_throw = data->may_throw;
1348 data->may_throw = save_may_throw;
1350 /* If the body cannot throw, then we can drop the entire TRY_CATCH_EXPR. */
1351 if (!this_may_throw)
1353 if (warn_notreached)
1354 remove_useless_stmts_warn_notreached (TREE_OPERAND (*stmt_p, 1));
1355 *stmt_p = TREE_OPERAND (*stmt_p, 0);
1356 data->repeat = true;
1357 return;
1360 /* Process the catch clause specially. We may be able to tell that
1361 no exceptions propagate past this point. */
1363 this_may_throw = true;
1364 i = tsi_start (TREE_OPERAND (*stmt_p, 1));
1365 stmt = tsi_stmt (i);
1366 data->last_goto = NULL;
1368 switch (TREE_CODE (stmt))
1370 case CATCH_EXPR:
1371 for (; !tsi_end_p (i); tsi_next (&i))
1373 stmt = tsi_stmt (i);
1374 /* If we catch all exceptions, then the body does not
1375 propagate exceptions past this point. */
1376 if (CATCH_TYPES (stmt) == NULL)
1377 this_may_throw = false;
1378 data->last_goto = NULL;
1379 remove_useless_stmts_1 (&CATCH_BODY (stmt), data);
1381 break;
1383 case EH_FILTER_EXPR:
1384 if (EH_FILTER_MUST_NOT_THROW (stmt))
1385 this_may_throw = false;
1386 else if (EH_FILTER_TYPES (stmt) == NULL)
1387 this_may_throw = false;
1388 remove_useless_stmts_1 (&EH_FILTER_FAILURE (stmt), data);
1389 break;
1391 default:
1392 /* Otherwise this is a cleanup. */
1393 remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 1), data);
1395 /* If the cleanup is empty, then we can emit the TRY block without
1396 the enclosing TRY_CATCH_EXPR. */
1397 if (!TREE_SIDE_EFFECTS (TREE_OPERAND (*stmt_p, 1)))
1399 *stmt_p = TREE_OPERAND (*stmt_p, 0);
1400 data->repeat = true;
1402 break;
1404 data->may_throw |= this_may_throw;
1408 static void
1409 remove_useless_stmts_bind (tree *stmt_p, struct rus_data *data)
1411 tree block;
1413 /* First remove anything underneath the BIND_EXPR. */
1414 remove_useless_stmts_1 (&BIND_EXPR_BODY (*stmt_p), data);
1416 /* If the BIND_EXPR has no variables, then we can pull everything
1417 up one level and remove the BIND_EXPR, unless this is the toplevel
1418 BIND_EXPR for the current function or an inlined function.
1420 When this situation occurs we will want to apply this
1421 optimization again. */
1422 block = BIND_EXPR_BLOCK (*stmt_p);
1423 if (BIND_EXPR_VARS (*stmt_p) == NULL_TREE
1424 && *stmt_p != DECL_SAVED_TREE (current_function_decl)
1425 && (! block
1426 || ! BLOCK_ABSTRACT_ORIGIN (block)
1427 || (TREE_CODE (BLOCK_ABSTRACT_ORIGIN (block))
1428 != FUNCTION_DECL)))
1430 *stmt_p = BIND_EXPR_BODY (*stmt_p);
1431 data->repeat = true;
1436 static void
1437 remove_useless_stmts_goto (tree *stmt_p, struct rus_data *data)
1439 tree dest = GOTO_DESTINATION (*stmt_p);
1441 data->may_branch = true;
1442 data->last_goto = NULL;
1444 /* Record the last goto expr, so that we can delete it if unnecessary. */
1445 if (TREE_CODE (dest) == LABEL_DECL)
1446 data->last_goto = stmt_p;
1450 static void
1451 remove_useless_stmts_label (tree *stmt_p, struct rus_data *data)
1453 tree label = LABEL_EXPR_LABEL (*stmt_p);
1455 data->has_label = true;
1457 /* We do want to jump across non-local label receiver code. */
1458 if (DECL_NONLOCAL (label))
1459 data->last_goto = NULL;
1461 else if (data->last_goto && GOTO_DESTINATION (*data->last_goto) == label)
1463 *data->last_goto = build_empty_stmt ();
1464 data->repeat = true;
1467 /* ??? Add something here to delete unused labels. */
1471 /* If the function is "const" or "pure", then clear TREE_SIDE_EFFECTS on its
1472 decl. This allows us to eliminate redundant or useless
1473 calls to "const" functions.
1475 Gimplifier already does the same operation, but we may notice functions
1476 being const and pure once their calls has been gimplified, so we need
1477 to update the flag. */
1479 static void
1480 update_call_expr_flags (tree call)
1482 tree decl = get_callee_fndecl (call);
1483 if (!decl)
1484 return;
1485 if (call_expr_flags (call) & (ECF_CONST | ECF_PURE))
1486 TREE_SIDE_EFFECTS (call) = 0;
1487 if (TREE_NOTHROW (decl))
1488 TREE_NOTHROW (call) = 1;
1492 /* T is CALL_EXPR. Set current_function_calls_* flags. */
1494 void
1495 notice_special_calls (tree t)
1497 int flags = call_expr_flags (t);
1499 if (flags & ECF_MAY_BE_ALLOCA)
1500 current_function_calls_alloca = true;
1501 if (flags & ECF_RETURNS_TWICE)
1502 current_function_calls_setjmp = true;
1506 /* Clear flags set by notice_special_calls. Used by dead code removal
1507 to update the flags. */
1509 void
1510 clear_special_calls (void)
1512 current_function_calls_alloca = false;
1513 current_function_calls_setjmp = false;
1517 static void
1518 remove_useless_stmts_1 (tree *tp, struct rus_data *data)
1520 tree t = *tp, op;
1522 switch (TREE_CODE (t))
1524 case COND_EXPR:
1525 remove_useless_stmts_cond (tp, data);
1526 break;
1528 case TRY_FINALLY_EXPR:
1529 remove_useless_stmts_tf (tp, data);
1530 break;
1532 case TRY_CATCH_EXPR:
1533 remove_useless_stmts_tc (tp, data);
1534 break;
1536 case BIND_EXPR:
1537 remove_useless_stmts_bind (tp, data);
1538 break;
1540 case GOTO_EXPR:
1541 remove_useless_stmts_goto (tp, data);
1542 break;
1544 case LABEL_EXPR:
1545 remove_useless_stmts_label (tp, data);
1546 break;
1548 case RETURN_EXPR:
1549 fold_stmt (tp);
1550 data->last_goto = NULL;
1551 data->may_branch = true;
1552 break;
1554 case CALL_EXPR:
1555 fold_stmt (tp);
1556 data->last_goto = NULL;
1557 notice_special_calls (t);
1558 update_call_expr_flags (t);
1559 if (tree_could_throw_p (t))
1560 data->may_throw = true;
1561 break;
1563 case MODIFY_EXPR:
1564 data->last_goto = NULL;
1565 fold_stmt (tp);
1566 op = get_call_expr_in (t);
1567 if (op)
1569 update_call_expr_flags (op);
1570 notice_special_calls (op);
1572 if (tree_could_throw_p (t))
1573 data->may_throw = true;
1574 break;
1576 case STATEMENT_LIST:
1578 tree_stmt_iterator i = tsi_start (t);
1579 while (!tsi_end_p (i))
1581 t = tsi_stmt (i);
1582 if (IS_EMPTY_STMT (t))
1584 tsi_delink (&i);
1585 continue;
1588 remove_useless_stmts_1 (tsi_stmt_ptr (i), data);
1590 t = tsi_stmt (i);
1591 if (TREE_CODE (t) == STATEMENT_LIST)
1593 tsi_link_before (&i, t, TSI_SAME_STMT);
1594 tsi_delink (&i);
1596 else
1597 tsi_next (&i);
1600 break;
1601 case SWITCH_EXPR:
1602 fold_stmt (tp);
1603 data->last_goto = NULL;
1604 break;
1606 default:
1607 data->last_goto = NULL;
1608 break;
1612 static void
1613 remove_useless_stmts (void)
1615 struct rus_data data;
1617 clear_special_calls ();
1621 memset (&data, 0, sizeof (data));
1622 remove_useless_stmts_1 (&DECL_SAVED_TREE (current_function_decl), &data);
1624 while (data.repeat);
1628 struct tree_opt_pass pass_remove_useless_stmts =
1630 "useless", /* name */
1631 NULL, /* gate */
1632 remove_useless_stmts, /* execute */
1633 NULL, /* sub */
1634 NULL, /* next */
1635 0, /* static_pass_number */
1636 0, /* tv_id */
1637 PROP_gimple_any, /* properties_required */
1638 0, /* properties_provided */
1639 0, /* properties_destroyed */
1640 0, /* todo_flags_start */
1641 TODO_dump_func, /* todo_flags_finish */
1642 0 /* letter */
1646 /* Remove obviously useless statements in basic block BB. */
1648 static void
1649 cfg_remove_useless_stmts_bb (basic_block bb)
1651 block_stmt_iterator bsi;
1652 tree stmt = NULL_TREE;
1653 tree cond, var = NULL_TREE, val = NULL_TREE;
1654 struct var_ann_d *ann;
1656 /* Check whether we come here from a condition, and if so, get the
1657 condition. */
1658 if (EDGE_COUNT (bb->preds) != 1
1659 || !(EDGE_PRED (bb, 0)->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
1660 return;
1662 cond = COND_EXPR_COND (last_stmt (EDGE_PRED (bb, 0)->src));
1664 if (TREE_CODE (cond) == VAR_DECL || TREE_CODE (cond) == PARM_DECL)
1666 var = cond;
1667 val = (EDGE_PRED (bb, 0)->flags & EDGE_FALSE_VALUE
1668 ? boolean_false_node : boolean_true_node);
1670 else if (TREE_CODE (cond) == TRUTH_NOT_EXPR
1671 && (TREE_CODE (TREE_OPERAND (cond, 0)) == VAR_DECL
1672 || TREE_CODE (TREE_OPERAND (cond, 0)) == PARM_DECL))
1674 var = TREE_OPERAND (cond, 0);
1675 val = (EDGE_PRED (bb, 0)->flags & EDGE_FALSE_VALUE
1676 ? boolean_true_node : boolean_false_node);
1678 else
1680 if (EDGE_PRED (bb, 0)->flags & EDGE_FALSE_VALUE)
1681 cond = invert_truthvalue (cond);
1682 if (TREE_CODE (cond) == EQ_EXPR
1683 && (TREE_CODE (TREE_OPERAND (cond, 0)) == VAR_DECL
1684 || TREE_CODE (TREE_OPERAND (cond, 0)) == PARM_DECL)
1685 && (TREE_CODE (TREE_OPERAND (cond, 1)) == VAR_DECL
1686 || TREE_CODE (TREE_OPERAND (cond, 1)) == PARM_DECL
1687 || TREE_CONSTANT (TREE_OPERAND (cond, 1))))
1689 var = TREE_OPERAND (cond, 0);
1690 val = TREE_OPERAND (cond, 1);
1692 else
1693 return;
1696 /* Only work for normal local variables. */
1697 ann = var_ann (var);
1698 if (!ann
1699 || ann->may_aliases
1700 || TREE_ADDRESSABLE (var))
1701 return;
1703 if (! TREE_CONSTANT (val))
1705 ann = var_ann (val);
1706 if (!ann
1707 || ann->may_aliases
1708 || TREE_ADDRESSABLE (val))
1709 return;
1712 /* Ignore floating point variables, since comparison behaves weird for
1713 them. */
1714 if (FLOAT_TYPE_P (TREE_TYPE (var)))
1715 return;
1717 for (bsi = bsi_start (bb); !bsi_end_p (bsi);)
1719 stmt = bsi_stmt (bsi);
1721 /* If the THEN/ELSE clause merely assigns a value to a variable/parameter
1722 which is already known to contain that value, then remove the useless
1723 THEN/ELSE clause. */
1724 if (TREE_CODE (stmt) == MODIFY_EXPR
1725 && TREE_OPERAND (stmt, 0) == var
1726 && operand_equal_p (val, TREE_OPERAND (stmt, 1), 0))
1728 bsi_remove (&bsi);
1729 continue;
1732 /* Invalidate the var if we encounter something that could modify it.
1733 Likewise for the value it was previously set to. Note that we only
1734 consider values that are either a VAR_DECL or PARM_DECL so we
1735 can test for conflict very simply. */
1736 if (TREE_CODE (stmt) == ASM_EXPR
1737 || (TREE_CODE (stmt) == MODIFY_EXPR
1738 && (TREE_OPERAND (stmt, 0) == var
1739 || TREE_OPERAND (stmt, 0) == val)))
1740 return;
1742 bsi_next (&bsi);
1747 /* A CFG-aware version of remove_useless_stmts. */
1749 void
1750 cfg_remove_useless_stmts (void)
1752 basic_block bb;
1754 #ifdef ENABLE_CHECKING
1755 verify_flow_info ();
1756 #endif
1758 FOR_EACH_BB (bb)
1760 cfg_remove_useless_stmts_bb (bb);
1765 /* Remove PHI nodes associated with basic block BB and all edges out of BB. */
1767 static void
1768 remove_phi_nodes_and_edges_for_unreachable_block (basic_block bb)
1770 tree phi;
1772 /* Since this block is no longer reachable, we can just delete all
1773 of its PHI nodes. */
1774 phi = phi_nodes (bb);
1775 while (phi)
1777 tree next = PHI_CHAIN (phi);
1778 remove_phi_node (phi, NULL_TREE, bb);
1779 phi = next;
1782 /* Remove edges to BB's successors. */
1783 while (EDGE_COUNT (bb->succs) > 0)
1784 ssa_remove_edge (EDGE_SUCC (bb, 0));
1788 /* Remove statements of basic block BB. */
1790 static void
1791 remove_bb (basic_block bb)
1793 block_stmt_iterator i;
1794 source_locus loc = 0;
1796 if (dump_file)
1798 fprintf (dump_file, "Removing basic block %d\n", bb->index);
1799 if (dump_flags & TDF_DETAILS)
1801 dump_bb (bb, dump_file, 0);
1802 fprintf (dump_file, "\n");
1806 /* Remove all the instructions in the block. */
1807 for (i = bsi_start (bb); !bsi_end_p (i); bsi_remove (&i))
1809 tree stmt = bsi_stmt (i);
1810 release_defs (stmt);
1812 set_bb_for_stmt (stmt, NULL);
1814 /* Don't warn for removed gotos. Gotos are often removed due to
1815 jump threading, thus resulting in bogus warnings. Not great,
1816 since this way we lose warnings for gotos in the original
1817 program that are indeed unreachable. */
1818 if (TREE_CODE (stmt) != GOTO_EXPR && EXPR_HAS_LOCATION (stmt) && !loc)
1819 #ifdef USE_MAPPED_LOCATION
1820 loc = EXPR_LOCATION (stmt);
1821 #else
1822 loc = EXPR_LOCUS (stmt);
1823 #endif
1826 /* If requested, give a warning that the first statement in the
1827 block is unreachable. We walk statements backwards in the
1828 loop above, so the last statement we process is the first statement
1829 in the block. */
1830 if (warn_notreached && loc)
1831 #ifdef USE_MAPPED_LOCATION
1832 warning ("%Hwill never be executed", &loc);
1833 #else
1834 warning ("%Hwill never be executed", loc);
1835 #endif
1837 remove_phi_nodes_and_edges_for_unreachable_block (bb);
1841 /* Examine BB to determine if it is a forwarding block (a block which only
1842 transfers control to a new destination). If BB is a forwarding block,
1843 then return the edge leading to the ultimate destination. */
1845 edge
1846 tree_block_forwards_to (basic_block bb)
1848 block_stmt_iterator bsi;
1849 bb_ann_t ann = bb_ann (bb);
1850 tree stmt;
1852 /* If this block is not forwardable, then avoid useless work. */
1853 if (! ann->forwardable)
1854 return NULL;
1856 /* Set this block to not be forwardable. This prevents infinite loops since
1857 any block currently under examination is considered non-forwardable. */
1858 ann->forwardable = 0;
1860 /* No forwarding is possible if this block is a special block (ENTRY/EXIT),
1861 this block has more than one successor, this block's single successor is
1862 reached via an abnormal edge, this block has phi nodes, or this block's
1863 single successor has phi nodes. */
1864 if (bb == EXIT_BLOCK_PTR
1865 || bb == ENTRY_BLOCK_PTR
1866 || EDGE_COUNT (bb->succs) != 1
1867 || EDGE_SUCC (bb, 0)->dest == EXIT_BLOCK_PTR
1868 || (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL) != 0
1869 || phi_nodes (bb)
1870 || phi_nodes (EDGE_SUCC (bb, 0)->dest))
1871 return NULL;
1873 /* Walk past any labels at the start of this block. */
1874 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1876 stmt = bsi_stmt (bsi);
1877 if (TREE_CODE (stmt) != LABEL_EXPR)
1878 break;
1881 /* If we reached the end of this block we may be able to optimize this
1882 case. */
1883 if (bsi_end_p (bsi))
1885 edge dest;
1887 /* Recursive call to pick up chains of forwarding blocks. */
1888 dest = tree_block_forwards_to (EDGE_SUCC (bb, 0)->dest);
1890 /* If none found, we forward to bb->succs[0] at minimum. */
1891 if (!dest)
1892 dest = EDGE_SUCC (bb, 0);
1894 ann->forwardable = 1;
1895 return dest;
1898 /* No forwarding possible. */
1899 return NULL;
1903 /* Try to remove superfluous control structures. */
1905 static bool
1906 cleanup_control_flow (void)
1908 basic_block bb;
1909 block_stmt_iterator bsi;
1910 bool retval = false;
1911 tree stmt;
1913 FOR_EACH_BB (bb)
1915 bsi = bsi_last (bb);
1917 if (bsi_end_p (bsi))
1918 continue;
1920 stmt = bsi_stmt (bsi);
1921 if (TREE_CODE (stmt) == COND_EXPR
1922 || TREE_CODE (stmt) == SWITCH_EXPR)
1923 retval |= cleanup_control_expr_graph (bb, bsi);
1925 return retval;
1929 /* Disconnect an unreachable block in the control expression starting
1930 at block BB. */
1932 static bool
1933 cleanup_control_expr_graph (basic_block bb, block_stmt_iterator bsi)
1935 edge taken_edge;
1936 bool retval = false;
1937 tree expr = bsi_stmt (bsi), val;
1939 if (EDGE_COUNT (bb->succs) > 1)
1941 edge e;
1942 edge_iterator ei;
1944 switch (TREE_CODE (expr))
1946 case COND_EXPR:
1947 val = COND_EXPR_COND (expr);
1948 break;
1950 case SWITCH_EXPR:
1951 val = SWITCH_COND (expr);
1952 if (TREE_CODE (val) != INTEGER_CST)
1953 return false;
1954 break;
1956 default:
1957 gcc_unreachable ();
1960 taken_edge = find_taken_edge (bb, val);
1961 if (!taken_edge)
1962 return false;
1964 /* Remove all the edges except the one that is always executed. */
1965 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
1967 if (e != taken_edge)
1969 taken_edge->probability += e->probability;
1970 taken_edge->count += e->count;
1971 ssa_remove_edge (e);
1972 retval = true;
1974 else
1975 ei_next (&ei);
1977 if (taken_edge->probability > REG_BR_PROB_BASE)
1978 taken_edge->probability = REG_BR_PROB_BASE;
1980 else
1981 taken_edge = EDGE_SUCC (bb, 0);
1983 bsi_remove (&bsi);
1984 taken_edge->flags = EDGE_FALLTHRU;
1986 /* We removed some paths from the cfg. */
1987 if (dom_computed[CDI_DOMINATORS] >= DOM_CONS_OK)
1988 dom_computed[CDI_DOMINATORS] = DOM_CONS_OK;
1990 return retval;
1994 /* Given a control block BB and a predicate VAL, return the edge that
1995 will be taken out of the block. If VAL does not match a unique
1996 edge, NULL is returned. */
1998 edge
1999 find_taken_edge (basic_block bb, tree val)
2001 tree stmt;
2003 stmt = last_stmt (bb);
2005 gcc_assert (stmt);
2006 gcc_assert (is_ctrl_stmt (stmt));
2008 /* If VAL is a predicate of the form N RELOP N, where N is an
2009 SSA_NAME, we can usually determine its truth value. */
2010 if (val && COMPARISON_CLASS_P (val))
2011 val = fold (val);
2013 /* If VAL is not a constant, we can't determine which edge might
2014 be taken. */
2015 if (val == NULL || !really_constant_p (val))
2016 return NULL;
2018 if (TREE_CODE (stmt) == COND_EXPR)
2019 return find_taken_edge_cond_expr (bb, val);
2021 if (TREE_CODE (stmt) == SWITCH_EXPR)
2022 return find_taken_edge_switch_expr (bb, val);
2024 return EDGE_SUCC (bb, 0);
2028 /* Given a constant value VAL and the entry block BB to a COND_EXPR
2029 statement, determine which of the two edges will be taken out of the
2030 block. Return NULL if either edge may be taken. */
2032 static edge
2033 find_taken_edge_cond_expr (basic_block bb, tree val)
2035 edge true_edge, false_edge;
2037 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
2039 /* If both edges of the branch lead to the same basic block, it doesn't
2040 matter which edge is taken. */
2041 if (true_edge->dest == false_edge->dest)
2042 return true_edge;
2044 /* Otherwise, try to determine which branch of the if() will be taken.
2045 If VAL is a constant but it can't be reduced to a 0 or a 1, then
2046 we don't really know which edge will be taken at runtime. This
2047 may happen when comparing addresses (e.g., if (&var1 == 4)). */
2048 if (integer_nonzerop (val))
2049 return true_edge;
2050 else if (integer_zerop (val))
2051 return false_edge;
2052 else
2053 return NULL;
2057 /* Given a constant value VAL and the entry block BB to a SWITCH_EXPR
2058 statement, determine which edge will be taken out of the block. Return
2059 NULL if any edge may be taken. */
2061 static edge
2062 find_taken_edge_switch_expr (basic_block bb, tree val)
2064 tree switch_expr, taken_case;
2065 basic_block dest_bb;
2066 edge e;
2068 if (TREE_CODE (val) != INTEGER_CST)
2069 return NULL;
2071 switch_expr = last_stmt (bb);
2072 taken_case = find_case_label_for_value (switch_expr, val);
2073 dest_bb = label_to_block (CASE_LABEL (taken_case));
2075 e = find_edge (bb, dest_bb);
2076 gcc_assert (e);
2077 return e;
2081 /* Return the CASE_LABEL_EXPR that SWITCH_EXPR will take for VAL.
2082 We can make optimal use here of the fact that the case labels are
2083 sorted: We can do a binary search for a case matching VAL. */
2085 static tree
2086 find_case_label_for_value (tree switch_expr, tree val)
2088 tree vec = SWITCH_LABELS (switch_expr);
2089 size_t low, high, n = TREE_VEC_LENGTH (vec);
2090 tree default_case = TREE_VEC_ELT (vec, n - 1);
2092 for (low = -1, high = n - 1; high - low > 1; )
2094 size_t i = (high + low) / 2;
2095 tree t = TREE_VEC_ELT (vec, i);
2096 int cmp;
2098 /* Cache the result of comparing CASE_LOW and val. */
2099 cmp = tree_int_cst_compare (CASE_LOW (t), val);
2101 if (cmp > 0)
2102 high = i;
2103 else
2104 low = i;
2106 if (CASE_HIGH (t) == NULL)
2108 /* A singe-valued case label. */
2109 if (cmp == 0)
2110 return t;
2112 else
2114 /* A case range. We can only handle integer ranges. */
2115 if (cmp <= 0 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
2116 return t;
2120 return default_case;
2124 /* If all the PHI nodes in DEST have alternatives for E1 and E2 and
2125 those alternatives are equal in each of the PHI nodes, then return
2126 true, else return false. */
2128 static bool
2129 phi_alternatives_equal (basic_block dest, edge e1, edge e2)
2131 tree phi, val1, val2;
2132 int n1, n2;
2134 for (phi = phi_nodes (dest); phi; phi = PHI_CHAIN (phi))
2136 n1 = phi_arg_from_edge (phi, e1);
2137 n2 = phi_arg_from_edge (phi, e2);
2139 gcc_assert (n1 >= 0);
2140 gcc_assert (n2 >= 0);
2142 val1 = PHI_ARG_DEF (phi, n1);
2143 val2 = PHI_ARG_DEF (phi, n2);
2145 if (!operand_equal_p (val1, val2, 0))
2146 return false;
2149 return true;
2153 /*---------------------------------------------------------------------------
2154 Debugging functions
2155 ---------------------------------------------------------------------------*/
2157 /* Dump tree-specific information of block BB to file OUTF. */
2159 void
2160 tree_dump_bb (basic_block bb, FILE *outf, int indent)
2162 dump_generic_bb (outf, bb, indent, TDF_VOPS);
2166 /* Dump a basic block on stderr. */
2168 void
2169 debug_tree_bb (basic_block bb)
2171 dump_bb (bb, stderr, 0);
2175 /* Dump basic block with index N on stderr. */
2177 basic_block
2178 debug_tree_bb_n (int n)
2180 debug_tree_bb (BASIC_BLOCK (n));
2181 return BASIC_BLOCK (n);
2185 /* Dump the CFG on stderr.
2187 FLAGS are the same used by the tree dumping functions
2188 (see TDF_* in tree.h). */
2190 void
2191 debug_tree_cfg (int flags)
2193 dump_tree_cfg (stderr, flags);
2197 /* Dump the program showing basic block boundaries on the given FILE.
2199 FLAGS are the same used by the tree dumping functions (see TDF_* in
2200 tree.h). */
2202 void
2203 dump_tree_cfg (FILE *file, int flags)
2205 if (flags & TDF_DETAILS)
2207 const char *funcname
2208 = lang_hooks.decl_printable_name (current_function_decl, 2);
2210 fputc ('\n', file);
2211 fprintf (file, ";; Function %s\n\n", funcname);
2212 fprintf (file, ";; \n%d basic blocks, %d edges, last basic block %d.\n\n",
2213 n_basic_blocks, n_edges, last_basic_block);
2215 brief_dump_cfg (file);
2216 fprintf (file, "\n");
2219 if (flags & TDF_STATS)
2220 dump_cfg_stats (file);
2222 dump_function_to_file (current_function_decl, file, flags | TDF_BLOCKS);
2226 /* Dump CFG statistics on FILE. */
2228 void
2229 dump_cfg_stats (FILE *file)
2231 static long max_num_merged_labels = 0;
2232 unsigned long size, total = 0;
2233 int n_edges;
2234 basic_block bb;
2235 const char * const fmt_str = "%-30s%-13s%12s\n";
2236 const char * const fmt_str_1 = "%-30s%13d%11lu%c\n";
2237 const char * const fmt_str_3 = "%-43s%11lu%c\n";
2238 const char *funcname
2239 = lang_hooks.decl_printable_name (current_function_decl, 2);
2242 fprintf (file, "\nCFG Statistics for %s\n\n", funcname);
2244 fprintf (file, "---------------------------------------------------------\n");
2245 fprintf (file, fmt_str, "", " Number of ", "Memory");
2246 fprintf (file, fmt_str, "", " instances ", "used ");
2247 fprintf (file, "---------------------------------------------------------\n");
2249 size = n_basic_blocks * sizeof (struct basic_block_def);
2250 total += size;
2251 fprintf (file, fmt_str_1, "Basic blocks", n_basic_blocks,
2252 SCALE (size), LABEL (size));
2254 n_edges = 0;
2255 FOR_EACH_BB (bb)
2256 n_edges += EDGE_COUNT (bb->succs);
2257 size = n_edges * sizeof (struct edge_def);
2258 total += size;
2259 fprintf (file, fmt_str_1, "Edges", n_edges, SCALE (size), LABEL (size));
2261 size = n_basic_blocks * sizeof (struct bb_ann_d);
2262 total += size;
2263 fprintf (file, fmt_str_1, "Basic block annotations", n_basic_blocks,
2264 SCALE (size), LABEL (size));
2266 fprintf (file, "---------------------------------------------------------\n");
2267 fprintf (file, fmt_str_3, "Total memory used by CFG data", SCALE (total),
2268 LABEL (total));
2269 fprintf (file, "---------------------------------------------------------\n");
2270 fprintf (file, "\n");
2272 if (cfg_stats.num_merged_labels > max_num_merged_labels)
2273 max_num_merged_labels = cfg_stats.num_merged_labels;
2275 fprintf (file, "Coalesced label blocks: %ld (Max so far: %ld)\n",
2276 cfg_stats.num_merged_labels, max_num_merged_labels);
2278 fprintf (file, "\n");
2282 /* Dump CFG statistics on stderr. Keep extern so that it's always
2283 linked in the final executable. */
2285 void
2286 debug_cfg_stats (void)
2288 dump_cfg_stats (stderr);
2292 /* Dump the flowgraph to a .vcg FILE. */
2294 static void
2295 tree_cfg2vcg (FILE *file)
2297 edge e;
2298 edge_iterator ei;
2299 basic_block bb;
2300 const char *funcname
2301 = lang_hooks.decl_printable_name (current_function_decl, 2);
2303 /* Write the file header. */
2304 fprintf (file, "graph: { title: \"%s\"\n", funcname);
2305 fprintf (file, "node: { title: \"ENTRY\" label: \"ENTRY\" }\n");
2306 fprintf (file, "node: { title: \"EXIT\" label: \"EXIT\" }\n");
2308 /* Write blocks and edges. */
2309 FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
2311 fprintf (file, "edge: { sourcename: \"ENTRY\" targetname: \"%d\"",
2312 e->dest->index);
2314 if (e->flags & EDGE_FAKE)
2315 fprintf (file, " linestyle: dotted priority: 10");
2316 else
2317 fprintf (file, " linestyle: solid priority: 100");
2319 fprintf (file, " }\n");
2321 fputc ('\n', file);
2323 FOR_EACH_BB (bb)
2325 enum tree_code head_code, end_code;
2326 const char *head_name, *end_name;
2327 int head_line = 0;
2328 int end_line = 0;
2329 tree first = first_stmt (bb);
2330 tree last = last_stmt (bb);
2332 if (first)
2334 head_code = TREE_CODE (first);
2335 head_name = tree_code_name[head_code];
2336 head_line = get_lineno (first);
2338 else
2339 head_name = "no-statement";
2341 if (last)
2343 end_code = TREE_CODE (last);
2344 end_name = tree_code_name[end_code];
2345 end_line = get_lineno (last);
2347 else
2348 end_name = "no-statement";
2350 fprintf (file, "node: { title: \"%d\" label: \"#%d\\n%s (%d)\\n%s (%d)\"}\n",
2351 bb->index, bb->index, head_name, head_line, end_name,
2352 end_line);
2354 FOR_EACH_EDGE (e, ei, bb->succs)
2356 if (e->dest == EXIT_BLOCK_PTR)
2357 fprintf (file, "edge: { sourcename: \"%d\" targetname: \"EXIT\"", bb->index);
2358 else
2359 fprintf (file, "edge: { sourcename: \"%d\" targetname: \"%d\"", bb->index, e->dest->index);
2361 if (e->flags & EDGE_FAKE)
2362 fprintf (file, " priority: 10 linestyle: dotted");
2363 else
2364 fprintf (file, " priority: 100 linestyle: solid");
2366 fprintf (file, " }\n");
2369 if (bb->next_bb != EXIT_BLOCK_PTR)
2370 fputc ('\n', file);
2373 fputs ("}\n\n", file);
2378 /*---------------------------------------------------------------------------
2379 Miscellaneous helpers
2380 ---------------------------------------------------------------------------*/
2382 /* Return true if T represents a stmt that always transfers control. */
2384 bool
2385 is_ctrl_stmt (tree t)
2387 return (TREE_CODE (t) == COND_EXPR
2388 || TREE_CODE (t) == SWITCH_EXPR
2389 || TREE_CODE (t) == GOTO_EXPR
2390 || TREE_CODE (t) == RETURN_EXPR
2391 || TREE_CODE (t) == RESX_EXPR);
2395 /* Return true if T is a statement that may alter the flow of control
2396 (e.g., a call to a non-returning function). */
2398 bool
2399 is_ctrl_altering_stmt (tree t)
2401 tree call;
2403 gcc_assert (t);
2404 call = get_call_expr_in (t);
2405 if (call)
2407 /* A non-pure/const CALL_EXPR alters flow control if the current
2408 function has nonlocal labels. */
2409 if (TREE_SIDE_EFFECTS (call) && current_function_has_nonlocal_label)
2410 return true;
2412 /* A CALL_EXPR also alters control flow if it does not return. */
2413 if (call_expr_flags (call) & (ECF_NORETURN | ECF_LONGJMP))
2414 return true;
2417 /* If a statement can throw, it alters control flow. */
2418 return tree_can_throw_internal (t);
2422 /* Return true if T is a computed goto. */
2424 bool
2425 computed_goto_p (tree t)
2427 return (TREE_CODE (t) == GOTO_EXPR
2428 && TREE_CODE (GOTO_DESTINATION (t)) != LABEL_DECL);
2432 /* Checks whether EXPR is a simple local goto. */
2434 bool
2435 simple_goto_p (tree expr)
2437 return (TREE_CODE (expr) == GOTO_EXPR
2438 && TREE_CODE (GOTO_DESTINATION (expr)) == LABEL_DECL);
2442 /* Return true if T should start a new basic block. PREV_T is the
2443 statement preceding T. It is used when T is a label or a case label.
2444 Labels should only start a new basic block if their previous statement
2445 wasn't a label. Otherwise, sequence of labels would generate
2446 unnecessary basic blocks that only contain a single label. */
2448 static inline bool
2449 stmt_starts_bb_p (tree t, tree prev_t)
2451 enum tree_code code;
2453 if (t == NULL_TREE)
2454 return false;
2456 /* LABEL_EXPRs start a new basic block only if the preceding
2457 statement wasn't a label of the same type. This prevents the
2458 creation of consecutive blocks that have nothing but a single
2459 label. */
2460 code = TREE_CODE (t);
2461 if (code == LABEL_EXPR)
2463 /* Nonlocal and computed GOTO targets always start a new block. */
2464 if (code == LABEL_EXPR
2465 && (DECL_NONLOCAL (LABEL_EXPR_LABEL (t))
2466 || FORCED_LABEL (LABEL_EXPR_LABEL (t))))
2467 return true;
2469 if (prev_t && TREE_CODE (prev_t) == code)
2471 if (DECL_NONLOCAL (LABEL_EXPR_LABEL (prev_t)))
2472 return true;
2474 cfg_stats.num_merged_labels++;
2475 return false;
2477 else
2478 return true;
2481 return false;
2485 /* Return true if T should end a basic block. */
2487 bool
2488 stmt_ends_bb_p (tree t)
2490 return is_ctrl_stmt (t) || is_ctrl_altering_stmt (t);
2494 /* Add gotos that used to be represented implicitly in the CFG. */
2496 void
2497 disband_implicit_edges (void)
2499 basic_block bb;
2500 block_stmt_iterator last;
2501 edge e;
2502 edge_iterator ei;
2503 tree stmt, label;
2505 FOR_EACH_BB (bb)
2507 last = bsi_last (bb);
2508 stmt = last_stmt (bb);
2510 if (stmt && TREE_CODE (stmt) == COND_EXPR)
2512 /* Remove superfluous gotos from COND_EXPR branches. Moved
2513 from cfg_remove_useless_stmts here since it violates the
2514 invariants for tree--cfg correspondence and thus fits better
2515 here where we do it anyway. */
2516 FOR_EACH_EDGE (e, ei, bb->succs)
2518 if (e->dest != bb->next_bb)
2519 continue;
2521 if (e->flags & EDGE_TRUE_VALUE)
2522 COND_EXPR_THEN (stmt) = build_empty_stmt ();
2523 else if (e->flags & EDGE_FALSE_VALUE)
2524 COND_EXPR_ELSE (stmt) = build_empty_stmt ();
2525 else
2526 gcc_unreachable ();
2527 e->flags |= EDGE_FALLTHRU;
2530 continue;
2533 if (stmt && TREE_CODE (stmt) == RETURN_EXPR)
2535 /* Remove the RETURN_EXPR if we may fall though to the exit
2536 instead. */
2537 gcc_assert (EDGE_COUNT (bb->succs) == 1);
2538 gcc_assert (EDGE_SUCC (bb, 0)->dest == EXIT_BLOCK_PTR);
2540 if (bb->next_bb == EXIT_BLOCK_PTR
2541 && !TREE_OPERAND (stmt, 0))
2543 bsi_remove (&last);
2544 EDGE_SUCC (bb, 0)->flags |= EDGE_FALLTHRU;
2546 continue;
2549 /* There can be no fallthru edge if the last statement is a control
2550 one. */
2551 if (stmt && is_ctrl_stmt (stmt))
2552 continue;
2554 /* Find a fallthru edge and emit the goto if necessary. */
2555 FOR_EACH_EDGE (e, ei, bb->succs)
2556 if (e->flags & EDGE_FALLTHRU)
2557 break;
2559 if (!e || e->dest == bb->next_bb)
2560 continue;
2562 gcc_assert (e->dest != EXIT_BLOCK_PTR);
2563 label = tree_block_label (e->dest);
2565 stmt = build1 (GOTO_EXPR, void_type_node, label);
2566 #ifdef USE_MAPPED_LOCATION
2567 SET_EXPR_LOCATION (stmt, e->goto_locus);
2568 #else
2569 SET_EXPR_LOCUS (stmt, e->goto_locus);
2570 #endif
2571 bsi_insert_after (&last, stmt, BSI_NEW_STMT);
2572 e->flags &= ~EDGE_FALLTHRU;
2576 /* Remove block annotations and other datastructures. */
2578 void
2579 delete_tree_cfg_annotations (void)
2581 basic_block bb;
2582 if (n_basic_blocks > 0)
2583 free_blocks_annotations ();
2585 label_to_block_map = NULL;
2586 free_rbi_pool ();
2587 FOR_EACH_BB (bb)
2588 bb->rbi = NULL;
2592 /* Return the first statement in basic block BB. */
2594 tree
2595 first_stmt (basic_block bb)
2597 block_stmt_iterator i = bsi_start (bb);
2598 return !bsi_end_p (i) ? bsi_stmt (i) : NULL_TREE;
2602 /* Return the last statement in basic block BB. */
2604 tree
2605 last_stmt (basic_block bb)
2607 block_stmt_iterator b = bsi_last (bb);
2608 return !bsi_end_p (b) ? bsi_stmt (b) : NULL_TREE;
2612 /* Return a pointer to the last statement in block BB. */
2614 tree *
2615 last_stmt_ptr (basic_block bb)
2617 block_stmt_iterator last = bsi_last (bb);
2618 return !bsi_end_p (last) ? bsi_stmt_ptr (last) : NULL;
2622 /* Return the last statement of an otherwise empty block. Return NULL
2623 if the block is totally empty, or if it contains more than one
2624 statement. */
2626 tree
2627 last_and_only_stmt (basic_block bb)
2629 block_stmt_iterator i = bsi_last (bb);
2630 tree last, prev;
2632 if (bsi_end_p (i))
2633 return NULL_TREE;
2635 last = bsi_stmt (i);
2636 bsi_prev (&i);
2637 if (bsi_end_p (i))
2638 return last;
2640 /* Empty statements should no longer appear in the instruction stream.
2641 Everything that might have appeared before should be deleted by
2642 remove_useless_stmts, and the optimizers should just bsi_remove
2643 instead of smashing with build_empty_stmt.
2645 Thus the only thing that should appear here in a block containing
2646 one executable statement is a label. */
2647 prev = bsi_stmt (i);
2648 if (TREE_CODE (prev) == LABEL_EXPR)
2649 return last;
2650 else
2651 return NULL_TREE;
2655 /* Mark BB as the basic block holding statement T. */
2657 void
2658 set_bb_for_stmt (tree t, basic_block bb)
2660 if (TREE_CODE (t) == PHI_NODE)
2661 PHI_BB (t) = bb;
2662 else if (TREE_CODE (t) == STATEMENT_LIST)
2664 tree_stmt_iterator i;
2665 for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
2666 set_bb_for_stmt (tsi_stmt (i), bb);
2668 else
2670 stmt_ann_t ann = get_stmt_ann (t);
2671 ann->bb = bb;
2673 /* If the statement is a label, add the label to block-to-labels map
2674 so that we can speed up edge creation for GOTO_EXPRs. */
2675 if (TREE_CODE (t) == LABEL_EXPR)
2677 int uid;
2679 t = LABEL_EXPR_LABEL (t);
2680 uid = LABEL_DECL_UID (t);
2681 if (uid == -1)
2683 LABEL_DECL_UID (t) = uid = cfun->last_label_uid++;
2684 if (VARRAY_SIZE (label_to_block_map) <= (unsigned) uid)
2685 VARRAY_GROW (label_to_block_map, 3 * uid / 2);
2687 else
2688 /* We're moving an existing label. Make sure that we've
2689 removed it from the old block. */
2690 gcc_assert (!bb || !VARRAY_BB (label_to_block_map, uid));
2691 VARRAY_BB (label_to_block_map, uid) = bb;
2696 /* Finds iterator for STMT. */
2698 extern block_stmt_iterator
2699 stmt_for_bsi (tree stmt)
2701 block_stmt_iterator bsi;
2703 for (bsi = bsi_start (bb_for_stmt (stmt)); !bsi_end_p (bsi); bsi_next (&bsi))
2704 if (bsi_stmt (bsi) == stmt)
2705 return bsi;
2707 gcc_unreachable ();
2710 /* Insert statement (or statement list) T before the statement
2711 pointed-to by iterator I. M specifies how to update iterator I
2712 after insertion (see enum bsi_iterator_update). */
2714 void
2715 bsi_insert_before (block_stmt_iterator *i, tree t, enum bsi_iterator_update m)
2717 set_bb_for_stmt (t, i->bb);
2718 tsi_link_before (&i->tsi, t, m);
2719 modify_stmt (t);
2723 /* Insert statement (or statement list) T after the statement
2724 pointed-to by iterator I. M specifies how to update iterator I
2725 after insertion (see enum bsi_iterator_update). */
2727 void
2728 bsi_insert_after (block_stmt_iterator *i, tree t, enum bsi_iterator_update m)
2730 set_bb_for_stmt (t, i->bb);
2731 tsi_link_after (&i->tsi, t, m);
2732 modify_stmt (t);
2736 /* Remove the statement pointed to by iterator I. The iterator is updated
2737 to the next statement. */
2739 void
2740 bsi_remove (block_stmt_iterator *i)
2742 tree t = bsi_stmt (*i);
2743 set_bb_for_stmt (t, NULL);
2744 tsi_delink (&i->tsi);
2748 /* Move the statement at FROM so it comes right after the statement at TO. */
2750 void
2751 bsi_move_after (block_stmt_iterator *from, block_stmt_iterator *to)
2753 tree stmt = bsi_stmt (*from);
2754 bsi_remove (from);
2755 bsi_insert_after (to, stmt, BSI_SAME_STMT);
2759 /* Move the statement at FROM so it comes right before the statement at TO. */
2761 void
2762 bsi_move_before (block_stmt_iterator *from, block_stmt_iterator *to)
2764 tree stmt = bsi_stmt (*from);
2765 bsi_remove (from);
2766 bsi_insert_before (to, stmt, BSI_SAME_STMT);
2770 /* Move the statement at FROM to the end of basic block BB. */
2772 void
2773 bsi_move_to_bb_end (block_stmt_iterator *from, basic_block bb)
2775 block_stmt_iterator last = bsi_last (bb);
2777 /* Have to check bsi_end_p because it could be an empty block. */
2778 if (!bsi_end_p (last) && is_ctrl_stmt (bsi_stmt (last)))
2779 bsi_move_before (from, &last);
2780 else
2781 bsi_move_after (from, &last);
2785 /* Replace the contents of the statement pointed to by iterator BSI
2786 with STMT. If PRESERVE_EH_INFO is true, the exception handling
2787 information of the original statement is preserved. */
2789 void
2790 bsi_replace (const block_stmt_iterator *bsi, tree stmt, bool preserve_eh_info)
2792 int eh_region;
2793 tree orig_stmt = bsi_stmt (*bsi);
2795 SET_EXPR_LOCUS (stmt, EXPR_LOCUS (orig_stmt));
2796 set_bb_for_stmt (stmt, bsi->bb);
2798 /* Preserve EH region information from the original statement, if
2799 requested by the caller. */
2800 if (preserve_eh_info)
2802 eh_region = lookup_stmt_eh_region (orig_stmt);
2803 if (eh_region >= 0)
2804 add_stmt_to_eh_region (stmt, eh_region);
2807 *bsi_stmt_ptr (*bsi) = stmt;
2808 modify_stmt (stmt);
2812 /* Insert the statement pointed-to by BSI into edge E. Every attempt
2813 is made to place the statement in an existing basic block, but
2814 sometimes that isn't possible. When it isn't possible, the edge is
2815 split and the statement is added to the new block.
2817 In all cases, the returned *BSI points to the correct location. The
2818 return value is true if insertion should be done after the location,
2819 or false if it should be done before the location. If new basic block
2820 has to be created, it is stored in *NEW_BB. */
2822 static bool
2823 tree_find_edge_insert_loc (edge e, block_stmt_iterator *bsi,
2824 basic_block *new_bb)
2826 basic_block dest, src;
2827 tree tmp;
2829 dest = e->dest;
2830 restart:
2832 /* If the destination has one predecessor which has no PHI nodes,
2833 insert there. Except for the exit block.
2835 The requirement for no PHI nodes could be relaxed. Basically we
2836 would have to examine the PHIs to prove that none of them used
2837 the value set by the statement we want to insert on E. That
2838 hardly seems worth the effort. */
2839 if (EDGE_COUNT (dest->preds) == 1
2840 && ! phi_nodes (dest)
2841 && dest != EXIT_BLOCK_PTR)
2843 *bsi = bsi_start (dest);
2844 if (bsi_end_p (*bsi))
2845 return true;
2847 /* Make sure we insert after any leading labels. */
2848 tmp = bsi_stmt (*bsi);
2849 while (TREE_CODE (tmp) == LABEL_EXPR)
2851 bsi_next (bsi);
2852 if (bsi_end_p (*bsi))
2853 break;
2854 tmp = bsi_stmt (*bsi);
2857 if (bsi_end_p (*bsi))
2859 *bsi = bsi_last (dest);
2860 return true;
2862 else
2863 return false;
2866 /* If the source has one successor, the edge is not abnormal and
2867 the last statement does not end a basic block, insert there.
2868 Except for the entry block. */
2869 src = e->src;
2870 if ((e->flags & EDGE_ABNORMAL) == 0
2871 && EDGE_COUNT (src->succs) == 1
2872 && src != ENTRY_BLOCK_PTR)
2874 *bsi = bsi_last (src);
2875 if (bsi_end_p (*bsi))
2876 return true;
2878 tmp = bsi_stmt (*bsi);
2879 if (!stmt_ends_bb_p (tmp))
2880 return true;
2882 /* Insert code just before returning the value. We may need to decompose
2883 the return in the case it contains non-trivial operand. */
2884 if (TREE_CODE (tmp) == RETURN_EXPR)
2886 tree op = TREE_OPERAND (tmp, 0);
2887 if (!is_gimple_val (op))
2889 gcc_assert (TREE_CODE (op) == MODIFY_EXPR);
2890 bsi_insert_before (bsi, op, BSI_NEW_STMT);
2891 TREE_OPERAND (tmp, 0) = TREE_OPERAND (op, 0);
2893 bsi_prev (bsi);
2894 return true;
2898 /* Otherwise, create a new basic block, and split this edge. */
2899 dest = split_edge (e);
2900 if (new_bb)
2901 *new_bb = dest;
2902 e = EDGE_PRED (dest, 0);
2903 goto restart;
2907 /* This routine will commit all pending edge insertions, creating any new
2908 basic blocks which are necessary.
2910 If specified, NEW_BLOCKS returns a count of the number of new basic
2911 blocks which were created. */
2913 void
2914 bsi_commit_edge_inserts (int *new_blocks)
2916 basic_block bb;
2917 edge e;
2918 int blocks;
2919 edge_iterator ei;
2921 blocks = n_basic_blocks;
2923 bsi_commit_edge_inserts_1 (EDGE_SUCC (ENTRY_BLOCK_PTR, 0));
2925 FOR_EACH_BB (bb)
2926 FOR_EACH_EDGE (e, ei, bb->succs)
2927 bsi_commit_edge_inserts_1 (e);
2929 if (new_blocks)
2930 *new_blocks = n_basic_blocks - blocks;
2934 /* Commit insertions pending at edge E. */
2936 static void
2937 bsi_commit_edge_inserts_1 (edge e)
2939 if (PENDING_STMT (e))
2941 block_stmt_iterator bsi;
2942 tree stmt = PENDING_STMT (e);
2944 PENDING_STMT (e) = NULL_TREE;
2946 if (tree_find_edge_insert_loc (e, &bsi, NULL))
2947 bsi_insert_after (&bsi, stmt, BSI_NEW_STMT);
2948 else
2949 bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
2954 /* Add STMT to the pending list of edge E. No actual insertion is
2955 made until a call to bsi_commit_edge_inserts () is made. */
2957 void
2958 bsi_insert_on_edge (edge e, tree stmt)
2960 append_to_statement_list (stmt, &PENDING_STMT (e));
2963 /* Similar to bsi_insert_on_edge+bsi_commit_edge_inserts. If new block has to
2964 be created, it is returned. */
2966 basic_block
2967 bsi_insert_on_edge_immediate (edge e, tree stmt)
2969 block_stmt_iterator bsi;
2970 basic_block new_bb = NULL;
2972 gcc_assert (!PENDING_STMT (e));
2974 if (tree_find_edge_insert_loc (e, &bsi, &new_bb))
2975 bsi_insert_after (&bsi, stmt, BSI_NEW_STMT);
2976 else
2977 bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
2979 return new_bb;
2982 /*---------------------------------------------------------------------------
2983 Tree specific functions for CFG manipulation
2984 ---------------------------------------------------------------------------*/
2986 /* Split a (typically critical) edge EDGE_IN. Return the new block.
2987 Abort on abnormal edges. */
2989 static basic_block
2990 tree_split_edge (edge edge_in)
2992 basic_block new_bb, after_bb, dest, src;
2993 edge new_edge, e;
2994 tree phi;
2995 int i, num_elem;
2996 edge_iterator ei;
2998 /* Abnormal edges cannot be split. */
2999 gcc_assert (!(edge_in->flags & EDGE_ABNORMAL));
3001 src = edge_in->src;
3002 dest = edge_in->dest;
3004 /* Place the new block in the block list. Try to keep the new block
3005 near its "logical" location. This is of most help to humans looking
3006 at debugging dumps. */
3007 FOR_EACH_EDGE (e, ei, dest->preds)
3008 if (e->src->next_bb == dest)
3009 break;
3010 if (!e)
3011 after_bb = dest->prev_bb;
3012 else
3013 after_bb = edge_in->src;
3015 new_bb = create_empty_bb (after_bb);
3016 new_bb->frequency = EDGE_FREQUENCY (edge_in);
3017 new_bb->count = edge_in->count;
3018 new_edge = make_edge (new_bb, dest, EDGE_FALLTHRU);
3019 new_edge->probability = REG_BR_PROB_BASE;
3020 new_edge->count = edge_in->count;
3022 /* Find all the PHI arguments on the original edge, and change them to
3023 the new edge. Do it before redirection, so that the argument does not
3024 get removed. */
3025 for (phi = phi_nodes (dest); phi; phi = PHI_CHAIN (phi))
3027 num_elem = PHI_NUM_ARGS (phi);
3028 for (i = 0; i < num_elem; i++)
3029 if (PHI_ARG_EDGE (phi, i) == edge_in)
3031 PHI_ARG_EDGE (phi, i) = new_edge;
3032 break;
3036 e = redirect_edge_and_branch (edge_in, new_bb);
3037 gcc_assert (e);
3038 gcc_assert (!PENDING_STMT (edge_in));
3040 return new_bb;
3044 /* Return true when BB has label LABEL in it. */
3046 static bool
3047 has_label_p (basic_block bb, tree label)
3049 block_stmt_iterator bsi;
3051 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3053 tree stmt = bsi_stmt (bsi);
3055 if (TREE_CODE (stmt) != LABEL_EXPR)
3056 return false;
3057 if (LABEL_EXPR_LABEL (stmt) == label)
3058 return true;
3060 return false;
3064 /* Callback for walk_tree, check that all elements with address taken are
3065 properly noticed as such. */
3067 static tree
3068 verify_expr (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
3070 tree t = *tp, x;
3072 if (TYPE_P (t))
3073 *walk_subtrees = 0;
3075 /* Check operand N for being valid GIMPLE and give error MSG if not.
3076 We check for constants explicitly since they are not considered
3077 gimple invariants if they overflowed. */
3078 #define CHECK_OP(N, MSG) \
3079 do { if (!CONSTANT_CLASS_P (TREE_OPERAND (t, N)) \
3080 && !is_gimple_val (TREE_OPERAND (t, N))) \
3081 { error (MSG); return TREE_OPERAND (t, N); }} while (0)
3083 switch (TREE_CODE (t))
3085 case SSA_NAME:
3086 if (SSA_NAME_IN_FREE_LIST (t))
3088 error ("SSA name in freelist but still referenced");
3089 return *tp;
3091 break;
3093 case MODIFY_EXPR:
3094 x = TREE_OPERAND (t, 0);
3095 if (TREE_CODE (x) == BIT_FIELD_REF
3096 && is_gimple_reg (TREE_OPERAND (x, 0)))
3098 error ("GIMPLE register modified with BIT_FIELD_REF");
3099 return t;
3101 break;
3103 case ADDR_EXPR:
3104 /* Skip any references (they will be checked when we recurse down the
3105 tree) and ensure that any variable used as a prefix is marked
3106 addressable. */
3107 for (x = TREE_OPERAND (t, 0);
3108 (handled_component_p (x)
3109 || TREE_CODE (x) == REALPART_EXPR
3110 || TREE_CODE (x) == IMAGPART_EXPR);
3111 x = TREE_OPERAND (x, 0))
3114 if (TREE_CODE (x) != VAR_DECL && TREE_CODE (x) != PARM_DECL)
3115 return NULL;
3116 if (!TREE_ADDRESSABLE (x))
3118 error ("address taken, but ADDRESSABLE bit not set");
3119 return x;
3121 break;
3123 case COND_EXPR:
3124 x = TREE_OPERAND (t, 0);
3125 if (TREE_CODE (TREE_TYPE (x)) != BOOLEAN_TYPE)
3127 error ("non-boolean used in condition");
3128 return x;
3130 break;
3132 case NOP_EXPR:
3133 case CONVERT_EXPR:
3134 case FIX_TRUNC_EXPR:
3135 case FIX_CEIL_EXPR:
3136 case FIX_FLOOR_EXPR:
3137 case FIX_ROUND_EXPR:
3138 case FLOAT_EXPR:
3139 case NEGATE_EXPR:
3140 case ABS_EXPR:
3141 case BIT_NOT_EXPR:
3142 case NON_LVALUE_EXPR:
3143 case TRUTH_NOT_EXPR:
3144 CHECK_OP (0, "Invalid operand to unary operator");
3145 break;
3147 case REALPART_EXPR:
3148 case IMAGPART_EXPR:
3149 case COMPONENT_REF:
3150 case ARRAY_REF:
3151 case ARRAY_RANGE_REF:
3152 case BIT_FIELD_REF:
3153 case VIEW_CONVERT_EXPR:
3154 /* We have a nest of references. Verify that each of the operands
3155 that determine where to reference is either a constant or a variable,
3156 verify that the base is valid, and then show we've already checked
3157 the subtrees. */
3158 while (TREE_CODE (t) == REALPART_EXPR || TREE_CODE (t) == IMAGPART_EXPR
3159 || handled_component_p (t))
3161 if (TREE_CODE (t) == COMPONENT_REF && TREE_OPERAND (t, 2))
3162 CHECK_OP (2, "Invalid COMPONENT_REF offset operator");
3163 else if (TREE_CODE (t) == ARRAY_REF
3164 || TREE_CODE (t) == ARRAY_RANGE_REF)
3166 CHECK_OP (1, "Invalid array index.");
3167 if (TREE_OPERAND (t, 2))
3168 CHECK_OP (2, "Invalid array lower bound.");
3169 if (TREE_OPERAND (t, 3))
3170 CHECK_OP (3, "Invalid array stride.");
3172 else if (TREE_CODE (t) == BIT_FIELD_REF)
3174 CHECK_OP (1, "Invalid operand to BIT_FIELD_REF");
3175 CHECK_OP (2, "Invalid operand to BIT_FIELD_REF");
3178 t = TREE_OPERAND (t, 0);
3181 if (!CONSTANT_CLASS_P (t) && !is_gimple_lvalue (t))
3183 error ("Invalid reference prefix.");
3184 return t;
3186 *walk_subtrees = 0;
3187 break;
3189 case LT_EXPR:
3190 case LE_EXPR:
3191 case GT_EXPR:
3192 case GE_EXPR:
3193 case EQ_EXPR:
3194 case NE_EXPR:
3195 case UNORDERED_EXPR:
3196 case ORDERED_EXPR:
3197 case UNLT_EXPR:
3198 case UNLE_EXPR:
3199 case UNGT_EXPR:
3200 case UNGE_EXPR:
3201 case UNEQ_EXPR:
3202 case LTGT_EXPR:
3203 case PLUS_EXPR:
3204 case MINUS_EXPR:
3205 case MULT_EXPR:
3206 case TRUNC_DIV_EXPR:
3207 case CEIL_DIV_EXPR:
3208 case FLOOR_DIV_EXPR:
3209 case ROUND_DIV_EXPR:
3210 case TRUNC_MOD_EXPR:
3211 case CEIL_MOD_EXPR:
3212 case FLOOR_MOD_EXPR:
3213 case ROUND_MOD_EXPR:
3214 case RDIV_EXPR:
3215 case EXACT_DIV_EXPR:
3216 case MIN_EXPR:
3217 case MAX_EXPR:
3218 case LSHIFT_EXPR:
3219 case RSHIFT_EXPR:
3220 case LROTATE_EXPR:
3221 case RROTATE_EXPR:
3222 case BIT_IOR_EXPR:
3223 case BIT_XOR_EXPR:
3224 case BIT_AND_EXPR:
3225 CHECK_OP (0, "Invalid operand to binary operator");
3226 CHECK_OP (1, "Invalid operand to binary operator");
3227 break;
3229 default:
3230 break;
3232 return NULL;
3234 #undef CHECK_OP
3238 /* Verify STMT, return true if STMT is not in GIMPLE form.
3239 TODO: Implement type checking. */
3241 static bool
3242 verify_stmt (tree stmt, bool last_in_block)
3244 tree addr;
3246 if (!is_gimple_stmt (stmt))
3248 error ("Is not a valid GIMPLE statement.");
3249 goto fail;
3252 addr = walk_tree (&stmt, verify_expr, NULL, NULL);
3253 if (addr)
3255 debug_generic_stmt (addr);
3256 return true;
3259 /* If the statement is marked as part of an EH region, then it is
3260 expected that the statement could throw. Verify that when we
3261 have optimizations that simplify statements such that we prove
3262 that they cannot throw, that we update other data structures
3263 to match. */
3264 if (lookup_stmt_eh_region (stmt) >= 0)
3266 if (!tree_could_throw_p (stmt))
3268 error ("Statement marked for throw, but doesn%'t.");
3269 goto fail;
3271 if (!last_in_block && tree_can_throw_internal (stmt))
3273 error ("Statement marked for throw in middle of block.");
3274 goto fail;
3278 return false;
3280 fail:
3281 debug_generic_stmt (stmt);
3282 return true;
3286 /* Return true when the T can be shared. */
3288 static bool
3289 tree_node_can_be_shared (tree t)
3291 if (IS_TYPE_OR_DECL_P (t)
3292 /* We check for constants explicitly since they are not considered
3293 gimple invariants if they overflowed. */
3294 || CONSTANT_CLASS_P (t)
3295 || is_gimple_min_invariant (t)
3296 || TREE_CODE (t) == SSA_NAME)
3297 return true;
3299 while (((TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
3300 /* We check for constants explicitly since they are not considered
3301 gimple invariants if they overflowed. */
3302 && (CONSTANT_CLASS_P (TREE_OPERAND (t, 1))
3303 || is_gimple_min_invariant (TREE_OPERAND (t, 1))))
3304 || (TREE_CODE (t) == COMPONENT_REF
3305 || TREE_CODE (t) == REALPART_EXPR
3306 || TREE_CODE (t) == IMAGPART_EXPR))
3307 t = TREE_OPERAND (t, 0);
3309 if (DECL_P (t))
3310 return true;
3312 return false;
3316 /* Called via walk_trees. Verify tree sharing. */
3318 static tree
3319 verify_node_sharing (tree * tp, int *walk_subtrees, void *data)
3321 htab_t htab = (htab_t) data;
3322 void **slot;
3324 if (tree_node_can_be_shared (*tp))
3326 *walk_subtrees = false;
3327 return NULL;
3330 slot = htab_find_slot (htab, *tp, INSERT);
3331 if (*slot)
3332 return *slot;
3333 *slot = *tp;
3335 return NULL;
3339 /* Verify the GIMPLE statement chain. */
3341 void
3342 verify_stmts (void)
3344 basic_block bb;
3345 block_stmt_iterator bsi;
3346 bool err = false;
3347 htab_t htab;
3348 tree addr;
3350 timevar_push (TV_TREE_STMT_VERIFY);
3351 htab = htab_create (37, htab_hash_pointer, htab_eq_pointer, NULL);
3353 FOR_EACH_BB (bb)
3355 tree phi;
3356 int i;
3358 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
3360 int phi_num_args = PHI_NUM_ARGS (phi);
3362 for (i = 0; i < phi_num_args; i++)
3364 tree t = PHI_ARG_DEF (phi, i);
3365 tree addr;
3367 /* Addressable variables do have SSA_NAMEs but they
3368 are not considered gimple values. */
3369 if (TREE_CODE (t) != SSA_NAME
3370 && TREE_CODE (t) != FUNCTION_DECL
3371 && !is_gimple_val (t))
3373 error ("PHI def is not a GIMPLE value");
3374 debug_generic_stmt (phi);
3375 debug_generic_stmt (t);
3376 err |= true;
3379 addr = walk_tree (&t, verify_expr, NULL, NULL);
3380 if (addr)
3382 debug_generic_stmt (addr);
3383 err |= true;
3386 addr = walk_tree (&t, verify_node_sharing, htab, NULL);
3387 if (addr)
3389 error ("Incorrect sharing of tree nodes");
3390 debug_generic_stmt (phi);
3391 debug_generic_stmt (addr);
3392 err |= true;
3397 for (bsi = bsi_start (bb); !bsi_end_p (bsi); )
3399 tree stmt = bsi_stmt (bsi);
3400 bsi_next (&bsi);
3401 err |= verify_stmt (stmt, bsi_end_p (bsi));
3402 addr = walk_tree (&stmt, verify_node_sharing, htab, NULL);
3403 if (addr)
3405 error ("Incorrect sharing of tree nodes");
3406 debug_generic_stmt (stmt);
3407 debug_generic_stmt (addr);
3408 err |= true;
3413 if (err)
3414 internal_error ("verify_stmts failed.");
3416 htab_delete (htab);
3417 timevar_pop (TV_TREE_STMT_VERIFY);
3421 /* Verifies that the flow information is OK. */
3423 static int
3424 tree_verify_flow_info (void)
3426 int err = 0;
3427 basic_block bb;
3428 block_stmt_iterator bsi;
3429 tree stmt;
3430 edge e;
3431 edge_iterator ei;
3433 if (ENTRY_BLOCK_PTR->stmt_list)
3435 error ("ENTRY_BLOCK has a statement list associated with it\n");
3436 err = 1;
3439 if (EXIT_BLOCK_PTR->stmt_list)
3441 error ("EXIT_BLOCK has a statement list associated with it\n");
3442 err = 1;
3445 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
3446 if (e->flags & EDGE_FALLTHRU)
3448 error ("Fallthru to exit from bb %d\n", e->src->index);
3449 err = 1;
3452 FOR_EACH_BB (bb)
3454 bool found_ctrl_stmt = false;
3456 /* Skip labels on the start of basic block. */
3457 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3459 if (TREE_CODE (bsi_stmt (bsi)) != LABEL_EXPR)
3460 break;
3462 if (label_to_block (LABEL_EXPR_LABEL (bsi_stmt (bsi))) != bb)
3464 error ("Label %s to block does not match in bb %d\n",
3465 IDENTIFIER_POINTER (DECL_NAME (bsi_stmt (bsi))),
3466 bb->index);
3467 err = 1;
3470 if (decl_function_context (LABEL_EXPR_LABEL (bsi_stmt (bsi)))
3471 != current_function_decl)
3473 error ("Label %s has incorrect context in bb %d\n",
3474 IDENTIFIER_POINTER (DECL_NAME (bsi_stmt (bsi))),
3475 bb->index);
3476 err = 1;
3480 /* Verify that body of basic block BB is free of control flow. */
3481 for (; !bsi_end_p (bsi); bsi_next (&bsi))
3483 tree stmt = bsi_stmt (bsi);
3485 if (found_ctrl_stmt)
3487 error ("Control flow in the middle of basic block %d\n",
3488 bb->index);
3489 err = 1;
3492 if (stmt_ends_bb_p (stmt))
3493 found_ctrl_stmt = true;
3495 if (TREE_CODE (stmt) == LABEL_EXPR)
3497 error ("Label %s in the middle of basic block %d\n",
3498 IDENTIFIER_POINTER (DECL_NAME (stmt)),
3499 bb->index);
3500 err = 1;
3503 bsi = bsi_last (bb);
3504 if (bsi_end_p (bsi))
3505 continue;
3507 stmt = bsi_stmt (bsi);
3509 if (is_ctrl_stmt (stmt))
3511 FOR_EACH_EDGE (e, ei, bb->succs)
3512 if (e->flags & EDGE_FALLTHRU)
3514 error ("Fallthru edge after a control statement in bb %d \n",
3515 bb->index);
3516 err = 1;
3520 switch (TREE_CODE (stmt))
3522 case COND_EXPR:
3524 edge true_edge;
3525 edge false_edge;
3526 if (TREE_CODE (COND_EXPR_THEN (stmt)) != GOTO_EXPR
3527 || TREE_CODE (COND_EXPR_ELSE (stmt)) != GOTO_EXPR)
3529 error ("Structured COND_EXPR at the end of bb %d\n", bb->index);
3530 err = 1;
3533 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
3535 if (!true_edge || !false_edge
3536 || !(true_edge->flags & EDGE_TRUE_VALUE)
3537 || !(false_edge->flags & EDGE_FALSE_VALUE)
3538 || (true_edge->flags & (EDGE_FALLTHRU | EDGE_ABNORMAL))
3539 || (false_edge->flags & (EDGE_FALLTHRU | EDGE_ABNORMAL))
3540 || EDGE_COUNT (bb->succs) >= 3)
3542 error ("Wrong outgoing edge flags at end of bb %d\n",
3543 bb->index);
3544 err = 1;
3547 if (!has_label_p (true_edge->dest,
3548 GOTO_DESTINATION (COND_EXPR_THEN (stmt))))
3550 error ("%<then%> label does not match edge at end of bb %d\n",
3551 bb->index);
3552 err = 1;
3555 if (!has_label_p (false_edge->dest,
3556 GOTO_DESTINATION (COND_EXPR_ELSE (stmt))))
3558 error ("%<else%> label does not match edge at end of bb %d\n",
3559 bb->index);
3560 err = 1;
3563 break;
3565 case GOTO_EXPR:
3566 if (simple_goto_p (stmt))
3568 error ("Explicit goto at end of bb %d\n", bb->index);
3569 err = 1;
3571 else
3573 /* FIXME. We should double check that the labels in the
3574 destination blocks have their address taken. */
3575 FOR_EACH_EDGE (e, ei, bb->succs)
3576 if ((e->flags & (EDGE_FALLTHRU | EDGE_TRUE_VALUE
3577 | EDGE_FALSE_VALUE))
3578 || !(e->flags & EDGE_ABNORMAL))
3580 error ("Wrong outgoing edge flags at end of bb %d\n",
3581 bb->index);
3582 err = 1;
3585 break;
3587 case RETURN_EXPR:
3588 if (EDGE_COUNT (bb->succs) != 1
3589 || (EDGE_SUCC (bb, 0)->flags & (EDGE_FALLTHRU | EDGE_ABNORMAL
3590 | EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
3592 error ("Wrong outgoing edge flags at end of bb %d\n", bb->index);
3593 err = 1;
3595 if (EDGE_SUCC (bb, 0)->dest != EXIT_BLOCK_PTR)
3597 error ("Return edge does not point to exit in bb %d\n",
3598 bb->index);
3599 err = 1;
3601 break;
3603 case SWITCH_EXPR:
3605 tree prev;
3606 edge e;
3607 size_t i, n;
3608 tree vec;
3610 vec = SWITCH_LABELS (stmt);
3611 n = TREE_VEC_LENGTH (vec);
3613 /* Mark all the destination basic blocks. */
3614 for (i = 0; i < n; ++i)
3616 tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i));
3617 basic_block label_bb = label_to_block (lab);
3619 gcc_assert (!label_bb->aux || label_bb->aux == (void *)1);
3620 label_bb->aux = (void *)1;
3623 /* Verify that the case labels are sorted. */
3624 prev = TREE_VEC_ELT (vec, 0);
3625 for (i = 1; i < n - 1; ++i)
3627 tree c = TREE_VEC_ELT (vec, i);
3628 if (! CASE_LOW (c))
3630 error ("Found default case not at end of case vector");
3631 err = 1;
3632 continue;
3634 if (! tree_int_cst_lt (CASE_LOW (prev), CASE_LOW (c)))
3636 error ("Case labels not sorted:\n ");
3637 print_generic_expr (stderr, prev, 0);
3638 fprintf (stderr," is greater than ");
3639 print_generic_expr (stderr, c, 0);
3640 fprintf (stderr," but comes before it.\n");
3641 err = 1;
3643 prev = c;
3645 if (CASE_LOW (TREE_VEC_ELT (vec, n - 1)))
3647 error ("No default case found at end of case vector");
3648 err = 1;
3651 FOR_EACH_EDGE (e, ei, bb->succs)
3653 if (!e->dest->aux)
3655 error ("Extra outgoing edge %d->%d\n",
3656 bb->index, e->dest->index);
3657 err = 1;
3659 e->dest->aux = (void *)2;
3660 if ((e->flags & (EDGE_FALLTHRU | EDGE_ABNORMAL
3661 | EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
3663 error ("Wrong outgoing edge flags at end of bb %d\n",
3664 bb->index);
3665 err = 1;
3669 /* Check that we have all of them. */
3670 for (i = 0; i < n; ++i)
3672 tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i));
3673 basic_block label_bb = label_to_block (lab);
3675 if (label_bb->aux != (void *)2)
3677 error ("Missing edge %i->%i\n",
3678 bb->index, label_bb->index);
3679 err = 1;
3683 FOR_EACH_EDGE (e, ei, bb->succs)
3684 e->dest->aux = (void *)0;
3687 default: ;
3691 if (dom_computed[CDI_DOMINATORS] >= DOM_NO_FAST_QUERY)
3692 verify_dominators (CDI_DOMINATORS);
3694 return err;
3698 /* Updates phi nodes after creating forwarder block joined
3699 by edge FALLTHRU. */
3701 static void
3702 tree_make_forwarder_block (edge fallthru)
3704 edge e;
3705 edge_iterator ei;
3706 basic_block dummy, bb;
3707 tree phi, new_phi, var, prev, next;
3709 dummy = fallthru->src;
3710 bb = fallthru->dest;
3712 if (EDGE_COUNT (bb->preds) == 1)
3713 return;
3715 /* If we redirected a branch we must create new phi nodes at the
3716 start of BB. */
3717 for (phi = phi_nodes (dummy); phi; phi = PHI_CHAIN (phi))
3719 var = PHI_RESULT (phi);
3720 new_phi = create_phi_node (var, bb);
3721 SSA_NAME_DEF_STMT (var) = new_phi;
3722 SET_PHI_RESULT (phi, make_ssa_name (SSA_NAME_VAR (var), phi));
3723 add_phi_arg (&new_phi, PHI_RESULT (phi), fallthru);
3726 /* Ensure that the PHI node chain is in the same order. */
3727 prev = NULL;
3728 for (phi = phi_nodes (bb); phi; phi = next)
3730 next = PHI_CHAIN (phi);
3731 PHI_CHAIN (phi) = prev;
3732 prev = phi;
3734 set_phi_nodes (bb, prev);
3736 /* Add the arguments we have stored on edges. */
3737 FOR_EACH_EDGE (e, ei, bb->preds)
3739 if (e == fallthru)
3740 continue;
3742 for (phi = phi_nodes (bb), var = PENDING_STMT (e);
3743 phi;
3744 phi = PHI_CHAIN (phi), var = TREE_CHAIN (var))
3745 add_phi_arg (&phi, TREE_VALUE (var), e);
3747 PENDING_STMT (e) = NULL;
3752 /* Return true if basic block BB does nothing except pass control
3753 flow to another block and that we can safely insert a label at
3754 the start of the successor block. */
3756 static bool
3757 tree_forwarder_block_p (basic_block bb)
3759 block_stmt_iterator bsi;
3760 edge e;
3761 edge_iterator ei;
3763 /* If we have already determined that this block is not forwardable,
3764 then no further checks are necessary. */
3765 if (! bb_ann (bb)->forwardable)
3766 return false;
3768 /* BB must have a single outgoing normal edge. Otherwise it can not be
3769 a forwarder block. */
3770 if (EDGE_COUNT (bb->succs) != 1
3771 || EDGE_SUCC (bb, 0)->dest == EXIT_BLOCK_PTR
3772 || (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL)
3773 || bb == ENTRY_BLOCK_PTR)
3775 bb_ann (bb)->forwardable = 0;
3776 return false;
3779 /* Successors of the entry block are not forwarders. */
3780 FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
3781 if (e->dest == bb)
3783 bb_ann (bb)->forwardable = 0;
3784 return false;
3787 /* BB can not have any PHI nodes. This could potentially be relaxed
3788 early in compilation if we re-rewrote the variables appearing in
3789 any PHI nodes in forwarder blocks. */
3790 if (phi_nodes (bb))
3792 bb_ann (bb)->forwardable = 0;
3793 return false;
3796 /* Now walk through the statements. We can ignore labels, anything else
3797 means this is not a forwarder block. */
3798 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3800 tree stmt = bsi_stmt (bsi);
3802 switch (TREE_CODE (stmt))
3804 case LABEL_EXPR:
3805 if (DECL_NONLOCAL (LABEL_EXPR_LABEL (stmt)))
3806 return false;
3807 break;
3809 default:
3810 bb_ann (bb)->forwardable = 0;
3811 return false;
3815 return true;
3819 /* Thread jumps over empty statements.
3821 This code should _not_ thread over obviously equivalent conditions
3822 as that requires nontrivial updates to the SSA graph. */
3824 static bool
3825 thread_jumps (void)
3827 edge e, last, old;
3828 basic_block bb, dest, tmp, old_dest, curr, dom;
3829 tree phi;
3830 int arg;
3831 bool retval = false;
3833 FOR_EACH_BB (bb)
3834 bb_ann (bb)->forwardable = 1;
3836 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
3838 edge_iterator ei;
3840 /* Don't waste time on unreachable blocks. */
3841 if (EDGE_COUNT (bb->preds) == 0)
3842 continue;
3844 /* Nor on forwarders. */
3845 if (tree_forwarder_block_p (bb))
3846 continue;
3848 /* This block is now part of a forwarding path, mark it as not
3849 forwardable so that we can detect loops. This bit will be
3850 reset below. */
3851 bb_ann (bb)->forwardable = 0;
3853 /* Examine each of our block's successors to see if it is
3854 forwardable. */
3855 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
3857 int freq;
3858 gcov_type count;
3860 /* If the edge is abnormal or its destination is not
3861 forwardable, then there's nothing to do. */
3862 if ((e->flags & EDGE_ABNORMAL)
3863 || !tree_forwarder_block_p (e->dest))
3865 ei_next (&ei);
3866 continue;
3869 count = e->count;
3870 freq = EDGE_FREQUENCY (e);
3872 /* Now walk through as many forwarder blocks as possible to
3873 find the ultimate destination we want to thread our jump
3874 to. */
3875 last = EDGE_SUCC (e->dest, 0);
3876 bb_ann (e->dest)->forwardable = 0;
3877 for (dest = EDGE_SUCC (e->dest, 0)->dest;
3878 tree_forwarder_block_p (dest);
3879 last = EDGE_SUCC (dest, 0),
3880 dest = EDGE_SUCC (dest, 0)->dest)
3882 /* An infinite loop detected. We redirect the edge anyway, so
3883 that the loop is shrunk into single basic block. */
3884 if (!bb_ann (dest)->forwardable)
3885 break;
3887 if (EDGE_SUCC (dest, 0)->dest == EXIT_BLOCK_PTR)
3888 break;
3890 bb_ann (dest)->forwardable = 0;
3893 /* Reset the forwardable marks to 1. */
3894 for (tmp = e->dest;
3895 tmp != dest;
3896 tmp = EDGE_SUCC (tmp, 0)->dest)
3897 bb_ann (tmp)->forwardable = 1;
3899 if (dest == e->dest)
3901 ei_next (&ei);
3902 continue;
3905 old = find_edge (bb, dest);
3906 if (old)
3908 /* If there already is an edge, check whether the values
3909 in phi nodes differ. */
3910 if (!phi_alternatives_equal (dest, last, old))
3912 /* The previous block is forwarder. Redirect our jump
3913 to that target instead since we know it has no PHI
3914 nodes that will need updating. */
3915 dest = last->src;
3917 /* That might mean that no forwarding at all is possible. */
3918 if (dest == e->dest)
3920 ei_next (&ei);
3921 continue;
3924 old = find_edge (bb, dest);
3928 /* Perform the redirection. */
3929 retval = true;
3930 old_dest = e->dest;
3931 e = redirect_edge_and_branch (e, dest);
3933 /* Update the profile. */
3934 if (profile_status != PROFILE_ABSENT)
3935 for (curr = old_dest; curr != dest; curr = EDGE_SUCC (curr, 0)->dest)
3937 curr->frequency -= freq;
3938 if (curr->frequency < 0)
3939 curr->frequency = 0;
3940 curr->count -= count;
3941 if (curr->count < 0)
3942 curr->count = 0;
3943 EDGE_SUCC (curr, 0)->count -= count;
3944 if (EDGE_SUCC (curr, 0)->count < 0)
3945 EDGE_SUCC (curr, 0)->count = 0;
3948 if (!old)
3950 /* Update PHI nodes. We know that the new argument should
3951 have the same value as the argument associated with LAST.
3952 Otherwise we would have changed our target block above. */
3953 for (phi = phi_nodes (dest); phi; phi = PHI_CHAIN (phi))
3955 arg = phi_arg_from_edge (phi, last);
3956 gcc_assert (arg >= 0);
3957 add_phi_arg (&phi, PHI_ARG_DEF (phi, arg), e);
3961 /* Update the dominators. */
3962 if (dom_computed[CDI_DOMINATORS] >= DOM_CONS_OK)
3964 /* Remove the unreachable blocks (observe that if all blocks
3965 were reachable before, only those in the path we threaded
3966 over and did not have any predecessor outside of the path
3967 become unreachable). */
3968 for (; old_dest != dest; old_dest = tmp)
3970 tmp = EDGE_SUCC (old_dest, 0)->dest;
3972 if (EDGE_COUNT (old_dest->preds) > 0)
3973 break;
3975 delete_basic_block (old_dest);
3977 /* If the dominator of the destination was in the path, set its
3978 dominator to the start of the redirected edge. */
3979 if (get_immediate_dominator (CDI_DOMINATORS, old_dest) == NULL)
3980 set_immediate_dominator (CDI_DOMINATORS, old_dest, bb);
3982 /* Now proceed like if we forwarded just over one edge at a time.
3983 Algorithm for forwarding edge S --> A over edge A --> B then
3986 if (idom (B) == A
3987 && !dominated_by (S, B))
3988 idom (B) = idom (A);
3989 recount_idom (A); */
3991 for (; old_dest != dest; old_dest = tmp)
3993 tmp = EDGE_SUCC (old_dest, 0)->dest;
3995 if (get_immediate_dominator (CDI_DOMINATORS, tmp) == old_dest
3996 && !dominated_by_p (CDI_DOMINATORS, bb, tmp))
3998 dom = get_immediate_dominator (CDI_DOMINATORS, old_dest);
3999 set_immediate_dominator (CDI_DOMINATORS, tmp, dom);
4002 dom = recount_dominator (CDI_DOMINATORS, old_dest);
4003 set_immediate_dominator (CDI_DOMINATORS, old_dest, dom);
4008 /* Reset the forwardable bit on our block since it's no longer in
4009 a forwarding chain path. */
4010 bb_ann (bb)->forwardable = 1;
4013 return retval;
4017 /* Return a non-special label in the head of basic block BLOCK.
4018 Create one if it doesn't exist. */
4020 tree
4021 tree_block_label (basic_block bb)
4023 block_stmt_iterator i, s = bsi_start (bb);
4024 bool first = true;
4025 tree label, stmt;
4027 for (i = s; !bsi_end_p (i); first = false, bsi_next (&i))
4029 stmt = bsi_stmt (i);
4030 if (TREE_CODE (stmt) != LABEL_EXPR)
4031 break;
4032 label = LABEL_EXPR_LABEL (stmt);
4033 if (!DECL_NONLOCAL (label))
4035 if (!first)
4036 bsi_move_before (&i, &s);
4037 return label;
4041 label = create_artificial_label ();
4042 stmt = build1 (LABEL_EXPR, void_type_node, label);
4043 bsi_insert_before (&s, stmt, BSI_NEW_STMT);
4044 return label;
4048 /* Attempt to perform edge redirection by replacing a possibly complex
4049 jump instruction by a goto or by removing the jump completely.
4050 This can apply only if all edges now point to the same block. The
4051 parameters and return values are equivalent to
4052 redirect_edge_and_branch. */
4054 static edge
4055 tree_try_redirect_by_replacing_jump (edge e, basic_block target)
4057 basic_block src = e->src;
4058 edge tmp;
4059 block_stmt_iterator b;
4060 tree stmt;
4061 edge_iterator ei;
4063 /* Verify that all targets will be TARGET. */
4064 FOR_EACH_EDGE (tmp, ei, src->succs)
4065 if (tmp->dest != target && tmp != e)
4066 break;
4068 if (tmp)
4069 return NULL;
4071 b = bsi_last (src);
4072 if (bsi_end_p (b))
4073 return NULL;
4074 stmt = bsi_stmt (b);
4076 if (TREE_CODE (stmt) == COND_EXPR
4077 || TREE_CODE (stmt) == SWITCH_EXPR)
4079 bsi_remove (&b);
4080 e = ssa_redirect_edge (e, target);
4081 e->flags = EDGE_FALLTHRU;
4082 return e;
4085 return NULL;
4089 /* Redirect E to DEST. Return NULL on failure. Otherwise, return the
4090 edge representing the redirected branch. */
4092 static edge
4093 tree_redirect_edge_and_branch (edge e, basic_block dest)
4095 basic_block bb = e->src;
4096 block_stmt_iterator bsi;
4097 edge ret;
4098 tree label, stmt;
4100 if (e->flags & (EDGE_ABNORMAL_CALL | EDGE_EH))
4101 return NULL;
4103 if (e->src != ENTRY_BLOCK_PTR
4104 && (ret = tree_try_redirect_by_replacing_jump (e, dest)))
4105 return ret;
4107 if (e->dest == dest)
4108 return NULL;
4110 label = tree_block_label (dest);
4112 bsi = bsi_last (bb);
4113 stmt = bsi_end_p (bsi) ? NULL : bsi_stmt (bsi);
4115 switch (stmt ? TREE_CODE (stmt) : ERROR_MARK)
4117 case COND_EXPR:
4118 stmt = (e->flags & EDGE_TRUE_VALUE
4119 ? COND_EXPR_THEN (stmt)
4120 : COND_EXPR_ELSE (stmt));
4121 GOTO_DESTINATION (stmt) = label;
4122 break;
4124 case GOTO_EXPR:
4125 /* No non-abnormal edges should lead from a non-simple goto, and
4126 simple ones should be represented implicitly. */
4127 gcc_unreachable ();
4129 case SWITCH_EXPR:
4131 tree vec = SWITCH_LABELS (stmt);
4132 size_t i, n = TREE_VEC_LENGTH (vec);
4134 for (i = 0; i < n; ++i)
4136 tree elt = TREE_VEC_ELT (vec, i);
4137 if (label_to_block (CASE_LABEL (elt)) == e->dest)
4138 CASE_LABEL (elt) = label;
4141 break;
4143 case RETURN_EXPR:
4144 bsi_remove (&bsi);
4145 e->flags |= EDGE_FALLTHRU;
4146 break;
4148 default:
4149 /* Otherwise it must be a fallthru edge, and we don't need to
4150 do anything besides redirecting it. */
4151 gcc_assert (e->flags & EDGE_FALLTHRU);
4152 break;
4155 /* Update/insert PHI nodes as necessary. */
4157 /* Now update the edges in the CFG. */
4158 e = ssa_redirect_edge (e, dest);
4160 return e;
4164 /* Simple wrapper, as we can always redirect fallthru edges. */
4166 static basic_block
4167 tree_redirect_edge_and_branch_force (edge e, basic_block dest)
4169 e = tree_redirect_edge_and_branch (e, dest);
4170 gcc_assert (e);
4172 return NULL;
4176 /* Splits basic block BB after statement STMT (but at least after the
4177 labels). If STMT is NULL, BB is split just after the labels. */
4179 static basic_block
4180 tree_split_block (basic_block bb, void *stmt)
4182 block_stmt_iterator bsi, bsi_tgt;
4183 tree act;
4184 basic_block new_bb;
4185 edge e;
4186 edge_iterator ei;
4188 new_bb = create_empty_bb (bb);
4190 /* Redirect the outgoing edges. */
4191 new_bb->succs = bb->succs;
4192 bb->succs = NULL;
4193 FOR_EACH_EDGE (e, ei, new_bb->succs)
4194 e->src = new_bb;
4196 if (stmt && TREE_CODE ((tree) stmt) == LABEL_EXPR)
4197 stmt = NULL;
4199 /* Move everything from BSI to the new basic block. */
4200 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4202 act = bsi_stmt (bsi);
4203 if (TREE_CODE (act) == LABEL_EXPR)
4204 continue;
4206 if (!stmt)
4207 break;
4209 if (stmt == act)
4211 bsi_next (&bsi);
4212 break;
4216 bsi_tgt = bsi_start (new_bb);
4217 while (!bsi_end_p (bsi))
4219 act = bsi_stmt (bsi);
4220 bsi_remove (&bsi);
4221 bsi_insert_after (&bsi_tgt, act, BSI_NEW_STMT);
4224 return new_bb;
4228 /* Moves basic block BB after block AFTER. */
4230 static bool
4231 tree_move_block_after (basic_block bb, basic_block after)
4233 if (bb->prev_bb == after)
4234 return true;
4236 unlink_block (bb);
4237 link_block (bb, after);
4239 return true;
4243 /* Return true if basic_block can be duplicated. */
4245 static bool
4246 tree_can_duplicate_bb_p (basic_block bb ATTRIBUTE_UNUSED)
4248 return true;
4251 /* Create a duplicate of the basic block BB. NOTE: This does not
4252 preserve SSA form. */
4254 static basic_block
4255 tree_duplicate_bb (basic_block bb)
4257 basic_block new_bb;
4258 block_stmt_iterator bsi, bsi_tgt;
4259 tree phi, val;
4260 ssa_op_iter op_iter;
4262 new_bb = create_empty_bb (EXIT_BLOCK_PTR->prev_bb);
4264 /* First copy the phi nodes. We do not copy phi node arguments here,
4265 since the edges are not ready yet. Keep the chain of phi nodes in
4266 the same order, so that we can add them later. */
4267 for (phi = phi_nodes (bb); phi; phi = TREE_CHAIN (phi))
4269 mark_for_rewrite (PHI_RESULT (phi));
4270 create_phi_node (PHI_RESULT (phi), new_bb);
4272 set_phi_nodes (new_bb, nreverse (phi_nodes (new_bb)));
4274 bsi_tgt = bsi_start (new_bb);
4275 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4277 tree stmt = bsi_stmt (bsi);
4278 tree copy;
4280 if (TREE_CODE (stmt) == LABEL_EXPR)
4281 continue;
4283 /* Record the definitions. */
4284 get_stmt_operands (stmt);
4286 FOR_EACH_SSA_TREE_OPERAND (val, stmt, op_iter, SSA_OP_ALL_DEFS)
4287 mark_for_rewrite (val);
4289 copy = unshare_expr (stmt);
4291 /* Copy also the virtual operands. */
4292 get_stmt_ann (copy);
4293 copy_virtual_operands (copy, stmt);
4295 bsi_insert_after (&bsi_tgt, copy, BSI_NEW_STMT);
4298 return new_bb;
4301 /* Basic block BB_COPY was created by code duplication. Add phi node
4302 arguments for edges going out of BB_COPY. The blocks that were
4303 duplicated have rbi->duplicated set to one. */
4305 void
4306 add_phi_args_after_copy_bb (basic_block bb_copy)
4308 basic_block bb, dest;
4309 edge e, e_copy;
4310 edge_iterator ei;
4311 tree phi, phi_copy, phi_next, def;
4313 bb = bb_copy->rbi->original;
4315 FOR_EACH_EDGE (e_copy, ei, bb_copy->succs)
4317 if (!phi_nodes (e_copy->dest))
4318 continue;
4320 if (e_copy->dest->rbi->duplicated)
4321 dest = e_copy->dest->rbi->original;
4322 else
4323 dest = e_copy->dest;
4325 e = find_edge (bb, dest);
4326 if (!e)
4328 /* During loop unrolling the target of the latch edge is copied.
4329 In this case we are not looking for edge to dest, but to
4330 duplicated block whose original was dest. */
4331 FOR_EACH_EDGE (e, ei, bb->succs)
4332 if (e->dest->rbi->duplicated
4333 && e->dest->rbi->original == dest)
4334 break;
4336 gcc_assert (e != NULL);
4339 for (phi = phi_nodes (e->dest), phi_copy = phi_nodes (e_copy->dest);
4340 phi;
4341 phi = phi_next, phi_copy = TREE_CHAIN (phi_copy))
4343 phi_next = TREE_CHAIN (phi);
4345 gcc_assert (PHI_RESULT (phi) == PHI_RESULT (phi_copy));
4346 def = PHI_ARG_DEF_FROM_EDGE (phi, e);
4347 add_phi_arg (&phi_copy, def, e_copy);
4352 /* Blocks in REGION_COPY array of length N_REGION were created by
4353 duplication of basic blocks. Add phi node arguments for edges
4354 going from these blocks. */
4356 void
4357 add_phi_args_after_copy (basic_block *region_copy, unsigned n_region)
4359 unsigned i;
4361 for (i = 0; i < n_region; i++)
4362 region_copy[i]->rbi->duplicated = 1;
4364 for (i = 0; i < n_region; i++)
4365 add_phi_args_after_copy_bb (region_copy[i]);
4367 for (i = 0; i < n_region; i++)
4368 region_copy[i]->rbi->duplicated = 0;
4371 /* Maps the old ssa name FROM_NAME to TO_NAME. */
4373 struct ssa_name_map_entry
4375 tree from_name;
4376 tree to_name;
4379 /* Hash function for ssa_name_map_entry. */
4381 static hashval_t
4382 ssa_name_map_entry_hash (const void *entry)
4384 const struct ssa_name_map_entry *en = entry;
4385 return SSA_NAME_VERSION (en->from_name);
4388 /* Equality function for ssa_name_map_entry. */
4390 static int
4391 ssa_name_map_entry_eq (const void *in_table, const void *ssa_name)
4393 const struct ssa_name_map_entry *en = in_table;
4395 return en->from_name == ssa_name;
4398 /* Allocate duplicates of ssa names in list DEFINITIONS and store the mapping
4399 to MAP. */
4401 void
4402 allocate_ssa_names (bitmap definitions, htab_t *map)
4404 tree name;
4405 struct ssa_name_map_entry *entry;
4406 PTR *slot;
4407 unsigned ver;
4408 bitmap_iterator bi;
4410 if (!*map)
4411 *map = htab_create (10, ssa_name_map_entry_hash,
4412 ssa_name_map_entry_eq, free);
4413 EXECUTE_IF_SET_IN_BITMAP (definitions, 0, ver, bi)
4415 name = ssa_name (ver);
4416 slot = htab_find_slot_with_hash (*map, name, SSA_NAME_VERSION (name),
4417 INSERT);
4418 if (*slot)
4419 entry = *slot;
4420 else
4422 entry = xmalloc (sizeof (struct ssa_name_map_entry));
4423 entry->from_name = name;
4424 *slot = entry;
4426 entry->to_name = duplicate_ssa_name (name, SSA_NAME_DEF_STMT (name));
4430 /* Rewrite the definition DEF in statement STMT to new ssa name as specified
4431 by the mapping MAP. */
4433 static void
4434 rewrite_to_new_ssa_names_def (def_operand_p def, tree stmt, htab_t map)
4436 tree name = DEF_FROM_PTR (def);
4437 struct ssa_name_map_entry *entry;
4439 gcc_assert (TREE_CODE (name) == SSA_NAME);
4441 entry = htab_find_with_hash (map, name, SSA_NAME_VERSION (name));
4442 if (!entry)
4443 return;
4445 SET_DEF (def, entry->to_name);
4446 SSA_NAME_DEF_STMT (entry->to_name) = stmt;
4449 /* Rewrite the USE to new ssa name as specified by the mapping MAP. */
4451 static void
4452 rewrite_to_new_ssa_names_use (use_operand_p use, htab_t map)
4454 tree name = USE_FROM_PTR (use);
4455 struct ssa_name_map_entry *entry;
4457 if (TREE_CODE (name) != SSA_NAME)
4458 return;
4460 entry = htab_find_with_hash (map, name, SSA_NAME_VERSION (name));
4461 if (!entry)
4462 return;
4464 SET_USE (use, entry->to_name);
4467 /* Rewrite the ssa names in basic block BB to new ones as specified by the
4468 mapping MAP. */
4470 void
4471 rewrite_to_new_ssa_names_bb (basic_block bb, htab_t map)
4473 unsigned i;
4474 edge e;
4475 edge_iterator ei;
4476 tree phi, stmt;
4477 block_stmt_iterator bsi;
4478 use_optype uses;
4479 vuse_optype vuses;
4480 def_optype defs;
4481 v_may_def_optype v_may_defs;
4482 v_must_def_optype v_must_defs;
4483 stmt_ann_t ann;
4485 FOR_EACH_EDGE (e, ei, bb->preds)
4486 if (e->flags & EDGE_ABNORMAL)
4487 break;
4489 for (phi = phi_nodes (bb); phi; phi = TREE_CHAIN (phi))
4491 rewrite_to_new_ssa_names_def (PHI_RESULT_PTR (phi), phi, map);
4492 if (e)
4493 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)) = 1;
4496 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4498 stmt = bsi_stmt (bsi);
4499 get_stmt_operands (stmt);
4500 ann = stmt_ann (stmt);
4502 uses = USE_OPS (ann);
4503 for (i = 0; i < NUM_USES (uses); i++)
4504 rewrite_to_new_ssa_names_use (USE_OP_PTR (uses, i), map);
4506 defs = DEF_OPS (ann);
4507 for (i = 0; i < NUM_DEFS (defs); i++)
4508 rewrite_to_new_ssa_names_def (DEF_OP_PTR (defs, i), stmt, map);
4510 vuses = VUSE_OPS (ann);
4511 for (i = 0; i < NUM_VUSES (vuses); i++)
4512 rewrite_to_new_ssa_names_use (VUSE_OP_PTR (vuses, i), map);
4514 v_may_defs = V_MAY_DEF_OPS (ann);
4515 for (i = 0; i < NUM_V_MAY_DEFS (v_may_defs); i++)
4517 rewrite_to_new_ssa_names_use
4518 (V_MAY_DEF_OP_PTR (v_may_defs, i), map);
4519 rewrite_to_new_ssa_names_def
4520 (V_MAY_DEF_RESULT_PTR (v_may_defs, i), stmt, map);
4523 v_must_defs = V_MUST_DEF_OPS (ann);
4524 for (i = 0; i < NUM_V_MUST_DEFS (v_must_defs); i++)
4525 rewrite_to_new_ssa_names_def
4526 (V_MUST_DEF_OP_PTR (v_must_defs, i), stmt, map);
4529 FOR_EACH_EDGE (e, ei, bb->succs)
4530 for (phi = phi_nodes (e->dest); phi; phi = TREE_CHAIN (phi))
4532 rewrite_to_new_ssa_names_use
4533 (PHI_ARG_DEF_PTR_FROM_EDGE (phi, e), map);
4535 if (e->flags & EDGE_ABNORMAL)
4537 tree op = PHI_ARG_DEF_FROM_EDGE (phi, e);
4538 SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op) = 1;
4543 /* Rewrite the ssa names in N_REGION blocks REGION to the new ones as specified
4544 by the mapping MAP. */
4546 void
4547 rewrite_to_new_ssa_names (basic_block *region, unsigned n_region, htab_t map)
4549 unsigned r;
4551 for (r = 0; r < n_region; r++)
4552 rewrite_to_new_ssa_names_bb (region[r], map);
4555 /* Duplicates a REGION (set of N_REGION basic blocks) with just a single
4556 important exit edge EXIT. By important we mean that no SSA name defined
4557 inside region is live over the other exit edges of the region. All entry
4558 edges to the region must go to ENTRY->dest. The edge ENTRY is redirected
4559 to the duplicate of the region. SSA form, dominance and loop information
4560 is updated. The new basic blocks are stored to REGION_COPY in the same
4561 order as they had in REGION, provided that REGION_COPY is not NULL.
4562 The function returns false if it is unable to copy the region,
4563 true otherwise. */
4565 bool
4566 tree_duplicate_sese_region (edge entry, edge exit,
4567 basic_block *region, unsigned n_region,
4568 basic_block *region_copy)
4570 unsigned i, n_doms, ver;
4571 bool free_region_copy = false, copying_header = false;
4572 struct loop *loop = entry->dest->loop_father;
4573 edge exit_copy;
4574 bitmap definitions;
4575 tree phi, var;
4576 basic_block *doms;
4577 htab_t ssa_name_map = NULL;
4578 edge redirected;
4579 bitmap_iterator bi;
4581 if (!can_copy_bbs_p (region, n_region))
4582 return false;
4584 /* Some sanity checking. Note that we do not check for all possible
4585 missuses of the functions. I.e. if you ask to copy something weird,
4586 it will work, but the state of structures probably will not be
4587 correct. */
4589 for (i = 0; i < n_region; i++)
4591 /* We do not handle subloops, i.e. all the blocks must belong to the
4592 same loop. */
4593 if (region[i]->loop_father != loop)
4594 return false;
4596 if (region[i] != entry->dest
4597 && region[i] == loop->header)
4598 return false;
4601 loop->copy = loop;
4603 /* In case the function is used for loop header copying (which is the primary
4604 use), ensure that EXIT and its copy will be new latch and entry edges. */
4605 if (loop->header == entry->dest)
4607 copying_header = true;
4608 loop->copy = loop->outer;
4610 if (!dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src))
4611 return false;
4613 for (i = 0; i < n_region; i++)
4614 if (region[i] != exit->src
4615 && dominated_by_p (CDI_DOMINATORS, region[i], exit->src))
4616 return false;
4619 if (!region_copy)
4621 region_copy = xmalloc (sizeof (basic_block) * n_region);
4622 free_region_copy = true;
4625 gcc_assert (!any_marked_for_rewrite_p ());
4627 /* Record blocks outside the region that are duplicated by something
4628 inside. */
4629 doms = xmalloc (sizeof (basic_block) * n_basic_blocks);
4630 n_doms = get_dominated_by_region (CDI_DOMINATORS, region, n_region, doms);
4632 copy_bbs (region, n_region, region_copy, &exit, 1, &exit_copy, loop);
4633 definitions = marked_ssa_names ();
4635 if (copying_header)
4637 loop->header = exit->dest;
4638 loop->latch = exit->src;
4641 /* Redirect the entry and add the phi node arguments. */
4642 redirected = redirect_edge_and_branch (entry, entry->dest->rbi->copy);
4643 gcc_assert (redirected != NULL);
4644 for (phi = phi_nodes (entry->dest), var = PENDING_STMT (entry);
4645 phi;
4646 phi = TREE_CHAIN (phi), var = TREE_CHAIN (var))
4647 add_phi_arg (&phi, TREE_VALUE (var), entry);
4648 PENDING_STMT (entry) = NULL;
4650 /* Concerning updating of dominators: We must recount dominators
4651 for entry block and its copy. Anything that is outside of the region, but
4652 was dominated by something inside needs recounting as well. */
4653 set_immediate_dominator (CDI_DOMINATORS, entry->dest, entry->src);
4654 doms[n_doms++] = entry->dest->rbi->original;
4655 iterate_fix_dominators (CDI_DOMINATORS, doms, n_doms);
4656 free (doms);
4658 /* Add the other phi node arguments. */
4659 add_phi_args_after_copy (region_copy, n_region);
4661 /* Add phi nodes for definitions at exit. TODO -- once we have immediate
4662 uses, it should be possible to emit phi nodes just for definitions that
4663 are used outside region. */
4664 EXECUTE_IF_SET_IN_BITMAP (definitions, 0, ver, bi)
4666 tree name = ssa_name (ver);
4668 phi = create_phi_node (name, exit->dest);
4669 add_phi_arg (&phi, name, exit);
4670 add_phi_arg (&phi, name, exit_copy);
4672 SSA_NAME_DEF_STMT (name) = phi;
4675 /* And create new definitions inside region and its copy. TODO -- once we
4676 have immediate uses, it might be better to leave definitions in region
4677 unchanged, create new ssa names for phi nodes on exit, and rewrite
4678 the uses, to avoid changing the copied region. */
4679 allocate_ssa_names (definitions, &ssa_name_map);
4680 rewrite_to_new_ssa_names (region, n_region, ssa_name_map);
4681 allocate_ssa_names (definitions, &ssa_name_map);
4682 rewrite_to_new_ssa_names (region_copy, n_region, ssa_name_map);
4683 htab_delete (ssa_name_map);
4685 if (free_region_copy)
4686 free (region_copy);
4688 unmark_all_for_rewrite ();
4689 BITMAP_XFREE (definitions);
4691 return true;
4694 /* Dump FUNCTION_DECL FN to file FILE using FLAGS (see TDF_* in tree.h) */
4696 void
4697 dump_function_to_file (tree fn, FILE *file, int flags)
4699 tree arg, vars, var;
4700 bool ignore_topmost_bind = false, any_var = false;
4701 basic_block bb;
4702 tree chain;
4704 fprintf (file, "%s (", lang_hooks.decl_printable_name (fn, 2));
4706 arg = DECL_ARGUMENTS (fn);
4707 while (arg)
4709 print_generic_expr (file, arg, dump_flags);
4710 if (TREE_CHAIN (arg))
4711 fprintf (file, ", ");
4712 arg = TREE_CHAIN (arg);
4714 fprintf (file, ")\n");
4716 if (flags & TDF_RAW)
4718 dump_node (fn, TDF_SLIM | flags, file);
4719 return;
4722 /* When GIMPLE is lowered, the variables are no longer available in
4723 BIND_EXPRs, so display them separately. */
4724 if (cfun && cfun->unexpanded_var_list)
4726 ignore_topmost_bind = true;
4728 fprintf (file, "{\n");
4729 for (vars = cfun->unexpanded_var_list; vars; vars = TREE_CHAIN (vars))
4731 var = TREE_VALUE (vars);
4733 print_generic_decl (file, var, flags);
4734 fprintf (file, "\n");
4736 any_var = true;
4740 if (basic_block_info)
4742 /* Make a CFG based dump. */
4743 check_bb_profile (ENTRY_BLOCK_PTR, file);
4744 if (!ignore_topmost_bind)
4745 fprintf (file, "{\n");
4747 if (any_var && n_basic_blocks)
4748 fprintf (file, "\n");
4750 FOR_EACH_BB (bb)
4751 dump_generic_bb (file, bb, 2, flags);
4753 fprintf (file, "}\n");
4754 check_bb_profile (EXIT_BLOCK_PTR, file);
4756 else
4758 int indent;
4760 /* Make a tree based dump. */
4761 chain = DECL_SAVED_TREE (fn);
4763 if (TREE_CODE (chain) == BIND_EXPR)
4765 if (ignore_topmost_bind)
4767 chain = BIND_EXPR_BODY (chain);
4768 indent = 2;
4770 else
4771 indent = 0;
4773 else
4775 if (!ignore_topmost_bind)
4776 fprintf (file, "{\n");
4777 indent = 2;
4780 if (any_var)
4781 fprintf (file, "\n");
4783 print_generic_stmt_indented (file, chain, flags, indent);
4784 if (ignore_topmost_bind)
4785 fprintf (file, "}\n");
4788 fprintf (file, "\n\n");
4792 /* Pretty print of the loops intermediate representation. */
4793 static void print_loop (FILE *, struct loop *, int);
4794 static void print_pred_bbs (FILE *, basic_block bb);
4795 static void print_succ_bbs (FILE *, basic_block bb);
4798 /* Print the predecessors indexes of edge E on FILE. */
4800 static void
4801 print_pred_bbs (FILE *file, basic_block bb)
4803 edge e;
4804 edge_iterator ei;
4806 FOR_EACH_EDGE (e, ei, bb->preds)
4807 fprintf (file, "bb_%d", e->src->index);
4811 /* Print the successors indexes of edge E on FILE. */
4813 static void
4814 print_succ_bbs (FILE *file, basic_block bb)
4816 edge e;
4817 edge_iterator ei;
4819 FOR_EACH_EDGE (e, ei, bb->succs)
4820 fprintf (file, "bb_%d", e->src->index);
4824 /* Pretty print LOOP on FILE, indented INDENT spaces. */
4826 static void
4827 print_loop (FILE *file, struct loop *loop, int indent)
4829 char *s_indent;
4830 basic_block bb;
4832 if (loop == NULL)
4833 return;
4835 s_indent = (char *) alloca ((size_t) indent + 1);
4836 memset ((void *) s_indent, ' ', (size_t) indent);
4837 s_indent[indent] = '\0';
4839 /* Print the loop's header. */
4840 fprintf (file, "%sloop_%d\n", s_indent, loop->num);
4842 /* Print the loop's body. */
4843 fprintf (file, "%s{\n", s_indent);
4844 FOR_EACH_BB (bb)
4845 if (bb->loop_father == loop)
4847 /* Print the basic_block's header. */
4848 fprintf (file, "%s bb_%d (preds = {", s_indent, bb->index);
4849 print_pred_bbs (file, bb);
4850 fprintf (file, "}, succs = {");
4851 print_succ_bbs (file, bb);
4852 fprintf (file, "})\n");
4854 /* Print the basic_block's body. */
4855 fprintf (file, "%s {\n", s_indent);
4856 tree_dump_bb (bb, file, indent + 4);
4857 fprintf (file, "%s }\n", s_indent);
4860 print_loop (file, loop->inner, indent + 2);
4861 fprintf (file, "%s}\n", s_indent);
4862 print_loop (file, loop->next, indent);
4866 /* Follow a CFG edge from the entry point of the program, and on entry
4867 of a loop, pretty print the loop structure on FILE. */
4869 void
4870 print_loop_ir (FILE *file)
4872 basic_block bb;
4874 bb = BASIC_BLOCK (0);
4875 if (bb && bb->loop_father)
4876 print_loop (file, bb->loop_father, 0);
4880 /* Debugging loops structure at tree level. */
4882 void
4883 debug_loop_ir (void)
4885 print_loop_ir (stderr);
4889 /* Return true if BB ends with a call, possibly followed by some
4890 instructions that must stay with the call. Return false,
4891 otherwise. */
4893 static bool
4894 tree_block_ends_with_call_p (basic_block bb)
4896 block_stmt_iterator bsi = bsi_last (bb);
4897 return get_call_expr_in (bsi_stmt (bsi)) != NULL;
4901 /* Return true if BB ends with a conditional branch. Return false,
4902 otherwise. */
4904 static bool
4905 tree_block_ends_with_condjump_p (basic_block bb)
4907 tree stmt = tsi_stmt (bsi_last (bb).tsi);
4908 return (TREE_CODE (stmt) == COND_EXPR);
4912 /* Return true if we need to add fake edge to exit at statement T.
4913 Helper function for tree_flow_call_edges_add. */
4915 static bool
4916 need_fake_edge_p (tree t)
4918 tree call;
4920 /* NORETURN and LONGJMP calls already have an edge to exit.
4921 CONST, PURE and ALWAYS_RETURN calls do not need one.
4922 We don't currently check for CONST and PURE here, although
4923 it would be a good idea, because those attributes are
4924 figured out from the RTL in mark_constant_function, and
4925 the counter incrementation code from -fprofile-arcs
4926 leads to different results from -fbranch-probabilities. */
4927 call = get_call_expr_in (t);
4928 if (call
4929 && !(call_expr_flags (call) &
4930 (ECF_NORETURN | ECF_LONGJMP | ECF_ALWAYS_RETURN)))
4931 return true;
4933 if (TREE_CODE (t) == ASM_EXPR
4934 && (ASM_VOLATILE_P (t) || ASM_INPUT_P (t)))
4935 return true;
4937 return false;
4941 /* Add fake edges to the function exit for any non constant and non
4942 noreturn calls, volatile inline assembly in the bitmap of blocks
4943 specified by BLOCKS or to the whole CFG if BLOCKS is zero. Return
4944 the number of blocks that were split.
4946 The goal is to expose cases in which entering a basic block does
4947 not imply that all subsequent instructions must be executed. */
4949 static int
4950 tree_flow_call_edges_add (sbitmap blocks)
4952 int i;
4953 int blocks_split = 0;
4954 int last_bb = last_basic_block;
4955 bool check_last_block = false;
4957 if (n_basic_blocks == 0)
4958 return 0;
4960 if (! blocks)
4961 check_last_block = true;
4962 else
4963 check_last_block = TEST_BIT (blocks, EXIT_BLOCK_PTR->prev_bb->index);
4965 /* In the last basic block, before epilogue generation, there will be
4966 a fallthru edge to EXIT. Special care is required if the last insn
4967 of the last basic block is a call because make_edge folds duplicate
4968 edges, which would result in the fallthru edge also being marked
4969 fake, which would result in the fallthru edge being removed by
4970 remove_fake_edges, which would result in an invalid CFG.
4972 Moreover, we can't elide the outgoing fake edge, since the block
4973 profiler needs to take this into account in order to solve the minimal
4974 spanning tree in the case that the call doesn't return.
4976 Handle this by adding a dummy instruction in a new last basic block. */
4977 if (check_last_block)
4979 edge_iterator ei;
4980 basic_block bb = EXIT_BLOCK_PTR->prev_bb;
4981 block_stmt_iterator bsi = bsi_last (bb);
4982 tree t = NULL_TREE;
4983 if (!bsi_end_p (bsi))
4984 t = bsi_stmt (bsi);
4986 if (need_fake_edge_p (t))
4988 edge e;
4990 FOR_EACH_EDGE (e, ei, bb->succs)
4991 if (e->dest == EXIT_BLOCK_PTR)
4993 bsi_insert_on_edge (e, build_empty_stmt ());
4994 bsi_commit_edge_inserts ((int *)NULL);
4995 break;
5000 /* Now add fake edges to the function exit for any non constant
5001 calls since there is no way that we can determine if they will
5002 return or not... */
5003 for (i = 0; i < last_bb; i++)
5005 basic_block bb = BASIC_BLOCK (i);
5006 block_stmt_iterator bsi;
5007 tree stmt, last_stmt;
5009 if (!bb)
5010 continue;
5012 if (blocks && !TEST_BIT (blocks, i))
5013 continue;
5015 bsi = bsi_last (bb);
5016 if (!bsi_end_p (bsi))
5018 last_stmt = bsi_stmt (bsi);
5021 stmt = bsi_stmt (bsi);
5022 if (need_fake_edge_p (stmt))
5024 edge e;
5025 /* The handling above of the final block before the
5026 epilogue should be enough to verify that there is
5027 no edge to the exit block in CFG already.
5028 Calling make_edge in such case would cause us to
5029 mark that edge as fake and remove it later. */
5030 #ifdef ENABLE_CHECKING
5031 if (stmt == last_stmt)
5033 edge_iterator ei;
5034 FOR_EACH_EDGE (e, ei, bb->succs)
5035 gcc_assert (e->dest != EXIT_BLOCK_PTR);
5037 #endif
5039 /* Note that the following may create a new basic block
5040 and renumber the existing basic blocks. */
5041 if (stmt != last_stmt)
5043 e = split_block (bb, stmt);
5044 if (e)
5045 blocks_split++;
5047 make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
5049 bsi_prev (&bsi);
5051 while (!bsi_end_p (bsi));
5055 if (blocks_split)
5056 verify_flow_info ();
5058 return blocks_split;
5061 bool
5062 tree_purge_dead_eh_edges (basic_block bb)
5064 bool changed = false;
5065 edge e;
5066 edge_iterator ei;
5067 tree stmt = last_stmt (bb);
5069 if (stmt && tree_can_throw_internal (stmt))
5070 return false;
5072 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
5074 if (e->flags & EDGE_EH)
5076 ssa_remove_edge (e);
5077 changed = true;
5079 else
5080 ei_next (&ei);
5083 return changed;
5086 bool
5087 tree_purge_all_dead_eh_edges (bitmap blocks)
5089 bool changed = false;
5090 size_t i;
5091 bitmap_iterator bi;
5093 EXECUTE_IF_SET_IN_BITMAP (blocks, 0, i, bi)
5095 changed |= tree_purge_dead_eh_edges (BASIC_BLOCK (i));
5098 return changed;
5101 struct cfg_hooks tree_cfg_hooks = {
5102 "tree",
5103 tree_verify_flow_info,
5104 tree_dump_bb, /* dump_bb */
5105 create_bb, /* create_basic_block */
5106 tree_redirect_edge_and_branch,/* redirect_edge_and_branch */
5107 tree_redirect_edge_and_branch_force,/* redirect_edge_and_branch_force */
5108 remove_bb, /* delete_basic_block */
5109 tree_split_block, /* split_block */
5110 tree_move_block_after, /* move_block_after */
5111 tree_can_merge_blocks_p, /* can_merge_blocks_p */
5112 tree_merge_blocks, /* merge_blocks */
5113 tree_predict_edge, /* predict_edge */
5114 tree_predicted_by_p, /* predicted_by_p */
5115 tree_can_duplicate_bb_p, /* can_duplicate_block_p */
5116 tree_duplicate_bb, /* duplicate_block */
5117 tree_split_edge, /* split_edge */
5118 tree_make_forwarder_block, /* make_forward_block */
5119 NULL, /* tidy_fallthru_edge */
5120 tree_block_ends_with_call_p, /* block_ends_with_call_p */
5121 tree_block_ends_with_condjump_p, /* block_ends_with_condjump_p */
5122 tree_flow_call_edges_add /* flow_call_edges_add */
5126 /* Split all critical edges. */
5128 static void
5129 split_critical_edges (void)
5131 basic_block bb;
5132 edge e;
5133 edge_iterator ei;
5135 FOR_ALL_BB (bb)
5137 FOR_EACH_EDGE (e, ei, bb->succs)
5138 if (EDGE_CRITICAL_P (e) && !(e->flags & EDGE_ABNORMAL))
5140 split_edge (e);
5145 struct tree_opt_pass pass_split_crit_edges =
5147 "crited", /* name */
5148 NULL, /* gate */
5149 split_critical_edges, /* execute */
5150 NULL, /* sub */
5151 NULL, /* next */
5152 0, /* static_pass_number */
5153 TV_TREE_SPLIT_EDGES, /* tv_id */
5154 PROP_cfg, /* properties required */
5155 PROP_no_crit_edges, /* properties_provided */
5156 0, /* properties_destroyed */
5157 0, /* todo_flags_start */
5158 TODO_dump_func, /* todo_flags_finish */
5159 0 /* letter */
5163 /* Return EXP if it is a valid GIMPLE rvalue, else gimplify it into
5164 a temporary, make sure and register it to be renamed if necessary,
5165 and finally return the temporary. Put the statements to compute
5166 EXP before the current statement in BSI. */
5168 tree
5169 gimplify_val (block_stmt_iterator *bsi, tree type, tree exp)
5171 tree t, new_stmt, orig_stmt;
5173 if (is_gimple_val (exp))
5174 return exp;
5176 t = make_rename_temp (type, NULL);
5177 new_stmt = build (MODIFY_EXPR, type, t, exp);
5179 orig_stmt = bsi_stmt (*bsi);
5180 SET_EXPR_LOCUS (new_stmt, EXPR_LOCUS (orig_stmt));
5181 TREE_BLOCK (new_stmt) = TREE_BLOCK (orig_stmt);
5183 bsi_insert_before (bsi, new_stmt, BSI_SAME_STMT);
5185 return t;
5188 /* Build a ternary operation and gimplify it. Emit code before BSI.
5189 Return the gimple_val holding the result. */
5191 tree
5192 gimplify_build3 (block_stmt_iterator *bsi, enum tree_code code,
5193 tree type, tree a, tree b, tree c)
5195 tree ret;
5197 ret = fold (build3 (code, type, a, b, c));
5198 STRIP_NOPS (ret);
5200 return gimplify_val (bsi, type, ret);
5203 /* Build a binary operation and gimplify it. Emit code before BSI.
5204 Return the gimple_val holding the result. */
5206 tree
5207 gimplify_build2 (block_stmt_iterator *bsi, enum tree_code code,
5208 tree type, tree a, tree b)
5210 tree ret;
5212 ret = fold (build2 (code, type, a, b));
5213 STRIP_NOPS (ret);
5215 return gimplify_val (bsi, type, ret);
5218 /* Build a unary operation and gimplify it. Emit code before BSI.
5219 Return the gimple_val holding the result. */
5221 tree
5222 gimplify_build1 (block_stmt_iterator *bsi, enum tree_code code, tree type,
5223 tree a)
5225 tree ret;
5227 ret = fold (build1 (code, type, a));
5228 STRIP_NOPS (ret);
5230 return gimplify_val (bsi, type, ret);
5235 /* Emit return warnings. */
5237 static void
5238 execute_warn_function_return (void)
5240 #ifdef USE_MAPPED_LOCATION
5241 source_location location;
5242 #else
5243 location_t *locus;
5244 #endif
5245 tree last;
5246 edge e;
5247 edge_iterator ei;
5249 if (warn_missing_noreturn
5250 && !TREE_THIS_VOLATILE (cfun->decl)
5251 && EDGE_COUNT (EXIT_BLOCK_PTR->preds) == 0
5252 && !lang_hooks.function.missing_noreturn_ok_p (cfun->decl))
5253 warning ("%Jfunction might be possible candidate for "
5254 "attribute %<noreturn%>",
5255 cfun->decl);
5257 /* If we have a path to EXIT, then we do return. */
5258 if (TREE_THIS_VOLATILE (cfun->decl)
5259 && EDGE_COUNT (EXIT_BLOCK_PTR->preds) > 0)
5261 #ifdef USE_MAPPED_LOCATION
5262 location = UNKNOWN_LOCATION;
5263 #else
5264 locus = NULL;
5265 #endif
5266 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
5268 last = last_stmt (e->src);
5269 if (TREE_CODE (last) == RETURN_EXPR
5270 #ifdef USE_MAPPED_LOCATION
5271 && (location = EXPR_LOCATION (last)) != UNKNOWN_LOCATION)
5272 #else
5273 && (locus = EXPR_LOCUS (last)) != NULL)
5274 #endif
5275 break;
5277 #ifdef USE_MAPPED_LOCATION
5278 if (location == UNKNOWN_LOCATION)
5279 location = cfun->function_end_locus;
5280 warning ("%H%<noreturn%> function does return", &location);
5281 #else
5282 if (!locus)
5283 locus = &cfun->function_end_locus;
5284 warning ("%H%<noreturn%> function does return", locus);
5285 #endif
5288 /* If we see "return;" in some basic block, then we do reach the end
5289 without returning a value. */
5290 else if (warn_return_type
5291 && EDGE_COUNT (EXIT_BLOCK_PTR->preds) > 0
5292 && !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (cfun->decl))))
5294 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
5296 tree last = last_stmt (e->src);
5297 if (TREE_CODE (last) == RETURN_EXPR
5298 && TREE_OPERAND (last, 0) == NULL)
5300 #ifdef USE_MAPPED_LOCATION
5301 location = EXPR_LOCATION (last);
5302 if (location == UNKNOWN_LOCATION)
5303 location = cfun->function_end_locus;
5304 warning ("%Hcontrol reaches end of non-void function", &location);
5305 #else
5306 locus = EXPR_LOCUS (last);
5307 if (!locus)
5308 locus = &cfun->function_end_locus;
5309 warning ("%Hcontrol reaches end of non-void function", locus);
5310 #endif
5311 break;
5318 /* Given a basic block B which ends with a conditional and has
5319 precisely two successors, determine which of the edges is taken if
5320 the conditional is true and which is taken if the conditional is
5321 false. Set TRUE_EDGE and FALSE_EDGE appropriately. */
5323 void
5324 extract_true_false_edges_from_block (basic_block b,
5325 edge *true_edge,
5326 edge *false_edge)
5328 edge e = EDGE_SUCC (b, 0);
5330 if (e->flags & EDGE_TRUE_VALUE)
5332 *true_edge = e;
5333 *false_edge = EDGE_SUCC (b, 1);
5335 else
5337 *false_edge = e;
5338 *true_edge = EDGE_SUCC (b, 1);
5342 struct tree_opt_pass pass_warn_function_return =
5344 NULL, /* name */
5345 NULL, /* gate */
5346 execute_warn_function_return, /* execute */
5347 NULL, /* sub */
5348 NULL, /* next */
5349 0, /* static_pass_number */
5350 0, /* tv_id */
5351 PROP_cfg, /* properties_required */
5352 0, /* properties_provided */
5353 0, /* properties_destroyed */
5354 0, /* todo_flags_start */
5355 0, /* todo_flags_finish */
5356 0 /* letter */
5359 #include "gt-tree-cfg.h"