OSDN Git Service

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