OSDN Git Service

gcc/ada/
[pf3gnuchains/gcc-fork.git] / gcc / tree-cfg.c
1 /* Control flow functions for trees.
2    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007
3    Free Software Foundation, Inc.
4    Contributed by Diego Novillo <dnovillo@redhat.com>
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
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 "flags.h"
33 #include "function.h"
34 #include "expr.h"
35 #include "ggc.h"
36 #include "langhooks.h"
37 #include "diagnostic.h"
38 #include "tree-flow.h"
39 #include "timevar.h"
40 #include "tree-dump.h"
41 #include "tree-pass.h"
42 #include "toplev.h"
43 #include "except.h"
44 #include "cfgloop.h"
45 #include "cfglayout.h"
46 #include "tree-ssa-propagate.h"
47 #include "value-prof.h"
48 #include "pointer-set.h"
49 #include "tree-inline.h"
50
51 /* This file contains functions for building the Control Flow Graph (CFG)
52    for a function tree.  */
53
54 /* Local declarations.  */
55
56 /* Initial capacity for the basic block array.  */
57 static const int initial_cfg_capacity = 20;
58
59 /* This hash table allows us to efficiently lookup all CASE_LABEL_EXPRs
60    which use a particular edge.  The CASE_LABEL_EXPRs are chained together
61    via their TREE_CHAIN field, which we clear after we're done with the
62    hash table to prevent problems with duplication of SWITCH_EXPRs.
63
64    Access to this list of CASE_LABEL_EXPRs allows us to efficiently
65    update the case vector in response to edge redirections.
66
67    Right now this table is set up and torn down at key points in the
68    compilation process.  It would be nice if we could make the table
69    more persistent.  The key is getting notification of changes to
70    the CFG (particularly edge removal, creation and redirection).  */
71
72 static struct pointer_map_t *edge_to_cases;
73
74 /* CFG statistics.  */
75 struct cfg_stats_d
76 {
77   long num_merged_labels;
78 };
79
80 static struct cfg_stats_d cfg_stats;
81
82 /* Nonzero if we found a computed goto while building basic blocks.  */
83 static bool found_computed_goto;
84
85 /* Basic blocks and flowgraphs.  */
86 static basic_block create_bb (void *, void *, basic_block);
87 static void make_blocks (tree);
88 static void factor_computed_gotos (void);
89
90 /* Edges.  */
91 static void make_edges (void);
92 static void make_cond_expr_edges (basic_block);
93 static void make_switch_expr_edges (basic_block);
94 static void make_goto_expr_edges (basic_block);
95 static edge tree_redirect_edge_and_branch (edge, basic_block);
96 static edge tree_try_redirect_by_replacing_jump (edge, basic_block);
97 static unsigned int split_critical_edges (void);
98
99 /* Various helpers.  */
100 static inline bool stmt_starts_bb_p (const_tree, const_tree);
101 static int tree_verify_flow_info (void);
102 static void tree_make_forwarder_block (edge);
103 static void tree_cfg2vcg (FILE *);
104 static inline void change_bb_for_stmt (tree t, basic_block bb);
105
106 /* Flowgraph optimization and cleanup.  */
107 static void tree_merge_blocks (basic_block, basic_block);
108 static bool tree_can_merge_blocks_p (basic_block, basic_block);
109 static void remove_bb (basic_block);
110 static edge find_taken_edge_computed_goto (basic_block, tree);
111 static edge find_taken_edge_cond_expr (basic_block, tree);
112 static edge find_taken_edge_switch_expr (basic_block, tree);
113 static tree find_case_label_for_value (tree, tree);
114
115 void
116 init_empty_tree_cfg (void)
117 {
118   /* Initialize the basic block array.  */
119   init_flow ();
120   profile_status = PROFILE_ABSENT;
121   n_basic_blocks = NUM_FIXED_BLOCKS;
122   last_basic_block = NUM_FIXED_BLOCKS;
123   basic_block_info = VEC_alloc (basic_block, gc, initial_cfg_capacity);
124   VEC_safe_grow_cleared (basic_block, gc, basic_block_info,
125                          initial_cfg_capacity);
126
127   /* Build a mapping of labels to their associated blocks.  */
128   label_to_block_map = VEC_alloc (basic_block, gc, initial_cfg_capacity);
129   VEC_safe_grow_cleared (basic_block, gc, label_to_block_map,
130                          initial_cfg_capacity);
131
132   SET_BASIC_BLOCK (ENTRY_BLOCK, ENTRY_BLOCK_PTR);
133   SET_BASIC_BLOCK (EXIT_BLOCK, EXIT_BLOCK_PTR);
134   ENTRY_BLOCK_PTR->next_bb = EXIT_BLOCK_PTR;
135   EXIT_BLOCK_PTR->prev_bb = ENTRY_BLOCK_PTR;
136 }
137
138 /*---------------------------------------------------------------------------
139                               Create basic blocks
140 ---------------------------------------------------------------------------*/
141
142 /* Entry point to the CFG builder for trees.  TP points to the list of
143    statements to be added to the flowgraph.  */
144
145 static void
146 build_tree_cfg (tree *tp)
147 {
148   /* Register specific tree functions.  */
149   tree_register_cfg_hooks ();
150
151   memset ((void *) &cfg_stats, 0, sizeof (cfg_stats));
152
153   init_empty_tree_cfg ();
154
155   found_computed_goto = 0;
156   make_blocks (*tp);
157
158   /* Computed gotos are hell to deal with, especially if there are
159      lots of them with a large number of destinations.  So we factor
160      them to a common computed goto location before we build the
161      edge list.  After we convert back to normal form, we will un-factor
162      the computed gotos since factoring introduces an unwanted jump.  */
163   if (found_computed_goto)
164     factor_computed_gotos ();
165
166   /* Make sure there is always at least one block, even if it's empty.  */
167   if (n_basic_blocks == NUM_FIXED_BLOCKS)
168     create_empty_bb (ENTRY_BLOCK_PTR);
169
170   /* Adjust the size of the array.  */
171   if (VEC_length (basic_block, basic_block_info) < (size_t) n_basic_blocks)
172     VEC_safe_grow_cleared (basic_block, gc, basic_block_info, n_basic_blocks);
173
174   /* To speed up statement iterator walks, we first purge dead labels.  */
175   cleanup_dead_labels ();
176
177   /* Group case nodes to reduce the number of edges.
178      We do this after cleaning up dead labels because otherwise we miss
179      a lot of obvious case merging opportunities.  */
180   group_case_labels ();
181
182   /* Create the edges of the flowgraph.  */
183   make_edges ();
184   cleanup_dead_labels ();
185
186   /* Debugging dumps.  */
187
188   /* Write the flowgraph to a VCG file.  */
189   {
190     int local_dump_flags;
191     FILE *vcg_file = dump_begin (TDI_vcg, &local_dump_flags);
192     if (vcg_file)
193       {
194         tree_cfg2vcg (vcg_file);
195         dump_end (TDI_vcg, vcg_file);
196       }
197   }
198
199 #ifdef ENABLE_CHECKING
200   verify_stmts ();
201 #endif
202
203   /* Dump a textual representation of the flowgraph.  */
204   if (dump_file)
205     dump_tree_cfg (dump_file, dump_flags);
206 }
207
208 static unsigned int
209 execute_build_cfg (void)
210 {
211   build_tree_cfg (&DECL_SAVED_TREE (current_function_decl));
212   return 0;
213 }
214
215 struct tree_opt_pass pass_build_cfg =
216 {
217   "cfg",                                /* name */
218   NULL,                                 /* gate */
219   execute_build_cfg,                    /* execute */
220   NULL,                                 /* sub */
221   NULL,                                 /* next */
222   0,                                    /* static_pass_number */
223   TV_TREE_CFG,                          /* tv_id */
224   PROP_gimple_leh,                      /* properties_required */
225   PROP_cfg,                             /* properties_provided */
226   0,                                    /* properties_destroyed */
227   0,                                    /* todo_flags_start */
228   TODO_verify_stmts | TODO_cleanup_cfg, /* todo_flags_finish */
229   0                                     /* letter */
230 };
231
232 /* Search the CFG for any computed gotos.  If found, factor them to a
233    common computed goto site.  Also record the location of that site so
234    that we can un-factor the gotos after we have converted back to
235    normal form.  */
236
237 static void
238 factor_computed_gotos (void)
239 {
240   basic_block bb;
241   tree factored_label_decl = NULL;
242   tree var = NULL;
243   tree factored_computed_goto_label = NULL;
244   tree factored_computed_goto = NULL;
245
246   /* We know there are one or more computed gotos in this function.
247      Examine the last statement in each basic block to see if the block
248      ends with a computed goto.  */
249
250   FOR_EACH_BB (bb)
251     {
252       block_stmt_iterator bsi = bsi_last (bb);
253       tree last;
254
255       if (bsi_end_p (bsi))
256         continue;
257       last = bsi_stmt (bsi);
258
259       /* Ignore the computed goto we create when we factor the original
260          computed gotos.  */
261       if (last == factored_computed_goto)
262         continue;
263
264       /* If the last statement is a computed goto, factor it.  */
265       if (computed_goto_p (last))
266         {
267           tree assignment;
268
269           /* The first time we find a computed goto we need to create
270              the factored goto block and the variable each original
271              computed goto will use for their goto destination.  */
272           if (! factored_computed_goto)
273             {
274               basic_block new_bb = create_empty_bb (bb);
275               block_stmt_iterator new_bsi = bsi_start (new_bb);
276
277               /* Create the destination of the factored goto.  Each original
278                  computed goto will put its desired destination into this
279                  variable and jump to the label we create immediately
280                  below.  */
281               var = create_tmp_var (ptr_type_node, "gotovar");
282
283               /* Build a label for the new block which will contain the
284                  factored computed goto.  */
285               factored_label_decl = create_artificial_label ();
286               factored_computed_goto_label
287                 = build1 (LABEL_EXPR, void_type_node, factored_label_decl);
288               bsi_insert_after (&new_bsi, factored_computed_goto_label,
289                                 BSI_NEW_STMT);
290
291               /* Build our new computed goto.  */
292               factored_computed_goto = build1 (GOTO_EXPR, void_type_node, var);
293               bsi_insert_after (&new_bsi, factored_computed_goto,
294                                 BSI_NEW_STMT);
295             }
296
297           /* Copy the original computed goto's destination into VAR.  */
298           assignment = build_gimple_modify_stmt (var,
299                                                  GOTO_DESTINATION (last));
300           bsi_insert_before (&bsi, assignment, BSI_SAME_STMT);
301
302           /* And re-vector the computed goto to the new destination.  */
303           GOTO_DESTINATION (last) = factored_label_decl;
304         }
305     }
306 }
307
308
309 /* Build a flowgraph for the statement_list STMT_LIST.  */
310
311 static void
312 make_blocks (tree stmt_list)
313 {
314   tree_stmt_iterator i = tsi_start (stmt_list);
315   tree stmt = NULL;
316   bool start_new_block = true;
317   bool first_stmt_of_list = true;
318   basic_block bb = ENTRY_BLOCK_PTR;
319
320   while (!tsi_end_p (i))
321     {
322       tree prev_stmt;
323
324       prev_stmt = stmt;
325       stmt = tsi_stmt (i);
326
327       /* If the statement starts a new basic block or if we have determined
328          in a previous pass that we need to create a new block for STMT, do
329          so now.  */
330       if (start_new_block || stmt_starts_bb_p (stmt, prev_stmt))
331         {
332           if (!first_stmt_of_list)
333             stmt_list = tsi_split_statement_list_before (&i);
334           bb = create_basic_block (stmt_list, NULL, bb);
335           start_new_block = false;
336         }
337
338       /* Now add STMT to BB and create the subgraphs for special statement
339          codes.  */
340       set_bb_for_stmt (stmt, bb);
341
342       if (computed_goto_p (stmt))
343         found_computed_goto = true;
344
345       /* If STMT is a basic block terminator, set START_NEW_BLOCK for the
346          next iteration.  */
347       if (stmt_ends_bb_p (stmt))
348         start_new_block = true;
349
350       tsi_next (&i);
351       first_stmt_of_list = false;
352     }
353 }
354
355
356 /* Create and return a new empty basic block after bb AFTER.  */
357
358 static basic_block
359 create_bb (void *h, void *e, basic_block after)
360 {
361   basic_block bb;
362
363   gcc_assert (!e);
364
365   /* Create and initialize a new basic block.  Since alloc_block uses
366      ggc_alloc_cleared to allocate a basic block, we do not have to
367      clear the newly allocated basic block here.  */
368   bb = alloc_block ();
369
370   bb->index = last_basic_block;
371   bb->flags = BB_NEW;
372   bb->il.tree = GGC_CNEW (struct tree_bb_info);
373   set_bb_stmt_list (bb, h ? (tree) h : alloc_stmt_list ());
374
375   /* Add the new block to the linked list of blocks.  */
376   link_block (bb, after);
377
378   /* Grow the basic block array if needed.  */
379   if ((size_t) last_basic_block == VEC_length (basic_block, basic_block_info))
380     {
381       size_t new_size = last_basic_block + (last_basic_block + 3) / 4;
382       VEC_safe_grow_cleared (basic_block, gc, basic_block_info, new_size);
383     }
384
385   /* Add the newly created block to the array.  */
386   SET_BASIC_BLOCK (last_basic_block, bb);
387
388   n_basic_blocks++;
389   last_basic_block++;
390
391   return bb;
392 }
393
394
395 /*---------------------------------------------------------------------------
396                                  Edge creation
397 ---------------------------------------------------------------------------*/
398
399 /* Fold COND_EXPR_COND of each COND_EXPR.  */
400
401 void
402 fold_cond_expr_cond (void)
403 {
404   basic_block bb;
405
406   FOR_EACH_BB (bb)
407     {
408       tree stmt = last_stmt (bb);
409
410       if (stmt
411           && TREE_CODE (stmt) == COND_EXPR)
412         {
413           tree cond;
414           bool zerop, onep;
415
416           fold_defer_overflow_warnings ();
417           cond = fold (COND_EXPR_COND (stmt));
418           zerop = integer_zerop (cond);
419           onep = integer_onep (cond);
420           fold_undefer_overflow_warnings (zerop || onep,
421                                           stmt,
422                                           WARN_STRICT_OVERFLOW_CONDITIONAL);
423           if (zerop)
424             COND_EXPR_COND (stmt) = boolean_false_node;
425           else if (onep)
426             COND_EXPR_COND (stmt) = boolean_true_node;
427         }
428     }
429 }
430
431 /* Join all the blocks in the flowgraph.  */
432
433 static void
434 make_edges (void)
435 {
436   basic_block bb;
437   struct omp_region *cur_region = NULL;
438
439   /* Create an edge from entry to the first block with executable
440      statements in it.  */
441   make_edge (ENTRY_BLOCK_PTR, BASIC_BLOCK (NUM_FIXED_BLOCKS), EDGE_FALLTHRU);
442
443   /* Traverse the basic block array placing edges.  */
444   FOR_EACH_BB (bb)
445     {
446       tree last = last_stmt (bb);
447       bool fallthru;
448
449       if (last)
450         {
451           enum tree_code code = TREE_CODE (last);
452           switch (code)
453             {
454             case GOTO_EXPR:
455               make_goto_expr_edges (bb);
456               fallthru = false;
457               break;
458             case RETURN_EXPR:
459               make_edge (bb, EXIT_BLOCK_PTR, 0);
460               fallthru = false;
461               break;
462             case COND_EXPR:
463               make_cond_expr_edges (bb);
464               fallthru = false;
465               break;
466             case SWITCH_EXPR:
467               make_switch_expr_edges (bb);
468               fallthru = false;
469               break;
470             case RESX_EXPR:
471               make_eh_edges (last);
472               fallthru = false;
473               break;
474
475             case CALL_EXPR:
476               /* If this function receives a nonlocal goto, then we need to
477                  make edges from this call site to all the nonlocal goto
478                  handlers.  */
479               if (tree_can_make_abnormal_goto (last))
480                 make_abnormal_goto_edges (bb, true);
481
482               /* If this statement has reachable exception handlers, then
483                  create abnormal edges to them.  */
484               make_eh_edges (last);
485
486               /* Some calls are known not to return.  */
487               fallthru = !(call_expr_flags (last) & ECF_NORETURN);
488               break;
489
490             case MODIFY_EXPR:
491               gcc_unreachable ();
492
493             case GIMPLE_MODIFY_STMT:
494               if (is_ctrl_altering_stmt (last))
495                 {
496                   /* A GIMPLE_MODIFY_STMT may have a CALL_EXPR on its RHS and
497                      the CALL_EXPR may have an abnormal edge.  Search the RHS
498                      for this case and create any required edges.  */
499                   if (tree_can_make_abnormal_goto (last))
500                     make_abnormal_goto_edges (bb, true);  
501
502                   make_eh_edges (last);
503                 }
504               fallthru = true;
505               break;
506
507             case OMP_PARALLEL:
508             case OMP_FOR:
509             case OMP_SINGLE:
510             case OMP_MASTER:
511             case OMP_ORDERED:
512             case OMP_CRITICAL:
513             case OMP_SECTION:
514               cur_region = new_omp_region (bb, code, cur_region);
515               fallthru = true;
516               break;
517
518             case OMP_SECTIONS:
519               cur_region = new_omp_region (bb, code, cur_region);
520               fallthru = true;
521               break;
522
523             case OMP_SECTIONS_SWITCH:
524               fallthru = false;
525               break;
526
527
528             case OMP_ATOMIC_LOAD:
529             case OMP_ATOMIC_STORE:
530                fallthru = true;
531                break;
532
533
534             case OMP_RETURN:
535               /* In the case of an OMP_SECTION, the edge will go somewhere
536                  other than the next block.  This will be created later.  */
537               cur_region->exit = bb;
538               fallthru = cur_region->type != OMP_SECTION;
539               cur_region = cur_region->outer;
540               break;
541
542             case OMP_CONTINUE:
543               cur_region->cont = bb;
544               switch (cur_region->type)
545                 {
546                 case OMP_FOR:
547                   /* Make the loopback edge.  */
548                   make_edge (bb, single_succ (cur_region->entry), 0);
549               
550                   /* Create an edge from OMP_FOR to exit, which corresponds to
551                      the case that the body of the loop is not executed at
552                      all.  */
553                   make_edge (cur_region->entry, bb->next_bb, 0);
554                   fallthru = true;
555                   break;
556
557                 case OMP_SECTIONS:
558                   /* Wire up the edges into and out of the nested sections.  */
559                   {
560                     basic_block switch_bb = single_succ (cur_region->entry);
561
562                     struct omp_region *i;
563                     for (i = cur_region->inner; i ; i = i->next)
564                       {
565                         gcc_assert (i->type == OMP_SECTION);
566                         make_edge (switch_bb, i->entry, 0);
567                         make_edge (i->exit, bb, EDGE_FALLTHRU);
568                       }
569
570                     /* Make the loopback edge to the block with
571                        OMP_SECTIONS_SWITCH.  */
572                     make_edge (bb, switch_bb, 0);
573
574                     /* Make the edge from the switch to exit.  */
575                     make_edge (switch_bb, bb->next_bb, 0);
576                     fallthru = false;
577                   }
578                   break;
579
580                 default:
581                   gcc_unreachable ();
582                 }
583               break;
584
585             default:
586               gcc_assert (!stmt_ends_bb_p (last));
587               fallthru = true;
588             }
589         }
590       else
591         fallthru = true;
592
593       if (fallthru)
594         make_edge (bb, bb->next_bb, EDGE_FALLTHRU);
595     }
596
597   if (root_omp_region)
598     free_omp_regions ();
599
600   /* Fold COND_EXPR_COND of each COND_EXPR.  */
601   fold_cond_expr_cond ();
602 }
603
604
605 /* Create the edges for a COND_EXPR starting at block BB.
606    At this point, both clauses must contain only simple gotos.  */
607
608 static void
609 make_cond_expr_edges (basic_block bb)
610 {
611   tree entry = last_stmt (bb);
612   basic_block then_bb, else_bb;
613   tree then_label, else_label;
614   edge e;
615
616   gcc_assert (entry);
617   gcc_assert (TREE_CODE (entry) == COND_EXPR);
618
619   /* Entry basic blocks for each component.  */
620   then_label = GOTO_DESTINATION (COND_EXPR_THEN (entry));
621   else_label = GOTO_DESTINATION (COND_EXPR_ELSE (entry));
622   then_bb = label_to_block (then_label);
623   else_bb = label_to_block (else_label);
624
625   e = make_edge (bb, then_bb, EDGE_TRUE_VALUE);
626 #ifdef USE_MAPPED_LOCATION
627   e->goto_locus = EXPR_LOCATION (COND_EXPR_THEN (entry));
628 #else
629   e->goto_locus = EXPR_LOCUS (COND_EXPR_THEN (entry));
630 #endif
631   e = make_edge (bb, else_bb, EDGE_FALSE_VALUE);
632   if (e)
633     {
634 #ifdef USE_MAPPED_LOCATION
635       e->goto_locus = EXPR_LOCATION (COND_EXPR_ELSE (entry));
636 #else
637       e->goto_locus = EXPR_LOCUS (COND_EXPR_ELSE (entry));
638 #endif
639     }
640
641   /* We do not need the gotos anymore.  */
642   COND_EXPR_THEN (entry) = NULL_TREE;
643   COND_EXPR_ELSE (entry) = NULL_TREE;
644 }
645
646
647 /* Called for each element in the hash table (P) as we delete the
648    edge to cases hash table.
649
650    Clear all the TREE_CHAINs to prevent problems with copying of
651    SWITCH_EXPRs and structure sharing rules, then free the hash table
652    element.  */
653
654 static bool
655 edge_to_cases_cleanup (const void *key ATTRIBUTE_UNUSED, void **value,
656                        void *data ATTRIBUTE_UNUSED)
657 {
658   tree t, next;
659
660   for (t = (tree) *value; t; t = next)
661     {
662       next = TREE_CHAIN (t);
663       TREE_CHAIN (t) = NULL;
664     }
665
666   *value = NULL;
667   return false;
668 }
669
670 /* Start recording information mapping edges to case labels.  */
671
672 void
673 start_recording_case_labels (void)
674 {
675   gcc_assert (edge_to_cases == NULL);
676   edge_to_cases = pointer_map_create ();
677 }
678
679 /* Return nonzero if we are recording information for case labels.  */
680
681 static bool
682 recording_case_labels_p (void)
683 {
684   return (edge_to_cases != NULL);
685 }
686
687 /* Stop recording information mapping edges to case labels and
688    remove any information we have recorded.  */
689 void
690 end_recording_case_labels (void)
691 {
692   pointer_map_traverse (edge_to_cases, edge_to_cases_cleanup, NULL);
693   pointer_map_destroy (edge_to_cases);
694   edge_to_cases = NULL;
695 }
696
697 /* If we are inside a {start,end}_recording_cases block, then return
698    a chain of CASE_LABEL_EXPRs from T which reference E.
699
700    Otherwise return NULL.  */
701
702 static tree
703 get_cases_for_edge (edge e, tree t)
704 {
705   void **slot;
706   size_t i, n;
707   tree vec;
708
709   /* If we are not recording cases, then we do not have CASE_LABEL_EXPR
710      chains available.  Return NULL so the caller can detect this case.  */
711   if (!recording_case_labels_p ())
712     return NULL;
713
714   slot = pointer_map_contains (edge_to_cases, e);
715   if (slot)
716     return (tree) *slot;
717
718   /* If we did not find E in the hash table, then this must be the first
719      time we have been queried for information about E & T.  Add all the
720      elements from T to the hash table then perform the query again.  */
721
722   vec = SWITCH_LABELS (t);
723   n = TREE_VEC_LENGTH (vec);
724   for (i = 0; i < n; i++)
725     {
726       tree elt = TREE_VEC_ELT (vec, i);
727       tree lab = CASE_LABEL (elt);
728       basic_block label_bb = label_to_block (lab);
729       edge this_edge = find_edge (e->src, label_bb);
730
731       /* Add it to the chain of CASE_LABEL_EXPRs referencing E, or create
732          a new chain.  */
733       slot = pointer_map_insert (edge_to_cases, this_edge);
734       TREE_CHAIN (elt) = (tree) *slot;
735       *slot = elt;
736     }
737
738   return (tree) *pointer_map_contains (edge_to_cases, e);
739 }
740
741 /* Create the edges for a SWITCH_EXPR starting at block BB.
742    At this point, the switch body has been lowered and the
743    SWITCH_LABELS filled in, so this is in effect a multi-way branch.  */
744
745 static void
746 make_switch_expr_edges (basic_block bb)
747 {
748   tree entry = last_stmt (bb);
749   size_t i, n;
750   tree vec;
751
752   vec = SWITCH_LABELS (entry);
753   n = TREE_VEC_LENGTH (vec);
754
755   for (i = 0; i < n; ++i)
756     {
757       tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i));
758       basic_block label_bb = label_to_block (lab);
759       make_edge (bb, label_bb, 0);
760     }
761 }
762
763
764 /* Return the basic block holding label DEST.  */
765
766 basic_block
767 label_to_block_fn (struct function *ifun, tree dest)
768 {
769   int uid = LABEL_DECL_UID (dest);
770
771   /* We would die hard when faced by an undefined label.  Emit a label to
772      the very first basic block.  This will hopefully make even the dataflow
773      and undefined variable warnings quite right.  */
774   if ((errorcount || sorrycount) && uid < 0)
775     {
776       block_stmt_iterator bsi =
777         bsi_start (BASIC_BLOCK (NUM_FIXED_BLOCKS));
778       tree stmt;
779
780       stmt = build1 (LABEL_EXPR, void_type_node, dest);
781       bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
782       uid = LABEL_DECL_UID (dest);
783     }
784   if (VEC_length (basic_block, ifun->cfg->x_label_to_block_map)
785       <= (unsigned int) uid)
786     return NULL;
787   return VEC_index (basic_block, ifun->cfg->x_label_to_block_map, uid);
788 }
789
790 /* Create edges for an abnormal goto statement at block BB.  If FOR_CALL
791    is true, the source statement is a CALL_EXPR instead of a GOTO_EXPR.  */
792
793 void
794 make_abnormal_goto_edges (basic_block bb, bool for_call)
795 {
796   basic_block target_bb;
797   block_stmt_iterator bsi;
798
799   FOR_EACH_BB (target_bb)
800     for (bsi = bsi_start (target_bb); !bsi_end_p (bsi); bsi_next (&bsi))
801       {
802         tree target = bsi_stmt (bsi);
803
804         if (TREE_CODE (target) != LABEL_EXPR)
805           break;
806
807         target = LABEL_EXPR_LABEL (target);
808
809         /* Make an edge to every label block that has been marked as a
810            potential target for a computed goto or a non-local goto.  */
811         if ((FORCED_LABEL (target) && !for_call)
812             || (DECL_NONLOCAL (target) && for_call))
813           {
814             make_edge (bb, target_bb, EDGE_ABNORMAL);
815             break;
816           }
817       }
818 }
819
820 /* Create edges for a goto statement at block BB.  */
821
822 static void
823 make_goto_expr_edges (basic_block bb)
824 {
825   block_stmt_iterator last = bsi_last (bb);
826   tree goto_t = bsi_stmt (last);
827
828   /* A simple GOTO creates normal edges.  */
829   if (simple_goto_p (goto_t))
830     {
831       tree dest = GOTO_DESTINATION (goto_t);
832       edge e = make_edge (bb, label_to_block (dest), EDGE_FALLTHRU);
833 #ifdef USE_MAPPED_LOCATION
834       e->goto_locus = EXPR_LOCATION (goto_t);
835 #else
836       e->goto_locus = EXPR_LOCUS (goto_t);
837 #endif
838       bsi_remove (&last, true);
839       return;
840     }
841
842   /* A computed GOTO creates abnormal edges.  */
843   make_abnormal_goto_edges (bb, false);
844 }
845
846
847 /*---------------------------------------------------------------------------
848                                Flowgraph analysis
849 ---------------------------------------------------------------------------*/
850
851 /* Cleanup useless labels in basic blocks.  This is something we wish
852    to do early because it allows us to group case labels before creating
853    the edges for the CFG, and it speeds up block statement iterators in
854    all passes later on.
855    We rerun this pass after CFG is created, to get rid of the labels that
856    are no longer referenced.  After then we do not run it any more, since
857    (almost) no new labels should be created.  */
858
859 /* A map from basic block index to the leading label of that block.  */
860 static struct label_record
861 {
862   /* The label.  */
863   tree label;
864
865   /* True if the label is referenced from somewhere.  */
866   bool used;
867 } *label_for_bb;
868
869 /* Callback for for_each_eh_region.  Helper for cleanup_dead_labels.  */
870 static void
871 update_eh_label (struct eh_region *region)
872 {
873   tree old_label = get_eh_region_tree_label (region);
874   if (old_label)
875     {
876       tree new_label;
877       basic_block bb = label_to_block (old_label);
878
879       /* ??? After optimizing, there may be EH regions with labels
880          that have already been removed from the function body, so
881          there is no basic block for them.  */
882       if (! bb)
883         return;
884
885       new_label = label_for_bb[bb->index].label;
886       label_for_bb[bb->index].used = true;
887       set_eh_region_tree_label (region, new_label);
888     }
889 }
890
891 /* Given LABEL return the first label in the same basic block.  */
892 static tree
893 main_block_label (tree label)
894 {
895   basic_block bb = label_to_block (label);
896   tree main_label = label_for_bb[bb->index].label;
897
898   /* label_to_block possibly inserted undefined label into the chain.  */
899   if (!main_label)
900     {
901       label_for_bb[bb->index].label = label;
902       main_label = label;
903     }
904
905   label_for_bb[bb->index].used = true;
906   return main_label;
907 }
908
909 /* Cleanup redundant labels.  This is a three-step process:
910      1) Find the leading label for each block.
911      2) Redirect all references to labels to the leading labels.
912      3) Cleanup all useless labels.  */
913
914 void
915 cleanup_dead_labels (void)
916 {
917   basic_block bb;
918   label_for_bb = XCNEWVEC (struct label_record, last_basic_block);
919
920   /* Find a suitable label for each block.  We use the first user-defined
921      label if there is one, or otherwise just the first label we see.  */
922   FOR_EACH_BB (bb)
923     {
924       block_stmt_iterator i;
925
926       for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
927         {
928           tree label, stmt = bsi_stmt (i);
929
930           if (TREE_CODE (stmt) != LABEL_EXPR)
931             break;
932
933           label = LABEL_EXPR_LABEL (stmt);
934
935           /* If we have not yet seen a label for the current block,
936              remember this one and see if there are more labels.  */
937           if (!label_for_bb[bb->index].label)
938             {
939               label_for_bb[bb->index].label = label;
940               continue;
941             }
942
943           /* If we did see a label for the current block already, but it
944              is an artificially created label, replace it if the current
945              label is a user defined label.  */
946           if (!DECL_ARTIFICIAL (label)
947               && DECL_ARTIFICIAL (label_for_bb[bb->index].label))
948             {
949               label_for_bb[bb->index].label = label;
950               break;
951             }
952         }
953     }
954
955   /* Now redirect all jumps/branches to the selected label.
956      First do so for each block ending in a control statement.  */
957   FOR_EACH_BB (bb)
958     {
959       tree stmt = last_stmt (bb);
960       if (!stmt)
961         continue;
962
963       switch (TREE_CODE (stmt))
964         {
965         case COND_EXPR:
966           {
967             tree true_branch, false_branch;
968
969             true_branch = COND_EXPR_THEN (stmt);
970             false_branch = COND_EXPR_ELSE (stmt);
971
972             if (true_branch)
973               GOTO_DESTINATION (true_branch)
974                       = main_block_label (GOTO_DESTINATION (true_branch));
975             if (false_branch)
976               GOTO_DESTINATION (false_branch)
977                       = main_block_label (GOTO_DESTINATION (false_branch));
978
979             break;
980           }
981
982         case SWITCH_EXPR:
983           {
984             size_t i;
985             tree vec = SWITCH_LABELS (stmt);
986             size_t n = TREE_VEC_LENGTH (vec);
987
988             /* Replace all destination labels.  */
989             for (i = 0; i < n; ++i)
990               {
991                 tree elt = TREE_VEC_ELT (vec, i);
992                 tree label = main_block_label (CASE_LABEL (elt));
993                 CASE_LABEL (elt) = label;
994               }
995             break;
996           }
997
998         /* We have to handle GOTO_EXPRs until they're removed, and we don't
999            remove them until after we've created the CFG edges.  */
1000         case GOTO_EXPR:
1001           if (! computed_goto_p (stmt))
1002             {
1003               GOTO_DESTINATION (stmt)
1004                 = main_block_label (GOTO_DESTINATION (stmt));
1005               break;
1006             }
1007
1008         default:
1009           break;
1010       }
1011     }
1012
1013   for_each_eh_region (update_eh_label);
1014
1015   /* Finally, purge dead labels.  All user-defined labels and labels that
1016      can be the target of non-local gotos and labels which have their
1017      address taken are preserved.  */
1018   FOR_EACH_BB (bb)
1019     {
1020       block_stmt_iterator i;
1021       tree label_for_this_bb = label_for_bb[bb->index].label;
1022
1023       if (!label_for_this_bb)
1024         continue;
1025
1026       /* If the main label of the block is unused, we may still remove it.  */
1027       if (!label_for_bb[bb->index].used)
1028         label_for_this_bb = NULL;
1029
1030       for (i = bsi_start (bb); !bsi_end_p (i); )
1031         {
1032           tree label, stmt = bsi_stmt (i);
1033
1034           if (TREE_CODE (stmt) != LABEL_EXPR)
1035             break;
1036
1037           label = LABEL_EXPR_LABEL (stmt);
1038
1039           if (label == label_for_this_bb
1040               || ! DECL_ARTIFICIAL (label)
1041               || DECL_NONLOCAL (label)
1042               || FORCED_LABEL (label))
1043             bsi_next (&i);
1044           else
1045             bsi_remove (&i, true);
1046         }
1047     }
1048
1049   free (label_for_bb);
1050 }
1051
1052 /* Look for blocks ending in a multiway branch (a SWITCH_EXPR in GIMPLE),
1053    and scan the sorted vector of cases.  Combine the ones jumping to the
1054    same label.
1055    Eg. three separate entries 1: 2: 3: become one entry 1..3:  */
1056
1057 void
1058 group_case_labels (void)
1059 {
1060   basic_block bb;
1061
1062   FOR_EACH_BB (bb)
1063     {
1064       tree stmt = last_stmt (bb);
1065       if (stmt && TREE_CODE (stmt) == SWITCH_EXPR)
1066         {
1067           tree labels = SWITCH_LABELS (stmt);
1068           int old_size = TREE_VEC_LENGTH (labels);
1069           int i, j, new_size = old_size;
1070           tree default_case = TREE_VEC_ELT (labels, old_size - 1);
1071           tree default_label;
1072
1073           /* The default label is always the last case in a switch
1074              statement after gimplification.  */
1075           default_label = CASE_LABEL (default_case);
1076
1077           /* Look for possible opportunities to merge cases.
1078              Ignore the last element of the label vector because it
1079              must be the default case.  */
1080           i = 0;
1081           while (i < old_size - 1)
1082             {
1083               tree base_case, base_label, base_high;
1084               base_case = TREE_VEC_ELT (labels, i);
1085
1086               gcc_assert (base_case);
1087               base_label = CASE_LABEL (base_case);
1088
1089               /* Discard cases that have the same destination as the
1090                  default case.  */
1091               if (base_label == default_label)
1092                 {
1093                   TREE_VEC_ELT (labels, i) = NULL_TREE;
1094                   i++;
1095                   new_size--;
1096                   continue;
1097                 }
1098
1099               base_high = CASE_HIGH (base_case) ?
1100                 CASE_HIGH (base_case) : CASE_LOW (base_case);
1101               i++;
1102               /* Try to merge case labels.  Break out when we reach the end
1103                  of the label vector or when we cannot merge the next case
1104                  label with the current one.  */
1105               while (i < old_size - 1)
1106                 {
1107                   tree merge_case = TREE_VEC_ELT (labels, i);
1108                   tree merge_label = CASE_LABEL (merge_case);
1109                   tree t = int_const_binop (PLUS_EXPR, base_high,
1110                                             integer_one_node, 1);
1111
1112                   /* Merge the cases if they jump to the same place,
1113                      and their ranges are consecutive.  */
1114                   if (merge_label == base_label
1115                       && tree_int_cst_equal (CASE_LOW (merge_case), t))
1116                     {
1117                       base_high = CASE_HIGH (merge_case) ?
1118                         CASE_HIGH (merge_case) : CASE_LOW (merge_case);
1119                       CASE_HIGH (base_case) = base_high;
1120                       TREE_VEC_ELT (labels, i) = NULL_TREE;
1121                       new_size--;
1122                       i++;
1123                     }
1124                   else
1125                     break;
1126                 }
1127             }
1128
1129           /* Compress the case labels in the label vector, and adjust the
1130              length of the vector.  */
1131           for (i = 0, j = 0; i < new_size; i++)
1132             {
1133               while (! TREE_VEC_ELT (labels, j))
1134                 j++;
1135               TREE_VEC_ELT (labels, i) = TREE_VEC_ELT (labels, j++);
1136             }
1137           TREE_VEC_LENGTH (labels) = new_size;
1138         }
1139     }
1140 }
1141
1142 /* Checks whether we can merge block B into block A.  */
1143
1144 static bool
1145 tree_can_merge_blocks_p (basic_block a, basic_block b)
1146 {
1147   const_tree stmt;
1148   block_stmt_iterator bsi;
1149   tree phi;
1150
1151   if (!single_succ_p (a))
1152     return false;
1153
1154   if (single_succ_edge (a)->flags & EDGE_ABNORMAL)
1155     return false;
1156
1157   if (single_succ (a) != b)
1158     return false;
1159
1160   if (!single_pred_p (b))
1161     return false;
1162
1163   if (b == EXIT_BLOCK_PTR)
1164     return false;
1165
1166   /* If A ends by a statement causing exceptions or something similar, we
1167      cannot merge the blocks.  */
1168   /* This CONST_CAST is okay because last_stmt doesn't modify its
1169      argument and the return value is assign to a const_tree.  */
1170   stmt = last_stmt (CONST_CAST_BB (a));
1171   if (stmt && stmt_ends_bb_p (stmt))
1172     return false;
1173
1174   /* Do not allow a block with only a non-local label to be merged.  */
1175   if (stmt && TREE_CODE (stmt) == LABEL_EXPR
1176       && DECL_NONLOCAL (LABEL_EXPR_LABEL (stmt)))
1177     return false;
1178
1179   /* It must be possible to eliminate all phi nodes in B.  If ssa form
1180      is not up-to-date, we cannot eliminate any phis; however, if only
1181      some symbols as whole are marked for renaming, this is not a problem,
1182      as phi nodes for those symbols are irrelevant in updating anyway.  */
1183   phi = phi_nodes (b);
1184   if (phi)
1185     {
1186       if (name_mappings_registered_p ())
1187         return false;
1188
1189       for (; phi; phi = PHI_CHAIN (phi))
1190         if (!is_gimple_reg (PHI_RESULT (phi))
1191             && !may_propagate_copy (PHI_RESULT (phi), PHI_ARG_DEF (phi, 0)))
1192           return false;
1193     }
1194
1195   /* Do not remove user labels.  */
1196   for (bsi = bsi_start (b); !bsi_end_p (bsi); bsi_next (&bsi))
1197     {
1198       stmt = bsi_stmt (bsi);
1199       if (TREE_CODE (stmt) != LABEL_EXPR)
1200         break;
1201       if (!DECL_ARTIFICIAL (LABEL_EXPR_LABEL (stmt)))
1202         return false;
1203     }
1204
1205   /* Protect the loop latches.  */
1206   if (current_loops
1207       && b->loop_father->latch == b)
1208     return false;
1209
1210   return true;
1211 }
1212
1213 /* Replaces all uses of NAME by VAL.  */
1214
1215 void
1216 replace_uses_by (tree name, tree val)
1217 {
1218   imm_use_iterator imm_iter;
1219   use_operand_p use;
1220   tree stmt;
1221   edge e;
1222
1223   FOR_EACH_IMM_USE_STMT (stmt, imm_iter, name)
1224     {
1225       if (TREE_CODE (stmt) != PHI_NODE)
1226         push_stmt_changes (&stmt);
1227
1228       FOR_EACH_IMM_USE_ON_STMT (use, imm_iter)
1229         {
1230           replace_exp (use, val);
1231
1232           if (TREE_CODE (stmt) == PHI_NODE)
1233             {
1234               e = PHI_ARG_EDGE (stmt, PHI_ARG_INDEX_FROM_USE (use));
1235               if (e->flags & EDGE_ABNORMAL)
1236                 {
1237                   /* This can only occur for virtual operands, since
1238                      for the real ones SSA_NAME_OCCURS_IN_ABNORMAL_PHI (name))
1239                      would prevent replacement.  */
1240                   gcc_assert (!is_gimple_reg (name));
1241                   SSA_NAME_OCCURS_IN_ABNORMAL_PHI (val) = 1;
1242                 }
1243             }
1244         }
1245
1246       if (TREE_CODE (stmt) != PHI_NODE)
1247         {
1248           tree rhs;
1249
1250           fold_stmt_inplace (stmt);
1251           if (cfgcleanup_altered_bbs)
1252             bitmap_set_bit (cfgcleanup_altered_bbs, bb_for_stmt (stmt)->index);
1253
1254           /* FIXME.  This should go in pop_stmt_changes.  */
1255           rhs = get_rhs (stmt);
1256           if (TREE_CODE (rhs) == ADDR_EXPR)
1257             recompute_tree_invariant_for_addr_expr (rhs);
1258
1259           maybe_clean_or_replace_eh_stmt (stmt, stmt);
1260
1261           pop_stmt_changes (&stmt);
1262         }
1263     }
1264
1265   gcc_assert (has_zero_uses (name));
1266
1267   /* Also update the trees stored in loop structures.  */
1268   if (current_loops)
1269     {
1270       struct loop *loop;
1271       loop_iterator li;
1272
1273       FOR_EACH_LOOP (li, loop, 0)
1274         {
1275           substitute_in_loop_info (loop, name, val);
1276         }
1277     }
1278 }
1279
1280 /* Merge block B into block A.  */
1281
1282 static void
1283 tree_merge_blocks (basic_block a, basic_block b)
1284 {
1285   block_stmt_iterator bsi;
1286   tree_stmt_iterator last;
1287   tree phi;
1288
1289   if (dump_file)
1290     fprintf (dump_file, "Merging blocks %d and %d\n", a->index, b->index);
1291
1292   /* Remove all single-valued PHI nodes from block B of the form
1293      V_i = PHI <V_j> by propagating V_j to all the uses of V_i.  */
1294   bsi = bsi_last (a);
1295   for (phi = phi_nodes (b); phi; phi = phi_nodes (b))
1296     {
1297       tree def = PHI_RESULT (phi), use = PHI_ARG_DEF (phi, 0);
1298       tree copy;
1299       bool may_replace_uses = may_propagate_copy (def, use);
1300
1301       /* In case we maintain loop closed ssa form, do not propagate arguments
1302          of loop exit phi nodes.  */
1303       if (current_loops
1304           && loops_state_satisfies_p (LOOP_CLOSED_SSA)
1305           && is_gimple_reg (def)
1306           && TREE_CODE (use) == SSA_NAME
1307           && a->loop_father != b->loop_father)
1308         may_replace_uses = false;
1309
1310       if (!may_replace_uses)
1311         {
1312           gcc_assert (is_gimple_reg (def));
1313
1314           /* Note that just emitting the copies is fine -- there is no problem
1315              with ordering of phi nodes.  This is because A is the single
1316              predecessor of B, therefore results of the phi nodes cannot
1317              appear as arguments of the phi nodes.  */
1318           copy = build_gimple_modify_stmt (def, use);
1319           bsi_insert_after (&bsi, copy, BSI_NEW_STMT);
1320           SSA_NAME_DEF_STMT (def) = copy;
1321           remove_phi_node (phi, NULL, false);
1322         }
1323       else
1324         {
1325           replace_uses_by (def, use);
1326           remove_phi_node (phi, NULL, true);
1327         }
1328     }
1329
1330   /* Ensure that B follows A.  */
1331   move_block_after (b, a);
1332
1333   gcc_assert (single_succ_edge (a)->flags & EDGE_FALLTHRU);
1334   gcc_assert (!last_stmt (a) || !stmt_ends_bb_p (last_stmt (a)));
1335
1336   /* Remove labels from B and set bb_for_stmt to A for other statements.  */
1337   for (bsi = bsi_start (b); !bsi_end_p (bsi);)
1338     {
1339       if (TREE_CODE (bsi_stmt (bsi)) == LABEL_EXPR)
1340         {
1341           tree label = bsi_stmt (bsi);
1342
1343           bsi_remove (&bsi, false);
1344           /* Now that we can thread computed gotos, we might have
1345              a situation where we have a forced label in block B
1346              However, the label at the start of block B might still be
1347              used in other ways (think about the runtime checking for
1348              Fortran assigned gotos).  So we can not just delete the
1349              label.  Instead we move the label to the start of block A.  */
1350           if (FORCED_LABEL (LABEL_EXPR_LABEL (label)))
1351             {
1352               block_stmt_iterator dest_bsi = bsi_start (a);
1353               bsi_insert_before (&dest_bsi, label, BSI_NEW_STMT);
1354             }
1355         }
1356       else
1357         {
1358           change_bb_for_stmt (bsi_stmt (bsi), a);
1359           bsi_next (&bsi);
1360         }
1361     }
1362
1363   /* Merge the chains.  */
1364   last = tsi_last (bb_stmt_list (a));
1365   tsi_link_after (&last, bb_stmt_list (b), TSI_NEW_STMT);
1366   set_bb_stmt_list (b, NULL_TREE);
1367
1368   if (cfgcleanup_altered_bbs)
1369     bitmap_set_bit (cfgcleanup_altered_bbs, a->index);
1370 }
1371
1372
1373 /* Return the one of two successors of BB that is not reachable by a
1374    reached by a complex edge, if there is one.  Else, return BB.  We use
1375    this in optimizations that use post-dominators for their heuristics,
1376    to catch the cases in C++ where function calls are involved.  */
1377
1378 basic_block
1379 single_noncomplex_succ (basic_block bb)
1380 {
1381   edge e0, e1;
1382   if (EDGE_COUNT (bb->succs) != 2)
1383     return bb;
1384
1385   e0 = EDGE_SUCC (bb, 0);
1386   e1 = EDGE_SUCC (bb, 1);
1387   if (e0->flags & EDGE_COMPLEX)
1388     return e1->dest;
1389   if (e1->flags & EDGE_COMPLEX)
1390     return e0->dest;
1391
1392   return bb;
1393 }
1394
1395
1396 /* Walk the function tree removing unnecessary statements.
1397
1398      * Empty statement nodes are removed
1399
1400      * Unnecessary TRY_FINALLY and TRY_CATCH blocks are removed
1401
1402      * Unnecessary COND_EXPRs are removed
1403
1404      * Some unnecessary BIND_EXPRs are removed
1405
1406    Clearly more work could be done.  The trick is doing the analysis
1407    and removal fast enough to be a net improvement in compile times.
1408
1409    Note that when we remove a control structure such as a COND_EXPR
1410    BIND_EXPR, or TRY block, we will need to repeat this optimization pass
1411    to ensure we eliminate all the useless code.  */
1412
1413 struct rus_data
1414 {
1415   tree *last_goto;
1416   bool repeat;
1417   bool may_throw;
1418   bool may_branch;
1419   bool has_label;
1420 };
1421
1422 static void remove_useless_stmts_1 (tree *, struct rus_data *);
1423
1424 static bool
1425 remove_useless_stmts_warn_notreached (tree stmt)
1426 {
1427   if (EXPR_HAS_LOCATION (stmt))
1428     {
1429       location_t loc = EXPR_LOCATION (stmt);
1430       if (LOCATION_LINE (loc) > 0)
1431         {
1432           warning (OPT_Wunreachable_code, "%Hwill never be executed", &loc);
1433           return true;
1434         }
1435     }
1436
1437   switch (TREE_CODE (stmt))
1438     {
1439     case STATEMENT_LIST:
1440       {
1441         tree_stmt_iterator i;
1442         for (i = tsi_start (stmt); !tsi_end_p (i); tsi_next (&i))
1443           if (remove_useless_stmts_warn_notreached (tsi_stmt (i)))
1444             return true;
1445       }
1446       break;
1447
1448     case COND_EXPR:
1449       if (remove_useless_stmts_warn_notreached (COND_EXPR_COND (stmt)))
1450         return true;
1451       if (remove_useless_stmts_warn_notreached (COND_EXPR_THEN (stmt)))
1452         return true;
1453       if (remove_useless_stmts_warn_notreached (COND_EXPR_ELSE (stmt)))
1454         return true;
1455       break;
1456
1457     case TRY_FINALLY_EXPR:
1458     case TRY_CATCH_EXPR:
1459       if (remove_useless_stmts_warn_notreached (TREE_OPERAND (stmt, 0)))
1460         return true;
1461       if (remove_useless_stmts_warn_notreached (TREE_OPERAND (stmt, 1)))
1462         return true;
1463       break;
1464
1465     case CATCH_EXPR:
1466       return remove_useless_stmts_warn_notreached (CATCH_BODY (stmt));
1467     case EH_FILTER_EXPR:
1468       return remove_useless_stmts_warn_notreached (EH_FILTER_FAILURE (stmt));
1469     case BIND_EXPR:
1470       return remove_useless_stmts_warn_notreached (BIND_EXPR_BLOCK (stmt));
1471
1472     default:
1473       /* Not a live container.  */
1474       break;
1475     }
1476
1477   return false;
1478 }
1479
1480 static void
1481 remove_useless_stmts_cond (tree *stmt_p, struct rus_data *data)
1482 {
1483   tree then_clause, else_clause, cond;
1484   bool save_has_label, then_has_label, else_has_label;
1485
1486   save_has_label = data->has_label;
1487   data->has_label = false;
1488   data->last_goto = NULL;
1489
1490   remove_useless_stmts_1 (&COND_EXPR_THEN (*stmt_p), data);
1491
1492   then_has_label = data->has_label;
1493   data->has_label = false;
1494   data->last_goto = NULL;
1495
1496   remove_useless_stmts_1 (&COND_EXPR_ELSE (*stmt_p), data);
1497
1498   else_has_label = data->has_label;
1499   data->has_label = save_has_label | then_has_label | else_has_label;
1500
1501   then_clause = COND_EXPR_THEN (*stmt_p);
1502   else_clause = COND_EXPR_ELSE (*stmt_p);
1503   cond = fold (COND_EXPR_COND (*stmt_p));
1504
1505   /* If neither arm does anything at all, we can remove the whole IF.  */
1506   if (!TREE_SIDE_EFFECTS (then_clause) && !TREE_SIDE_EFFECTS (else_clause))
1507     {
1508       *stmt_p = build_empty_stmt ();
1509       data->repeat = true;
1510     }
1511
1512   /* If there are no reachable statements in an arm, then we can
1513      zap the entire conditional.  */
1514   else if (integer_nonzerop (cond) && !else_has_label)
1515     {
1516       if (warn_notreached)
1517         remove_useless_stmts_warn_notreached (else_clause);
1518       *stmt_p = then_clause;
1519       data->repeat = true;
1520     }
1521   else if (integer_zerop (cond) && !then_has_label)
1522     {
1523       if (warn_notreached)
1524         remove_useless_stmts_warn_notreached (then_clause);
1525       *stmt_p = else_clause;
1526       data->repeat = true;
1527     }
1528
1529   /* Check a couple of simple things on then/else with single stmts.  */
1530   else
1531     {
1532       tree then_stmt = expr_only (then_clause);
1533       tree else_stmt = expr_only (else_clause);
1534
1535       /* Notice branches to a common destination.  */
1536       if (then_stmt && else_stmt
1537           && TREE_CODE (then_stmt) == GOTO_EXPR
1538           && TREE_CODE (else_stmt) == GOTO_EXPR
1539           && (GOTO_DESTINATION (then_stmt) == GOTO_DESTINATION (else_stmt)))
1540         {
1541           *stmt_p = then_stmt;
1542           data->repeat = true;
1543         }
1544
1545       /* If the THEN/ELSE clause merely assigns a value to a variable or
1546          parameter which is already known to contain that value, then
1547          remove the useless THEN/ELSE clause.  */
1548       else if (TREE_CODE (cond) == VAR_DECL || TREE_CODE (cond) == PARM_DECL)
1549         {
1550           if (else_stmt
1551               && TREE_CODE (else_stmt) == GIMPLE_MODIFY_STMT
1552               && GIMPLE_STMT_OPERAND (else_stmt, 0) == cond
1553               && integer_zerop (GIMPLE_STMT_OPERAND (else_stmt, 1)))
1554             COND_EXPR_ELSE (*stmt_p) = alloc_stmt_list ();
1555         }
1556       else if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
1557                && (TREE_CODE (TREE_OPERAND (cond, 0)) == VAR_DECL
1558                    || TREE_CODE (TREE_OPERAND (cond, 0)) == PARM_DECL)
1559                && TREE_CONSTANT (TREE_OPERAND (cond, 1)))
1560         {
1561           tree stmt = (TREE_CODE (cond) == EQ_EXPR
1562                        ? then_stmt : else_stmt);
1563           tree *location = (TREE_CODE (cond) == EQ_EXPR
1564                             ? &COND_EXPR_THEN (*stmt_p)
1565                             : &COND_EXPR_ELSE (*stmt_p));
1566
1567           if (stmt
1568               && TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
1569               && GIMPLE_STMT_OPERAND (stmt, 0) == TREE_OPERAND (cond, 0)
1570               && GIMPLE_STMT_OPERAND (stmt, 1) == TREE_OPERAND (cond, 1))
1571             *location = alloc_stmt_list ();
1572         }
1573     }
1574
1575   /* Protect GOTOs in the arm of COND_EXPRs from being removed.  They
1576      would be re-introduced during lowering.  */
1577   data->last_goto = NULL;
1578 }
1579
1580
1581 static void
1582 remove_useless_stmts_tf (tree *stmt_p, struct rus_data *data)
1583 {
1584   bool save_may_branch, save_may_throw;
1585   bool this_may_branch, this_may_throw;
1586
1587   /* Collect may_branch and may_throw information for the body only.  */
1588   save_may_branch = data->may_branch;
1589   save_may_throw = data->may_throw;
1590   data->may_branch = false;
1591   data->may_throw = false;
1592   data->last_goto = NULL;
1593
1594   remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 0), data);
1595
1596   this_may_branch = data->may_branch;
1597   this_may_throw = data->may_throw;
1598   data->may_branch |= save_may_branch;
1599   data->may_throw |= save_may_throw;
1600   data->last_goto = NULL;
1601
1602   remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 1), data);
1603
1604   /* If the body is empty, then we can emit the FINALLY block without
1605      the enclosing TRY_FINALLY_EXPR.  */
1606   if (!TREE_SIDE_EFFECTS (TREE_OPERAND (*stmt_p, 0)))
1607     {
1608       *stmt_p = TREE_OPERAND (*stmt_p, 1);
1609       data->repeat = true;
1610     }
1611
1612   /* If the handler is empty, then we can emit the TRY block without
1613      the enclosing TRY_FINALLY_EXPR.  */
1614   else if (!TREE_SIDE_EFFECTS (TREE_OPERAND (*stmt_p, 1)))
1615     {
1616       *stmt_p = TREE_OPERAND (*stmt_p, 0);
1617       data->repeat = true;
1618     }
1619
1620   /* If the body neither throws, nor branches, then we can safely
1621      string the TRY and FINALLY blocks together.  */
1622   else if (!this_may_branch && !this_may_throw)
1623     {
1624       tree stmt = *stmt_p;
1625       *stmt_p = TREE_OPERAND (stmt, 0);
1626       append_to_statement_list (TREE_OPERAND (stmt, 1), stmt_p);
1627       data->repeat = true;
1628     }
1629 }
1630
1631
1632 static void
1633 remove_useless_stmts_tc (tree *stmt_p, struct rus_data *data)
1634 {
1635   bool save_may_throw, this_may_throw;
1636   tree_stmt_iterator i;
1637   tree stmt;
1638
1639   /* Collect may_throw information for the body only.  */
1640   save_may_throw = data->may_throw;
1641   data->may_throw = false;
1642   data->last_goto = NULL;
1643
1644   remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 0), data);
1645
1646   this_may_throw = data->may_throw;
1647   data->may_throw = save_may_throw;
1648
1649   /* If the body cannot throw, then we can drop the entire TRY_CATCH_EXPR.  */
1650   if (!this_may_throw)
1651     {
1652       if (warn_notreached)
1653         remove_useless_stmts_warn_notreached (TREE_OPERAND (*stmt_p, 1));
1654       *stmt_p = TREE_OPERAND (*stmt_p, 0);
1655       data->repeat = true;
1656       return;
1657     }
1658
1659   /* Process the catch clause specially.  We may be able to tell that
1660      no exceptions propagate past this point.  */
1661
1662   this_may_throw = true;
1663   i = tsi_start (TREE_OPERAND (*stmt_p, 1));
1664   stmt = tsi_stmt (i);
1665   data->last_goto = NULL;
1666
1667   switch (TREE_CODE (stmt))
1668     {
1669     case CATCH_EXPR:
1670       for (; !tsi_end_p (i); tsi_next (&i))
1671         {
1672           stmt = tsi_stmt (i);
1673           /* If we catch all exceptions, then the body does not
1674              propagate exceptions past this point.  */
1675           if (CATCH_TYPES (stmt) == NULL)
1676             this_may_throw = false;
1677           data->last_goto = NULL;
1678           remove_useless_stmts_1 (&CATCH_BODY (stmt), data);
1679         }
1680       break;
1681
1682     case EH_FILTER_EXPR:
1683       if (EH_FILTER_MUST_NOT_THROW (stmt))
1684         this_may_throw = false;
1685       else if (EH_FILTER_TYPES (stmt) == NULL)
1686         this_may_throw = false;
1687       remove_useless_stmts_1 (&EH_FILTER_FAILURE (stmt), data);
1688       break;
1689
1690     default:
1691       /* Otherwise this is a cleanup.  */
1692       remove_useless_stmts_1 (&TREE_OPERAND (*stmt_p, 1), data);
1693
1694       /* If the cleanup is empty, then we can emit the TRY block without
1695          the enclosing TRY_CATCH_EXPR.  */
1696       if (!TREE_SIDE_EFFECTS (TREE_OPERAND (*stmt_p, 1)))
1697         {
1698           *stmt_p = TREE_OPERAND (*stmt_p, 0);
1699           data->repeat = true;
1700         }
1701       break;
1702     }
1703   data->may_throw |= this_may_throw;
1704 }
1705
1706
1707 static void
1708 remove_useless_stmts_bind (tree *stmt_p, struct rus_data *data)
1709 {
1710   tree block;
1711
1712   /* First remove anything underneath the BIND_EXPR.  */
1713   remove_useless_stmts_1 (&BIND_EXPR_BODY (*stmt_p), data);
1714
1715   /* If the BIND_EXPR has no variables, then we can pull everything
1716      up one level and remove the BIND_EXPR, unless this is the toplevel
1717      BIND_EXPR for the current function or an inlined function.
1718
1719      When this situation occurs we will want to apply this
1720      optimization again.  */
1721   block = BIND_EXPR_BLOCK (*stmt_p);
1722   if (BIND_EXPR_VARS (*stmt_p) == NULL_TREE
1723       && *stmt_p != DECL_SAVED_TREE (current_function_decl)
1724       && (! block
1725           || ! BLOCK_ABSTRACT_ORIGIN (block)
1726           || (TREE_CODE (BLOCK_ABSTRACT_ORIGIN (block))
1727               != FUNCTION_DECL)))
1728     {
1729       *stmt_p = BIND_EXPR_BODY (*stmt_p);
1730       data->repeat = true;
1731     }
1732 }
1733
1734
1735 static void
1736 remove_useless_stmts_goto (tree *stmt_p, struct rus_data *data)
1737 {
1738   tree dest = GOTO_DESTINATION (*stmt_p);
1739
1740   data->may_branch = true;
1741   data->last_goto = NULL;
1742
1743   /* Record the last goto expr, so that we can delete it if unnecessary.  */
1744   if (TREE_CODE (dest) == LABEL_DECL)
1745     data->last_goto = stmt_p;
1746 }
1747
1748
1749 static void
1750 remove_useless_stmts_label (tree *stmt_p, struct rus_data *data)
1751 {
1752   tree label = LABEL_EXPR_LABEL (*stmt_p);
1753
1754   data->has_label = true;
1755
1756   /* We do want to jump across non-local label receiver code.  */
1757   if (DECL_NONLOCAL (label))
1758     data->last_goto = NULL;
1759
1760   else if (data->last_goto && GOTO_DESTINATION (*data->last_goto) == label)
1761     {
1762       *data->last_goto = build_empty_stmt ();
1763       data->repeat = true;
1764     }
1765
1766   /* ??? Add something here to delete unused labels.  */
1767 }
1768
1769
1770 /* If the function is "const" or "pure", then clear TREE_SIDE_EFFECTS on its
1771    decl.  This allows us to eliminate redundant or useless
1772    calls to "const" functions.
1773
1774    Gimplifier already does the same operation, but we may notice functions
1775    being const and pure once their calls has been gimplified, so we need
1776    to update the flag.  */
1777
1778 static void
1779 update_call_expr_flags (tree call)
1780 {
1781   tree decl = get_callee_fndecl (call);
1782   if (!decl)
1783     return;
1784   if (call_expr_flags (call) & (ECF_CONST | ECF_PURE))
1785     TREE_SIDE_EFFECTS (call) = 0;
1786   if (TREE_NOTHROW (decl))
1787     TREE_NOTHROW (call) = 1;
1788 }
1789
1790
1791 /* T is CALL_EXPR.  Set current_function_calls_* flags.  */
1792
1793 void
1794 notice_special_calls (tree t)
1795 {
1796   int flags = call_expr_flags (t);
1797
1798   if (flags & ECF_MAY_BE_ALLOCA)
1799     current_function_calls_alloca = true;
1800   if (flags & ECF_RETURNS_TWICE)
1801     current_function_calls_setjmp = true;
1802 }
1803
1804
1805 /* Clear flags set by notice_special_calls.  Used by dead code removal
1806    to update the flags.  */
1807
1808 void
1809 clear_special_calls (void)
1810 {
1811   current_function_calls_alloca = false;
1812   current_function_calls_setjmp = false;
1813 }
1814
1815
1816 static void
1817 remove_useless_stmts_1 (tree *tp, struct rus_data *data)
1818 {
1819   tree t = *tp, op;
1820
1821   switch (TREE_CODE (t))
1822     {
1823     case COND_EXPR:
1824       remove_useless_stmts_cond (tp, data);
1825       break;
1826
1827     case TRY_FINALLY_EXPR:
1828       remove_useless_stmts_tf (tp, data);
1829       break;
1830
1831     case TRY_CATCH_EXPR:
1832       remove_useless_stmts_tc (tp, data);
1833       break;
1834
1835     case BIND_EXPR:
1836       remove_useless_stmts_bind (tp, data);
1837       break;
1838
1839     case GOTO_EXPR:
1840       remove_useless_stmts_goto (tp, data);
1841       break;
1842
1843     case LABEL_EXPR:
1844       remove_useless_stmts_label (tp, data);
1845       break;
1846
1847     case RETURN_EXPR:
1848       fold_stmt (tp);
1849       data->last_goto = NULL;
1850       data->may_branch = true;
1851       break;
1852
1853     case CALL_EXPR:
1854       fold_stmt (tp);
1855       data->last_goto = NULL;
1856       notice_special_calls (t);
1857       update_call_expr_flags (t);
1858       if (tree_could_throw_p (t))
1859         data->may_throw = true;
1860       break;
1861
1862     case MODIFY_EXPR:
1863       gcc_unreachable ();
1864
1865     case GIMPLE_MODIFY_STMT:
1866       data->last_goto = NULL;
1867       fold_stmt (tp);
1868       op = get_call_expr_in (t);
1869       if (op)
1870         {
1871           update_call_expr_flags (op);
1872           notice_special_calls (op);
1873         }
1874       if (tree_could_throw_p (t))
1875         data->may_throw = true;
1876       break;
1877
1878     case STATEMENT_LIST:
1879       {
1880         tree_stmt_iterator i = tsi_start (t);
1881         while (!tsi_end_p (i))
1882           {
1883             t = tsi_stmt (i);
1884             if (IS_EMPTY_STMT (t))
1885               {
1886                 tsi_delink (&i);
1887                 continue;
1888               }
1889
1890             remove_useless_stmts_1 (tsi_stmt_ptr (i), data);
1891
1892             t = tsi_stmt (i);
1893             if (TREE_CODE (t) == STATEMENT_LIST)
1894               {
1895                 tsi_link_before (&i, t, TSI_SAME_STMT);
1896                 tsi_delink (&i);
1897               }
1898             else
1899               tsi_next (&i);
1900           }
1901       }
1902       break;
1903     case ASM_EXPR:
1904       fold_stmt (tp);
1905       data->last_goto = NULL;
1906       break;
1907
1908     default:
1909       data->last_goto = NULL;
1910       break;
1911     }
1912 }
1913
1914 static unsigned int
1915 remove_useless_stmts (void)
1916 {
1917   struct rus_data data;
1918
1919   clear_special_calls ();
1920
1921   do
1922     {
1923       memset (&data, 0, sizeof (data));
1924       remove_useless_stmts_1 (&DECL_SAVED_TREE (current_function_decl), &data);
1925     }
1926   while (data.repeat);
1927   return 0;
1928 }
1929
1930
1931 struct tree_opt_pass pass_remove_useless_stmts =
1932 {
1933   "useless",                            /* name */
1934   NULL,                                 /* gate */
1935   remove_useless_stmts,                 /* execute */
1936   NULL,                                 /* sub */
1937   NULL,                                 /* next */
1938   0,                                    /* static_pass_number */
1939   0,                                    /* tv_id */
1940   PROP_gimple_any,                      /* properties_required */
1941   0,                                    /* properties_provided */
1942   0,                                    /* properties_destroyed */
1943   0,                                    /* todo_flags_start */
1944   TODO_dump_func,                       /* todo_flags_finish */
1945   0                                     /* letter */
1946 };
1947
1948 /* Remove PHI nodes associated with basic block BB and all edges out of BB.  */
1949
1950 static void
1951 remove_phi_nodes_and_edges_for_unreachable_block (basic_block bb)
1952 {
1953   tree phi;
1954
1955   /* Since this block is no longer reachable, we can just delete all
1956      of its PHI nodes.  */
1957   phi = phi_nodes (bb);
1958   while (phi)
1959     {
1960       tree next = PHI_CHAIN (phi);
1961       remove_phi_node (phi, NULL_TREE, true);
1962       phi = next;
1963     }
1964
1965   /* Remove edges to BB's successors.  */
1966   while (EDGE_COUNT (bb->succs) > 0)
1967     remove_edge (EDGE_SUCC (bb, 0));
1968 }
1969
1970
1971 /* Remove statements of basic block BB.  */
1972
1973 static void
1974 remove_bb (basic_block bb)
1975 {
1976   block_stmt_iterator i;
1977 #ifdef USE_MAPPED_LOCATION
1978   source_location loc = UNKNOWN_LOCATION;
1979 #else
1980   source_locus loc = 0;
1981 #endif
1982
1983   if (dump_file)
1984     {
1985       fprintf (dump_file, "Removing basic block %d\n", bb->index);
1986       if (dump_flags & TDF_DETAILS)
1987         {
1988           dump_bb (bb, dump_file, 0);
1989           fprintf (dump_file, "\n");
1990         }
1991     }
1992
1993   if (current_loops)
1994     {
1995       struct loop *loop = bb->loop_father;
1996
1997       /* If a loop gets removed, clean up the information associated
1998          with it.  */
1999       if (loop->latch == bb
2000           || loop->header == bb)
2001         free_numbers_of_iterations_estimates_loop (loop);
2002     }
2003
2004   /* Remove all the instructions in the block.  */
2005   if (bb_stmt_list (bb) != NULL_TREE)
2006     {
2007       for (i = bsi_start (bb); !bsi_end_p (i);)
2008         {
2009           tree stmt = bsi_stmt (i);
2010           if (TREE_CODE (stmt) == LABEL_EXPR
2011               && (FORCED_LABEL (LABEL_EXPR_LABEL (stmt))
2012                   || DECL_NONLOCAL (LABEL_EXPR_LABEL (stmt))))
2013             {
2014               basic_block new_bb;
2015               block_stmt_iterator new_bsi;
2016
2017               /* A non-reachable non-local label may still be referenced.
2018                  But it no longer needs to carry the extra semantics of
2019                  non-locality.  */
2020               if (DECL_NONLOCAL (LABEL_EXPR_LABEL (stmt)))
2021                 {
2022                   DECL_NONLOCAL (LABEL_EXPR_LABEL (stmt)) = 0;
2023                   FORCED_LABEL (LABEL_EXPR_LABEL (stmt)) = 1;
2024                 }
2025
2026               new_bb = bb->prev_bb;
2027               new_bsi = bsi_start (new_bb);
2028               bsi_remove (&i, false);
2029               bsi_insert_before (&new_bsi, stmt, BSI_NEW_STMT);
2030             }
2031           else
2032             {
2033               /* Release SSA definitions if we are in SSA.  Note that we
2034                  may be called when not in SSA.  For example,
2035                  final_cleanup calls this function via
2036                  cleanup_tree_cfg.  */
2037               if (gimple_in_ssa_p (cfun))
2038                 release_defs (stmt);
2039
2040               bsi_remove (&i, true);
2041             }
2042
2043           /* Don't warn for removed gotos.  Gotos are often removed due to
2044              jump threading, thus resulting in bogus warnings.  Not great,
2045              since this way we lose warnings for gotos in the original
2046              program that are indeed unreachable.  */
2047           if (TREE_CODE (stmt) != GOTO_EXPR && EXPR_HAS_LOCATION (stmt) && !loc)
2048             {
2049 #ifdef USE_MAPPED_LOCATION
2050               if (EXPR_HAS_LOCATION (stmt))
2051                 loc = EXPR_LOCATION (stmt);
2052 #else
2053               source_locus t;
2054               t = EXPR_LOCUS (stmt);
2055               if (t && LOCATION_LINE (*t) > 0)
2056                 loc = t;
2057 #endif
2058             }
2059         }
2060     }
2061
2062   /* If requested, give a warning that the first statement in the
2063      block is unreachable.  We walk statements backwards in the
2064      loop above, so the last statement we process is the first statement
2065      in the block.  */
2066 #ifdef USE_MAPPED_LOCATION
2067   if (loc > BUILTINS_LOCATION && LOCATION_LINE (loc) > 0)
2068     warning (OPT_Wunreachable_code, "%Hwill never be executed", &loc);
2069 #else
2070   if (loc)
2071     warning (OPT_Wunreachable_code, "%Hwill never be executed", loc);
2072 #endif
2073
2074   remove_phi_nodes_and_edges_for_unreachable_block (bb);
2075   bb->il.tree = NULL;
2076 }
2077
2078
2079 /* Given a basic block BB ending with COND_EXPR or SWITCH_EXPR, and a
2080    predicate VAL, return the edge that will be taken out of the block.
2081    If VAL does not match a unique edge, NULL is returned.  */
2082
2083 edge
2084 find_taken_edge (basic_block bb, tree val)
2085 {
2086   tree stmt;
2087
2088   stmt = last_stmt (bb);
2089
2090   gcc_assert (stmt);
2091   gcc_assert (is_ctrl_stmt (stmt));
2092   gcc_assert (val);
2093
2094   if (! is_gimple_min_invariant (val))
2095     return NULL;
2096
2097   if (TREE_CODE (stmt) == COND_EXPR)
2098     return find_taken_edge_cond_expr (bb, val);
2099
2100   if (TREE_CODE (stmt) == SWITCH_EXPR)
2101     return find_taken_edge_switch_expr (bb, val);
2102
2103   if (computed_goto_p (stmt))
2104     {
2105       /* Only optimize if the argument is a label, if the argument is
2106          not a label then we can not construct a proper CFG.
2107
2108          It may be the case that we only need to allow the LABEL_REF to
2109          appear inside an ADDR_EXPR, but we also allow the LABEL_REF to
2110          appear inside a LABEL_EXPR just to be safe.  */
2111       if ((TREE_CODE (val) == ADDR_EXPR || TREE_CODE (val) == LABEL_EXPR)
2112           && TREE_CODE (TREE_OPERAND (val, 0)) == LABEL_DECL)
2113         return find_taken_edge_computed_goto (bb, TREE_OPERAND (val, 0));
2114       return NULL;
2115     }
2116
2117   gcc_unreachable ();
2118 }
2119
2120 /* Given a constant value VAL and the entry block BB to a GOTO_EXPR
2121    statement, determine which of the outgoing edges will be taken out of the
2122    block.  Return NULL if either edge may be taken.  */
2123
2124 static edge
2125 find_taken_edge_computed_goto (basic_block bb, tree val)
2126 {
2127   basic_block dest;
2128   edge e = NULL;
2129
2130   dest = label_to_block (val);
2131   if (dest)
2132     {
2133       e = find_edge (bb, dest);
2134       gcc_assert (e != NULL);
2135     }
2136
2137   return e;
2138 }
2139
2140 /* Given a constant value VAL and the entry block BB to a COND_EXPR
2141    statement, determine which of the two edges will be taken out of the
2142    block.  Return NULL if either edge may be taken.  */
2143
2144 static edge
2145 find_taken_edge_cond_expr (basic_block bb, tree val)
2146 {
2147   edge true_edge, false_edge;
2148
2149   extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
2150
2151   gcc_assert (TREE_CODE (val) == INTEGER_CST);
2152   return (integer_zerop (val) ? false_edge : true_edge);
2153 }
2154
2155 /* Given an INTEGER_CST VAL and the entry block BB to a SWITCH_EXPR
2156    statement, determine which edge will be taken out of the block.  Return
2157    NULL if any edge may be taken.  */
2158
2159 static edge
2160 find_taken_edge_switch_expr (basic_block bb, tree val)
2161 {
2162   tree switch_expr, taken_case;
2163   basic_block dest_bb;
2164   edge e;
2165
2166   switch_expr = last_stmt (bb);
2167   taken_case = find_case_label_for_value (switch_expr, val);
2168   dest_bb = label_to_block (CASE_LABEL (taken_case));
2169
2170   e = find_edge (bb, dest_bb);
2171   gcc_assert (e);
2172   return e;
2173 }
2174
2175
2176 /* Return the CASE_LABEL_EXPR that SWITCH_EXPR will take for VAL.
2177    We can make optimal use here of the fact that the case labels are
2178    sorted: We can do a binary search for a case matching VAL.  */
2179
2180 static tree
2181 find_case_label_for_value (tree switch_expr, tree val)
2182 {
2183   tree vec = SWITCH_LABELS (switch_expr);
2184   size_t low, high, n = TREE_VEC_LENGTH (vec);
2185   tree default_case = TREE_VEC_ELT (vec, n - 1);
2186
2187   for (low = -1, high = n - 1; high - low > 1; )
2188     {
2189       size_t i = (high + low) / 2;
2190       tree t = TREE_VEC_ELT (vec, i);
2191       int cmp;
2192
2193       /* Cache the result of comparing CASE_LOW and val.  */
2194       cmp = tree_int_cst_compare (CASE_LOW (t), val);
2195
2196       if (cmp > 0)
2197         high = i;
2198       else
2199         low = i;
2200
2201       if (CASE_HIGH (t) == NULL)
2202         {
2203           /* A singe-valued case label.  */
2204           if (cmp == 0)
2205             return t;
2206         }
2207       else
2208         {
2209           /* A case range.  We can only handle integer ranges.  */
2210           if (cmp <= 0 && tree_int_cst_compare (CASE_HIGH (t), val) >= 0)
2211             return t;
2212         }
2213     }
2214
2215   return default_case;
2216 }
2217
2218
2219
2220
2221 /*---------------------------------------------------------------------------
2222                               Debugging functions
2223 ---------------------------------------------------------------------------*/
2224
2225 /* Dump tree-specific information of block BB to file OUTF.  */
2226
2227 void
2228 tree_dump_bb (basic_block bb, FILE *outf, int indent)
2229 {
2230   dump_generic_bb (outf, bb, indent, TDF_VOPS|TDF_MEMSYMS);
2231 }
2232
2233
2234 /* Dump a basic block on stderr.  */
2235
2236 void
2237 debug_tree_bb (basic_block bb)
2238 {
2239   dump_bb (bb, stderr, 0);
2240 }
2241
2242
2243 /* Dump basic block with index N on stderr.  */
2244
2245 basic_block
2246 debug_tree_bb_n (int n)
2247 {
2248   debug_tree_bb (BASIC_BLOCK (n));
2249   return BASIC_BLOCK (n);
2250 }
2251
2252
2253 /* Dump the CFG on stderr.
2254
2255    FLAGS are the same used by the tree dumping functions
2256    (see TDF_* in tree-pass.h).  */
2257
2258 void
2259 debug_tree_cfg (int flags)
2260 {
2261   dump_tree_cfg (stderr, flags);
2262 }
2263
2264
2265 /* Dump the program showing basic block boundaries on the given FILE.
2266
2267    FLAGS are the same used by the tree dumping functions (see TDF_* in
2268    tree.h).  */
2269
2270 void
2271 dump_tree_cfg (FILE *file, int flags)
2272 {
2273   if (flags & TDF_DETAILS)
2274     {
2275       const char *funcname
2276         = lang_hooks.decl_printable_name (current_function_decl, 2);
2277
2278       fputc ('\n', file);
2279       fprintf (file, ";; Function %s\n\n", funcname);
2280       fprintf (file, ";; \n%d basic blocks, %d edges, last basic block %d.\n\n",
2281                n_basic_blocks, n_edges, last_basic_block);
2282
2283       brief_dump_cfg (file);
2284       fprintf (file, "\n");
2285     }
2286
2287   if (flags & TDF_STATS)
2288     dump_cfg_stats (file);
2289
2290   dump_function_to_file (current_function_decl, file, flags | TDF_BLOCKS);
2291 }
2292
2293
2294 /* Dump CFG statistics on FILE.  */
2295
2296 void
2297 dump_cfg_stats (FILE *file)
2298 {
2299   static long max_num_merged_labels = 0;
2300   unsigned long size, total = 0;
2301   long num_edges;
2302   basic_block bb;
2303   const char * const fmt_str   = "%-30s%-13s%12s\n";
2304   const char * const fmt_str_1 = "%-30s%13d%11lu%c\n";
2305   const char * const fmt_str_2 = "%-30s%13ld%11lu%c\n";
2306   const char * const fmt_str_3 = "%-43s%11lu%c\n";
2307   const char *funcname
2308     = lang_hooks.decl_printable_name (current_function_decl, 2);
2309
2310
2311   fprintf (file, "\nCFG Statistics for %s\n\n", funcname);
2312
2313   fprintf (file, "---------------------------------------------------------\n");
2314   fprintf (file, fmt_str, "", "  Number of  ", "Memory");
2315   fprintf (file, fmt_str, "", "  instances  ", "used ");
2316   fprintf (file, "---------------------------------------------------------\n");
2317
2318   size = n_basic_blocks * sizeof (struct basic_block_def);
2319   total += size;
2320   fprintf (file, fmt_str_1, "Basic blocks", n_basic_blocks,
2321            SCALE (size), LABEL (size));
2322
2323   num_edges = 0;
2324   FOR_EACH_BB (bb)
2325     num_edges += EDGE_COUNT (bb->succs);
2326   size = num_edges * sizeof (struct edge_def);
2327   total += size;
2328   fprintf (file, fmt_str_2, "Edges", num_edges, SCALE (size), LABEL (size));
2329
2330   fprintf (file, "---------------------------------------------------------\n");
2331   fprintf (file, fmt_str_3, "Total memory used by CFG data", SCALE (total),
2332            LABEL (total));
2333   fprintf (file, "---------------------------------------------------------\n");
2334   fprintf (file, "\n");
2335
2336   if (cfg_stats.num_merged_labels > max_num_merged_labels)
2337     max_num_merged_labels = cfg_stats.num_merged_labels;
2338
2339   fprintf (file, "Coalesced label blocks: %ld (Max so far: %ld)\n",
2340            cfg_stats.num_merged_labels, max_num_merged_labels);
2341
2342   fprintf (file, "\n");
2343 }
2344
2345
2346 /* Dump CFG statistics on stderr.  Keep extern so that it's always
2347    linked in the final executable.  */
2348
2349 void
2350 debug_cfg_stats (void)
2351 {
2352   dump_cfg_stats (stderr);
2353 }
2354
2355
2356 /* Dump the flowgraph to a .vcg FILE.  */
2357
2358 static void
2359 tree_cfg2vcg (FILE *file)
2360 {
2361   edge e;
2362   edge_iterator ei;
2363   basic_block bb;
2364   const char *funcname
2365     = lang_hooks.decl_printable_name (current_function_decl, 2);
2366
2367   /* Write the file header.  */
2368   fprintf (file, "graph: { title: \"%s\"\n", funcname);
2369   fprintf (file, "node: { title: \"ENTRY\" label: \"ENTRY\" }\n");
2370   fprintf (file, "node: { title: \"EXIT\" label: \"EXIT\" }\n");
2371
2372   /* Write blocks and edges.  */
2373   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
2374     {
2375       fprintf (file, "edge: { sourcename: \"ENTRY\" targetname: \"%d\"",
2376                e->dest->index);
2377
2378       if (e->flags & EDGE_FAKE)
2379         fprintf (file, " linestyle: dotted priority: 10");
2380       else
2381         fprintf (file, " linestyle: solid priority: 100");
2382
2383       fprintf (file, " }\n");
2384     }
2385   fputc ('\n', file);
2386
2387   FOR_EACH_BB (bb)
2388     {
2389       enum tree_code head_code, end_code;
2390       const char *head_name, *end_name;
2391       int head_line = 0;
2392       int end_line = 0;
2393       tree first = first_stmt (bb);
2394       tree last = last_stmt (bb);
2395
2396       if (first)
2397         {
2398           head_code = TREE_CODE (first);
2399           head_name = tree_code_name[head_code];
2400           head_line = get_lineno (first);
2401         }
2402       else
2403         head_name = "no-statement";
2404
2405       if (last)
2406         {
2407           end_code = TREE_CODE (last);
2408           end_name = tree_code_name[end_code];
2409           end_line = get_lineno (last);
2410         }
2411       else
2412         end_name = "no-statement";
2413
2414       fprintf (file, "node: { title: \"%d\" label: \"#%d\\n%s (%d)\\n%s (%d)\"}\n",
2415                bb->index, bb->index, head_name, head_line, end_name,
2416                end_line);
2417
2418       FOR_EACH_EDGE (e, ei, bb->succs)
2419         {
2420           if (e->dest == EXIT_BLOCK_PTR)
2421             fprintf (file, "edge: { sourcename: \"%d\" targetname: \"EXIT\"", bb->index);
2422           else
2423             fprintf (file, "edge: { sourcename: \"%d\" targetname: \"%d\"", bb->index, e->dest->index);
2424
2425           if (e->flags & EDGE_FAKE)
2426             fprintf (file, " priority: 10 linestyle: dotted");
2427           else
2428             fprintf (file, " priority: 100 linestyle: solid");
2429
2430           fprintf (file, " }\n");
2431         }
2432
2433       if (bb->next_bb != EXIT_BLOCK_PTR)
2434         fputc ('\n', file);
2435     }
2436
2437   fputs ("}\n\n", file);
2438 }
2439
2440
2441
2442 /*---------------------------------------------------------------------------
2443                              Miscellaneous helpers
2444 ---------------------------------------------------------------------------*/
2445
2446 /* Return true if T represents a stmt that always transfers control.  */
2447
2448 bool
2449 is_ctrl_stmt (const_tree t)
2450 {
2451   return (TREE_CODE (t) == COND_EXPR
2452           || TREE_CODE (t) == SWITCH_EXPR
2453           || TREE_CODE (t) == GOTO_EXPR
2454           || TREE_CODE (t) == RETURN_EXPR
2455           || TREE_CODE (t) == RESX_EXPR);
2456 }
2457
2458
2459 /* Return true if T is a statement that may alter the flow of control
2460    (e.g., a call to a non-returning function).  */
2461
2462 bool
2463 is_ctrl_altering_stmt (const_tree t)
2464 {
2465   const_tree call;
2466
2467   gcc_assert (t);
2468   call = get_call_expr_in (CONST_CAST_TREE (t));
2469   if (call)
2470     {
2471       /* A non-pure/const CALL_EXPR alters flow control if the current
2472          function has nonlocal labels.  */
2473       if (TREE_SIDE_EFFECTS (call) && current_function_has_nonlocal_label)
2474         return true;
2475
2476       /* A CALL_EXPR also alters control flow if it does not return.  */
2477       if (call_expr_flags (call) & ECF_NORETURN)
2478         return true;
2479     }
2480
2481   /* OpenMP directives alter control flow.  */
2482   if (OMP_DIRECTIVE_P (t))
2483     return true;
2484
2485   /* If a statement can throw, it alters control flow.  */
2486   return tree_can_throw_internal (t);
2487 }
2488
2489
2490 /* Return true if T is a computed goto.  */
2491
2492 bool
2493 computed_goto_p (const_tree t)
2494 {
2495   return (TREE_CODE (t) == GOTO_EXPR
2496           && TREE_CODE (GOTO_DESTINATION (t)) != LABEL_DECL);
2497 }
2498
2499
2500 /* Return true if T is a simple local goto.  */
2501
2502 bool
2503 simple_goto_p (const_tree t)
2504 {
2505   return (TREE_CODE (t) == GOTO_EXPR
2506           && TREE_CODE (GOTO_DESTINATION (t)) == LABEL_DECL);
2507 }
2508
2509
2510 /* Return true if T can make an abnormal transfer of control flow.
2511    Transfers of control flow associated with EH are excluded.  */
2512
2513 bool
2514 tree_can_make_abnormal_goto (const_tree t)
2515 {
2516   if (computed_goto_p (t))
2517     return true;
2518   if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
2519     t = GIMPLE_STMT_OPERAND (t, 1);
2520   if (TREE_CODE (t) == WITH_SIZE_EXPR)
2521     t = TREE_OPERAND (t, 0);
2522   if (TREE_CODE (t) == CALL_EXPR)
2523     return TREE_SIDE_EFFECTS (t) && current_function_has_nonlocal_label;
2524   return false;
2525 }
2526
2527
2528 /* Return true if T should start a new basic block.  PREV_T is the
2529    statement preceding T.  It is used when T is a label or a case label.
2530    Labels should only start a new basic block if their previous statement
2531    wasn't a label.  Otherwise, sequence of labels would generate
2532    unnecessary basic blocks that only contain a single label.  */
2533
2534 static inline bool
2535 stmt_starts_bb_p (const_tree t, const_tree prev_t)
2536 {
2537   if (t == NULL_TREE)
2538     return false;
2539
2540   /* LABEL_EXPRs start a new basic block only if the preceding
2541      statement wasn't a label of the same type.  This prevents the
2542      creation of consecutive blocks that have nothing but a single
2543      label.  */
2544   if (TREE_CODE (t) == LABEL_EXPR)
2545     {
2546       /* Nonlocal and computed GOTO targets always start a new block.  */
2547       if (DECL_NONLOCAL (LABEL_EXPR_LABEL (t))
2548           || FORCED_LABEL (LABEL_EXPR_LABEL (t)))
2549         return true;
2550
2551       if (prev_t && TREE_CODE (prev_t) == LABEL_EXPR)
2552         {
2553           if (DECL_NONLOCAL (LABEL_EXPR_LABEL (prev_t)))
2554             return true;
2555
2556           cfg_stats.num_merged_labels++;
2557           return false;
2558         }
2559       else
2560         return true;
2561     }
2562
2563   return false;
2564 }
2565
2566
2567 /* Return true if T should end a basic block.  */
2568
2569 bool
2570 stmt_ends_bb_p (const_tree t)
2571 {
2572   return is_ctrl_stmt (t) || is_ctrl_altering_stmt (t);
2573 }
2574
2575 /* Remove block annotations and other datastructures.  */
2576
2577 void
2578 delete_tree_cfg_annotations (void)
2579 {
2580   basic_block bb;
2581   block_stmt_iterator bsi;
2582
2583   /* Remove annotations from every tree in the function.  */
2584   FOR_EACH_BB (bb)
2585     for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
2586       {
2587         tree stmt = bsi_stmt (bsi);
2588         ggc_free (stmt->base.ann);
2589         stmt->base.ann = NULL;
2590       }
2591   label_to_block_map = NULL;
2592 }
2593
2594
2595 /* Return the first statement in basic block BB.  */
2596
2597 tree
2598 first_stmt (basic_block bb)
2599 {
2600   block_stmt_iterator i = bsi_start (bb);
2601   return !bsi_end_p (i) ? bsi_stmt (i) : NULL_TREE;
2602 }
2603
2604 /* Return the last statement in basic block BB.  */
2605
2606 tree
2607 last_stmt (basic_block bb)
2608 {
2609   block_stmt_iterator b = bsi_last (bb);
2610   return !bsi_end_p (b) ? bsi_stmt (b) : NULL_TREE;
2611 }
2612
2613 /* Return the last statement of an otherwise empty block.  Return NULL
2614    if the block is totally empty, or if it contains more than one
2615    statement.  */
2616
2617 tree
2618 last_and_only_stmt (basic_block bb)
2619 {
2620   block_stmt_iterator i = bsi_last (bb);
2621   tree last, prev;
2622
2623   if (bsi_end_p (i))
2624     return NULL_TREE;
2625
2626   last = bsi_stmt (i);
2627   bsi_prev (&i);
2628   if (bsi_end_p (i))
2629     return last;
2630
2631   /* Empty statements should no longer appear in the instruction stream.
2632      Everything that might have appeared before should be deleted by
2633      remove_useless_stmts, and the optimizers should just bsi_remove
2634      instead of smashing with build_empty_stmt.
2635
2636      Thus the only thing that should appear here in a block containing
2637      one executable statement is a label.  */
2638   prev = bsi_stmt (i);
2639   if (TREE_CODE (prev) == LABEL_EXPR)
2640     return last;
2641   else
2642     return NULL_TREE;
2643 }
2644
2645
2646 /* Mark BB as the basic block holding statement T.  */
2647
2648 void
2649 set_bb_for_stmt (tree t, basic_block bb)
2650 {
2651   if (TREE_CODE (t) == PHI_NODE)
2652     PHI_BB (t) = bb;
2653   else if (TREE_CODE (t) == STATEMENT_LIST)
2654     {
2655       tree_stmt_iterator i;
2656       for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
2657         set_bb_for_stmt (tsi_stmt (i), bb);
2658     }
2659   else
2660     {
2661       stmt_ann_t ann = get_stmt_ann (t);
2662       ann->bb = bb;
2663
2664       /* If the statement is a label, add the label to block-to-labels map
2665         so that we can speed up edge creation for GOTO_EXPRs.  */
2666       if (TREE_CODE (t) == LABEL_EXPR)
2667         {
2668           int uid;
2669
2670           t = LABEL_EXPR_LABEL (t);
2671           uid = LABEL_DECL_UID (t);
2672           if (uid == -1)
2673             {
2674               unsigned old_len = VEC_length (basic_block, label_to_block_map);
2675               LABEL_DECL_UID (t) = uid = cfun->last_label_uid++;
2676               if (old_len <= (unsigned) uid)
2677                 {
2678                   unsigned new_len = 3 * uid / 2;
2679
2680                   VEC_safe_grow_cleared (basic_block, gc, label_to_block_map,
2681                                          new_len);
2682                 }
2683             }
2684           else
2685             /* We're moving an existing label.  Make sure that we've
2686                 removed it from the old block.  */
2687             gcc_assert (!bb
2688                         || !VEC_index (basic_block, label_to_block_map, uid));
2689           VEC_replace (basic_block, label_to_block_map, uid, bb);
2690         }
2691     }
2692 }
2693
2694 /* Faster version of set_bb_for_stmt that assume that statement is being moved
2695    from one basic block to another.  
2696    For BB splitting we can run into quadratic case, so performance is quite
2697    important and knowing that the tables are big enough, change_bb_for_stmt
2698    can inline as leaf function.  */
2699 static inline void
2700 change_bb_for_stmt (tree t, basic_block bb)
2701 {
2702   get_stmt_ann (t)->bb = bb;
2703   if (TREE_CODE (t) == LABEL_EXPR)
2704     VEC_replace (basic_block, label_to_block_map,
2705                  LABEL_DECL_UID (LABEL_EXPR_LABEL (t)), bb);
2706 }
2707
2708 /* Finds iterator for STMT.  */
2709
2710 extern block_stmt_iterator
2711 bsi_for_stmt (tree stmt)
2712 {
2713   block_stmt_iterator bsi;
2714
2715   for (bsi = bsi_start (bb_for_stmt (stmt)); !bsi_end_p (bsi); bsi_next (&bsi))
2716     if (bsi_stmt (bsi) == stmt)
2717       return bsi;
2718
2719   gcc_unreachable ();
2720 }
2721
2722 /* Mark statement T as modified, and update it.  */
2723 static inline void
2724 update_modified_stmts (tree t)
2725 {
2726   if (!ssa_operands_active ())
2727     return;
2728   if (TREE_CODE (t) == STATEMENT_LIST)
2729     {
2730       tree_stmt_iterator i;
2731       tree stmt;
2732       for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
2733         {
2734           stmt = tsi_stmt (i);
2735           update_stmt_if_modified (stmt);
2736         }
2737     }
2738   else
2739     update_stmt_if_modified (t);
2740 }
2741
2742 /* Insert statement (or statement list) T before the statement
2743    pointed-to by iterator I.  M specifies how to update iterator I
2744    after insertion (see enum bsi_iterator_update).  */
2745
2746 void
2747 bsi_insert_before (block_stmt_iterator *i, tree t, enum bsi_iterator_update m)
2748 {
2749   set_bb_for_stmt (t, i->bb);
2750   update_modified_stmts (t);
2751   tsi_link_before (&i->tsi, t, m);
2752 }
2753
2754
2755 /* Insert statement (or statement list) T after the statement
2756    pointed-to by iterator I.  M specifies how to update iterator I
2757    after insertion (see enum bsi_iterator_update).  */
2758
2759 void
2760 bsi_insert_after (block_stmt_iterator *i, tree t, enum bsi_iterator_update m)
2761 {
2762   set_bb_for_stmt (t, i->bb);
2763   update_modified_stmts (t);
2764   tsi_link_after (&i->tsi, t, m);
2765 }
2766
2767
2768 /* Remove the statement pointed to by iterator I.  The iterator is updated
2769    to the next statement.
2770
2771    When REMOVE_EH_INFO is true we remove the statement pointed to by
2772    iterator I from the EH tables.  Otherwise we do not modify the EH
2773    tables.
2774
2775    Generally, REMOVE_EH_INFO should be true when the statement is going to
2776    be removed from the IL and not reinserted elsewhere.  */
2777
2778 void
2779 bsi_remove (block_stmt_iterator *i, bool remove_eh_info)
2780 {
2781   tree t = bsi_stmt (*i);
2782   set_bb_for_stmt (t, NULL);
2783   delink_stmt_imm_use (t);
2784   tsi_delink (&i->tsi);
2785   mark_stmt_modified (t);
2786   if (remove_eh_info)
2787     {
2788       remove_stmt_from_eh_region (t);
2789       gimple_remove_stmt_histograms (cfun, t);
2790     }
2791 }
2792
2793
2794 /* Move the statement at FROM so it comes right after the statement at TO.  */
2795
2796 void
2797 bsi_move_after (block_stmt_iterator *from, block_stmt_iterator *to)
2798 {
2799   tree stmt = bsi_stmt (*from);
2800   bsi_remove (from, false);
2801   /* We must have BSI_NEW_STMT here, as bsi_move_after is sometimes used to
2802      move statements to an empty block.  */
2803   bsi_insert_after (to, stmt, BSI_NEW_STMT);
2804 }
2805
2806
2807 /* Move the statement at FROM so it comes right before the statement at TO.  */
2808
2809 void
2810 bsi_move_before (block_stmt_iterator *from, block_stmt_iterator *to)
2811 {
2812   tree stmt = bsi_stmt (*from);
2813   bsi_remove (from, false);
2814   /* For consistency with bsi_move_after, it might be better to have
2815      BSI_NEW_STMT here; however, that breaks several places that expect
2816      that TO does not change.  */
2817   bsi_insert_before (to, stmt, BSI_SAME_STMT);
2818 }
2819
2820
2821 /* Move the statement at FROM to the end of basic block BB.  */
2822
2823 void
2824 bsi_move_to_bb_end (block_stmt_iterator *from, basic_block bb)
2825 {
2826   block_stmt_iterator last = bsi_last (bb);
2827
2828   /* Have to check bsi_end_p because it could be an empty block.  */
2829   if (!bsi_end_p (last) && is_ctrl_stmt (bsi_stmt (last)))
2830     bsi_move_before (from, &last);
2831   else
2832     bsi_move_after (from, &last);
2833 }
2834
2835
2836 /* Replace the contents of the statement pointed to by iterator BSI
2837    with STMT.  If UPDATE_EH_INFO is true, the exception handling
2838    information of the original statement is moved to the new statement.  */
2839
2840 void
2841 bsi_replace (const block_stmt_iterator *bsi, tree stmt, bool update_eh_info)
2842 {
2843   int eh_region;
2844   tree orig_stmt = bsi_stmt (*bsi);
2845
2846   if (stmt == orig_stmt)
2847     return;
2848   SET_EXPR_LOCUS (stmt, EXPR_LOCUS (orig_stmt));
2849   set_bb_for_stmt (stmt, bsi->bb);
2850
2851   /* Preserve EH region information from the original statement, if
2852      requested by the caller.  */
2853   if (update_eh_info)
2854     {
2855       eh_region = lookup_stmt_eh_region (orig_stmt);
2856       if (eh_region >= 0)
2857         {
2858           remove_stmt_from_eh_region (orig_stmt);
2859           add_stmt_to_eh_region (stmt, eh_region);
2860         }
2861     }
2862
2863   gimple_duplicate_stmt_histograms (cfun, stmt, cfun, orig_stmt);
2864   gimple_remove_stmt_histograms (cfun, orig_stmt);
2865   delink_stmt_imm_use (orig_stmt);
2866   *bsi_stmt_ptr (*bsi) = stmt;
2867   mark_stmt_modified (stmt);
2868   update_modified_stmts (stmt);
2869 }
2870
2871
2872 /* Insert the statement pointed-to by BSI into edge E.  Every attempt
2873    is made to place the statement in an existing basic block, but
2874    sometimes that isn't possible.  When it isn't possible, the edge is
2875    split and the statement is added to the new block.
2876
2877    In all cases, the returned *BSI points to the correct location.  The
2878    return value is true if insertion should be done after the location,
2879    or false if it should be done before the location.  If new basic block
2880    has to be created, it is stored in *NEW_BB.  */
2881
2882 static bool
2883 tree_find_edge_insert_loc (edge e, block_stmt_iterator *bsi,
2884                            basic_block *new_bb)
2885 {
2886   basic_block dest, src;
2887   tree tmp;
2888
2889   dest = e->dest;
2890  restart:
2891
2892   /* If the destination has one predecessor which has no PHI nodes,
2893      insert there.  Except for the exit block.
2894
2895      The requirement for no PHI nodes could be relaxed.  Basically we
2896      would have to examine the PHIs to prove that none of them used
2897      the value set by the statement we want to insert on E.  That
2898      hardly seems worth the effort.  */
2899   if (single_pred_p (dest)
2900       && ! phi_nodes (dest)
2901       && dest != EXIT_BLOCK_PTR)
2902     {
2903       *bsi = bsi_start (dest);
2904       if (bsi_end_p (*bsi))
2905         return true;
2906
2907       /* Make sure we insert after any leading labels.  */
2908       tmp = bsi_stmt (*bsi);
2909       while (TREE_CODE (tmp) == LABEL_EXPR)
2910         {
2911           bsi_next (bsi);
2912           if (bsi_end_p (*bsi))
2913             break;
2914           tmp = bsi_stmt (*bsi);
2915         }
2916
2917       if (bsi_end_p (*bsi))
2918         {
2919           *bsi = bsi_last (dest);
2920           return true;
2921         }
2922       else
2923         return false;
2924     }
2925
2926   /* If the source has one successor, the edge is not abnormal and
2927      the last statement does not end a basic block, insert there.
2928      Except for the entry block.  */
2929   src = e->src;
2930   if ((e->flags & EDGE_ABNORMAL) == 0
2931       && single_succ_p (src)
2932       && src != ENTRY_BLOCK_PTR)
2933     {
2934       *bsi = bsi_last (src);
2935       if (bsi_end_p (*bsi))
2936         return true;
2937
2938       tmp = bsi_stmt (*bsi);
2939       if (!stmt_ends_bb_p (tmp))
2940         return true;
2941
2942       /* Insert code just before returning the value.  We may need to decompose
2943          the return in the case it contains non-trivial operand.  */
2944       if (TREE_CODE (tmp) == RETURN_EXPR)
2945         {
2946           tree op = TREE_OPERAND (tmp, 0);
2947           if (op && !is_gimple_val (op))
2948             {
2949               gcc_assert (TREE_CODE (op) == GIMPLE_MODIFY_STMT);
2950               bsi_insert_before (bsi, op, BSI_NEW_STMT);
2951               TREE_OPERAND (tmp, 0) = GIMPLE_STMT_OPERAND (op, 0);
2952             }
2953           bsi_prev (bsi);
2954           return true;
2955         }
2956     }
2957
2958   /* Otherwise, create a new basic block, and split this edge.  */
2959   dest = split_edge (e);
2960   if (new_bb)
2961     *new_bb = dest;
2962   e = single_pred_edge (dest);
2963   goto restart;
2964 }
2965
2966
2967 /* This routine will commit all pending edge insertions, creating any new
2968    basic blocks which are necessary.  */
2969
2970 void
2971 bsi_commit_edge_inserts (void)
2972 {
2973   basic_block bb;
2974   edge e;
2975   edge_iterator ei;
2976
2977   bsi_commit_one_edge_insert (single_succ_edge (ENTRY_BLOCK_PTR), NULL);
2978
2979   FOR_EACH_BB (bb)
2980     FOR_EACH_EDGE (e, ei, bb->succs)
2981       bsi_commit_one_edge_insert (e, NULL);
2982 }
2983
2984
2985 /* Commit insertions pending at edge E. If a new block is created, set NEW_BB
2986    to this block, otherwise set it to NULL.  */
2987
2988 void
2989 bsi_commit_one_edge_insert (edge e, basic_block *new_bb)
2990 {
2991   if (new_bb)
2992     *new_bb = NULL;
2993   if (PENDING_STMT (e))
2994     {
2995       block_stmt_iterator bsi;
2996       tree stmt = PENDING_STMT (e);
2997
2998       PENDING_STMT (e) = NULL_TREE;
2999
3000       if (tree_find_edge_insert_loc (e, &bsi, new_bb))
3001         bsi_insert_after (&bsi, stmt, BSI_NEW_STMT);
3002       else
3003         bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
3004     }
3005 }
3006
3007
3008 /* Add STMT to the pending list of edge E.  No actual insertion is
3009    made until a call to bsi_commit_edge_inserts () is made.  */
3010
3011 void
3012 bsi_insert_on_edge (edge e, tree stmt)
3013 {
3014   append_to_statement_list (stmt, &PENDING_STMT (e));
3015 }
3016
3017 /* Similar to bsi_insert_on_edge+bsi_commit_edge_inserts.  If a new
3018    block has to be created, it is returned.  */
3019
3020 basic_block
3021 bsi_insert_on_edge_immediate (edge e, tree stmt)
3022 {
3023   block_stmt_iterator bsi;
3024   basic_block new_bb = NULL;
3025
3026   gcc_assert (!PENDING_STMT (e));
3027
3028   if (tree_find_edge_insert_loc (e, &bsi, &new_bb))
3029     bsi_insert_after (&bsi, stmt, BSI_NEW_STMT);
3030   else
3031     bsi_insert_before (&bsi, stmt, BSI_NEW_STMT);
3032
3033   return new_bb;
3034 }
3035
3036 /*---------------------------------------------------------------------------
3037              Tree specific functions for CFG manipulation
3038 ---------------------------------------------------------------------------*/
3039
3040 /* Reinstall those PHI arguments queued in OLD_EDGE to NEW_EDGE.  */
3041
3042 static void
3043 reinstall_phi_args (edge new_edge, edge old_edge)
3044 {
3045   tree var, phi;
3046
3047   if (!PENDING_STMT (old_edge))
3048     return;
3049
3050   for (var = PENDING_STMT (old_edge), phi = phi_nodes (new_edge->dest);
3051        var && phi;
3052        var = TREE_CHAIN (var), phi = PHI_CHAIN (phi))
3053     {
3054       tree result = TREE_PURPOSE (var);
3055       tree arg = TREE_VALUE (var);
3056
3057       gcc_assert (result == PHI_RESULT (phi));
3058
3059       add_phi_arg (phi, arg, new_edge);
3060     }
3061
3062   PENDING_STMT (old_edge) = NULL;
3063 }
3064
3065 /* Returns the basic block after which the new basic block created
3066    by splitting edge EDGE_IN should be placed.  Tries to keep the new block
3067    near its "logical" location.  This is of most help to humans looking
3068    at debugging dumps.  */
3069
3070 static basic_block
3071 split_edge_bb_loc (edge edge_in)
3072 {
3073   basic_block dest = edge_in->dest;
3074
3075   if (dest->prev_bb && find_edge (dest->prev_bb, dest))
3076     return edge_in->src;
3077   else
3078     return dest->prev_bb;
3079 }
3080
3081 /* Split a (typically critical) edge EDGE_IN.  Return the new block.
3082    Abort on abnormal edges.  */
3083
3084 static basic_block
3085 tree_split_edge (edge edge_in)
3086 {
3087   basic_block new_bb, after_bb, dest;
3088   edge new_edge, e;
3089
3090   /* Abnormal edges cannot be split.  */
3091   gcc_assert (!(edge_in->flags & EDGE_ABNORMAL));
3092
3093   dest = edge_in->dest;
3094
3095   after_bb = split_edge_bb_loc (edge_in);
3096
3097   new_bb = create_empty_bb (after_bb);
3098   new_bb->frequency = EDGE_FREQUENCY (edge_in);
3099   new_bb->count = edge_in->count;
3100   new_edge = make_edge (new_bb, dest, EDGE_FALLTHRU);
3101   new_edge->probability = REG_BR_PROB_BASE;
3102   new_edge->count = edge_in->count;
3103
3104   e = redirect_edge_and_branch (edge_in, new_bb);
3105   gcc_assert (e == edge_in);
3106   reinstall_phi_args (new_edge, e);
3107
3108   return new_bb;
3109 }
3110
3111 /* Callback for walk_tree, check that all elements with address taken are
3112    properly noticed as such.  The DATA is an int* that is 1 if TP was seen
3113    inside a PHI node.  */
3114
3115 static tree
3116 verify_expr (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
3117 {
3118   tree t = *tp, x;
3119   bool in_phi = (data != NULL);
3120
3121   if (TYPE_P (t))
3122     *walk_subtrees = 0;
3123
3124   /* Check operand N for being valid GIMPLE and give error MSG if not.  */
3125 #define CHECK_OP(N, MSG) \
3126   do { if (!is_gimple_val (TREE_OPERAND (t, N)))                \
3127        { error (MSG); return TREE_OPERAND (t, N); }} while (0)
3128
3129   switch (TREE_CODE (t))
3130     {
3131     case SSA_NAME:
3132       if (SSA_NAME_IN_FREE_LIST (t))
3133         {
3134           error ("SSA name in freelist but still referenced");
3135           return *tp;
3136         }
3137       break;
3138
3139     case ASSERT_EXPR:
3140       x = fold (ASSERT_EXPR_COND (t));
3141       if (x == boolean_false_node)
3142         {
3143           error ("ASSERT_EXPR with an always-false condition");
3144           return *tp;
3145         }
3146       break;
3147
3148     case MODIFY_EXPR:
3149       gcc_unreachable ();
3150
3151     case GIMPLE_MODIFY_STMT:
3152       x = GIMPLE_STMT_OPERAND (t, 0);
3153       if (TREE_CODE (x) == BIT_FIELD_REF
3154           && is_gimple_reg (TREE_OPERAND (x, 0)))
3155         {
3156           error ("GIMPLE register modified with BIT_FIELD_REF");
3157           return t;
3158         }
3159       break;
3160
3161     case ADDR_EXPR:
3162       {
3163         bool old_invariant;
3164         bool old_constant;
3165         bool old_side_effects;
3166         bool new_invariant;
3167         bool new_constant;
3168         bool new_side_effects;
3169
3170         /* ??? tree-ssa-alias.c may have overlooked dead PHI nodes, missing
3171            dead PHIs that take the address of something.  But if the PHI
3172            result is dead, the fact that it takes the address of anything
3173            is irrelevant.  Because we can not tell from here if a PHI result
3174            is dead, we just skip this check for PHIs altogether.  This means
3175            we may be missing "valid" checks, but what can you do?
3176            This was PR19217.  */
3177         if (in_phi)
3178           break;
3179
3180         old_invariant = TREE_INVARIANT (t);
3181         old_constant = TREE_CONSTANT (t);
3182         old_side_effects = TREE_SIDE_EFFECTS (t);
3183
3184         recompute_tree_invariant_for_addr_expr (t);
3185         new_invariant = TREE_INVARIANT (t);
3186         new_side_effects = TREE_SIDE_EFFECTS (t);
3187         new_constant = TREE_CONSTANT (t);
3188
3189         if (old_invariant != new_invariant)
3190           {
3191             error ("invariant not recomputed when ADDR_EXPR changed");
3192             return t;
3193           }
3194
3195         if (old_constant != new_constant)
3196           {
3197             error ("constant not recomputed when ADDR_EXPR changed");
3198             return t;
3199           }
3200         if (old_side_effects != new_side_effects)
3201           {
3202             error ("side effects not recomputed when ADDR_EXPR changed");
3203             return t;
3204           }
3205
3206         /* Skip any references (they will be checked when we recurse down the
3207            tree) and ensure that any variable used as a prefix is marked
3208            addressable.  */
3209         for (x = TREE_OPERAND (t, 0);
3210              handled_component_p (x);
3211              x = TREE_OPERAND (x, 0))
3212           ;
3213
3214         if (TREE_CODE (x) != VAR_DECL && TREE_CODE (x) != PARM_DECL)
3215           return NULL;
3216         if (!TREE_ADDRESSABLE (x))
3217           {
3218             error ("address taken, but ADDRESSABLE bit not set");
3219             return x;
3220           }
3221         break;
3222       }
3223
3224     case COND_EXPR:
3225       x = COND_EXPR_COND (t);
3226       if (!INTEGRAL_TYPE_P (TREE_TYPE (x)))
3227         {
3228           error ("non-integral used in condition");
3229           return x;
3230         }
3231       if (!is_gimple_condexpr (x))
3232         {
3233           error ("invalid conditional operand");
3234           return x;
3235         }
3236       break;
3237
3238     case NOP_EXPR:
3239     case CONVERT_EXPR:
3240     case FIX_TRUNC_EXPR:
3241     case FLOAT_EXPR:
3242     case NEGATE_EXPR:
3243     case ABS_EXPR:
3244     case BIT_NOT_EXPR:
3245     case NON_LVALUE_EXPR:
3246     case TRUTH_NOT_EXPR:
3247       CHECK_OP (0, "invalid operand to unary operator");
3248       break;
3249
3250     case REALPART_EXPR:
3251     case IMAGPART_EXPR:
3252     case COMPONENT_REF:
3253     case ARRAY_REF:
3254     case ARRAY_RANGE_REF:
3255     case BIT_FIELD_REF:
3256     case VIEW_CONVERT_EXPR:
3257       /* We have a nest of references.  Verify that each of the operands
3258          that determine where to reference is either a constant or a variable,
3259          verify that the base is valid, and then show we've already checked
3260          the subtrees.  */
3261       while (handled_component_p (t))
3262         {
3263           if (TREE_CODE (t) == COMPONENT_REF && TREE_OPERAND (t, 2))
3264             CHECK_OP (2, "invalid COMPONENT_REF offset operator");
3265           else if (TREE_CODE (t) == ARRAY_REF
3266                    || TREE_CODE (t) == ARRAY_RANGE_REF)
3267             {
3268               CHECK_OP (1, "invalid array index");
3269               if (TREE_OPERAND (t, 2))
3270                 CHECK_OP (2, "invalid array lower bound");
3271               if (TREE_OPERAND (t, 3))
3272                 CHECK_OP (3, "invalid array stride");
3273             }
3274           else if (TREE_CODE (t) == BIT_FIELD_REF)
3275             {
3276               CHECK_OP (1, "invalid operand to BIT_FIELD_REF");
3277               CHECK_OP (2, "invalid operand to BIT_FIELD_REF");
3278             }
3279
3280           t = TREE_OPERAND (t, 0);
3281         }
3282
3283       if (!CONSTANT_CLASS_P (t) && !is_gimple_lvalue (t))
3284         {
3285           error ("invalid reference prefix");
3286           return t;
3287         }
3288       *walk_subtrees = 0;
3289       break;
3290     case PLUS_EXPR:
3291     case MINUS_EXPR:
3292       /* PLUS_EXPR and MINUS_EXPR don't work on pointers, they should be done using
3293          POINTER_PLUS_EXPR. */
3294       if (POINTER_TYPE_P (TREE_TYPE (t)))
3295         {
3296           error ("invalid operand to plus/minus, type is a pointer");
3297           return t;
3298         }
3299       CHECK_OP (0, "invalid operand to binary operator");
3300       CHECK_OP (1, "invalid operand to binary operator");
3301       break;
3302
3303     case POINTER_PLUS_EXPR:
3304       /* Check to make sure the first operand is a pointer or reference type. */
3305       if (!POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (t, 0))))
3306         {
3307           error ("invalid operand to pointer plus, first operand is not a pointer");
3308           return t;
3309         }
3310       /* Check to make sure the second operand is an integer with type of
3311          sizetype.  */
3312       if (!useless_type_conversion_p (sizetype,
3313                                      TREE_TYPE (TREE_OPERAND (t, 1))))
3314         {
3315           error ("invalid operand to pointer plus, second operand is not an "
3316                  "integer with type of sizetype.");
3317           return t;
3318         }
3319       /* FALLTHROUGH */
3320     case LT_EXPR:
3321     case LE_EXPR:
3322     case GT_EXPR:
3323     case GE_EXPR:
3324     case EQ_EXPR:
3325     case NE_EXPR:
3326     case UNORDERED_EXPR:
3327     case ORDERED_EXPR:
3328     case UNLT_EXPR:
3329     case UNLE_EXPR:
3330     case UNGT_EXPR:
3331     case UNGE_EXPR:
3332     case UNEQ_EXPR:
3333     case LTGT_EXPR:
3334     case MULT_EXPR:
3335     case TRUNC_DIV_EXPR:
3336     case CEIL_DIV_EXPR:
3337     case FLOOR_DIV_EXPR:
3338     case ROUND_DIV_EXPR:
3339     case TRUNC_MOD_EXPR:
3340     case CEIL_MOD_EXPR:
3341     case FLOOR_MOD_EXPR:
3342     case ROUND_MOD_EXPR:
3343     case RDIV_EXPR:
3344     case EXACT_DIV_EXPR:
3345     case MIN_EXPR:
3346     case MAX_EXPR:
3347     case LSHIFT_EXPR:
3348     case RSHIFT_EXPR:
3349     case LROTATE_EXPR:
3350     case RROTATE_EXPR:
3351     case BIT_IOR_EXPR:
3352     case BIT_XOR_EXPR:
3353     case BIT_AND_EXPR:
3354       CHECK_OP (0, "invalid operand to binary operator");
3355       CHECK_OP (1, "invalid operand to binary operator");
3356       break;
3357
3358     case CONSTRUCTOR:
3359       if (TREE_CONSTANT (t) && TREE_CODE (TREE_TYPE (t)) == VECTOR_TYPE)
3360         *walk_subtrees = 0;
3361       break;
3362
3363     default:
3364       break;
3365     }
3366   return NULL;
3367
3368 #undef CHECK_OP
3369 }
3370
3371 /* Verifies if EXPR is a valid GIMPLE unary expression.  Returns true
3372    if there is an error, otherwise false.  */
3373
3374 static bool
3375 verify_gimple_unary_expr (const_tree expr)
3376 {
3377   tree op = TREE_OPERAND (expr, 0);
3378   tree type = TREE_TYPE (expr);
3379
3380   if (!is_gimple_val (op))
3381     {
3382       error ("invalid operand in unary expression");
3383       return true;
3384     }
3385
3386   /* For general unary expressions we have the operations type
3387      as the effective type the operation is carried out on.  So all
3388      we need to require is that the operand is trivially convertible
3389      to that type.  */
3390   if (!useless_type_conversion_p (type, TREE_TYPE (op)))
3391     {
3392       error ("type mismatch in unary expression");
3393       debug_generic_expr (type);
3394       debug_generic_expr (TREE_TYPE (op));
3395       return true;
3396     }
3397
3398   return false;
3399 }
3400
3401 /* Verifies if EXPR is a valid GIMPLE binary expression.  Returns true
3402    if there is an error, otherwise false.  */
3403
3404 static bool
3405 verify_gimple_binary_expr (const_tree expr)
3406 {
3407   tree op0 = TREE_OPERAND (expr, 0);
3408   tree op1 = TREE_OPERAND (expr, 1);
3409   tree type = TREE_TYPE (expr);
3410
3411   if (!is_gimple_val (op0) || !is_gimple_val (op1))
3412     {
3413       error ("invalid operands in binary expression");
3414       return true;
3415     }
3416
3417   /* For general binary expressions we have the operations type
3418      as the effective type the operation is carried out on.  So all
3419      we need to require is that both operands are trivially convertible
3420      to that type.  */
3421   if (!useless_type_conversion_p (type, TREE_TYPE (op0))
3422       || !useless_type_conversion_p (type, TREE_TYPE (op1)))
3423     {
3424       error ("type mismatch in binary expression");
3425       debug_generic_stmt (type);
3426       debug_generic_stmt (TREE_TYPE (op0));
3427       debug_generic_stmt (TREE_TYPE (op1));
3428       return true;
3429     }
3430
3431   return false;
3432 }
3433
3434 /* Verify if EXPR is either a GIMPLE ID or a GIMPLE indirect reference.
3435    Returns true if there is an error, otherwise false.  */
3436
3437 static bool
3438 verify_gimple_min_lval (tree expr)
3439 {
3440   tree op;
3441
3442   if (is_gimple_id (expr))
3443     return false;
3444
3445   if (TREE_CODE (expr) != INDIRECT_REF
3446       && TREE_CODE (expr) != ALIGN_INDIRECT_REF
3447       && TREE_CODE (expr) != MISALIGNED_INDIRECT_REF)
3448     {
3449       error ("invalid expression for min lvalue");
3450       return true;
3451     }
3452
3453   op = TREE_OPERAND (expr, 0);
3454   if (!is_gimple_val (op))
3455     {
3456       error ("invalid operand in indirect reference");
3457       debug_generic_stmt (op);
3458       return true;
3459     }
3460   if (!useless_type_conversion_p (TREE_TYPE (expr),
3461                                   TREE_TYPE (TREE_TYPE (op))))
3462     {
3463       error ("type mismatch in indirect reference");
3464       debug_generic_stmt (TREE_TYPE (expr));
3465       debug_generic_stmt (TREE_TYPE (TREE_TYPE (op)));
3466       return true;
3467     }
3468
3469   return false;
3470 }
3471
3472 /* Verify if EXPR is a valid GIMPLE reference expression.  Returns true
3473    if there is an error, otherwise false.  */
3474
3475 static bool
3476 verify_gimple_reference (tree expr)
3477 {
3478   while (handled_component_p (expr))
3479     {
3480       tree op = TREE_OPERAND (expr, 0);
3481
3482       if (TREE_CODE (expr) == ARRAY_REF
3483           || TREE_CODE (expr) == ARRAY_RANGE_REF)
3484         {
3485           if (!is_gimple_val (TREE_OPERAND (expr, 1))
3486               || (TREE_OPERAND (expr, 2)
3487                   && !is_gimple_val (TREE_OPERAND (expr, 2)))
3488               || (TREE_OPERAND (expr, 3)
3489                   && !is_gimple_val (TREE_OPERAND (expr, 3))))
3490             {
3491               error ("invalid operands to array reference");
3492               debug_generic_stmt (expr);
3493               return true;
3494             }
3495         }
3496
3497       /* Verify if the reference array element types are compatible.  */
3498       if (TREE_CODE (expr) == ARRAY_REF
3499           && !useless_type_conversion_p (TREE_TYPE (expr),
3500                                          TREE_TYPE (TREE_TYPE (op))))
3501         {
3502           error ("type mismatch in array reference");
3503           debug_generic_stmt (TREE_TYPE (expr));
3504           debug_generic_stmt (TREE_TYPE (TREE_TYPE (op)));
3505           return true;
3506         }
3507       if (TREE_CODE (expr) == ARRAY_RANGE_REF
3508           && !useless_type_conversion_p (TREE_TYPE (TREE_TYPE (expr)),
3509                                          TREE_TYPE (TREE_TYPE (op))))
3510         {
3511           error ("type mismatch in array range reference");
3512           debug_generic_stmt (TREE_TYPE (TREE_TYPE (expr)));
3513           debug_generic_stmt (TREE_TYPE (TREE_TYPE (op)));
3514           return true;
3515         }
3516
3517       if ((TREE_CODE (expr) == REALPART_EXPR
3518            || TREE_CODE (expr) == IMAGPART_EXPR)
3519           && !useless_type_conversion_p (TREE_TYPE (expr),
3520                                          TREE_TYPE (TREE_TYPE (op))))
3521         {
3522           error ("type mismatch in real/imagpart reference");
3523           debug_generic_stmt (TREE_TYPE (expr));
3524           debug_generic_stmt (TREE_TYPE (TREE_TYPE (op)));
3525           return true;
3526         }
3527
3528       if (TREE_CODE (expr) == COMPONENT_REF
3529           && !useless_type_conversion_p (TREE_TYPE (expr),
3530                                          TREE_TYPE (TREE_OPERAND (expr, 1))))
3531         {
3532           error ("type mismatch in component reference");
3533           debug_generic_stmt (TREE_TYPE (expr));
3534           debug_generic_stmt (TREE_TYPE (TREE_OPERAND (expr, 1)));
3535           return true;
3536         }
3537
3538       /* For VIEW_CONVERT_EXPRs which are allowed here, too, there
3539          is nothing to verify.  Gross mismatches at most invoke
3540          undefined behavior.  */
3541
3542       expr = op;
3543     }
3544
3545   return verify_gimple_min_lval (expr);
3546 }
3547
3548 /* Returns true if there is one pointer type in TYPE_POINTER_TO (SRC_OBJ)
3549    list of pointer-to types that is trivially convertible to DEST.  */
3550
3551 static bool
3552 one_pointer_to_useless_type_conversion_p (tree dest, tree src_obj)
3553 {
3554   tree src;
3555
3556   if (!TYPE_POINTER_TO (src_obj))
3557     return true;
3558
3559   for (src = TYPE_POINTER_TO (src_obj); src; src = TYPE_NEXT_PTR_TO (src))
3560     if (useless_type_conversion_p (dest, src))
3561       return true;
3562
3563   return false;
3564 }
3565
3566 /* Verify the GIMPLE expression EXPR.  Returns true if there is an
3567    error, otherwise false.  */
3568
3569 static bool
3570 verify_gimple_expr (tree expr)
3571 {
3572   tree type = TREE_TYPE (expr);
3573
3574   if (is_gimple_val (expr))
3575     return false;
3576
3577   /* Special codes we cannot handle via their class.  */
3578   switch (TREE_CODE (expr))
3579     {
3580     case NOP_EXPR:
3581     case CONVERT_EXPR:
3582       {
3583         tree op = TREE_OPERAND (expr, 0);
3584         if (!is_gimple_val (op))
3585           {
3586             error ("invalid operand in conversion");
3587             return true;
3588           }
3589
3590         /* Allow conversions between integral types and between
3591            pointer types.  */
3592         if ((INTEGRAL_TYPE_P (type) && INTEGRAL_TYPE_P (TREE_TYPE (op)))
3593             || (POINTER_TYPE_P (type) && POINTER_TYPE_P (TREE_TYPE (op))))
3594           return false;
3595
3596         /* Allow conversions between integral types and pointers only if
3597            there is no sign or zero extension involved.  */
3598         if (((POINTER_TYPE_P (type) && INTEGRAL_TYPE_P (TREE_TYPE (op)))
3599              || (POINTER_TYPE_P (TREE_TYPE (op)) && INTEGRAL_TYPE_P (type)))
3600             && TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (op)))
3601           return false;
3602
3603         /* Allow conversion from integer to offset type and vice versa.  */
3604         if ((TREE_CODE (type) == OFFSET_TYPE
3605              && TREE_CODE (TREE_TYPE (op)) == INTEGER_TYPE)
3606             || (TREE_CODE (type) == INTEGER_TYPE
3607                 && TREE_CODE (TREE_TYPE (op)) == OFFSET_TYPE))
3608           return false;
3609
3610         /* Otherwise assert we are converting between types of the
3611            same kind.  */
3612         if (TREE_CODE (type) != TREE_CODE (TREE_TYPE (op)))
3613           {
3614             error ("invalid types in nop conversion");
3615             debug_generic_expr (type);
3616             debug_generic_expr (TREE_TYPE (op));
3617             return true;
3618           }
3619
3620         return false;
3621       }
3622
3623     case FLOAT_EXPR:
3624       {
3625         tree op = TREE_OPERAND (expr, 0);
3626         if (!is_gimple_val (op))
3627           {
3628             error ("invalid operand in int to float conversion");
3629             return true;
3630           }
3631         if (!INTEGRAL_TYPE_P (TREE_TYPE (op))
3632             || !SCALAR_FLOAT_TYPE_P (type))
3633           {
3634             error ("invalid types in conversion to floating point");
3635             debug_generic_expr (type);
3636             debug_generic_expr (TREE_TYPE (op));
3637             return true;
3638           }
3639         return false;
3640       }
3641
3642     case FIX_TRUNC_EXPR:
3643       {
3644         tree op = TREE_OPERAND (expr, 0);
3645         if (!is_gimple_val (op))
3646           {
3647             error ("invalid operand in float to int conversion");
3648             return true;
3649           }
3650         if (!INTEGRAL_TYPE_P (type)
3651             || !SCALAR_FLOAT_TYPE_P (TREE_TYPE (op)))
3652           {
3653             error ("invalid types in conversion to integer");
3654             debug_generic_expr (type);
3655             debug_generic_expr (TREE_TYPE (op));
3656             return true;
3657           }
3658         return false;
3659       }
3660
3661     case COMPLEX_EXPR:
3662       {
3663         tree op0 = TREE_OPERAND (expr, 0);
3664         tree op1 = TREE_OPERAND (expr, 1);
3665         if (!is_gimple_val (op0) || !is_gimple_val (op1))
3666           {
3667             error ("invalid operands in complex expression");
3668             return true;
3669           }
3670         if (!TREE_CODE (type) == COMPLEX_TYPE
3671             || !(TREE_CODE (TREE_TYPE (op0)) == INTEGER_TYPE
3672                  || SCALAR_FLOAT_TYPE_P (TREE_TYPE (op0)))
3673             || !(TREE_CODE (TREE_TYPE (op1)) == INTEGER_TYPE
3674                  || SCALAR_FLOAT_TYPE_P (TREE_TYPE (op1)))
3675             || !useless_type_conversion_p (TREE_TYPE (type),
3676                                            TREE_TYPE (op0))
3677             || !useless_type_conversion_p (TREE_TYPE (type),
3678                                            TREE_TYPE (op1)))
3679           {
3680             error ("type mismatch in complex expression");
3681             debug_generic_stmt (TREE_TYPE (expr));
3682             debug_generic_stmt (TREE_TYPE (op0));
3683             debug_generic_stmt (TREE_TYPE (op1));
3684             return true;
3685           }
3686         return false;
3687       }
3688
3689     case CONSTRUCTOR:
3690       {
3691         /* This is used like COMPLEX_EXPR but for vectors.  */
3692         if (TREE_CODE (type) != VECTOR_TYPE)
3693           {
3694             error ("constructor not allowed for non-vector types");
3695             debug_generic_stmt (type);
3696             return true;
3697           }
3698         /* FIXME: verify constructor arguments.  */
3699         return false;
3700       }
3701
3702     case LSHIFT_EXPR:
3703     case RSHIFT_EXPR:
3704     case LROTATE_EXPR:
3705     case RROTATE_EXPR:
3706       {
3707         tree op0 = TREE_OPERAND (expr, 0);
3708         tree op1 = TREE_OPERAND (expr, 1);
3709         if (!is_gimple_val (op0) || !is_gimple_val (op1))
3710           {
3711             error ("invalid operands in shift expression");
3712             return true;
3713           }
3714         if (!TREE_CODE (TREE_TYPE (op1)) == INTEGER_TYPE
3715             || !useless_type_conversion_p (type, TREE_TYPE (op0)))
3716           {
3717             error ("type mismatch in shift expression");
3718             debug_generic_stmt (TREE_TYPE (expr));
3719             debug_generic_stmt (TREE_TYPE (op0));
3720             debug_generic_stmt (TREE_TYPE (op1));
3721             return true;
3722           }
3723         return false;
3724       }
3725
3726     case PLUS_EXPR:
3727     case MINUS_EXPR:
3728       {
3729         tree op0 = TREE_OPERAND (expr, 0);
3730         tree op1 = TREE_OPERAND (expr, 1);
3731         if (POINTER_TYPE_P (type)
3732             || POINTER_TYPE_P (TREE_TYPE (op0))
3733             || POINTER_TYPE_P (TREE_TYPE (op1)))
3734           {
3735             error ("invalid (pointer) operands to plus/minus");
3736             return true;
3737           }
3738         /* Continue with generic binary expression handling.  */
3739         break;
3740       }
3741
3742     case POINTER_PLUS_EXPR:
3743       {
3744         tree op0 = TREE_OPERAND (expr, 0);
3745         tree op1 = TREE_OPERAND (expr, 1);
3746         if (!is_gimple_val (op0) || !is_gimple_val (op1))
3747           {
3748             error ("invalid operands in pointer plus expression");
3749             return true;
3750           }
3751         if (!POINTER_TYPE_P (TREE_TYPE (op0))
3752             || !useless_type_conversion_p (type, TREE_TYPE (op0))
3753             || !useless_type_conversion_p (sizetype, TREE_TYPE (op1)))
3754           {
3755             error ("type mismatch in pointer plus expression");
3756             debug_generic_stmt (type);
3757             debug_generic_stmt (TREE_TYPE (op0));
3758             debug_generic_stmt (TREE_TYPE (op1));
3759             return true;
3760           }
3761         return false;
3762       }
3763
3764     case COND_EXPR:
3765       {
3766         tree op0 = TREE_OPERAND (expr, 0);
3767         tree op1 = TREE_OPERAND (expr, 1);
3768         tree op2 = TREE_OPERAND (expr, 2);
3769         if ((!is_gimple_val (op1)
3770              && TREE_CODE (TREE_TYPE (op1)) != VOID_TYPE)
3771             || (!is_gimple_val (op2)
3772                 && TREE_CODE (TREE_TYPE (op2)) != VOID_TYPE))
3773           {
3774             error ("invalid operands in conditional expression");
3775             return true;
3776           }
3777         if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
3778             || (TREE_CODE (TREE_TYPE (op1)) != VOID_TYPE
3779                 && !useless_type_conversion_p (type, TREE_TYPE (op1)))
3780             || (TREE_CODE (TREE_TYPE (op2)) != VOID_TYPE
3781                 && !useless_type_conversion_p (type, TREE_TYPE (op2))))
3782           {
3783             error ("type mismatch in conditional expression");
3784             debug_generic_stmt (type);
3785             debug_generic_stmt (TREE_TYPE (op0));
3786             debug_generic_stmt (TREE_TYPE (op1));
3787             debug_generic_stmt (TREE_TYPE (op2));
3788             return true;
3789           }
3790         return verify_gimple_expr (op0);
3791       }
3792
3793     case ADDR_EXPR:
3794       {
3795         tree op = TREE_OPERAND (expr, 0);
3796         if (!is_gimple_addressable (op))
3797           {
3798             error ("invalid operand in unary expression");
3799             return true;
3800           }
3801         if (!one_pointer_to_useless_type_conversion_p (type, TREE_TYPE (op))
3802             /* FIXME: a longstanding wart, &a == &a[0].  */
3803             && (TREE_CODE (TREE_TYPE (op)) != ARRAY_TYPE
3804                 || !one_pointer_to_useless_type_conversion_p (type,
3805                       TREE_TYPE (TREE_TYPE (op)))))
3806           {
3807             error ("type mismatch in address expression");
3808             debug_generic_stmt (TREE_TYPE (expr));
3809             debug_generic_stmt (TYPE_POINTER_TO (TREE_TYPE (op)));
3810             return true;
3811           }
3812
3813         return verify_gimple_reference (op);
3814       }
3815
3816     case TRUTH_ANDIF_EXPR:
3817     case TRUTH_ORIF_EXPR:
3818     case TRUTH_AND_EXPR:
3819     case TRUTH_OR_EXPR:
3820     case TRUTH_XOR_EXPR:
3821       {
3822         tree op0 = TREE_OPERAND (expr, 0);
3823         tree op1 = TREE_OPERAND (expr, 1);
3824
3825         if (!is_gimple_val (op0) || !is_gimple_val (op1))
3826           {
3827             error ("invalid operands in truth expression");
3828             return true;
3829           }
3830
3831         /* We allow any kind of integral typed argument and result.  */
3832         if (!INTEGRAL_TYPE_P (TREE_TYPE (op0))
3833             || !INTEGRAL_TYPE_P (TREE_TYPE (op1))
3834             || !INTEGRAL_TYPE_P (type))
3835           {
3836             error ("type mismatch in binary truth expression");
3837             debug_generic_stmt (type);
3838             debug_generic_stmt (TREE_TYPE (op0));
3839             debug_generic_stmt (TREE_TYPE (op1));
3840             return true;
3841           }
3842
3843         return false;
3844       }
3845
3846     case TRUTH_NOT_EXPR:
3847       {
3848         tree op = TREE_OPERAND (expr, 0);
3849
3850         if (!is_gimple_val (op))
3851           {
3852             error ("invalid operand in unary not");
3853             return true;
3854           }
3855
3856         /* For TRUTH_NOT_EXPR we can have any kind of integral
3857            typed arguments and results.  */
3858         if (!INTEGRAL_TYPE_P (TREE_TYPE (op))
3859             || !INTEGRAL_TYPE_P (type))
3860           {
3861             error ("type mismatch in not expression");
3862             debug_generic_expr (TREE_TYPE (expr));
3863             debug_generic_expr (TREE_TYPE (op));
3864             return true;
3865           }
3866
3867         return false;
3868       }
3869
3870     case CALL_EXPR:
3871       /* FIXME.  The C frontend passes unpromoted arguments in case it
3872          didn't see a function declaration before the call.  */
3873       return false;
3874
3875     case OBJ_TYPE_REF:
3876       /* FIXME.  */
3877       return false;
3878
3879     default:;
3880     }
3881
3882   /* Generic handling via classes.  */
3883   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
3884     {
3885     case tcc_unary:
3886       return verify_gimple_unary_expr (expr);
3887
3888     case tcc_binary:
3889       return verify_gimple_binary_expr (expr);
3890
3891     case tcc_reference:
3892       return verify_gimple_reference (expr);
3893
3894     case tcc_comparison:
3895       {
3896         tree op0 = TREE_OPERAND (expr, 0);
3897         tree op1 = TREE_OPERAND (expr, 1);
3898         if (!is_gimple_val (op0) || !is_gimple_val (op1))
3899           {
3900             error ("invalid operands in comparison expression");
3901             return true;
3902           }
3903         /* For comparisons we do not have the operations type as the
3904            effective type the comparison is carried out in.  Instead
3905            we require that either the first operand is trivially
3906            convertible into the second, or the other way around.
3907            The resulting type of a comparison may be any integral type.
3908            Because we special-case pointers to void we allow
3909            comparisons of pointers with the same mode as well.  */
3910         if ((!useless_type_conversion_p (TREE_TYPE (op0), TREE_TYPE (op1))
3911              && !useless_type_conversion_p (TREE_TYPE (op1), TREE_TYPE (op0))
3912              && (!POINTER_TYPE_P (TREE_TYPE (op0))
3913                  || !POINTER_TYPE_P (TREE_TYPE (op1))
3914                  || TYPE_MODE (TREE_TYPE (op0)) != TYPE_MODE (TREE_TYPE (op1))))
3915             || !INTEGRAL_TYPE_P (type))
3916           {
3917             error ("type mismatch in comparison expression");
3918             debug_generic_stmt (TREE_TYPE (expr));
3919             debug_generic_stmt (TREE_TYPE (op0));
3920             debug_generic_stmt (TREE_TYPE (op1));
3921             return true;
3922           }
3923         break;
3924       }
3925
3926     default:
3927       gcc_unreachable ();
3928     }
3929
3930   return false;
3931 }
3932
3933 /* Verify the GIMPLE assignment statement STMT.  Returns true if there
3934    is an error, otherwise false.  */
3935
3936 static bool
3937 verify_gimple_modify_stmt (const_tree stmt)
3938 {
3939   tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
3940   tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
3941
3942   gcc_assert (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT);
3943
3944   if (!useless_type_conversion_p (TREE_TYPE (lhs),
3945                                   TREE_TYPE (rhs)))
3946     {
3947       error ("non-trivial conversion at assignment");
3948       debug_generic_expr (TREE_TYPE (lhs));
3949       debug_generic_expr (TREE_TYPE (rhs));
3950       return true;
3951     }
3952
3953   /* Loads/stores from/to a variable are ok.  */
3954   if ((is_gimple_val (lhs)
3955        && is_gimple_variable (rhs))
3956       || (is_gimple_val (rhs)
3957           && is_gimple_variable (lhs)))
3958     return false;
3959
3960   /* Aggregate copies are ok.  */
3961   if (!is_gimple_reg_type (TREE_TYPE (lhs))
3962       && !is_gimple_reg_type (TREE_TYPE (rhs)))
3963     return false;
3964
3965   /* We might get 'loads' from a parameter which is not a gimple value.  */
3966   if (TREE_CODE (rhs) == PARM_DECL)
3967     return verify_gimple_expr (lhs);
3968
3969   if (!is_gimple_variable (lhs)
3970       && verify_gimple_expr (lhs))
3971     return true;
3972
3973   if (!is_gimple_variable (rhs)
3974       && verify_gimple_expr (rhs))
3975     return true;
3976
3977   return false;
3978 }
3979
3980 /* Verify the GIMPLE statement STMT.  Returns true if there is an
3981    error, otherwise false.  */
3982
3983 static bool
3984 verify_gimple_stmt (tree stmt)
3985 {
3986   if (!is_gimple_stmt (stmt))
3987     {
3988       error ("is not a valid GIMPLE statement");
3989       return true;
3990     }
3991
3992   if (OMP_DIRECTIVE_P (stmt))
3993     {
3994       /* OpenMP directives are validated by the FE and never operated
3995          on by the optimizers.  Furthermore, OMP_FOR may contain
3996          non-gimple expressions when the main index variable has had
3997          its address taken.  This does not affect the loop itself
3998          because the header of an OMP_FOR is merely used to determine
3999          how to setup the parallel iteration.  */
4000       return false;
4001     }
4002
4003   switch (TREE_CODE (stmt))
4004     {
4005     case GIMPLE_MODIFY_STMT:
4006       return verify_gimple_modify_stmt (stmt);
4007
4008     case GOTO_EXPR:
4009     case LABEL_EXPR:
4010       return false;
4011
4012     case SWITCH_EXPR:
4013       if (!is_gimple_val (TREE_OPERAND (stmt, 0)))
4014         {
4015           error ("invalid operand to switch statement");
4016           debug_generic_expr (TREE_OPERAND (stmt, 0));
4017         }
4018       return false;
4019
4020     case RETURN_EXPR:
4021       {
4022         tree op = TREE_OPERAND (stmt, 0);
4023
4024         if (TREE_CODE (TREE_TYPE (stmt)) != VOID_TYPE)
4025           {
4026             error ("type error in return expression");
4027             return true;
4028           }
4029
4030         if (op == NULL_TREE
4031             || TREE_CODE (op) == RESULT_DECL)
4032           return false;
4033
4034         return verify_gimple_modify_stmt (op);
4035       }
4036
4037     case CALL_EXPR:
4038     case COND_EXPR:
4039       return verify_gimple_expr (stmt);
4040
4041     case NOP_EXPR:
4042     case CHANGE_DYNAMIC_TYPE_EXPR:
4043     case ASM_EXPR:
4044       return false;
4045
4046     default:
4047       gcc_unreachable ();
4048     }
4049 }
4050
4051 /* Verify the GIMPLE statements inside the statement list STMTS.
4052    Returns true if there were any errors.  */
4053
4054 static bool
4055 verify_gimple_2 (tree stmts)
4056 {
4057   tree_stmt_iterator tsi;
4058   bool err = false;
4059
4060   for (tsi = tsi_start (stmts); !tsi_end_p (tsi); tsi_next (&tsi))
4061     {
4062       tree stmt = tsi_stmt (tsi);
4063
4064       switch (TREE_CODE (stmt))
4065         {
4066         case BIND_EXPR:
4067           err |= verify_gimple_2 (BIND_EXPR_BODY (stmt));
4068           break;
4069
4070         case TRY_CATCH_EXPR:
4071         case TRY_FINALLY_EXPR:
4072           err |= verify_gimple_2 (TREE_OPERAND (stmt, 0));
4073           err |= verify_gimple_2 (TREE_OPERAND (stmt, 1));
4074           break;
4075
4076         case CATCH_EXPR:
4077           err |= verify_gimple_2 (CATCH_BODY (stmt));
4078           break;
4079
4080         case EH_FILTER_EXPR:
4081           err |= verify_gimple_2 (EH_FILTER_FAILURE (stmt));
4082           break;
4083
4084         default:
4085           {
4086             bool err2 = verify_gimple_stmt (stmt);
4087             if (err2)
4088               debug_generic_expr (stmt);
4089             err |= err2;
4090           }
4091         }
4092     }
4093
4094   return err;
4095 }
4096
4097
4098 /* Verify the GIMPLE statements inside the statement list STMTS.  */
4099
4100 void
4101 verify_gimple_1 (tree stmts)
4102 {
4103   if (verify_gimple_2 (stmts))
4104     internal_error ("verify_gimple failed");
4105 }
4106
4107 /* Verify the GIMPLE statements inside the current function.  */
4108
4109 void
4110 verify_gimple (void)
4111 {
4112   verify_gimple_1 (BIND_EXPR_BODY (DECL_SAVED_TREE (cfun->decl)));
4113 }
4114
4115 /* Verify STMT, return true if STMT is not in GIMPLE form.
4116    TODO: Implement type checking.  */
4117
4118 static bool
4119 verify_stmt (tree stmt, bool last_in_block)
4120 {
4121   tree addr;
4122
4123   if (OMP_DIRECTIVE_P (stmt))
4124     {
4125       /* OpenMP directives are validated by the FE and never operated
4126          on by the optimizers.  Furthermore, OMP_FOR may contain
4127          non-gimple expressions when the main index variable has had
4128          its address taken.  This does not affect the loop itself
4129          because the header of an OMP_FOR is merely used to determine
4130          how to setup the parallel iteration.  */
4131       return false;
4132     }
4133
4134   if (!is_gimple_stmt (stmt))
4135     {
4136       error ("is not a valid GIMPLE statement");
4137       goto fail;
4138     }
4139
4140   addr = walk_tree (&stmt, verify_expr, NULL, NULL);
4141   if (addr)
4142     {
4143       debug_generic_stmt (addr);
4144       return true;
4145     }
4146
4147   /* If the statement is marked as part of an EH region, then it is
4148      expected that the statement could throw.  Verify that when we
4149      have optimizations that simplify statements such that we prove
4150      that they cannot throw, that we update other data structures
4151      to match.  */
4152   if (lookup_stmt_eh_region (stmt) >= 0)
4153     {
4154       if (!tree_could_throw_p (stmt))
4155         {
4156           error ("statement marked for throw, but doesn%'t");
4157           goto fail;
4158         }
4159       if (!last_in_block && tree_can_throw_internal (stmt))
4160         {
4161           error ("statement marked for throw in middle of block");
4162           goto fail;
4163         }
4164     }
4165
4166   return false;
4167
4168  fail:
4169   debug_generic_stmt (stmt);
4170   return true;
4171 }
4172
4173
4174 /* Return true when the T can be shared.  */
4175
4176 static bool
4177 tree_node_can_be_shared (tree t)
4178 {
4179   if (IS_TYPE_OR_DECL_P (t)
4180       || is_gimple_min_invariant (t)
4181       || TREE_CODE (t) == SSA_NAME
4182       || t == error_mark_node
4183       || TREE_CODE (t) == IDENTIFIER_NODE)
4184     return true;
4185
4186   if (TREE_CODE (t) == CASE_LABEL_EXPR)
4187     return true;
4188
4189   while (((TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
4190            && is_gimple_min_invariant (TREE_OPERAND (t, 1)))
4191          || TREE_CODE (t) == COMPONENT_REF
4192          || TREE_CODE (t) == REALPART_EXPR
4193          || TREE_CODE (t) == IMAGPART_EXPR)
4194     t = TREE_OPERAND (t, 0);
4195
4196   if (DECL_P (t))
4197     return true;
4198
4199   return false;
4200 }
4201
4202
4203 /* Called via walk_trees.  Verify tree sharing.  */
4204
4205 static tree
4206 verify_node_sharing (tree * tp, int *walk_subtrees, void *data)
4207 {
4208   struct pointer_set_t *visited = (struct pointer_set_t *) data;
4209
4210   if (tree_node_can_be_shared (*tp))
4211     {
4212       *walk_subtrees = false;
4213       return NULL;
4214     }
4215
4216   if (pointer_set_insert (visited, *tp))
4217     return *tp;
4218
4219   return NULL;
4220 }
4221
4222
4223 /* Helper function for verify_gimple_tuples.  */
4224
4225 static tree
4226 verify_gimple_tuples_1 (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
4227                          void *data ATTRIBUTE_UNUSED)
4228 {
4229   switch (TREE_CODE (*tp))
4230     {
4231     case MODIFY_EXPR:
4232       error ("unexpected non-tuple");
4233       debug_tree (*tp);
4234       gcc_unreachable ();
4235       return NULL_TREE;
4236
4237     default:
4238       return NULL_TREE;
4239     }
4240 }
4241
4242 /* Verify that there are no trees that should have been converted to
4243    gimple tuples.  Return true if T contains a node that should have
4244    been converted to a gimple tuple, but hasn't.  */
4245
4246 static bool
4247 verify_gimple_tuples (tree t)
4248 {
4249   return walk_tree (&t, verify_gimple_tuples_1, NULL, NULL) != NULL;
4250 }
4251
4252 static bool eh_error_found;
4253 static int
4254 verify_eh_throw_stmt_node (void **slot, void *data)
4255 {
4256   struct throw_stmt_node *node = (struct throw_stmt_node *)*slot;
4257   struct pointer_set_t *visited = (struct pointer_set_t *) data;
4258
4259   if (!pointer_set_contains (visited, node->stmt))
4260     {
4261       error ("Dead STMT in EH table");
4262       debug_generic_stmt (node->stmt);
4263       eh_error_found = true;
4264     }
4265   return 0;
4266 }
4267
4268 /* Verify the GIMPLE statement chain.  */
4269
4270 void
4271 verify_stmts (void)
4272 {
4273   basic_block bb;
4274   block_stmt_iterator bsi;
4275   bool err = false;
4276   struct pointer_set_t *visited, *visited_stmts;
4277   tree addr;
4278
4279   timevar_push (TV_TREE_STMT_VERIFY);
4280   visited = pointer_set_create ();
4281   visited_stmts = pointer_set_create ();
4282
4283   FOR_EACH_BB (bb)
4284     {
4285       tree phi;
4286       int i;
4287
4288       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
4289         {
4290           int phi_num_args = PHI_NUM_ARGS (phi);
4291
4292           pointer_set_insert (visited_stmts, phi);
4293           if (bb_for_stmt (phi) != bb)
4294             {
4295               error ("bb_for_stmt (phi) is set to a wrong basic block");
4296               err |= true;
4297             }
4298
4299           for (i = 0; i < phi_num_args; i++)
4300             {
4301               tree t = PHI_ARG_DEF (phi, i);
4302               tree addr;
4303
4304               if (!t)
4305                 {
4306                   error ("missing PHI def");
4307                   debug_generic_stmt (phi);
4308                   err |= true;
4309                   continue;
4310                 }
4311               /* Addressable variables do have SSA_NAMEs but they
4312                  are not considered gimple values.  */
4313               else if (TREE_CODE (t) != SSA_NAME
4314                        && TREE_CODE (t) != FUNCTION_DECL
4315                        && !is_gimple_val (t))
4316                 {
4317                   error ("PHI def is not a GIMPLE value");
4318                   debug_generic_stmt (phi);
4319                   debug_generic_stmt (t);
4320                   err |= true;
4321                 }
4322
4323               addr = walk_tree (&t, verify_expr, (void *) 1, NULL);
4324               if (addr)
4325                 {
4326                   debug_generic_stmt (addr);
4327                   err |= true;
4328                 }
4329
4330               addr = walk_tree (&t, verify_node_sharing, visited, NULL);
4331               if (addr)
4332                 {
4333                   error ("incorrect sharing of tree nodes");
4334                   debug_generic_stmt (phi);
4335                   debug_generic_stmt (addr);
4336                   err |= true;
4337                 }
4338             }
4339         }
4340
4341       for (bsi = bsi_start (bb); !bsi_end_p (bsi); )
4342         {
4343           tree stmt = bsi_stmt (bsi);
4344
4345           pointer_set_insert (visited_stmts, stmt);
4346           err |= verify_gimple_tuples (stmt);
4347
4348           if (bb_for_stmt (stmt) != bb)
4349             {
4350               error ("bb_for_stmt (stmt) is set to a wrong basic block");
4351               err |= true;
4352             }
4353
4354           bsi_next (&bsi);
4355           err |= verify_stmt (stmt, bsi_end_p (bsi));
4356           addr = walk_tree (&stmt, verify_node_sharing, visited, NULL);
4357           if (addr)
4358             {
4359               error ("incorrect sharing of tree nodes");
4360               debug_generic_stmt (stmt);
4361               debug_generic_stmt (addr);
4362               err |= true;
4363             }
4364         }
4365     }
4366   eh_error_found = false;
4367   if (get_eh_throw_stmt_table (cfun))
4368     htab_traverse (get_eh_throw_stmt_table (cfun),
4369                    verify_eh_throw_stmt_node,
4370                    visited_stmts);
4371
4372   if (err | eh_error_found)
4373     internal_error ("verify_stmts failed");
4374
4375   pointer_set_destroy (visited);
4376   pointer_set_destroy (visited_stmts);
4377   verify_histograms ();
4378   timevar_pop (TV_TREE_STMT_VERIFY);
4379 }
4380
4381
4382 /* Verifies that the flow information is OK.  */
4383
4384 static int
4385 tree_verify_flow_info (void)
4386 {
4387   int err = 0;
4388   basic_block bb;
4389   block_stmt_iterator bsi;
4390   tree stmt;
4391   edge e;
4392   edge_iterator ei;
4393
4394   if (ENTRY_BLOCK_PTR->il.tree)
4395     {
4396       error ("ENTRY_BLOCK has IL associated with it");
4397       err = 1;
4398     }
4399
4400   if (EXIT_BLOCK_PTR->il.tree)
4401     {
4402       error ("EXIT_BLOCK has IL associated with it");
4403       err = 1;
4404     }
4405
4406   FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
4407     if (e->flags & EDGE_FALLTHRU)
4408       {
4409         error ("fallthru to exit from bb %d", e->src->index);
4410         err = 1;
4411       }
4412
4413   FOR_EACH_BB (bb)
4414     {
4415       bool found_ctrl_stmt = false;
4416
4417       stmt = NULL_TREE;
4418
4419       /* Skip labels on the start of basic block.  */
4420       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4421         {
4422           tree prev_stmt = stmt;
4423
4424           stmt = bsi_stmt (bsi);
4425
4426           if (TREE_CODE (stmt) != LABEL_EXPR)
4427             break;
4428
4429           if (prev_stmt && DECL_NONLOCAL (LABEL_EXPR_LABEL (stmt)))
4430             {
4431               error ("nonlocal label ");
4432               print_generic_expr (stderr, LABEL_EXPR_LABEL (stmt), 0);
4433               fprintf (stderr, " is not first in a sequence of labels in bb %d",
4434                        bb->index);
4435               err = 1;
4436             }
4437
4438           if (label_to_block (LABEL_EXPR_LABEL (stmt)) != bb)
4439             {
4440               error ("label ");
4441               print_generic_expr (stderr, LABEL_EXPR_LABEL (stmt), 0);
4442               fprintf (stderr, " to block does not match in bb %d",
4443                        bb->index);
4444               err = 1;
4445             }
4446
4447           if (decl_function_context (LABEL_EXPR_LABEL (stmt))
4448               != current_function_decl)
4449             {
4450               error ("label ");
4451               print_generic_expr (stderr, LABEL_EXPR_LABEL (stmt), 0);
4452               fprintf (stderr, " has incorrect context in bb %d",
4453                        bb->index);
4454               err = 1;
4455             }
4456         }
4457
4458       /* Verify that body of basic block BB is free of control flow.  */
4459       for (; !bsi_end_p (bsi); bsi_next (&bsi))
4460         {
4461           tree stmt = bsi_stmt (bsi);
4462
4463           if (found_ctrl_stmt)
4464             {
4465               error ("control flow in the middle of basic block %d",
4466                      bb->index);
4467               err = 1;
4468             }
4469
4470           if (stmt_ends_bb_p (stmt))
4471             found_ctrl_stmt = true;
4472
4473           if (TREE_CODE (stmt) == LABEL_EXPR)
4474             {
4475               error ("label ");
4476               print_generic_expr (stderr, LABEL_EXPR_LABEL (stmt), 0);
4477               fprintf (stderr, " in the middle of basic block %d", bb->index);
4478               err = 1;
4479             }
4480         }
4481
4482       bsi = bsi_last (bb);
4483       if (bsi_end_p (bsi))
4484         continue;
4485
4486       stmt = bsi_stmt (bsi);
4487
4488       err |= verify_eh_edges (stmt);
4489
4490       if (is_ctrl_stmt (stmt))
4491         {
4492           FOR_EACH_EDGE (e, ei, bb->succs)
4493             if (e->flags & EDGE_FALLTHRU)
4494               {
4495                 error ("fallthru edge after a control statement in bb %d",
4496                        bb->index);
4497                 err = 1;
4498               }
4499         }
4500
4501       if (TREE_CODE (stmt) != COND_EXPR)
4502         {
4503           /* Verify that there are no edges with EDGE_TRUE/FALSE_FLAG set
4504              after anything else but if statement.  */
4505           FOR_EACH_EDGE (e, ei, bb->succs)
4506             if (e->flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE))
4507               {
4508                 error ("true/false edge after a non-COND_EXPR in bb %d",
4509                        bb->index);
4510                 err = 1;
4511               }
4512         }
4513
4514       switch (TREE_CODE (stmt))
4515         {
4516         case COND_EXPR:
4517           {
4518             edge true_edge;
4519             edge false_edge;
4520   
4521             if (COND_EXPR_THEN (stmt) != NULL_TREE
4522                 || COND_EXPR_ELSE (stmt) != NULL_TREE)
4523               {
4524                 error ("COND_EXPR with code in branches at the end of bb %d",
4525                        bb->index);
4526                 err = 1;
4527               }
4528
4529             extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
4530
4531             if (!true_edge || !false_edge
4532                 || !(true_edge->flags & EDGE_TRUE_VALUE)
4533                 || !(false_edge->flags & EDGE_FALSE_VALUE)
4534                 || (true_edge->flags & (EDGE_FALLTHRU | EDGE_ABNORMAL))
4535                 || (false_edge->flags & (EDGE_FALLTHRU | EDGE_ABNORMAL))
4536                 || EDGE_COUNT (bb->succs) >= 3)
4537               {
4538                 error ("wrong outgoing edge flags at end of bb %d",
4539                        bb->index);
4540                 err = 1;
4541               }
4542           }
4543           break;
4544
4545         case GOTO_EXPR:
4546           if (simple_goto_p (stmt))
4547             {
4548               error ("explicit goto at end of bb %d", bb->index);
4549               err = 1;
4550             }
4551           else
4552             {
4553               /* FIXME.  We should double check that the labels in the
4554                  destination blocks have their address taken.  */
4555               FOR_EACH_EDGE (e, ei, bb->succs)
4556                 if ((e->flags & (EDGE_FALLTHRU | EDGE_TRUE_VALUE
4557                                  | EDGE_FALSE_VALUE))
4558                     || !(e->flags & EDGE_ABNORMAL))
4559                   {
4560                     error ("wrong outgoing edge flags at end of bb %d",
4561                            bb->index);
4562                     err = 1;
4563                   }
4564             }
4565           break;
4566
4567         case RETURN_EXPR:
4568           if (!single_succ_p (bb)
4569               || (single_succ_edge (bb)->flags
4570                   & (EDGE_FALLTHRU | EDGE_ABNORMAL
4571                      | EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
4572             {
4573               error ("wrong outgoing edge flags at end of bb %d", bb->index);
4574               err = 1;
4575             }
4576           if (single_succ (bb) != EXIT_BLOCK_PTR)
4577             {
4578               error ("return edge does not point to exit in bb %d",
4579                      bb->index);
4580               err = 1;
4581             }
4582           break;
4583
4584         case SWITCH_EXPR:
4585           {
4586             tree prev;
4587             edge e;
4588             size_t i, n;
4589             tree vec;
4590
4591             vec = SWITCH_LABELS (stmt);
4592             n = TREE_VEC_LENGTH (vec);
4593
4594             /* Mark all the destination basic blocks.  */
4595             for (i = 0; i < n; ++i)
4596               {
4597                 tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i));
4598                 basic_block label_bb = label_to_block (lab);
4599
4600                 gcc_assert (!label_bb->aux || label_bb->aux == (void *)1);
4601                 label_bb->aux = (void *)1;
4602               }
4603
4604             /* Verify that the case labels are sorted.  */
4605             prev = TREE_VEC_ELT (vec, 0);
4606             for (i = 1; i < n - 1; ++i)
4607               {
4608                 tree c = TREE_VEC_ELT (vec, i);
4609                 if (! CASE_LOW (c))
4610                   {
4611                     error ("found default case not at end of case vector");
4612                     err = 1;
4613                     continue;
4614                   }
4615                 if (! tree_int_cst_lt (CASE_LOW (prev), CASE_LOW (c)))
4616                   {
4617                     error ("case labels not sorted: ");
4618                     print_generic_expr (stderr, prev, 0);
4619                     fprintf (stderr," is greater than ");
4620                     print_generic_expr (stderr, c, 0);
4621                     fprintf (stderr," but comes before it.\n");
4622                     err = 1;
4623                   }
4624                 prev = c;
4625               }
4626             if (CASE_LOW (TREE_VEC_ELT (vec, n - 1)))
4627               {
4628                 error ("no default case found at end of case vector");
4629                 err = 1;
4630               }
4631
4632             FOR_EACH_EDGE (e, ei, bb->succs)
4633               {
4634                 if (!e->dest->aux)
4635                   {
4636                     error ("extra outgoing edge %d->%d",
4637                            bb->index, e->dest->index);
4638                     err = 1;
4639                   }
4640                 e->dest->aux = (void *)2;
4641                 if ((e->flags & (EDGE_FALLTHRU | EDGE_ABNORMAL
4642                                  | EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
4643                   {
4644                     error ("wrong outgoing edge flags at end of bb %d",
4645                            bb->index);
4646                     err = 1;
4647                   }
4648               }
4649
4650             /* Check that we have all of them.  */
4651             for (i = 0; i < n; ++i)
4652               {
4653                 tree lab = CASE_LABEL (TREE_VEC_ELT (vec, i));
4654                 basic_block label_bb = label_to_block (lab);
4655
4656                 if (label_bb->aux != (void *)2)
4657                   {
4658                     error ("missing edge %i->%i",
4659                            bb->index, label_bb->index);
4660                     err = 1;
4661                   }
4662               }
4663
4664             FOR_EACH_EDGE (e, ei, bb->succs)
4665               e->dest->aux = (void *)0;
4666           }
4667
4668         default: ;
4669         }
4670     }
4671
4672   if (dom_info_state (CDI_DOMINATORS) >= DOM_NO_FAST_QUERY)
4673     verify_dominators (CDI_DOMINATORS);
4674
4675   return err;
4676 }
4677
4678
4679 /* Updates phi nodes after creating a forwarder block joined
4680    by edge FALLTHRU.  */
4681
4682 static void
4683 tree_make_forwarder_block (edge fallthru)
4684 {
4685   edge e;
4686   edge_iterator ei;
4687   basic_block dummy, bb;
4688   tree phi, new_phi, var;
4689
4690   dummy = fallthru->src;
4691   bb = fallthru->dest;
4692
4693   if (single_pred_p (bb))
4694     return;
4695
4696   /* If we redirected a branch we must create new PHI nodes at the
4697      start of BB.  */
4698   for (phi = phi_nodes (dummy); phi; phi = PHI_CHAIN (phi))
4699     {
4700       var = PHI_RESULT (phi);
4701       new_phi = create_phi_node (var, bb);
4702       SSA_NAME_DEF_STMT (var) = new_phi;
4703       SET_PHI_RESULT (phi, make_ssa_name (SSA_NAME_VAR (var), phi));
4704       add_phi_arg (new_phi, PHI_RESULT (phi), fallthru);
4705     }
4706
4707   /* Ensure that the PHI node chain is in the same order.  */
4708   set_phi_nodes (bb, phi_reverse (phi_nodes (bb)));
4709
4710   /* Add the arguments we have stored on edges.  */
4711   FOR_EACH_EDGE (e, ei, bb->preds)
4712     {
4713       if (e == fallthru)
4714         continue;
4715
4716       flush_pending_stmts (e);
4717     }
4718 }
4719
4720
4721 /* Return a non-special label in the head of basic block BLOCK.
4722    Create one if it doesn't exist.  */
4723
4724 tree
4725 tree_block_label (basic_block bb)
4726 {
4727   block_stmt_iterator i, s = bsi_start (bb);
4728   bool first = true;
4729   tree label, stmt;
4730
4731   for (i = s; !bsi_end_p (i); first = false, bsi_next (&i))
4732     {
4733       stmt = bsi_stmt (i);
4734       if (TREE_CODE (stmt) != LABEL_EXPR)
4735         break;
4736       label = LABEL_EXPR_LABEL (stmt);
4737       if (!DECL_NONLOCAL (label))
4738         {
4739           if (!first)
4740             bsi_move_before (&i, &s);
4741           return label;
4742         }
4743     }
4744
4745   label = create_artificial_label ();
4746   stmt = build1 (LABEL_EXPR, void_type_node, label);
4747   bsi_insert_before (&s, stmt, BSI_NEW_STMT);
4748   return label;
4749 }
4750
4751
4752 /* Attempt to perform edge redirection by replacing a possibly complex
4753    jump instruction by a goto or by removing the jump completely.
4754    This can apply only if all edges now point to the same block.  The
4755    parameters and return values are equivalent to
4756    redirect_edge_and_branch.  */
4757
4758 static edge
4759 tree_try_redirect_by_replacing_jump (edge e, basic_block target)
4760 {
4761   basic_block src = e->src;
4762   block_stmt_iterator b;
4763   tree stmt;
4764
4765   /* We can replace or remove a complex jump only when we have exactly
4766      two edges.  */
4767   if (EDGE_COUNT (src->succs) != 2
4768       /* Verify that all targets will be TARGET.  Specifically, the
4769          edge that is not E must also go to TARGET.  */
4770       || EDGE_SUCC (src, EDGE_SUCC (src, 0) == e)->dest != target)
4771     return NULL;
4772
4773   b = bsi_last (src);
4774   if (bsi_end_p (b))
4775     return NULL;
4776   stmt = bsi_stmt (b);
4777
4778   if (TREE_CODE (stmt) == COND_EXPR
4779       || TREE_CODE (stmt) == SWITCH_EXPR)
4780     {
4781       bsi_remove (&b, true);
4782       e = ssa_redirect_edge (e, target);
4783       e->flags = EDGE_FALLTHRU;
4784       return e;
4785     }
4786
4787   return NULL;
4788 }
4789
4790
4791 /* Redirect E to DEST.  Return NULL on failure.  Otherwise, return the
4792    edge representing the redirected branch.  */
4793
4794 static edge
4795 tree_redirect_edge_and_branch (edge e, basic_block dest)
4796 {
4797   basic_block bb = e->src;
4798   block_stmt_iterator bsi;
4799   edge ret;
4800   tree stmt;
4801
4802   if (e->flags & EDGE_ABNORMAL)
4803     return NULL;
4804
4805   if (e->src != ENTRY_BLOCK_PTR
4806       && (ret = tree_try_redirect_by_replacing_jump (e, dest)))
4807     return ret;
4808
4809   if (e->dest == dest)
4810     return NULL;
4811
4812   bsi = bsi_last (bb);
4813   stmt = bsi_end_p (bsi) ? NULL : bsi_stmt (bsi);
4814
4815   switch (stmt ? TREE_CODE (stmt) : ERROR_MARK)
4816     {
4817     case COND_EXPR:
4818       /* For COND_EXPR, we only need to redirect the edge.  */
4819       break;
4820
4821     case GOTO_EXPR:
4822       /* No non-abnormal edges should lead from a non-simple goto, and
4823          simple ones should be represented implicitly.  */
4824       gcc_unreachable ();
4825
4826     case SWITCH_EXPR:
4827       {
4828         tree cases = get_cases_for_edge (e, stmt);
4829         tree label = tree_block_label (dest);
4830
4831         /* If we have a list of cases associated with E, then use it
4832            as it's a lot faster than walking the entire case vector.  */
4833         if (cases)
4834           {
4835             edge e2 = find_edge (e->src, dest);
4836             tree last, first;
4837
4838             first = cases;
4839             while (cases)
4840               {
4841                 last = cases;
4842                 CASE_LABEL (cases) = label;
4843                 cases = TREE_CHAIN (cases);
4844               }
4845
4846             /* If there was already an edge in the CFG, then we need
4847                to move all the cases associated with E to E2.  */
4848             if (e2)
4849               {
4850                 tree cases2 = get_cases_for_edge (e2, stmt);
4851
4852                 TREE_CHAIN (last) = TREE_CHAIN (cases2);
4853                 TREE_CHAIN (cases2) = first;
4854               }
4855           }
4856         else
4857           {
4858             tree vec = SWITCH_LABELS (stmt);
4859             size_t i, n = TREE_VEC_LENGTH (vec);
4860
4861             for (i = 0; i < n; i++)
4862               {
4863                 tree elt = TREE_VEC_ELT (vec, i);
4864
4865                 if (label_to_block (CASE_LABEL (elt)) == e->dest)
4866                   CASE_LABEL (elt) = label;
4867               }
4868           }
4869
4870         break;
4871       }
4872
4873     case RETURN_EXPR:
4874       bsi_remove (&bsi, true);
4875       e->flags |= EDGE_FALLTHRU;
4876       break;
4877
4878     case OMP_RETURN:
4879     case OMP_CONTINUE:
4880     case OMP_SECTIONS_SWITCH:
4881     case OMP_FOR:
4882       /* The edges from OMP constructs can be simply redirected.  */
4883       break;
4884
4885     default:
4886       /* Otherwise it must be a fallthru edge, and we don't need to
4887          do anything besides redirecting it.  */
4888       gcc_assert (e->flags & EDGE_FALLTHRU);
4889       break;
4890     }
4891
4892   /* Update/insert PHI nodes as necessary.  */
4893
4894   /* Now update the edges in the CFG.  */
4895   e = ssa_redirect_edge (e, dest);
4896
4897   return e;
4898 }
4899
4900 /* Returns true if it is possible to remove edge E by redirecting
4901    it to the destination of the other edge from E->src.  */
4902
4903 static bool
4904 tree_can_remove_branch_p (const_edge e)
4905 {
4906   if (e->flags & EDGE_ABNORMAL)
4907     return false;
4908
4909   return true;
4910 }
4911
4912 /* Simple wrapper, as we can always redirect fallthru edges.  */
4913
4914 static basic_block
4915 tree_redirect_edge_and_branch_force (edge e, basic_block dest)
4916 {
4917   e = tree_redirect_edge_and_branch (e, dest);
4918   gcc_assert (e);
4919
4920   return NULL;
4921 }
4922
4923
4924 /* Splits basic block BB after statement STMT (but at least after the
4925    labels).  If STMT is NULL, BB is split just after the labels.  */
4926
4927 static basic_block
4928 tree_split_block (basic_block bb, void *stmt)
4929 {
4930   block_stmt_iterator bsi;
4931   tree_stmt_iterator tsi_tgt;
4932   tree act, list;
4933   basic_block new_bb;
4934   edge e;
4935   edge_iterator ei;
4936
4937   new_bb = create_empty_bb (bb);
4938
4939   /* Redirect the outgoing edges.  */
4940   new_bb->succs = bb->succs;
4941   bb->succs = NULL;
4942   FOR_EACH_EDGE (e, ei, new_bb->succs)
4943     e->src = new_bb;
4944
4945   if (stmt && TREE_CODE ((tree) stmt) == LABEL_EXPR)
4946     stmt = NULL;
4947
4948   /* Move everything from BSI to the new basic block.  */
4949   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4950     {
4951       act = bsi_stmt (bsi);
4952       if (TREE_CODE (act) == LABEL_EXPR)
4953         continue;
4954
4955       if (!stmt)
4956         break;
4957
4958       if (stmt == act)
4959         {
4960           bsi_next (&bsi);
4961           break;
4962         }
4963     }
4964
4965   if (bsi_end_p (bsi))
4966     return new_bb;
4967
4968   /* Split the statement list - avoid re-creating new containers as this
4969      brings ugly quadratic memory consumption in the inliner.  
4970      (We are still quadratic since we need to update stmt BB pointers,
4971      sadly.)  */
4972   list = tsi_split_statement_list_before (&bsi.tsi);
4973   set_bb_stmt_list (new_bb, list);
4974   for (tsi_tgt = tsi_start (list);
4975        !tsi_end_p (tsi_tgt); tsi_next (&tsi_tgt))
4976     change_bb_for_stmt (tsi_stmt (tsi_tgt), new_bb);
4977
4978   return new_bb;
4979 }
4980
4981
4982 /* Moves basic block BB after block AFTER.  */
4983
4984 static bool
4985 tree_move_block_after (basic_block bb, basic_block after)
4986 {
4987   if (bb->prev_bb == after)
4988     return true;
4989
4990   unlink_block (bb);
4991   link_block (bb, after);
4992
4993   return true;
4994 }
4995
4996
4997 /* Return true if basic_block can be duplicated.  */
4998
4999 static bool
5000 tree_can_duplicate_bb_p (const_basic_block bb ATTRIBUTE_UNUSED)
5001 {
5002   return true;
5003 }
5004
5005
5006 /* Create a duplicate of the basic block BB.  NOTE: This does not
5007    preserve SSA form.  */
5008
5009 static basic_block
5010 tree_duplicate_bb (basic_block bb)
5011 {
5012   basic_block new_bb;
5013   block_stmt_iterator bsi, bsi_tgt;
5014   tree phi;
5015
5016   new_bb = create_empty_bb (EXIT_BLOCK_PTR->prev_bb);
5017
5018   /* Copy the PHI nodes.  We ignore PHI node arguments here because
5019      the incoming edges have not been setup yet.  */
5020   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
5021     {
5022       tree copy = create_phi_node (PHI_RESULT (phi), new_bb);
5023       create_new_def_for (PHI_RESULT (copy), copy, PHI_RESULT_PTR (copy));
5024     }
5025
5026   /* Keep the chain of PHI nodes in the same order so that they can be
5027      updated by ssa_redirect_edge.  */
5028   set_phi_nodes (new_bb, phi_reverse (phi_nodes (new_bb)));
5029
5030   bsi_tgt = bsi_start (new_bb);
5031   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
5032     {
5033       def_operand_p def_p;
5034       ssa_op_iter op_iter;
5035       tree stmt, copy;
5036       int region;
5037
5038       stmt = bsi_stmt (bsi);
5039       if (TREE_CODE (stmt) == LABEL_EXPR)
5040         continue;
5041
5042       /* Create a new copy of STMT and duplicate STMT's virtual
5043          operands.  */
5044       copy = unshare_expr (stmt);
5045       bsi_insert_after (&bsi_tgt, copy, BSI_NEW_STMT);
5046       copy_virtual_operands (copy, stmt);
5047       region = lookup_stmt_eh_region (stmt);
5048       if (region >= 0)
5049         add_stmt_to_eh_region (copy, region);
5050       gimple_duplicate_stmt_histograms (cfun, copy, cfun, stmt);
5051
5052       /* Create new names for all the definitions created by COPY and
5053          add replacement mappings for each new name.  */
5054       FOR_EACH_SSA_DEF_OPERAND (def_p, copy, op_iter, SSA_OP_ALL_DEFS)
5055         create_new_def_for (DEF_FROM_PTR (def_p), copy, def_p);
5056     }
5057
5058   return new_bb;
5059 }
5060
5061 /* Adds phi node arguments for edge E_COPY after basic block duplication.  */
5062
5063 static void
5064 add_phi_args_after_copy_edge (edge e_copy)
5065 {
5066   basic_block bb, bb_copy = e_copy->src, dest;
5067   edge e;
5068   edge_iterator ei;
5069   tree phi, phi_copy, phi_next, def;
5070
5071   if (!phi_nodes (e_copy->dest))
5072     return;
5073
5074   bb = bb_copy->flags & BB_DUPLICATED ? get_bb_original (bb_copy) : bb_copy;
5075
5076   if (e_copy->dest->flags & BB_DUPLICATED)
5077     dest = get_bb_original (e_copy->dest);
5078   else
5079     dest = e_copy->dest;
5080
5081   e = find_edge (bb, dest);
5082   if (!e)
5083     {
5084       /* During loop unrolling the target of the latch edge is copied.
5085          In this case we are not looking for edge to dest, but to
5086          duplicated block whose original was dest.  */
5087       FOR_EACH_EDGE (e, ei, bb->succs)
5088         {
5089           if ((e->dest->flags & BB_DUPLICATED)
5090               && get_bb_original (e->dest) == dest)
5091             break;
5092         }
5093
5094       gcc_assert (e != NULL);
5095     }
5096
5097   for (phi = phi_nodes (e->dest), phi_copy = phi_nodes (e_copy->dest);
5098        phi;
5099        phi = phi_next, phi_copy = PHI_CHAIN (phi_copy))
5100     {
5101       phi_next = PHI_CHAIN (phi);
5102       def = PHI_ARG_DEF_FROM_EDGE (phi, e);
5103       add_phi_arg (phi_copy, def, e_copy);
5104     }
5105 }
5106
5107
5108 /* Basic block BB_COPY was created by code duplication.  Add phi node
5109    arguments for edges going out of BB_COPY.  The blocks that were
5110    duplicated have BB_DUPLICATED set.  */
5111
5112 void
5113 add_phi_args_after_copy_bb (basic_block bb_copy)
5114 {
5115   edge_iterator ei;
5116   edge e_copy;
5117
5118   FOR_EACH_EDGE (e_copy, ei, bb_copy->succs)
5119     {
5120       add_phi_args_after_copy_edge (e_copy);
5121     }
5122 }
5123
5124 /* Blocks in REGION_COPY array of length N_REGION were created by
5125    duplication of basic blocks.  Add phi node arguments for edges
5126    going from these blocks.  If E_COPY is not NULL, also add
5127    phi node arguments for its destination.*/
5128
5129 void
5130 add_phi_args_after_copy (basic_block *region_copy, unsigned n_region,
5131                          edge e_copy)
5132 {
5133   unsigned i;
5134
5135   for (i = 0; i < n_region; i++)
5136     region_copy[i]->flags |= BB_DUPLICATED;
5137
5138   for (i = 0; i < n_region; i++)
5139     add_phi_args_after_copy_bb (region_copy[i]);
5140   if (e_copy)
5141     add_phi_args_after_copy_edge (e_copy);
5142
5143   for (i = 0; i < n_region; i++)
5144     region_copy[i]->flags &= ~BB_DUPLICATED;
5145 }
5146
5147 /* Duplicates a REGION (set of N_REGION basic blocks) with just a single
5148    important exit edge EXIT.  By important we mean that no SSA name defined
5149    inside region is live over the other exit edges of the region.  All entry
5150    edges to the region must go to ENTRY->dest.  The edge ENTRY is redirected
5151    to the duplicate of the region.  SSA form, dominance and loop information
5152    is updated.  The new basic blocks are stored to REGION_COPY in the same
5153    order as they had in REGION, provided that REGION_COPY is not NULL.
5154    The function returns false if it is unable to copy the region,
5155    true otherwise.  */
5156
5157 bool
5158 tree_duplicate_sese_region (edge entry, edge exit,
5159                             basic_block *region, unsigned n_region,
5160                             basic_block *region_copy)
5161 {
5162   unsigned i;
5163   bool free_region_copy = false, copying_header = false;
5164   struct loop *loop = entry->dest->loop_father;
5165   edge exit_copy;
5166   VEC (basic_block, heap) *doms;
5167   edge redirected;
5168   int total_freq = 0, entry_freq = 0;
5169   gcov_type total_count = 0, entry_count = 0;
5170
5171   if (!can_copy_bbs_p (region, n_region))
5172     return false;
5173
5174   /* Some sanity checking.  Note that we do not check for all possible
5175      missuses of the functions.  I.e. if you ask to copy something weird,
5176      it will work, but the state of structures probably will not be
5177      correct.  */
5178   for (i = 0; i < n_region; i++)
5179     {
5180       /* We do not handle subloops, i.e. all the blocks must belong to the
5181          same loop.  */
5182       if (region[i]->loop_father != loop)
5183         return false;
5184
5185       if (region[i] != entry->dest
5186           && region[i] == loop->header)
5187         return false;
5188     }
5189
5190   set_loop_copy (loop, loop);
5191
5192   /* In case the function is used for loop header copying (which is the primary
5193      use), ensure that EXIT and its copy will be new latch and entry edges.  */
5194   if (loop->header == entry->dest)
5195     {
5196       copying_header = true;
5197       set_loop_copy (loop, loop_outer (loop));
5198
5199       if (!dominated_by_p (CDI_DOMINATORS, loop->latch, exit->src))
5200         return false;
5201
5202       for (i = 0; i < n_region; i++)
5203         if (region[i] != exit->src
5204             && dominated_by_p (CDI_DOMINATORS, region[i], exit->src))
5205           return false;
5206     }
5207
5208   if (!region_copy)
5209     {
5210       region_copy = XNEWVEC (basic_block, n_region);
5211       free_region_copy = true;
5212     }
5213
5214   gcc_assert (!need_ssa_update_p ());
5215
5216   /* Record blocks outside the region that are dominated by something
5217      inside.  */
5218   doms = NULL;
5219   initialize_original_copy_tables ();
5220
5221   doms = get_dominated_by_region (CDI_DOMINATORS, region, n_region);
5222
5223   if (entry->dest->count)
5224     {
5225       total_count = entry->dest->count;
5226       entry_count = entry->count;
5227       /* Fix up corner cases, to avoid division by zero or creation of negative
5228          frequencies.  */
5229       if (entry_count > total_count)
5230         entry_count = total_count;
5231     }
5232   else
5233     {
5234       total_freq = entry->dest->frequency;
5235       entry_freq = EDGE_FREQUENCY (entry);
5236       /* Fix up corner cases, to avoid division by zero or creation of negative
5237          frequencies.  */
5238       if (total_freq == 0)
5239         total_freq = 1;
5240       else if (entry_freq > total_freq)
5241         entry_freq = total_freq;
5242     }
5243
5244   copy_bbs (region, n_region, region_copy, &exit, 1, &exit_copy, loop,
5245             split_edge_bb_loc (entry));
5246   if (total_count)
5247     {
5248       scale_bbs_frequencies_gcov_type (region, n_region,
5249                                        total_count - entry_count,
5250                                        total_count);
5251       scale_bbs_frequencies_gcov_type (region_copy, n_region, entry_count,
5252                                        total_count);
5253     }
5254   else
5255     {
5256       scale_bbs_frequencies_int (region, n_region, total_freq - entry_freq,
5257                                  total_freq);
5258       scale_bbs_frequencies_int (region_copy, n_region, entry_freq, total_freq);
5259     }
5260
5261   if (copying_header)
5262     {
5263       loop->header = exit->dest;
5264       loop->latch = exit->src;
5265     }
5266
5267   /* Redirect the entry and add the phi node arguments.  */
5268   redirected = redirect_edge_and_branch (entry, get_bb_copy (entry->dest));
5269   gcc_assert (redirected != NULL);
5270   flush_pending_stmts (entry);
5271
5272   /* Concerning updating of dominators:  We must recount dominators
5273      for entry block and its copy.  Anything that is outside of the
5274      region, but was dominated by something inside needs recounting as
5275      well.  */
5276   set_immediate_dominator (CDI_DOMINATORS, entry->dest, entry->src);
5277   VEC_safe_push (basic_block, heap, doms, get_bb_original (entry->dest));
5278   iterate_fix_dominators (CDI_DOMINATORS, doms, false);
5279   VEC_free (basic_block, heap, doms);
5280
5281   /* Add the other PHI node arguments.  */
5282   add_phi_args_after_copy (region_copy, n_region, NULL);
5283
5284   /* Update the SSA web.  */
5285   update_ssa (TODO_update_ssa);
5286
5287   if (free_region_copy)
5288     free (region_copy);
5289
5290   free_original_copy_tables ();
5291   return true;
5292 }
5293
5294 /* Duplicates REGION consisting of N_REGION blocks.  The new blocks
5295    are stored to REGION_COPY in the same order in that they appear
5296    in REGION, if REGION_COPY is not NULL.  ENTRY is the entry to
5297    the region, EXIT an exit from it.  The condition guarding EXIT
5298    is moved to ENTRY.  Returns true if duplication succeeds, false
5299    otherwise.
5300
5301    For example, 
5302  
5303    some_code;
5304    if (cond)
5305      A;
5306    else
5307      B;
5308
5309    is transformed to
5310
5311    if (cond)
5312      {
5313        some_code;
5314        A;
5315      }
5316    else
5317      {
5318        some_code;
5319        B;
5320      }
5321 */
5322
5323 bool
5324 tree_duplicate_sese_tail (edge entry, edge exit,
5325                           basic_block *region, unsigned n_region,
5326                           basic_block *region_copy)
5327 {
5328   unsigned i;
5329   bool free_region_copy = false;
5330   struct loop *loop = exit->dest->loop_father;
5331   struct loop *orig_loop = entry->dest->loop_father;
5332   basic_block switch_bb, entry_bb, nentry_bb;
5333   VEC (basic_block, heap) *doms;
5334   int total_freq = 0, exit_freq = 0;
5335   gcov_type total_count = 0, exit_count = 0;
5336   edge exits[2], nexits[2], e;
5337   block_stmt_iterator bsi;
5338   tree cond;
5339   edge sorig, snew;
5340
5341   gcc_assert (EDGE_COUNT (exit->src->succs) == 2);
5342   exits[0] = exit;
5343   exits[1] = EDGE_SUCC (exit->src, EDGE_SUCC (exit->src, 0) == exit);
5344
5345   if (!can_copy_bbs_p (region, n_region))
5346     return false;
5347
5348   /* Some sanity checking.  Note that we do not check for all possible
5349      missuses of the functions.  I.e. if you ask to copy something weird
5350      (e.g., in the example, if there is a jump from inside to the middle
5351      of some_code, or come_code defines some of the values used in cond)
5352      it will work, but the resulting code will not be correct.  */
5353   for (i = 0; i < n_region; i++)
5354     {
5355       /* We do not handle subloops, i.e. all the blocks must belong to the
5356          same loop.  */
5357       if (region[i]->loop_father != orig_loop)
5358         return false;
5359
5360       if (region[i] == orig_loop->latch)
5361         return false;
5362     }
5363
5364   initialize_original_copy_tables ();
5365   set_loop_copy (orig_loop, loop);
5366
5367   if (!region_copy)
5368     {
5369       region_copy = XNEWVEC (basic_block, n_region);
5370       free_region_copy = true;
5371     }
5372
5373   gcc_assert (!need_ssa_update_p ());
5374
5375   /* Record blocks outside the region that are dominated by something
5376      inside.  */
5377   doms = get_dominated_by_region (CDI_DOMINATORS, region, n_region);
5378
5379   if (exit->src->count)
5380     {
5381       total_count = exit->src->count;
5382       exit_count = exit->count;
5383       /* Fix up corner cases, to avoid division by zero or creation of negative
5384          frequencies.  */
5385       if (exit_count > total_count)
5386         exit_count = total_count;
5387     }
5388   else
5389     {
5390       total_freq = exit->src->frequency;
5391       exit_freq = EDGE_FREQUENCY (exit);
5392       /* Fix up corner cases, to avoid division by zero or creation of negative
5393          frequencies.  */
5394       if (total_freq == 0)
5395         total_freq = 1;
5396       if (exit_freq > total_freq)
5397         exit_freq = total_freq;
5398     }
5399
5400   copy_bbs (region, n_region, region_copy, exits, 2, nexits, orig_loop,
5401             split_edge_bb_loc (exit));
5402   if (total_count)
5403     {
5404       scale_bbs_frequencies_gcov_type (region, n_region,
5405                                        total_count - exit_count,
5406                                        total_count);
5407       scale_bbs_frequencies_gcov_type (region_copy, n_region, exit_count,
5408                                        total_count);
5409     }
5410   else
5411     {
5412       scale_bbs_frequencies_int (region, n_region, total_freq - exit_freq,
5413                                  total_freq);
5414       scale_bbs_frequencies_int (region_copy, n_region, exit_freq, total_freq);
5415     }
5416
5417   /* Create the switch block, and put the exit condition to it.  */
5418   entry_bb = entry->dest;
5419   nentry_bb = get_bb_copy (entry_bb);
5420   if (!last_stmt (entry->src)
5421       || !stmt_ends_bb_p (last_stmt (entry->src)))
5422     switch_bb = entry->src;
5423   else
5424     switch_bb = split_edge (entry);
5425   set_immediate_dominator (CDI_DOMINATORS, nentry_bb, switch_bb);
5426
5427   bsi = bsi_last (switch_bb);
5428   cond = last_stmt (exit->src);
5429   gcc_assert (TREE_CODE (cond) == COND_EXPR);
5430   bsi_insert_after (&bsi, unshare_expr (cond), BSI_NEW_STMT);
5431
5432   sorig = single_succ_edge (switch_bb);
5433   sorig->flags = exits[1]->flags;
5434   snew = make_edge (switch_bb, nentry_bb, exits[0]->flags);
5435
5436   /* Register the new edge from SWITCH_BB in loop exit lists.  */
5437   rescan_loop_exit (snew, true, false);
5438
5439   /* Add the PHI node arguments.  */
5440   add_phi_args_after_copy (region_copy, n_region, snew);
5441
5442   /* Get rid of now superfluous conditions and associated edges (and phi node
5443      arguments).  */
5444   e = redirect_edge_and_branch (exits[0], exits[1]->dest);
5445   PENDING_STMT (e) = NULL_TREE;
5446   e = redirect_edge_and_branch (nexits[1], nexits[0]->dest);
5447   PENDING_STMT (e) = NULL_TREE;
5448
5449   /* Anything that is outside of the region, but was dominated by something
5450      inside needs to update dominance info.  */
5451   iterate_fix_dominators (CDI_DOMINATORS, doms, false);
5452   VEC_free (basic_block, heap, doms);
5453
5454   /* Update the SSA web.  */
5455   update_ssa (TODO_update_ssa);
5456
5457   if (free_region_copy)
5458     free (region_copy);
5459
5460   free_original_copy_tables ();
5461   return true;
5462 }
5463
5464 /*
5465 DEF_VEC_P(basic_block);
5466 DEF_VEC_ALLOC_P(basic_block,heap);
5467 */
5468
5469 /* Add all the blocks dominated by ENTRY to the array BBS_P.  Stop
5470    adding blocks when the dominator traversal reaches EXIT.  This
5471    function silently assumes that ENTRY strictly dominates EXIT.  */
5472
5473 static void
5474 gather_blocks_in_sese_region (basic_block entry, basic_block exit,
5475                               VEC(basic_block,heap) **bbs_p)
5476 {
5477   basic_block son;
5478
5479   for (son = first_dom_son (CDI_DOMINATORS, entry);
5480        son;
5481        son = next_dom_son (CDI_DOMINATORS, son))
5482     {
5483       VEC_safe_push (basic_block, heap, *bbs_p, son);
5484       if (son != exit)
5485         gather_blocks_in_sese_region (son, exit, bbs_p);
5486     }
5487 }
5488
5489 /* Replaces *TP with a duplicate (belonging to function TO_CONTEXT).
5490    The duplicates are recorded in VARS_MAP.  */
5491
5492 static void
5493 replace_by_duplicate_decl (tree *tp, struct pointer_map_t *vars_map,
5494                            tree to_context)
5495 {
5496   tree t = *tp, new_t;
5497   struct function *f = DECL_STRUCT_FUNCTION (to_context);
5498   void **loc;
5499
5500   if (DECL_CONTEXT (t) == to_context)
5501     return;
5502
5503   loc = pointer_map_contains (vars_map, t);
5504
5505   if (!loc)
5506     {
5507       loc = pointer_map_insert (vars_map, t);
5508
5509       if (SSA_VAR_P (t))
5510         {
5511           new_t = copy_var_decl (t, DECL_NAME (t), TREE_TYPE (t));
5512           f->unexpanded_var_list
5513                   = tree_cons (NULL_TREE, new_t, f->unexpanded_var_list);
5514         }
5515       else
5516         {
5517           gcc_assert (TREE_CODE (t) == CONST_DECL);
5518           new_t = copy_node (t);
5519         }
5520       DECL_CONTEXT (new_t) = to_context;
5521
5522       *loc = new_t;
5523     }
5524   else
5525     new_t = *loc;
5526
5527   *tp = new_t;
5528 }
5529
5530 /* Creates an ssa name in TO_CONTEXT equivalent to NAME.
5531    VARS_MAP maps old ssa names and var_decls to the new ones.  */
5532
5533 static tree
5534 replace_ssa_name (tree name, struct pointer_map_t *vars_map,
5535                   tree to_context)
5536 {
5537   void **loc;
5538   tree new_name, decl = SSA_NAME_VAR (name);
5539
5540   gcc_assert (is_gimple_reg (name));
5541
5542   loc = pointer_map_contains (vars_map, name);
5543
5544   if (!loc)
5545     {
5546       replace_by_duplicate_decl (&decl, vars_map, to_context);
5547
5548       push_cfun (DECL_STRUCT_FUNCTION (to_context));
5549       if (gimple_in_ssa_p (cfun))
5550         add_referenced_var (decl);
5551
5552       new_name = make_ssa_name (decl, SSA_NAME_DEF_STMT (name));
5553       if (SSA_NAME_IS_DEFAULT_DEF (name))
5554         set_default_def (decl, new_name);
5555       pop_cfun ();
5556
5557       loc = pointer_map_insert (vars_map, name);
5558       *loc = new_name;
5559     }
5560   else
5561     new_name = *loc;
5562
5563   return new_name;
5564 }
5565
5566 struct move_stmt_d
5567 {
5568   tree block;
5569   tree from_context;
5570   tree to_context;
5571   struct pointer_map_t *vars_map;
5572   htab_t new_label_map;
5573   bool remap_decls_p;
5574 };
5575
5576 /* Helper for move_block_to_fn.  Set TREE_BLOCK in every expression
5577    contained in *TP and change the DECL_CONTEXT of every local
5578    variable referenced in *TP.  */
5579
5580 static tree
5581 move_stmt_r (tree *tp, int *walk_subtrees, void *data)
5582 {
5583   struct move_stmt_d *p = (struct move_stmt_d *) data;
5584   tree t = *tp;
5585
5586   if (p->block
5587       && (EXPR_P (t) || GIMPLE_STMT_P (t)))
5588     TREE_BLOCK (t) = p->block;
5589
5590   if (OMP_DIRECTIVE_P (t)
5591       && TREE_CODE (t) != OMP_RETURN
5592       && TREE_CODE (t) != OMP_CONTINUE)
5593     {
5594       /* Do not remap variables inside OMP directives.  Variables
5595          referenced in clauses and directive header belong to the
5596          parent function and should not be moved into the child
5597          function.  */
5598       bool save_remap_decls_p = p->remap_decls_p;
5599       p->remap_decls_p = false;
5600       *walk_subtrees = 0;
5601
5602       walk_tree (&OMP_BODY (t), move_stmt_r, p, NULL);
5603
5604       p->remap_decls_p = save_remap_decls_p;
5605     }
5606   else if (DECL_P (t) || TREE_CODE (t) == SSA_NAME)
5607     {
5608       if (TREE_CODE (t) == SSA_NAME)
5609         *tp = replace_ssa_name (t, p->vars_map, p->to_context);
5610       else if (TREE_CODE (t) == LABEL_DECL)
5611         {
5612           if (p->new_label_map)
5613             {
5614               struct tree_map in, *out;
5615               in.base.from = t;
5616               out = htab_find_with_hash (p->new_label_map, &in, DECL_UID (t));
5617               if (out)
5618                 *tp = t = out->to;
5619             }
5620
5621           DECL_CONTEXT (t) = p->to_context;
5622         }
5623       else if (p->remap_decls_p)
5624         {
5625           /* Replace T with its duplicate.  T should no longer appear in the
5626              parent function, so this looks wasteful; however, it may appear
5627              in referenced_vars, and more importantly, as virtual operands of
5628              statements, and in alias lists of other variables.  It would be
5629              quite difficult to expunge it from all those places.  ??? It might
5630              suffice to do this for addressable variables.  */
5631           if ((TREE_CODE (t) == VAR_DECL
5632                && !is_global_var (t))
5633               || TREE_CODE (t) == CONST_DECL)
5634             replace_by_duplicate_decl (tp, p->vars_map, p->to_context);
5635           
5636           if (SSA_VAR_P (t)
5637               && gimple_in_ssa_p (cfun))
5638             {
5639               push_cfun (DECL_STRUCT_FUNCTION (p->to_context));
5640               add_referenced_var (*tp);
5641               pop_cfun ();
5642             }
5643         }
5644       *walk_subtrees = 0;
5645     }
5646   else if (TYPE_P (t))
5647     *walk_subtrees = 0;
5648
5649   return NULL_TREE;
5650 }
5651
5652 /* Marks virtual operands of all statements in basic blocks BBS for
5653    renaming.  */
5654
5655 static void
5656 mark_virtual_ops_in_region (VEC (basic_block,heap) *bbs)
5657 {
5658   tree phi;
5659   block_stmt_iterator bsi;
5660   basic_block bb;
5661   unsigned i;
5662
5663   for (i = 0; VEC_iterate (basic_block, bbs, i, bb); i++)
5664     {
5665       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
5666         mark_virtual_ops_for_renaming (phi);
5667
5668       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
5669         mark_virtual_ops_for_renaming (bsi_stmt (bsi));
5670     }
5671 }
5672
5673 /* Move basic block BB from function CFUN to function DEST_FN.  The
5674    block is moved out of the original linked list and placed after
5675    block AFTER in the new list.  Also, the block is removed from the
5676    original array of blocks and placed in DEST_FN's array of blocks.
5677    If UPDATE_EDGE_COUNT_P is true, the edge counts on both CFGs is
5678    updated to reflect the moved edges.
5679
5680    The local variables are remapped to new instances, VARS_MAP is used
5681    to record the mapping.  */
5682
5683 static void
5684 move_block_to_fn (struct function *dest_cfun, basic_block bb,
5685                   basic_block after, bool update_edge_count_p,
5686                   struct pointer_map_t *vars_map, htab_t new_label_map,
5687                   int eh_offset)
5688 {
5689   struct control_flow_graph *cfg;
5690   edge_iterator ei;
5691   edge e;
5692   block_stmt_iterator si;
5693   struct move_stmt_d d;
5694   unsigned old_len, new_len;
5695   tree phi, next_phi;
5696
5697   /* Remove BB from dominance structures.  */
5698   delete_from_dominance_info (CDI_DOMINATORS, bb);
5699   if (current_loops)
5700     remove_bb_from_loops (bb);
5701
5702   /* Link BB to the new linked list.  */
5703   move_block_after (bb, after);
5704
5705   /* Update the edge count in the corresponding flowgraphs.  */
5706   if (update_edge_count_p)
5707     FOR_EACH_EDGE (e, ei, bb->succs)
5708       {
5709         cfun->cfg->x_n_edges--;
5710         dest_cfun->cfg->x_n_edges++;
5711       }
5712
5713   /* Remove BB from the original basic block array.  */
5714   VEC_replace (basic_block, cfun->cfg->x_basic_block_info, bb->index, NULL);
5715   cfun->cfg->x_n_basic_blocks--;
5716
5717   /* Grow DEST_CFUN's basic block array if needed.  */
5718   cfg = dest_cfun->cfg;
5719   cfg->x_n_basic_blocks++;
5720   if (bb->index >= cfg->x_last_basic_block)
5721     cfg->x_last_basic_block = bb->index + 1;
5722
5723   old_len = VEC_length (basic_block, cfg->x_basic_block_info);
5724   if ((unsigned) cfg->x_last_basic_block >= old_len)
5725     {
5726       new_len = cfg->x_last_basic_block + (cfg->x_last_basic_block + 3) / 4;
5727       VEC_safe_grow_cleared (basic_block, gc, cfg->x_basic_block_info,
5728                              new_len);
5729     }
5730
5731   VEC_replace (basic_block, cfg->x_basic_block_info,
5732                bb->index, bb);
5733
5734   /* Remap the variables in phi nodes.  */
5735   for (phi = phi_nodes (bb); phi; phi = next_phi)
5736     {
5737       use_operand_p use;
5738       tree op = PHI_RESULT (phi);
5739       ssa_op_iter oi;
5740
5741       next_phi = PHI_CHAIN (phi);
5742       if (!is_gimple_reg (op))
5743         {
5744           /* Remove the phi nodes for virtual operands (alias analysis will be
5745              run for the new function, anyway).  */
5746           remove_phi_node (phi, NULL, true);
5747           continue;
5748         }
5749
5750       SET_PHI_RESULT (phi, replace_ssa_name (op, vars_map, dest_cfun->decl));
5751       FOR_EACH_PHI_ARG (use, phi, oi, SSA_OP_USE)
5752         {
5753           op = USE_FROM_PTR (use);
5754           if (TREE_CODE (op) == SSA_NAME)
5755             SET_USE (use, replace_ssa_name (op, vars_map, dest_cfun->decl));
5756         }
5757     }
5758
5759   /* The statements in BB need to be associated with a new TREE_BLOCK.
5760      Labels need to be associated with a new label-to-block map.  */
5761   memset (&d, 0, sizeof (d));
5762   d.vars_map = vars_map;
5763   d.from_context = cfun->decl;
5764   d.to_context = dest_cfun->decl;
5765   d.new_label_map = new_label_map;
5766
5767   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
5768     {
5769       tree stmt = bsi_stmt (si);
5770       int region;
5771
5772       d.remap_decls_p = true;
5773       if (TREE_BLOCK (stmt))
5774         d.block = DECL_INITIAL (dest_cfun->decl);
5775
5776       walk_tree (&stmt, move_stmt_r, &d, NULL);
5777
5778       if (TREE_CODE (stmt) == LABEL_EXPR)
5779         {
5780           tree label = LABEL_EXPR_LABEL (stmt);
5781           int uid = LABEL_DECL_UID (label);
5782
5783           gcc_assert (uid > -1);
5784
5785           old_len = VEC_length (basic_block, cfg->x_label_to_block_map);
5786           if (old_len <= (unsigned) uid)
5787             {
5788               new_len = 3 * uid / 2;
5789               VEC_safe_grow_cleared (basic_block, gc,
5790                                      cfg->x_label_to_block_map, new_len);
5791             }
5792
5793           VEC_replace (basic_block, cfg->x_label_to_block_map, uid, bb);
5794           VEC_replace (basic_block, cfun->cfg->x_label_to_block_map, uid, NULL);
5795
5796           gcc_assert (DECL_CONTEXT (label) == dest_cfun->decl);
5797
5798           if (uid >= dest_cfun->last_label_uid)
5799             dest_cfun->last_label_uid = uid + 1;
5800         }
5801       else if (TREE_CODE (stmt) == RESX_EXPR && eh_offset != 0)
5802         TREE_OPERAND (stmt, 0) =
5803           build_int_cst (NULL_TREE,
5804                          TREE_INT_CST_LOW (TREE_OPERAND (stmt, 0))
5805                          + eh_offset);
5806
5807       region = lookup_stmt_eh_region (stmt);
5808       if (region >= 0)
5809         {
5810           add_stmt_to_eh_region_fn (dest_cfun, stmt, region + eh_offset);
5811           remove_stmt_from_eh_region (stmt);
5812           gimple_duplicate_stmt_histograms (dest_cfun, stmt, cfun, stmt);
5813           gimple_remove_stmt_histograms (cfun, stmt);
5814         }
5815
5816       /* We cannot leave any operands allocated from the operand caches of
5817          the current function.  */
5818       free_stmt_operands (stmt);
5819       push_cfun (dest_cfun);
5820       update_stmt (stmt);
5821       pop_cfun ();
5822     }
5823 }
5824
5825 /* Examine the statements in BB (which is in SRC_CFUN); find and return
5826    the outermost EH region.  Use REGION as the incoming base EH region.  */
5827
5828 static int
5829 find_outermost_region_in_block (struct function *src_cfun,
5830                                 basic_block bb, int region)
5831 {
5832   block_stmt_iterator si;
5833
5834   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
5835     {
5836       tree stmt = bsi_stmt (si);
5837       int stmt_region;
5838
5839       if (TREE_CODE (stmt) == RESX_EXPR)
5840         stmt_region = TREE_INT_CST_LOW (TREE_OPERAND (stmt, 0));
5841       else
5842         stmt_region = lookup_stmt_eh_region_fn (src_cfun, stmt);
5843       if (stmt_region > 0)
5844         {
5845           if (region < 0)
5846             region = stmt_region;
5847           else if (stmt_region != region)
5848             {
5849               region = eh_region_outermost (src_cfun, stmt_region, region);
5850               gcc_assert (region != -1);
5851             }
5852         }
5853     }
5854
5855   return region;
5856 }
5857
5858 static tree
5859 new_label_mapper (tree decl, void *data)
5860 {
5861   htab_t hash = (htab_t) data;
5862   struct tree_map *m;
5863   void **slot;
5864
5865   gcc_assert (TREE_CODE (decl) == LABEL_DECL);
5866
5867   m = xmalloc (sizeof (struct tree_map));
5868   m->hash = DECL_UID (decl);
5869   m->base.from = decl;
5870   m->to = create_artificial_label ();
5871   LABEL_DECL_UID (m->to) = LABEL_DECL_UID (decl);
5872
5873   slot = htab_find_slot_with_hash (hash, m, m->hash, INSERT);
5874   gcc_assert (*slot == NULL);
5875
5876   *slot = m;
5877
5878   return m->to;
5879 }
5880
5881 /* Move a single-entry, single-exit region delimited by ENTRY_BB and
5882    EXIT_BB to function DEST_CFUN.  The whole region is replaced by a
5883    single basic block in the original CFG and the new basic block is
5884    returned.  DEST_CFUN must not have a CFG yet.
5885
5886    Note that the region need not be a pure SESE region.  Blocks inside
5887    the region may contain calls to abort/exit.  The only restriction
5888    is that ENTRY_BB should be the only entry point and it must
5889    dominate EXIT_BB.
5890
5891    All local variables referenced in the region are assumed to be in
5892    the corresponding BLOCK_VARS and unexpanded variable lists
5893    associated with DEST_CFUN.  */
5894
5895 basic_block
5896 move_sese_region_to_fn (struct function *dest_cfun, basic_block entry_bb,
5897                         basic_block exit_bb)
5898 {
5899   VEC(basic_block,heap) *bbs, *dom_bbs;
5900   basic_block dom_entry = get_immediate_dominator (CDI_DOMINATORS, entry_bb);
5901   basic_block after, bb, *entry_pred, *exit_succ, abb;
5902   struct function *saved_cfun = cfun;
5903   int *entry_flag, *exit_flag, eh_offset;
5904   unsigned *entry_prob, *exit_prob;
5905   unsigned i, num_entry_edges, num_exit_edges;
5906   edge e;
5907   edge_iterator ei;
5908   htab_t new_label_map;
5909   struct pointer_map_t *vars_map;
5910   struct loop *loop = entry_bb->loop_father;
5911
5912   /* If ENTRY does not strictly dominate EXIT, this cannot be an SESE
5913      region.  */
5914   gcc_assert (entry_bb != exit_bb
5915               && (!exit_bb
5916                   || dominated_by_p (CDI_DOMINATORS, exit_bb, entry_bb)));
5917
5918   /* Collect all the blocks in the region.  Manually add ENTRY_BB
5919      because it won't be added by dfs_enumerate_from.  */
5920   bbs = NULL;
5921   VEC_safe_push (basic_block, heap, bbs, entry_bb);
5922   gather_blocks_in_sese_region (entry_bb, exit_bb, &bbs);
5923
5924   /* The blocks that used to be dominated by something in BBS will now be
5925      dominated by the new block.  */
5926   dom_bbs = get_dominated_by_region (CDI_DOMINATORS,
5927                                      VEC_address (basic_block, bbs),
5928                                      VEC_length (basic_block, bbs));
5929
5930   /* Detach ENTRY_BB and EXIT_BB from CFUN->CFG.  We need to remember
5931      the predecessor edges to ENTRY_BB and the successor edges to
5932      EXIT_BB so that we can re-attach them to the new basic block that
5933      will replace the region.  */
5934   num_entry_edges = EDGE_COUNT (entry_bb->preds);
5935   entry_pred = (basic_block *) xcalloc (num_entry_edges, sizeof (basic_block));
5936   entry_flag = (int *) xcalloc (num_entry_edges, sizeof (int));
5937   entry_prob = XNEWVEC (unsigned, num_entry_edges);
5938   i = 0;
5939   for (ei = ei_start (entry_bb->preds); (e = ei_safe_edge (ei)) != NULL;)
5940     {
5941       entry_prob[i] = e->probability;
5942       entry_flag[i] = e->flags;
5943       entry_pred[i++] = e->src;
5944       remove_edge (e);
5945     }
5946
5947   if (exit_bb)
5948     {
5949       num_exit_edges = EDGE_COUNT (exit_bb->succs);
5950       exit_succ = (basic_block *) xcalloc (num_exit_edges,
5951                                            sizeof (basic_block));
5952       exit_flag = (int *) xcalloc (num_exit_edges, sizeof (int));
5953       exit_prob = XNEWVEC (unsigned, num_exit_edges);
5954       i = 0;
5955       for (ei = ei_start (exit_bb->succs); (e = ei_safe_edge (ei)) != NULL;)
5956         {
5957           exit_prob[i] = e->probability;
5958           exit_flag[i] = e->flags;
5959           exit_succ[i++] = e->dest;
5960           remove_edge (e);
5961         }
5962     }
5963   else
5964     {
5965       num_exit_edges = 0;
5966       exit_succ = NULL;
5967       exit_flag = NULL;
5968       exit_prob = NULL;
5969     }
5970
5971   /* Switch context to the child function to initialize DEST_FN's CFG.  */
5972   gcc_assert (dest_cfun->cfg == NULL);
5973   push_cfun (dest_cfun);
5974
5975   init_empty_tree_cfg ();
5976
5977   /* Initialize EH information for the new function.  */
5978   eh_offset = 0;
5979   new_label_map = NULL;
5980   if (saved_cfun->eh)
5981     {
5982       int region = -1;
5983
5984       for (i = 0; VEC_iterate (basic_block, bbs, i, bb); i++)
5985         region = find_outermost_region_in_block (saved_cfun, bb, region);
5986
5987       init_eh_for_function ();
5988       if (region != -1)
5989         {
5990           new_label_map = htab_create (17, tree_map_hash, tree_map_eq, free);
5991           eh_offset = duplicate_eh_regions (saved_cfun, new_label_mapper,
5992                                             new_label_map, region, 0);
5993         }
5994     }
5995
5996   pop_cfun ();
5997
5998   /* The ssa form for virtual operands in the source function will have to
5999      be repaired.  We do not care for the real operands -- the sese region
6000      must be closed with respect to those.  */
6001   mark_virtual_ops_in_region (bbs);
6002
6003   /* Move blocks from BBS into DEST_CFUN.  */
6004   gcc_assert (VEC_length (basic_block, bbs) >= 2);
6005   after = dest_cfun->cfg->x_entry_block_ptr;
6006   vars_map = pointer_map_create ();
6007   for (i = 0; VEC_iterate (basic_block, bbs, i, bb); i++)
6008     {
6009       /* No need to update edge counts on the last block.  It has
6010          already been updated earlier when we detached the region from
6011          the original CFG.  */
6012       move_block_to_fn (dest_cfun, bb, after, bb != exit_bb, vars_map,
6013                         new_label_map, eh_offset);
6014       after = bb;
6015     }
6016
6017   if (new_label_map)
6018     htab_delete (new_label_map);
6019   pointer_map_destroy (vars_map);
6020
6021   /* Rewire the entry and exit blocks.  The successor to the entry
6022      block turns into the successor of DEST_FN's ENTRY_BLOCK_PTR in
6023      the child function.  Similarly, the predecessor of DEST_FN's
6024      EXIT_BLOCK_PTR turns into the predecessor of EXIT_BLOCK_PTR.  We
6025      need to switch CFUN between DEST_CFUN and SAVED_CFUN so that the
6026      various CFG manipulation function get to the right CFG.
6027
6028      FIXME, this is silly.  The CFG ought to become a parameter to
6029      these helpers.  */
6030   push_cfun (dest_cfun);
6031   make_edge (ENTRY_BLOCK_PTR, entry_bb, EDGE_FALLTHRU);
6032   if (exit_bb)
6033     make_edge (exit_bb,  EXIT_BLOCK_PTR, 0);
6034   pop_cfun ();
6035
6036   /* Back in the original function, the SESE region has disappeared,
6037      create a new basic block in its place.  */
6038   bb = create_empty_bb (entry_pred[0]);
6039   if (current_loops)
6040     add_bb_to_loop (bb, loop);
6041   for (i = 0; i < num_entry_edges; i++)
6042     {
6043       e = make_edge (entry_pred[i], bb, entry_flag[i]);
6044       e->probability = entry_prob[i];
6045     }
6046
6047   for (i = 0; i < num_exit_edges; i++)
6048     {
6049       e = make_edge (bb, exit_succ[i], exit_flag[i]);
6050       e->probability = exit_prob[i];
6051     }
6052
6053   set_immediate_dominator (CDI_DOMINATORS, bb, dom_entry);
6054   for (i = 0; VEC_iterate (basic_block, dom_bbs, i, abb); i++)
6055     set_immediate_dominator (CDI_DOMINATORS, abb, bb);
6056   VEC_free (basic_block, heap, dom_bbs);
6057
6058   if (exit_bb)
6059     {
6060       free (exit_prob);
6061       free (exit_flag);
6062       free (exit_succ);
6063     }
6064   free (entry_prob);
6065   free (entry_flag);
6066   free (entry_pred);
6067   VEC_free (basic_block, heap, bbs);
6068
6069   return bb;
6070 }
6071
6072
6073 /* Dump FUNCTION_DECL FN to file FILE using FLAGS (see TDF_* in tree.h)  */
6074
6075 void
6076 dump_function_to_file (tree fn, FILE *file, int flags)
6077 {
6078   tree arg, vars, var;
6079   struct function *dsf;
6080   bool ignore_topmost_bind = false, any_var = false;
6081   basic_block bb;
6082   tree chain;
6083
6084   fprintf (file, "%s (", lang_hooks.decl_printable_name (fn, 2));
6085
6086   arg = DECL_ARGUMENTS (fn);
6087   while (arg)
6088     {
6089       print_generic_expr (file, arg, dump_flags);
6090       if (TREE_CHAIN (arg))
6091         fprintf (file, ", ");
6092       arg = TREE_CHAIN (arg);
6093     }
6094   fprintf (file, ")\n");
6095
6096   dsf = DECL_STRUCT_FUNCTION (fn);
6097   if (dsf && (flags & TDF_DETAILS))
6098     dump_eh_tree (file, dsf);
6099
6100   if (flags & TDF_RAW)
6101     {
6102       dump_node (fn, TDF_SLIM | flags, file);
6103       return;
6104     }
6105
6106   /* Switch CFUN to point to FN.  */
6107   push_cfun (DECL_STRUCT_FUNCTION (fn));
6108
6109   /* When GIMPLE is lowered, the variables are no longer available in
6110      BIND_EXPRs, so display them separately.  */
6111   if (cfun && cfun->decl == fn && cfun->unexpanded_var_list)
6112     {
6113       ignore_topmost_bind = true;
6114
6115       fprintf (file, "{\n");
6116       for (vars = cfun->unexpanded_var_list; vars; vars = TREE_CHAIN (vars))
6117         {
6118           var = TREE_VALUE (vars);
6119
6120           print_generic_decl (file, var, flags);
6121           fprintf (file, "\n");
6122
6123           any_var = true;
6124         }
6125     }
6126
6127   if (cfun && cfun->decl == fn && cfun->cfg && basic_block_info)
6128     {
6129       /* Make a CFG based dump.  */
6130       check_bb_profile (ENTRY_BLOCK_PTR, file);
6131       if (!ignore_topmost_bind)
6132         fprintf (file, "{\n");
6133
6134       if (any_var && n_basic_blocks)
6135         fprintf (file, "\n");
6136
6137       FOR_EACH_BB (bb)
6138         dump_generic_bb (file, bb, 2, flags);
6139
6140       fprintf (file, "}\n");
6141       check_bb_profile (EXIT_BLOCK_PTR, file);
6142     }
6143   else
6144     {
6145       int indent;
6146
6147       /* Make a tree based dump.  */
6148       chain = DECL_SAVED_TREE (fn);
6149
6150       if (chain && TREE_CODE (chain) == BIND_EXPR)
6151         {
6152           if (ignore_topmost_bind)
6153             {
6154               chain = BIND_EXPR_BODY (chain);
6155               indent = 2;
6156             }
6157           else
6158             indent = 0;
6159         }
6160       else
6161         {
6162           if (!ignore_topmost_bind)
6163             fprintf (file, "{\n");
6164           indent = 2;
6165         }
6166
6167       if (any_var)
6168         fprintf (file, "\n");
6169
6170       print_generic_stmt_indented (file, chain, flags, indent);
6171       if (ignore_topmost_bind)
6172         fprintf (file, "}\n");
6173     }
6174
6175   fprintf (file, "\n\n");
6176
6177   /* Restore CFUN.  */
6178   pop_cfun ();
6179 }
6180
6181
6182 /* Dump FUNCTION_DECL FN to stderr using FLAGS (see TDF_* in tree.h)  */
6183
6184 void
6185 debug_function (tree fn, int flags)
6186 {
6187   dump_function_to_file (fn, stderr, flags);
6188 }
6189
6190
6191 /* Pretty print of the loops intermediate representation.  */
6192 static void print_loop (FILE *, struct loop *, int);
6193 static void print_pred_bbs (FILE *, basic_block bb);
6194 static void print_succ_bbs (FILE *, basic_block bb);
6195
6196
6197 /* Print on FILE the indexes for the predecessors of basic_block BB.  */
6198
6199 static void
6200 print_pred_bbs (FILE *file, basic_block bb)
6201 {
6202   edge e;
6203   edge_iterator ei;
6204
6205   FOR_EACH_EDGE (e, ei, bb->preds)
6206     fprintf (file, "bb_%d ", e->src->index);
6207 }
6208
6209
6210 /* Print on FILE the indexes for the successors of basic_block BB.  */
6211
6212 static void
6213 print_succ_bbs (FILE *file, basic_block bb)
6214 {
6215   edge e;
6216   edge_iterator ei;
6217
6218   FOR_EACH_EDGE (e, ei, bb->succs)
6219     fprintf (file, "bb_%d ", e->dest->index);
6220 }
6221
6222
6223 /* Pretty print LOOP on FILE, indented INDENT spaces.  */
6224
6225 static void
6226 print_loop (FILE *file, struct loop *loop, int indent)
6227 {
6228   char *s_indent;
6229   basic_block bb;
6230
6231   if (loop == NULL)
6232     return;
6233
6234   s_indent = (char *) alloca ((size_t) indent + 1);
6235   memset ((void *) s_indent, ' ', (size_t) indent);
6236   s_indent[indent] = '\0';
6237
6238   /* Print the loop's header.  */
6239   fprintf (file, "%sloop_%d\n", s_indent, loop->num);
6240
6241   /* Print the loop's body.  */
6242   fprintf (file, "%s{\n", s_indent);
6243   FOR_EACH_BB (bb)
6244     if (bb->loop_father == loop)
6245       {
6246         /* Print the basic_block's header.  */
6247         fprintf (file, "%s  bb_%d (preds = {", s_indent, bb->index);
6248         print_pred_bbs (file, bb);
6249         fprintf (file, "}, succs = {");
6250         print_succ_bbs (file, bb);
6251         fprintf (file, "})\n");
6252
6253         /* Print the basic_block's body.  */
6254         fprintf (file, "%s  {\n", s_indent);
6255         tree_dump_bb (bb, file, indent + 4);
6256         fprintf (file, "%s  }\n", s_indent);
6257       }
6258
6259   print_loop (file, loop->inner, indent + 2);
6260   fprintf (file, "%s}\n", s_indent);
6261   print_loop (file, loop->next, indent);
6262 }
6263
6264
6265 /* Follow a CFG edge from the entry point of the program, and on entry
6266    of a loop, pretty print the loop structure on FILE.  */
6267
6268 void
6269 print_loop_ir (FILE *file)
6270 {
6271   basic_block bb;
6272
6273   bb = BASIC_BLOCK (NUM_FIXED_BLOCKS);
6274   if (bb && bb->loop_father)
6275     print_loop (file, bb->loop_father, 0);
6276 }
6277
6278
6279 /* Debugging loops structure at tree level.  */
6280
6281 void
6282 debug_loop_ir (void)
6283 {
6284   print_loop_ir (stderr);
6285 }
6286
6287
6288 /* Return true if BB ends with a call, possibly followed by some
6289    instructions that must stay with the call.  Return false,
6290    otherwise.  */
6291
6292 static bool
6293 tree_block_ends_with_call_p (basic_block bb)
6294 {
6295   block_stmt_iterator bsi = bsi_last (bb);
6296   return get_call_expr_in (bsi_stmt (bsi)) != NULL;
6297 }
6298
6299
6300 /* Return true if BB ends with a conditional branch.  Return false,
6301    otherwise.  */
6302
6303 static bool
6304 tree_block_ends_with_condjump_p (const_basic_block bb)
6305 {
6306   /* This CONST_CAST is okay because last_stmt doesn't modify its
6307      argument and the return value is not modified.  */
6308   const_tree stmt = last_stmt (CONST_CAST_BB(bb));
6309   return (stmt && TREE_CODE (stmt) == COND_EXPR);
6310 }
6311
6312
6313 /* Return true if we need to add fake edge to exit at statement T.
6314    Helper function for tree_flow_call_edges_add.  */
6315
6316 static bool
6317 need_fake_edge_p (tree t)
6318 {
6319   tree call;
6320
6321   /* NORETURN and LONGJMP calls already have an edge to exit.
6322      CONST and PURE calls do not need one.
6323      We don't currently check for CONST and PURE here, although
6324      it would be a good idea, because those attributes are
6325      figured out from the RTL in mark_constant_function, and
6326      the counter incrementation code from -fprofile-arcs
6327      leads to different results from -fbranch-probabilities.  */
6328   call = get_call_expr_in (t);
6329   if (call
6330       && !(call_expr_flags (call) & ECF_NORETURN))
6331     return true;
6332
6333   if (TREE_CODE (t) == ASM_EXPR
6334        && (ASM_VOLATILE_P (t) || ASM_INPUT_P (t)))
6335     return true;
6336
6337   return false;
6338 }
6339
6340
6341 /* Add fake edges to the function exit for any non constant and non
6342    noreturn calls, volatile inline assembly in the bitmap of blocks
6343    specified by BLOCKS or to the whole CFG if BLOCKS is zero.  Return
6344    the number of blocks that were split.
6345
6346    The goal is to expose cases in which entering a basic block does
6347    not imply that all subsequent instructions must be executed.  */
6348
6349 static int
6350 tree_flow_call_edges_add (sbitmap blocks)
6351 {
6352   int i;
6353   int blocks_split = 0;
6354   int last_bb = last_basic_block;
6355   bool check_last_block = false;
6356
6357   if (n_basic_blocks == NUM_FIXED_BLOCKS)
6358     return 0;
6359
6360   if (! blocks)
6361     check_last_block = true;
6362   else
6363     check_last_block = TEST_BIT (blocks, EXIT_BLOCK_PTR->prev_bb->index);
6364
6365   /* In the last basic block, before epilogue generation, there will be
6366      a fallthru edge to EXIT.  Special care is required if the last insn
6367      of the last basic block is a call because make_edge folds duplicate
6368      edges, which would result in the fallthru edge also being marked
6369      fake, which would result in the fallthru edge being removed by
6370      remove_fake_edges, which would result in an invalid CFG.
6371
6372      Moreover, we can't elide the outgoing fake edge, since the block
6373      profiler needs to take this into account in order to solve the minimal
6374      spanning tree in the case that the call doesn't return.
6375
6376      Handle this by adding a dummy instruction in a new last basic block.  */
6377   if (check_last_block)
6378     {
6379       basic_block bb = EXIT_BLOCK_PTR->prev_bb;
6380       block_stmt_iterator bsi = bsi_last (bb);
6381       tree t = NULL_TREE;
6382       if (!bsi_end_p (bsi))
6383         t = bsi_stmt (bsi);
6384
6385       if (t && need_fake_edge_p (t))
6386         {
6387           edge e;
6388
6389           e = find_edge (bb, EXIT_BLOCK_PTR);
6390           if (e)
6391             {
6392               bsi_insert_on_edge (e, build_empty_stmt ());
6393               bsi_commit_edge_inserts ();
6394             }
6395         }
6396     }
6397
6398   /* Now add fake edges to the function exit for any non constant
6399      calls since there is no way that we can determine if they will
6400      return or not...  */
6401   for (i = 0; i < last_bb; i++)
6402     {
6403       basic_block bb = BASIC_BLOCK (i);
6404       block_stmt_iterator bsi;
6405       tree stmt, last_stmt;
6406
6407       if (!bb)
6408         continue;
6409
6410       if (blocks && !TEST_BIT (blocks, i))
6411         continue;
6412
6413       bsi = bsi_last (bb);
6414       if (!bsi_end_p (bsi))
6415         {
6416           last_stmt = bsi_stmt (bsi);
6417           do
6418             {
6419               stmt = bsi_stmt (bsi);
6420               if (need_fake_edge_p (stmt))
6421                 {
6422                   edge e;
6423                   /* The handling above of the final block before the
6424                      epilogue should be enough to verify that there is
6425                      no edge to the exit block in CFG already.
6426                      Calling make_edge in such case would cause us to
6427                      mark that edge as fake and remove it later.  */
6428 #ifdef ENABLE_CHECKING
6429                   if (stmt == last_stmt)
6430                     {
6431                       e = find_edge (bb, EXIT_BLOCK_PTR);
6432                       gcc_assert (e == NULL);
6433                     }
6434 #endif
6435
6436                   /* Note that the following may create a new basic block
6437                      and renumber the existing basic blocks.  */
6438                   if (stmt != last_stmt)
6439                     {
6440                       e = split_block (bb, stmt);
6441                       if (e)
6442                         blocks_split++;
6443                     }
6444                   make_edge (bb, EXIT_BLOCK_PTR, EDGE_FAKE);
6445                 }
6446               bsi_prev (&bsi);
6447             }
6448           while (!bsi_end_p (bsi));
6449         }
6450     }
6451
6452   if (blocks_split)
6453     verify_flow_info ();
6454
6455   return blocks_split;
6456 }
6457
6458 /* Purge dead abnormal call edges from basic block BB.  */
6459
6460 bool
6461 tree_purge_dead_abnormal_call_edges (basic_block bb)
6462 {
6463   bool changed = tree_purge_dead_eh_edges (bb);
6464
6465   if (current_function_has_nonlocal_label)
6466     {
6467       tree stmt = last_stmt (bb);
6468       edge_iterator ei;
6469       edge e;
6470
6471       if (!(stmt && tree_can_make_abnormal_goto (stmt)))
6472         for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
6473           {
6474             if (e->flags & EDGE_ABNORMAL)
6475               {
6476                 remove_edge (e);
6477                 changed = true;
6478               }
6479             else
6480               ei_next (&ei);
6481           }
6482
6483       /* See tree_purge_dead_eh_edges below.  */
6484       if (changed)
6485         free_dominance_info (CDI_DOMINATORS);
6486     }
6487
6488   return changed;
6489 }
6490
6491 /* Stores all basic blocks dominated by BB to DOM_BBS.  */
6492
6493 static void
6494 get_all_dominated_blocks (basic_block bb, VEC (basic_block, heap) **dom_bbs)
6495 {
6496   basic_block son;
6497
6498   VEC_safe_push (basic_block, heap, *dom_bbs, bb);
6499   for (son = first_dom_son (CDI_DOMINATORS, bb);
6500        son;
6501        son = next_dom_son (CDI_DOMINATORS, son))
6502     get_all_dominated_blocks (son, dom_bbs);
6503 }
6504
6505 /* Removes edge E and all the blocks dominated by it, and updates dominance
6506    information.  The IL in E->src needs to be updated separately.
6507    If dominance info is not available, only the edge E is removed.*/
6508
6509 void
6510 remove_edge_and_dominated_blocks (edge e)
6511 {
6512   VEC (basic_block, heap) *bbs_to_remove = NULL;
6513   VEC (basic_block, heap) *bbs_to_fix_dom = NULL;
6514   bitmap df, df_idom;
6515   edge f;
6516   edge_iterator ei;
6517   bool none_removed = false;
6518   unsigned i;
6519   basic_block bb, dbb;
6520   bitmap_iterator bi;
6521
6522   if (!dom_info_available_p (CDI_DOMINATORS))
6523     {
6524       remove_edge (e);
6525       return;
6526     }
6527
6528   /* No updating is needed for edges to exit.  */
6529   if (e->dest == EXIT_BLOCK_PTR)
6530     {
6531       if (cfgcleanup_altered_bbs)
6532         bitmap_set_bit (cfgcleanup_altered_bbs, e->src->index);
6533       remove_edge (e);
6534       return;
6535     }
6536
6537   /* First, we find the basic blocks to remove.  If E->dest has a predecessor
6538      that is not dominated by E->dest, then this set is empty.  Otherwise,
6539      all the basic blocks dominated by E->dest are removed.
6540
6541      Also, to DF_IDOM we store the immediate dominators of the blocks in
6542      the dominance frontier of E (i.e., of the successors of the
6543      removed blocks, if there are any, and of E->dest otherwise).  */
6544   FOR_EACH_EDGE (f, ei, e->dest->preds)
6545     {
6546       if (f == e)
6547         continue;
6548
6549       if (!dominated_by_p (CDI_DOMINATORS, f->src, e->dest))
6550         {
6551           none_removed = true;
6552           break;
6553         }
6554     }
6555
6556   df = BITMAP_ALLOC (NULL);
6557   df_idom = BITMAP_ALLOC (NULL);
6558
6559   if (none_removed)
6560     bitmap_set_bit (df_idom,
6561                     get_immediate_dominator (CDI_DOMINATORS, e->dest)->index);
6562   else
6563     {
6564       get_all_dominated_blocks (e->dest, &bbs_to_remove);
6565       for (i = 0; VEC_iterate (basic_block, bbs_to_remove, i, bb); i++)
6566         {
6567           FOR_EACH_EDGE (f, ei, bb->succs)
6568             {
6569               if (f->dest != EXIT_BLOCK_PTR)
6570                 bitmap_set_bit (df, f->dest->index);
6571             }
6572         }
6573       for (i = 0; VEC_iterate (basic_block, bbs_to_remove, i, bb); i++)
6574         bitmap_clear_bit (df, bb->index);
6575
6576       EXECUTE_IF_SET_IN_BITMAP (df, 0, i, bi)
6577         {
6578           bb = BASIC_BLOCK (i);
6579           bitmap_set_bit (df_idom,
6580                           get_immediate_dominator (CDI_DOMINATORS, bb)->index);
6581         }
6582     }
6583
6584   if (cfgcleanup_altered_bbs)
6585     {
6586       /* Record the set of the altered basic blocks.  */
6587       bitmap_set_bit (cfgcleanup_altered_bbs, e->src->index);
6588       bitmap_ior_into (cfgcleanup_altered_bbs, df);
6589     }
6590
6591   /* Remove E and the cancelled blocks.  */
6592   if (none_removed)
6593     remove_edge (e);
6594   else
6595     {
6596       for (i = 0; VEC_iterate (basic_block, bbs_to_remove, i, bb); i++)
6597         delete_basic_block (bb);
6598     }
6599
6600   /* Update the dominance information.  The immediate dominator may change only
6601      for blocks whose immediate dominator belongs to DF_IDOM:
6602    
6603      Suppose that idom(X) = Y before removal of E and idom(X) != Y after the
6604      removal.  Let Z the arbitrary block such that idom(Z) = Y and
6605      Z dominates X after the removal.  Before removal, there exists a path P
6606      from Y to X that avoids Z.  Let F be the last edge on P that is
6607      removed, and let W = F->dest.  Before removal, idom(W) = Y (since Y
6608      dominates W, and because of P, Z does not dominate W), and W belongs to
6609      the dominance frontier of E.  Therefore, Y belongs to DF_IDOM.  */ 
6610   EXECUTE_IF_SET_IN_BITMAP (df_idom, 0, i, bi)
6611     {
6612       bb = BASIC_BLOCK (i);
6613       for (dbb = first_dom_son (CDI_DOMINATORS, bb);
6614            dbb;
6615            dbb = next_dom_son (CDI_DOMINATORS, dbb))
6616         VEC_safe_push (basic_block, heap, bbs_to_fix_dom, dbb);
6617     }
6618
6619   iterate_fix_dominators (CDI_DOMINATORS, bbs_to_fix_dom, true);
6620
6621   BITMAP_FREE (df);
6622   BITMAP_FREE (df_idom);
6623   VEC_free (basic_block, heap, bbs_to_remove);
6624   VEC_free (basic_block, heap, bbs_to_fix_dom);
6625 }
6626
6627 /* Purge dead EH edges from basic block BB.  */
6628
6629 bool
6630 tree_purge_dead_eh_edges (basic_block bb)
6631 {
6632   bool changed = false;
6633   edge e;
6634   edge_iterator ei;
6635   tree stmt = last_stmt (bb);
6636
6637   if (stmt && tree_can_throw_internal (stmt))
6638     return false;
6639
6640   for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
6641     {
6642       if (e->flags & EDGE_EH)
6643         {
6644           remove_edge_and_dominated_blocks (e);
6645           changed = true;
6646         }
6647       else
6648         ei_next (&ei);
6649     }
6650
6651   return changed;
6652 }
6653
6654 bool
6655 tree_purge_all_dead_eh_edges (const_bitmap blocks)
6656 {
6657   bool changed = false;
6658   unsigned i;
6659   bitmap_iterator bi;
6660
6661   EXECUTE_IF_SET_IN_BITMAP (blocks, 0, i, bi)
6662     {
6663       changed |= tree_purge_dead_eh_edges (BASIC_BLOCK (i));
6664     }
6665
6666   return changed;
6667 }
6668
6669 /* This function is called whenever a new edge is created or
6670    redirected.  */
6671
6672 static void
6673 tree_execute_on_growing_pred (edge e)
6674 {
6675   basic_block bb = e->dest;
6676
6677   if (phi_nodes (bb))
6678     reserve_phi_args_for_new_edge (bb);
6679 }
6680
6681 /* This function is called immediately before edge E is removed from
6682    the edge vector E->dest->preds.  */
6683
6684 static void
6685 tree_execute_on_shrinking_pred (edge e)
6686 {
6687   if (phi_nodes (e->dest))
6688     remove_phi_args (e);
6689 }
6690
6691 /*---------------------------------------------------------------------------
6692   Helper functions for Loop versioning
6693   ---------------------------------------------------------------------------*/
6694
6695 /* Adjust phi nodes for 'first' basic block.  'second' basic block is a copy
6696    of 'first'. Both of them are dominated by 'new_head' basic block. When
6697    'new_head' was created by 'second's incoming edge it received phi arguments
6698    on the edge by split_edge(). Later, additional edge 'e' was created to
6699    connect 'new_head' and 'first'. Now this routine adds phi args on this
6700    additional edge 'e' that new_head to second edge received as part of edge
6701    splitting.
6702 */
6703
6704 static void
6705 tree_lv_adjust_loop_header_phi (basic_block first, basic_block second,
6706                                 basic_block new_head, edge e)
6707 {
6708   tree phi1, phi2;
6709   edge e2 = find_edge (new_head, second);
6710
6711   /* Because NEW_HEAD has been created by splitting SECOND's incoming
6712      edge, we should always have an edge from NEW_HEAD to SECOND.  */
6713   gcc_assert (e2 != NULL);
6714
6715   /* Browse all 'second' basic block phi nodes and add phi args to
6716      edge 'e' for 'first' head. PHI args are always in correct order.  */
6717
6718   for (phi2 = phi_nodes (second), phi1 = phi_nodes (first);
6719        phi2 && phi1;
6720        phi2 = PHI_CHAIN (phi2),  phi1 = PHI_CHAIN (phi1))
6721     {
6722       tree def = PHI_ARG_DEF (phi2, e2->dest_idx);
6723       add_phi_arg (phi1, def, e);
6724     }
6725 }
6726
6727 /* Adds a if else statement to COND_BB with condition COND_EXPR.
6728    SECOND_HEAD is the destination of the THEN and FIRST_HEAD is
6729    the destination of the ELSE part.  */
6730 static void
6731 tree_lv_add_condition_to_bb (basic_block first_head ATTRIBUTE_UNUSED,
6732                              basic_block second_head ATTRIBUTE_UNUSED,
6733                              basic_block cond_bb, void *cond_e)
6734 {
6735   block_stmt_iterator bsi;
6736   tree new_cond_expr = NULL_TREE;
6737   tree cond_expr = (tree) cond_e;
6738   edge e0;
6739
6740   /* Build new conditional expr */
6741   new_cond_expr = build3 (COND_EXPR, void_type_node, cond_expr,
6742                           NULL_TREE, NULL_TREE);
6743
6744   /* Add new cond in cond_bb.  */
6745   bsi = bsi_start (cond_bb);
6746   bsi_insert_after (&bsi, new_cond_expr, BSI_NEW_STMT);
6747   /* Adjust edges appropriately to connect new head with first head
6748      as well as second head.  */
6749   e0 = single_succ_edge (cond_bb);
6750   e0->flags &= ~EDGE_FALLTHRU;
6751   e0->flags |= EDGE_FALSE_VALUE;
6752 }
6753
6754 struct cfg_hooks tree_cfg_hooks = {
6755   "tree",
6756   tree_verify_flow_info,
6757   tree_dump_bb,                 /* dump_bb  */
6758   create_bb,                    /* create_basic_block  */
6759   tree_redirect_edge_and_branch,/* redirect_edge_and_branch  */
6760   tree_redirect_edge_and_branch_force,/* redirect_edge_and_branch_force  */
6761   tree_can_remove_branch_p,     /* can_remove_branch_p  */
6762   remove_bb,                    /* delete_basic_block  */
6763   tree_split_block,             /* split_block  */
6764   tree_move_block_after,        /* move_block_after  */
6765   tree_can_merge_blocks_p,      /* can_merge_blocks_p  */
6766   tree_merge_blocks,            /* merge_blocks  */
6767   tree_predict_edge,            /* predict_edge  */
6768   tree_predicted_by_p,          /* predicted_by_p  */
6769   tree_can_duplicate_bb_p,      /* can_duplicate_block_p  */
6770   tree_duplicate_bb,            /* duplicate_block  */
6771   tree_split_edge,              /* split_edge  */
6772   tree_make_forwarder_block,    /* make_forward_block  */
6773   NULL,                         /* tidy_fallthru_edge  */
6774   tree_block_ends_with_call_p,  /* block_ends_with_call_p */
6775   tree_block_ends_with_condjump_p, /* block_ends_with_condjump_p */
6776   tree_flow_call_edges_add,     /* flow_call_edges_add */
6777   tree_execute_on_growing_pred, /* execute_on_growing_pred */
6778   tree_execute_on_shrinking_pred, /* execute_on_shrinking_pred */
6779   tree_duplicate_loop_to_header_edge, /* duplicate loop for trees */
6780   tree_lv_add_condition_to_bb, /* lv_add_condition_to_bb */
6781   tree_lv_adjust_loop_header_phi, /* lv_adjust_loop_header_phi*/
6782   extract_true_false_edges_from_block, /* extract_cond_bb_edges */
6783   flush_pending_stmts           /* flush_pending_stmts */
6784 };
6785
6786
6787 /* Split all critical edges.  */
6788
6789 static unsigned int
6790 split_critical_edges (void)
6791 {
6792   basic_block bb;
6793   edge e;
6794   edge_iterator ei;
6795
6796   /* split_edge can redirect edges out of SWITCH_EXPRs, which can get
6797      expensive.  So we want to enable recording of edge to CASE_LABEL_EXPR
6798      mappings around the calls to split_edge.  */
6799   start_recording_case_labels ();
6800   FOR_ALL_BB (bb)
6801     {
6802       FOR_EACH_EDGE (e, ei, bb->succs)
6803         if (EDGE_CRITICAL_P (e) && !(e->flags & EDGE_ABNORMAL))
6804           {
6805             split_edge (e);
6806           }
6807     }
6808   end_recording_case_labels ();
6809   return 0;
6810 }
6811
6812 struct tree_opt_pass pass_split_crit_edges =
6813 {
6814   "crited",                          /* name */
6815   NULL,                          /* gate */
6816   split_critical_edges,          /* execute */
6817   NULL,                          /* sub */
6818   NULL,                          /* next */
6819   0,                             /* static_pass_number */
6820   TV_TREE_SPLIT_EDGES,           /* tv_id */
6821   PROP_cfg,                      /* properties required */
6822   PROP_no_crit_edges,            /* properties_provided */
6823   0,                             /* properties_destroyed */
6824   0,                             /* todo_flags_start */
6825   TODO_dump_func,                /* todo_flags_finish */
6826   0                              /* letter */
6827 };
6828
6829 \f
6830 /* Return EXP if it is a valid GIMPLE rvalue, else gimplify it into
6831    a temporary, make sure and register it to be renamed if necessary,
6832    and finally return the temporary.  Put the statements to compute
6833    EXP before the current statement in BSI.  */
6834
6835 tree
6836 gimplify_val (block_stmt_iterator *bsi, tree type, tree exp)
6837 {
6838   tree t, new_stmt, orig_stmt;
6839
6840   if (is_gimple_val (exp))
6841     return exp;
6842
6843   t = make_rename_temp (type, NULL);
6844   new_stmt = build_gimple_modify_stmt (t, exp);
6845
6846   orig_stmt = bsi_stmt (*bsi);
6847   SET_EXPR_LOCUS (new_stmt, EXPR_LOCUS (orig_stmt));
6848   TREE_BLOCK (new_stmt) = TREE_BLOCK (orig_stmt);
6849
6850   bsi_insert_before (bsi, new_stmt, BSI_SAME_STMT);
6851   if (gimple_in_ssa_p (cfun))
6852     mark_symbols_for_renaming (new_stmt);
6853
6854   return t;
6855 }
6856
6857 /* Build a ternary operation and gimplify it.  Emit code before BSI.
6858    Return the gimple_val holding the result.  */
6859
6860 tree
6861 gimplify_build3 (block_stmt_iterator *bsi, enum tree_code code,
6862                  tree type, tree a, tree b, tree c)
6863 {
6864   tree ret;
6865
6866   ret = fold_build3 (code, type, a, b, c);
6867   STRIP_NOPS (ret);
6868
6869   return gimplify_val (bsi, type, ret);
6870 }
6871
6872 /* Build a binary operation and gimplify it.  Emit code before BSI.
6873    Return the gimple_val holding the result.  */
6874
6875 tree
6876 gimplify_build2 (block_stmt_iterator *bsi, enum tree_code code,
6877                  tree type, tree a, tree b)
6878 {
6879   tree ret;
6880
6881   ret = fold_build2 (code, type, a, b);
6882   STRIP_NOPS (ret);
6883
6884   return gimplify_val (bsi, type, ret);
6885 }
6886
6887 /* Build a unary operation and gimplify it.  Emit code before BSI.
6888    Return the gimple_val holding the result.  */
6889
6890 tree
6891 gimplify_build1 (block_stmt_iterator *bsi, enum tree_code code, tree type,
6892                  tree a)
6893 {
6894   tree ret;
6895
6896   ret = fold_build1 (code, type, a);
6897   STRIP_NOPS (ret);
6898
6899   return gimplify_val (bsi, type, ret);
6900 }
6901
6902
6903 \f
6904 /* Emit return warnings.  */
6905
6906 static unsigned int
6907 execute_warn_function_return (void)
6908 {
6909 #ifdef USE_MAPPED_LOCATION
6910   source_location location;
6911 #else
6912   location_t *locus;
6913 #endif
6914   tree last;
6915   edge e;
6916   edge_iterator ei;
6917
6918   /* If we have a path to EXIT, then we do return.  */
6919   if (TREE_THIS_VOLATILE (cfun->decl)
6920       && EDGE_COUNT (EXIT_BLOCK_PTR->preds) > 0)
6921     {
6922 #ifdef USE_MAPPED_LOCATION
6923       location = UNKNOWN_LOCATION;
6924 #else
6925       locus = NULL;
6926 #endif
6927       FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
6928         {
6929           last = last_stmt (e->src);
6930           if (TREE_CODE (last) == RETURN_EXPR
6931 #ifdef USE_MAPPED_LOCATION
6932               && (location = EXPR_LOCATION (last)) != UNKNOWN_LOCATION)
6933 #else
6934               && (locus = EXPR_LOCUS (last)) != NULL)
6935 #endif
6936             break;
6937         }
6938 #ifdef USE_MAPPED_LOCATION
6939       if (location == UNKNOWN_LOCATION)
6940         location = cfun->function_end_locus;
6941       warning (0, "%H%<noreturn%> function does return", &location);
6942 #else
6943       if (!locus)
6944         locus = &cfun->function_end_locus;
6945       warning (0, "%H%<noreturn%> function does return", locus);
6946 #endif
6947     }
6948
6949   /* If we see "return;" in some basic block, then we do reach the end
6950      without returning a value.  */
6951   else if (warn_return_type
6952            && !TREE_NO_WARNING (cfun->decl)
6953            && EDGE_COUNT (EXIT_BLOCK_PTR->preds) > 0
6954            && !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (cfun->decl))))
6955     {
6956       FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
6957         {
6958           tree last = last_stmt (e->src);
6959           if (TREE_CODE (last) == RETURN_EXPR
6960               && TREE_OPERAND (last, 0) == NULL
6961               && !TREE_NO_WARNING (last))
6962             {
6963 #ifdef USE_MAPPED_LOCATION
6964               location = EXPR_LOCATION (last);
6965               if (location == UNKNOWN_LOCATION)
6966                   location = cfun->function_end_locus;
6967               warning (OPT_Wreturn_type, "%Hcontrol reaches end of non-void function", &location);
6968 #else
6969               locus = EXPR_LOCUS (last);
6970               if (!locus)
6971                 locus = &cfun->function_end_locus;
6972               warning (OPT_Wreturn_type, "%Hcontrol reaches end of non-void function", locus);
6973 #endif
6974               TREE_NO_WARNING (cfun->decl) = 1;
6975               break;
6976             }
6977         }
6978     }
6979   return 0;
6980 }
6981
6982
6983 /* Given a basic block B which ends with a conditional and has
6984    precisely two successors, determine which of the edges is taken if
6985    the conditional is true and which is taken if the conditional is
6986    false.  Set TRUE_EDGE and FALSE_EDGE appropriately.  */
6987
6988 void
6989 extract_true_false_edges_from_block (basic_block b,
6990                                      edge *true_edge,
6991                                      edge *false_edge)
6992 {
6993   edge e = EDGE_SUCC (b, 0);
6994
6995   if (e->flags & EDGE_TRUE_VALUE)
6996     {
6997       *true_edge = e;
6998       *false_edge = EDGE_SUCC (b, 1);
6999     }
7000   else
7001     {
7002       *false_edge = e;
7003       *true_edge = EDGE_SUCC (b, 1);
7004     }
7005 }
7006
7007 struct tree_opt_pass pass_warn_function_return =
7008 {
7009   NULL,                                 /* name */
7010   NULL,                                 /* gate */
7011   execute_warn_function_return,         /* execute */
7012   NULL,                                 /* sub */
7013   NULL,                                 /* next */
7014   0,                                    /* static_pass_number */
7015   0,                                    /* tv_id */
7016   PROP_cfg,                             /* properties_required */
7017   0,                                    /* properties_provided */
7018   0,                                    /* properties_destroyed */
7019   0,                                    /* todo_flags_start */
7020   0,                                    /* todo_flags_finish */
7021   0                                     /* letter */
7022 };
7023
7024 /* Emit noreturn warnings.  */
7025
7026 static unsigned int
7027 execute_warn_function_noreturn (void)
7028 {
7029   if (warn_missing_noreturn
7030       && !TREE_THIS_VOLATILE (cfun->decl)
7031       && EDGE_COUNT (EXIT_BLOCK_PTR->preds) == 0
7032       && !lang_hooks.function.missing_noreturn_ok_p (cfun->decl))
7033     warning (OPT_Wmissing_noreturn, "%Jfunction might be possible candidate "
7034              "for attribute %<noreturn%>",
7035              cfun->decl);
7036   return 0;
7037 }
7038
7039 struct tree_opt_pass pass_warn_function_noreturn =
7040 {
7041   NULL,                                 /* name */
7042   NULL,                                 /* gate */
7043   execute_warn_function_noreturn,       /* execute */
7044   NULL,                                 /* sub */
7045   NULL,                                 /* next */
7046   0,                                    /* static_pass_number */
7047   0,                                    /* tv_id */
7048   PROP_cfg,                             /* properties_required */
7049   0,                                    /* properties_provided */
7050   0,                                    /* properties_destroyed */
7051   0,                                    /* todo_flags_start */
7052   0,                                    /* todo_flags_finish */
7053   0                                     /* letter */
7054 };