OSDN Git Service

PR target/21101
[pf3gnuchains/gcc-fork.git] / gcc / tree-vectorizer.c
1 /* Loop Vectorization
2    Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
3    Contributed by Dorit Naishlos <dorit@il.ibm.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.  */
21
22 /* Loop Vectorization Pass.
23
24    This pass tries to vectorize loops. This first implementation focuses on
25    simple inner-most loops, with no conditional control flow, and a set of
26    simple operations which vector form can be expressed using existing
27    tree codes (PLUS, MULT etc).
28
29    For example, the vectorizer transforms the following simple loop:
30
31         short a[N]; short b[N]; short c[N]; int i;
32
33         for (i=0; i<N; i++){
34           a[i] = b[i] + c[i];
35         }
36
37    as if it was manually vectorized by rewriting the source code into:
38
39         typedef int __attribute__((mode(V8HI))) v8hi;
40         short a[N];  short b[N]; short c[N];   int i;
41         v8hi *pa = (v8hi*)a, *pb = (v8hi*)b, *pc = (v8hi*)c;
42         v8hi va, vb, vc;
43
44         for (i=0; i<N/8; i++){
45           vb = pb[i];
46           vc = pc[i];
47           va = vb + vc;
48           pa[i] = va;
49         }
50
51         The main entry to this pass is vectorize_loops(), in which
52    the vectorizer applies a set of analyses on a given set of loops,
53    followed by the actual vectorization transformation for the loops that
54    had successfully passed the analysis phase.
55
56         Throughout this pass we make a distinction between two types of
57    data: scalars (which are represented by SSA_NAMES), and memory references
58    ("data-refs"). These two types of data require different handling both 
59    during analysis and transformation. The types of data-refs that the 
60    vectorizer currently supports are ARRAY_REFS which base is an array DECL 
61    (not a pointer), and INDIRECT_REFS through pointers; both array and pointer
62    accesses are required to have a  simple (consecutive) access pattern.
63
64    Analysis phase:
65    ===============
66         The driver for the analysis phase is vect_analyze_loop_nest().
67    It applies a set of analyses, some of which rely on the scalar evolution 
68    analyzer (scev) developed by Sebastian Pop.
69
70         During the analysis phase the vectorizer records some information
71    per stmt in a "stmt_vec_info" struct which is attached to each stmt in the 
72    loop, as well as general information about the loop as a whole, which is
73    recorded in a "loop_vec_info" struct attached to each loop.
74
75    Transformation phase:
76    =====================
77         The loop transformation phase scans all the stmts in the loop, and
78    creates a vector stmt (or a sequence of stmts) for each scalar stmt S in
79    the loop that needs to be vectorized. It insert the vector code sequence
80    just before the scalar stmt S, and records a pointer to the vector code
81    in STMT_VINFO_VEC_STMT (stmt_info) (stmt_info is the stmt_vec_info struct 
82    attached to S). This pointer will be used for the vectorization of following
83    stmts which use the def of stmt S. Stmt S is removed if it writes to memory;
84    otherwise, we rely on dead code elimination for removing it.
85
86         For example, say stmt S1 was vectorized into stmt VS1:
87
88    VS1: vb = px[i];
89    S1:  b = x[i];    STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
90    S2:  a = b;
91
92    To vectorize stmt S2, the vectorizer first finds the stmt that defines
93    the operand 'b' (S1), and gets the relevant vector def 'vb' from the
94    vector stmt VS1 pointed by STMT_VINFO_VEC_STMT (stmt_info (S1)). The
95    resulting sequence would be:
96
97    VS1: vb = px[i];
98    S1:  b = x[i];       STMT_VINFO_VEC_STMT (stmt_info (S1)) = VS1
99    VS2: va = vb;
100    S2:  a = b;          STMT_VINFO_VEC_STMT (stmt_info (S2)) = VS2
101
102         Operands that are not SSA_NAMEs, are data-refs that appear in 
103    load/store operations (like 'x[i]' in S1), and are handled differently.
104
105    Target modeling:
106    =================
107         Currently the only target specific information that is used is the
108    size of the vector (in bytes) - "UNITS_PER_SIMD_WORD". Targets that can 
109    support different sizes of vectors, for now will need to specify one value 
110    for "UNITS_PER_SIMD_WORD". More flexibility will be added in the future.
111
112         Since we only vectorize operations which vector form can be
113    expressed using existing tree codes, to verify that an operation is
114    supported, the vectorizer checks the relevant optab at the relevant
115    machine_mode (e.g, add_optab->handlers[(int) V8HImode].insn_code). If
116    the value found is CODE_FOR_nothing, then there's no target support, and
117    we can't vectorize the stmt.
118
119    For additional information on this project see:
120    http://gcc.gnu.org/projects/tree-ssa/vectorization.html
121 */
122
123 #include "config.h"
124 #include "system.h"
125 #include "coretypes.h"
126 #include "tm.h"
127 #include "errors.h"
128 #include "ggc.h"
129 #include "tree.h"
130 #include "target.h"
131 #include "rtl.h"
132 #include "basic-block.h"
133 #include "diagnostic.h"
134 #include "tree-flow.h"
135 #include "tree-dump.h"
136 #include "timevar.h"
137 #include "cfgloop.h"
138 #include "cfglayout.h"
139 #include "expr.h"
140 #include "optabs.h"
141 #include "toplev.h"
142 #include "tree-chrec.h"
143 #include "tree-data-ref.h"
144 #include "tree-scalar-evolution.h"
145 #include "input.h"
146 #include "tree-vectorizer.h"
147 #include "tree-pass.h"
148
149 /*************************************************************************
150   Simple Loop Peeling Utilities
151  *************************************************************************/
152 static struct loop *slpeel_tree_duplicate_loop_to_edge_cfg 
153   (struct loop *, struct loops *, edge);
154 static void slpeel_update_phis_for_duplicate_loop 
155   (struct loop *, struct loop *, bool after);
156 static void slpeel_update_phi_nodes_for_guard1 
157   (edge, struct loop *, bool, basic_block *, bitmap *); 
158 static void slpeel_update_phi_nodes_for_guard2 
159   (edge, struct loop *, bool, basic_block *);
160 static edge slpeel_add_loop_guard (basic_block, tree, basic_block, basic_block);
161
162 static void rename_use_op (use_operand_p);
163 static void rename_variables_in_bb (basic_block);
164 static void rename_variables_in_loop (struct loop *);
165
166 /*************************************************************************
167   General Vectorization Utilities
168  *************************************************************************/
169 static void vect_set_dump_settings (void);
170
171 /* vect_dump will be set to stderr or dump_file if exist.  */
172 FILE *vect_dump;
173
174 /* vect_verbosity_level set to an invalid value 
175    to mark that it's uninitialized.  */
176 enum verbosity_levels vect_verbosity_level = MAX_VERBOSITY_LEVEL;
177
178 /* Number of loops, at the beginning of vectorization.  */
179 unsigned int vect_loops_num;
180 \f
181 /*************************************************************************
182   Simple Loop Peeling Utilities
183
184   Utilities to support loop peeling for vectorization purposes.
185  *************************************************************************/
186
187
188 /* Renames the use *OP_P.  */
189
190 static void
191 rename_use_op (use_operand_p op_p)
192 {
193   tree new_name;
194
195   if (TREE_CODE (USE_FROM_PTR (op_p)) != SSA_NAME)
196     return;
197
198   new_name = get_current_def (USE_FROM_PTR (op_p));
199
200   /* Something defined outside of the loop.  */
201   if (!new_name)
202     return;
203
204   /* An ordinary ssa name defined in the loop.  */
205
206   SET_USE (op_p, new_name);
207 }
208
209
210 /* Renames the variables in basic block BB.  */
211
212 static void
213 rename_variables_in_bb (basic_block bb)
214 {
215   tree phi;
216   block_stmt_iterator bsi;
217   tree stmt;
218   stmt_ann_t ann;
219   use_optype uses;
220   vuse_optype vuses;
221   v_may_def_optype v_may_defs;
222   v_must_def_optype v_must_defs;
223   unsigned i;
224   edge e;
225   edge_iterator ei;
226   struct loop *loop = bb->loop_father;
227
228   for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
229     {
230       stmt = bsi_stmt (bsi);
231       ann = stmt_ann (stmt);
232
233       uses = USE_OPS (ann);
234       for (i = 0; i < NUM_USES (uses); i++)
235         rename_use_op (USE_OP_PTR (uses, i));
236
237       vuses = VUSE_OPS (ann);
238       for (i = 0; i < NUM_VUSES (vuses); i++)
239         rename_use_op (VUSE_OP_PTR (vuses, i));
240
241       v_may_defs = V_MAY_DEF_OPS (ann);
242       for (i = 0; i < NUM_V_MAY_DEFS (v_may_defs); i++)
243         rename_use_op (V_MAY_DEF_OP_PTR (v_may_defs, i));
244
245       v_must_defs = V_MUST_DEF_OPS (ann);
246       for (i = 0; i < NUM_V_MUST_DEFS (v_must_defs); i++)
247         rename_use_op (V_MUST_DEF_KILL_PTR (v_must_defs, i));
248     }
249
250   FOR_EACH_EDGE (e, ei, bb->succs)
251     {
252       if (!flow_bb_inside_loop_p (loop, e->dest))
253         continue;
254       for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
255         rename_use_op (PHI_ARG_DEF_PTR_FROM_EDGE (phi, e));
256     }
257 }
258
259
260 /* Renames variables in new generated LOOP.  */
261
262 static void
263 rename_variables_in_loop (struct loop *loop)
264 {
265   unsigned i;
266   basic_block *bbs;
267
268   bbs = get_loop_body (loop);
269
270   for (i = 0; i < loop->num_nodes; i++)
271     rename_variables_in_bb (bbs[i]);
272
273   free (bbs);
274 }
275
276
277 /* Update the PHI nodes of NEW_LOOP.
278
279    NEW_LOOP is a duplicate of ORIG_LOOP.
280    AFTER indicates whether NEW_LOOP executes before or after ORIG_LOOP:
281    AFTER is true if NEW_LOOP executes after ORIG_LOOP, and false if it
282    executes before it.  */
283
284 static void
285 slpeel_update_phis_for_duplicate_loop (struct loop *orig_loop,
286                                        struct loop *new_loop, bool after)
287 {
288   tree new_ssa_name;
289   tree phi_new, phi_orig;
290   tree def;
291   edge orig_loop_latch = loop_latch_edge (orig_loop);
292   edge orig_entry_e = loop_preheader_edge (orig_loop);
293   edge new_loop_exit_e = new_loop->single_exit;
294   edge new_loop_entry_e = loop_preheader_edge (new_loop);
295   edge entry_arg_e = (after ? orig_loop_latch : orig_entry_e);
296
297   /*
298      step 1. For each loop-header-phi:
299              Add the first phi argument for the phi in NEW_LOOP
300             (the one associated with the entry of NEW_LOOP)
301
302      step 2. For each loop-header-phi:
303              Add the second phi argument for the phi in NEW_LOOP
304             (the one associated with the latch of NEW_LOOP)
305
306      step 3. Update the phis in the successor block of NEW_LOOP.
307
308         case 1: NEW_LOOP was placed before ORIG_LOOP:
309                 The successor block of NEW_LOOP is the header of ORIG_LOOP.
310                 Updating the phis in the successor block can therefore be done
311                 along with the scanning of the loop header phis, because the
312                 header blocks of ORIG_LOOP and NEW_LOOP have exactly the same
313                 phi nodes, organized in the same order.
314
315         case 2: NEW_LOOP was placed after ORIG_LOOP:
316                 The successor block of NEW_LOOP is the original exit block of 
317                 ORIG_LOOP - the phis to be updated are the loop-closed-ssa phis.
318                 We postpone updating these phis to a later stage (when
319                 loop guards are added).
320    */
321
322
323   /* Scan the phis in the headers of the old and new loops
324      (they are organized in exactly the same order).  */
325
326   for (phi_new = phi_nodes (new_loop->header),
327        phi_orig = phi_nodes (orig_loop->header);
328        phi_new && phi_orig;
329        phi_new = PHI_CHAIN (phi_new), phi_orig = PHI_CHAIN (phi_orig))
330     {
331       /* step 1.  */
332       def = PHI_ARG_DEF_FROM_EDGE (phi_orig, entry_arg_e);
333       add_phi_arg (phi_new, def, new_loop_entry_e);
334
335       /* step 2.  */
336       def = PHI_ARG_DEF_FROM_EDGE (phi_orig, orig_loop_latch);
337       if (TREE_CODE (def) != SSA_NAME)
338         continue;
339
340       new_ssa_name = get_current_def (def);
341       if (!new_ssa_name)
342         /* Something defined outside of the loop.  */
343         continue;
344
345       /* An ordinary ssa name defined in the loop.  */
346       add_phi_arg (phi_new, new_ssa_name, loop_latch_edge (new_loop));
347
348       /* step 3 (case 1).  */
349       if (!after)
350         {
351           gcc_assert (new_loop_exit_e == orig_entry_e);
352           SET_PHI_ARG_DEF (phi_orig,
353                            new_loop_exit_e->dest_idx,
354                            new_ssa_name);
355         }
356     }
357 }
358
359
360 /* Update PHI nodes for a guard of the LOOP.
361
362    Input:
363    - LOOP, GUARD_EDGE: LOOP is a loop for which we added guard code that
364         controls whether LOOP is to be executed.  GUARD_EDGE is the edge that
365         originates from the guard-bb, skips LOOP and reaches the (unique) exit
366         bb of LOOP.  This loop-exit-bb is an empty bb with one successor.
367         We denote this bb NEW_MERGE_BB because before the guard code was added
368         it had a single predecessor (the LOOP header), and now it became a merge
369         point of two paths - the path that ends with the LOOP exit-edge, and
370         the path that ends with GUARD_EDGE.
371    - NEW_EXIT_BB: New basic block that is added by this function between LOOP
372         and NEW_MERGE_BB. It is used to place loop-closed-ssa-form exit-phis.
373
374    ===> The CFG before the guard-code was added:
375         LOOP_header_bb:
376           loop_body
377           if (exit_loop) goto update_bb
378           else           goto LOOP_header_bb
379         update_bb:
380
381    ==> The CFG after the guard-code was added:
382         guard_bb:
383           if (LOOP_guard_condition) goto new_merge_bb
384           else                      goto LOOP_header_bb
385         LOOP_header_bb:
386           loop_body
387           if (exit_loop_condition) goto new_merge_bb
388           else                     goto LOOP_header_bb
389         new_merge_bb:
390           goto update_bb
391         update_bb:
392
393    ==> The CFG after this function:
394         guard_bb:
395           if (LOOP_guard_condition) goto new_merge_bb
396           else                      goto LOOP_header_bb
397         LOOP_header_bb:
398           loop_body
399           if (exit_loop_condition) goto new_exit_bb
400           else                     goto LOOP_header_bb
401         new_exit_bb:
402         new_merge_bb:
403           goto update_bb
404         update_bb:
405
406    This function:
407    1. creates and updates the relevant phi nodes to account for the new
408       incoming edge (GUARD_EDGE) into NEW_MERGE_BB. This involves:
409       1.1. Create phi nodes at NEW_MERGE_BB.
410       1.2. Update the phi nodes at the successor of NEW_MERGE_BB (denoted
411            UPDATE_BB).  UPDATE_BB was the exit-bb of LOOP before NEW_MERGE_BB
412    2. preserves loop-closed-ssa-form by creating the required phi nodes
413       at the exit of LOOP (i.e, in NEW_EXIT_BB).
414
415    There are two flavors to this function:
416
417    slpeel_update_phi_nodes_for_guard1:
418      Here the guard controls whether we enter or skip LOOP, where LOOP is a
419      prolog_loop (loop1 below), and the new phis created in NEW_MERGE_BB are
420      for variables that have phis in the loop header.
421
422    slpeel_update_phi_nodes_for_guard2:
423      Here the guard controls whether we enter or skip LOOP, where LOOP is an
424      epilog_loop (loop2 below), and the new phis created in NEW_MERGE_BB are
425      for variables that have phis in the loop exit.
426
427    I.E., the overall structure is:
428
429         loop1_preheader_bb:
430                 guard1 (goto loop1/merg1_bb)
431         loop1
432         loop1_exit_bb:
433                 guard2 (goto merge1_bb/merge2_bb)
434         merge1_bb
435         loop2
436         loop2_exit_bb
437         merge2_bb
438         next_bb
439
440    slpeel_update_phi_nodes_for_guard1 takes care of creating phis in
441    loop1_exit_bb and merge1_bb. These are entry phis (phis for the vars
442    that have phis in loop1->header).
443
444    slpeel_update_phi_nodes_for_guard2 takes care of creating phis in
445    loop2_exit_bb and merge2_bb. These are exit phis (phis for the vars
446    that have phis in next_bb). It also adds some of these phis to
447    loop1_exit_bb.
448
449    slpeel_update_phi_nodes_for_guard1 is always called before
450    slpeel_update_phi_nodes_for_guard2. They are both needed in order
451    to create correct data-flow and loop-closed-ssa-form.
452
453    Generally slpeel_update_phi_nodes_for_guard1 creates phis for variables
454    that change between iterations of a loop (and therefore have a phi-node
455    at the loop entry), whereas slpeel_update_phi_nodes_for_guard2 creates
456    phis for variables that are used out of the loop (and therefore have 
457    loop-closed exit phis). Some variables may be both updated between 
458    iterations and used after the loop. This is why in loop1_exit_bb we
459    may need both entry_phis (created by slpeel_update_phi_nodes_for_guard1)
460    and exit phis (created by slpeel_update_phi_nodes_for_guard2).
461
462    - IS_NEW_LOOP: if IS_NEW_LOOP is true, then LOOP is a newly created copy of
463      an original loop. i.e., we have:
464
465            orig_loop
466            guard_bb (goto LOOP/new_merge)
467            new_loop <-- LOOP
468            new_exit
469            new_merge
470            next_bb
471
472      If IS_NEW_LOOP is false, then LOOP is an original loop, in which case we
473      have:
474
475            new_loop
476            guard_bb (goto LOOP/new_merge)
477            orig_loop <-- LOOP
478            new_exit
479            new_merge
480            next_bb
481
482      The SSA names defined in the original loop have a current
483      reaching definition that that records the corresponding new
484      ssa-name used in the new duplicated loop copy.
485   */
486
487 /* Function slpeel_update_phi_nodes_for_guard1
488    
489    Input:
490    - GUARD_EDGE, LOOP, IS_NEW_LOOP, NEW_EXIT_BB - as explained above.
491    - DEFS - a bitmap of ssa names to mark new names for which we recorded
492             information. 
493    
494    In the context of the overall structure, we have:
495
496         loop1_preheader_bb: 
497                 guard1 (goto loop1/merg1_bb)
498 LOOP->  loop1
499         loop1_exit_bb:
500                 guard2 (goto merge1_bb/merge2_bb)
501         merge1_bb
502         loop2
503         loop2_exit_bb
504         merge2_bb
505         next_bb
506
507    For each name updated between loop iterations (i.e - for each name that has
508    an entry (loop-header) phi in LOOP) we create a new phi in:
509    1. merge1_bb (to account for the edge from guard1)
510    2. loop1_exit_bb (an exit-phi to keep LOOP in loop-closed form)
511 */
512
513 static void
514 slpeel_update_phi_nodes_for_guard1 (edge guard_edge, struct loop *loop,
515                                     bool is_new_loop, basic_block *new_exit_bb,
516                                     bitmap *defs)
517 {
518   tree orig_phi, new_phi;
519   tree update_phi, update_phi2;
520   tree guard_arg, loop_arg;
521   basic_block new_merge_bb = guard_edge->dest;
522   edge e = EDGE_SUCC (new_merge_bb, 0);
523   basic_block update_bb = e->dest;
524   basic_block orig_bb = loop->header;
525   edge new_exit_e;
526   tree current_new_name;
527
528   /* Create new bb between loop and new_merge_bb.  */
529   *new_exit_bb = split_edge (loop->single_exit);
530   add_bb_to_loop (*new_exit_bb, loop->outer);
531
532   new_exit_e = EDGE_SUCC (*new_exit_bb, 0);
533
534   for (orig_phi = phi_nodes (orig_bb), update_phi = phi_nodes (update_bb);
535        orig_phi && update_phi;
536        orig_phi = PHI_CHAIN (orig_phi), update_phi = PHI_CHAIN (update_phi))
537     {
538       /** 1. Handle new-merge-point phis  **/
539
540       /* 1.1. Generate new phi node in NEW_MERGE_BB:  */
541       new_phi = create_phi_node (SSA_NAME_VAR (PHI_RESULT (orig_phi)),
542                                  new_merge_bb);
543
544       /* 1.2. NEW_MERGE_BB has two incoming edges: GUARD_EDGE and the exit-edge
545             of LOOP. Set the two phi args in NEW_PHI for these edges:  */
546       loop_arg = PHI_ARG_DEF_FROM_EDGE (orig_phi, EDGE_SUCC (loop->latch, 0));
547       guard_arg = PHI_ARG_DEF_FROM_EDGE (orig_phi, loop_preheader_edge (loop));
548
549       add_phi_arg (new_phi, loop_arg, new_exit_e);
550       add_phi_arg (new_phi, guard_arg, guard_edge);
551
552       /* 1.3. Update phi in successor block.  */
553       gcc_assert (PHI_ARG_DEF_FROM_EDGE (update_phi, e) == loop_arg
554                   || PHI_ARG_DEF_FROM_EDGE (update_phi, e) == guard_arg);
555       SET_PHI_ARG_DEF (update_phi, e->dest_idx, PHI_RESULT (new_phi));
556       update_phi2 = new_phi;
557
558
559       /** 2. Handle loop-closed-ssa-form phis  **/
560
561       /* 2.1. Generate new phi node in NEW_EXIT_BB:  */
562       new_phi = create_phi_node (SSA_NAME_VAR (PHI_RESULT (orig_phi)),
563                                  *new_exit_bb);
564
565       /* 2.2. NEW_EXIT_BB has one incoming edge: the exit-edge of the loop.  */
566       add_phi_arg (new_phi, loop_arg, loop->single_exit);
567
568       /* 2.3. Update phi in successor of NEW_EXIT_BB:  */
569       gcc_assert (PHI_ARG_DEF_FROM_EDGE (update_phi2, new_exit_e) == loop_arg);
570       SET_PHI_ARG_DEF (update_phi2, new_exit_e->dest_idx, PHI_RESULT (new_phi));
571
572       /* 2.4. Record the newly created name with set_current_def.
573          We want to find a name such that
574                 name = get_current_def (orig_loop_name)
575          and to set its current definition as follows:
576                 set_current_def (name, new_phi_name)
577
578          If LOOP is a new loop then loop_arg is already the name we're
579          looking for. If LOOP is the original loop, then loop_arg is
580          the orig_loop_name and the relevant name is recorded in its
581          current reaching definition.  */
582       if (is_new_loop)
583         current_new_name = loop_arg;
584       else
585         {
586           current_new_name = get_current_def (loop_arg);
587           gcc_assert (current_new_name);
588         }
589 #ifdef ENABLE_CHECKING
590       gcc_assert (get_current_def (current_new_name) == NULL_TREE);
591 #endif
592
593       set_current_def (current_new_name, PHI_RESULT (new_phi));
594       bitmap_set_bit (*defs, SSA_NAME_VERSION (current_new_name));
595     }
596
597   set_phi_nodes (new_merge_bb, phi_reverse (phi_nodes (new_merge_bb)));
598 }
599
600
601 /* Function slpeel_update_phi_nodes_for_guard2
602
603    Input:
604    - GUARD_EDGE, LOOP, IS_NEW_LOOP, NEW_EXIT_BB - as explained above.
605
606    In the context of the overall structure, we have:
607
608         loop1_preheader_bb: 
609                 guard1 (goto loop1/merg1_bb)
610         loop1
611         loop1_exit_bb: 
612                 guard2 (goto merge1_bb/merge2_bb)
613         merge1_bb
614 LOOP->  loop2
615         loop2_exit_bb
616         merge2_bb
617         next_bb
618
619    For each name used out side the loop (i.e - for each name that has an exit
620    phi in next_bb) we create a new phi in:
621    1. merge2_bb (to account for the edge from guard_bb) 
622    2. loop2_exit_bb (an exit-phi to keep LOOP in loop-closed form)
623    3. guard2 bb (an exit phi to keep the preceding loop in loop-closed form),
624       if needed (if it wasn't handled by slpeel_update_phis_nodes_for_phi1).
625 */
626
627 static void
628 slpeel_update_phi_nodes_for_guard2 (edge guard_edge, struct loop *loop,
629                                     bool is_new_loop, basic_block *new_exit_bb)
630 {
631   tree orig_phi, new_phi;
632   tree update_phi, update_phi2;
633   tree guard_arg, loop_arg;
634   basic_block new_merge_bb = guard_edge->dest;
635   edge e = EDGE_SUCC (new_merge_bb, 0);
636   basic_block update_bb = e->dest;
637   edge new_exit_e;
638   tree orig_def, orig_def_new_name;
639   tree new_name, new_name2;
640   tree arg;
641
642   /* Create new bb between loop and new_merge_bb.  */
643   *new_exit_bb = split_edge (loop->single_exit);
644   add_bb_to_loop (*new_exit_bb, loop->outer);
645
646   new_exit_e = EDGE_SUCC (*new_exit_bb, 0);
647
648   for (update_phi = phi_nodes (update_bb); update_phi; 
649        update_phi = PHI_CHAIN (update_phi))
650     {
651       orig_phi = update_phi;
652       orig_def = PHI_ARG_DEF_FROM_EDGE (orig_phi, e);
653       orig_def_new_name = get_current_def (orig_def);
654       arg = NULL_TREE;
655
656       /** 1. Handle new-merge-point phis  **/
657
658       /* 1.1. Generate new phi node in NEW_MERGE_BB:  */
659       new_phi = create_phi_node (SSA_NAME_VAR (PHI_RESULT (orig_phi)),
660                                  new_merge_bb);
661
662       /* 1.2. NEW_MERGE_BB has two incoming edges: GUARD_EDGE and the exit-edge
663             of LOOP. Set the two PHI args in NEW_PHI for these edges:  */
664       new_name = orig_def;
665       new_name2 = NULL_TREE;
666       if (orig_def_new_name)
667         {
668           new_name = orig_def_new_name;
669           /* Some variables have both loop-entry-phis and loop-exit-phis.
670              Such variables were given yet newer names by phis placed in
671              guard_bb by slpeel_update_phi_nodes_for_guard1. I.e:
672              new_name2 = get_current_def (get_current_def (orig_name)).  */
673           new_name2 = get_current_def (new_name);
674         }
675   
676       if (is_new_loop)
677         {
678           guard_arg = orig_def;
679           loop_arg = new_name;
680         }
681       else
682         {
683           guard_arg = new_name;
684           loop_arg = orig_def;
685         }
686       if (new_name2)
687         guard_arg = new_name2;
688   
689       add_phi_arg (new_phi, loop_arg, new_exit_e);
690       add_phi_arg (new_phi, guard_arg, guard_edge);
691
692       /* 1.3. Update phi in successor block.  */
693       gcc_assert (PHI_ARG_DEF_FROM_EDGE (update_phi, e) == orig_def);
694       SET_PHI_ARG_DEF (update_phi, e->dest_idx, PHI_RESULT (new_phi));
695       update_phi2 = new_phi;
696
697
698       /** 2. Handle loop-closed-ssa-form phis  **/
699
700       /* 2.1. Generate new phi node in NEW_EXIT_BB:  */
701       new_phi = create_phi_node (SSA_NAME_VAR (PHI_RESULT (orig_phi)),
702                                  *new_exit_bb);
703
704       /* 2.2. NEW_EXIT_BB has one incoming edge: the exit-edge of the loop.  */
705       add_phi_arg (new_phi, loop_arg, loop->single_exit);
706
707       /* 2.3. Update phi in successor of NEW_EXIT_BB:  */
708       gcc_assert (PHI_ARG_DEF_FROM_EDGE (update_phi2, new_exit_e) == loop_arg);
709       SET_PHI_ARG_DEF (update_phi2, new_exit_e->dest_idx, PHI_RESULT (new_phi));
710
711
712       /** 3. Handle loop-closed-ssa-form phis for first loop  **/
713
714       /* 3.1. Find the relevant names that need an exit-phi in
715          GUARD_BB, i.e. names for which
716          slpeel_update_phi_nodes_for_guard1 had not already created a
717          phi node. This is the case for names that are used outside
718          the loop (and therefore need an exit phi) but are not updated
719          across loop iterations (and therefore don't have a
720          loop-header-phi).
721
722          slpeel_update_phi_nodes_for_guard1 is responsible for
723          creating loop-exit phis in GUARD_BB for names that have a
724          loop-header-phi.  When such a phi is created we also record
725          the new name in its current definition.  If this new name
726          exists, then guard_arg was set to this new name (see 1.2
727          above).  Therefore, if guard_arg is not this new name, this
728          is an indication that an exit-phi in GUARD_BB was not yet
729          created, so we take care of it here.  */
730       if (guard_arg == new_name2)
731         continue;
732       arg = guard_arg;
733
734       /* 3.2. Generate new phi node in GUARD_BB:  */
735       new_phi = create_phi_node (SSA_NAME_VAR (PHI_RESULT (orig_phi)),
736                                  guard_edge->src);
737
738       /* 3.3. GUARD_BB has one incoming edge:  */
739       gcc_assert (EDGE_COUNT (guard_edge->src->preds) == 1);
740       add_phi_arg (new_phi, arg, EDGE_PRED (guard_edge->src, 0));
741
742       /* 3.4. Update phi in successor of GUARD_BB:  */
743       gcc_assert (PHI_ARG_DEF_FROM_EDGE (update_phi2, guard_edge)
744                                                                 == guard_arg);
745       SET_PHI_ARG_DEF (update_phi2, guard_edge->dest_idx, PHI_RESULT (new_phi));
746     }
747
748   set_phi_nodes (new_merge_bb, phi_reverse (phi_nodes (new_merge_bb)));
749 }
750
751
752 /* Make the LOOP iterate NITERS times. This is done by adding a new IV
753    that starts at zero, increases by one and its limit is NITERS.
754
755    Assumption: the exit-condition of LOOP is the last stmt in the loop.  */
756
757 void
758 slpeel_make_loop_iterate_ntimes (struct loop *loop, tree niters)
759 {
760   tree indx_before_incr, indx_after_incr, cond_stmt, cond;
761   tree orig_cond;
762   edge exit_edge = loop->single_exit;
763   block_stmt_iterator loop_cond_bsi;
764   block_stmt_iterator incr_bsi;
765   bool insert_after;
766   tree begin_label = tree_block_label (loop->latch);
767   tree exit_label = tree_block_label (loop->single_exit->dest);
768   tree init = build_int_cst (TREE_TYPE (niters), 0);
769   tree step = build_int_cst (TREE_TYPE (niters), 1);
770   tree then_label;
771   tree else_label;
772   LOC loop_loc;
773
774   orig_cond = get_loop_exit_condition (loop);
775 #ifdef ENABLE_CHECKING
776   gcc_assert (orig_cond);
777 #endif
778   loop_cond_bsi = bsi_for_stmt (orig_cond);
779
780   standard_iv_increment_position (loop, &incr_bsi, &insert_after);
781   create_iv (init, step, NULL_TREE, loop,
782              &incr_bsi, insert_after, &indx_before_incr, &indx_after_incr);
783
784   if (exit_edge->flags & EDGE_TRUE_VALUE) /* 'then' edge exits the loop.  */
785     {
786       cond = build2 (GE_EXPR, boolean_type_node, indx_after_incr, niters);
787       then_label = build1 (GOTO_EXPR, void_type_node, exit_label);
788       else_label = build1 (GOTO_EXPR, void_type_node, begin_label);
789     }
790   else /* 'then' edge loops back.  */
791     {
792       cond = build2 (LT_EXPR, boolean_type_node, indx_after_incr, niters);
793       then_label = build1 (GOTO_EXPR, void_type_node, begin_label);
794       else_label = build1 (GOTO_EXPR, void_type_node, exit_label);
795     }
796
797   cond_stmt = build3 (COND_EXPR, TREE_TYPE (orig_cond), cond,
798                      then_label, else_label);
799   bsi_insert_before (&loop_cond_bsi, cond_stmt, BSI_SAME_STMT);
800
801   /* Remove old loop exit test:  */
802   bsi_remove (&loop_cond_bsi);
803
804   loop_loc = find_loop_location (loop);
805   if (dump_file && (dump_flags & TDF_DETAILS))
806     {
807       if (loop_loc != UNKNOWN_LOC)
808         fprintf (dump_file, "\nloop at %s:%d: ",
809                  LOC_FILE (loop_loc), LOC_LINE (loop_loc));
810       print_generic_expr (dump_file, cond_stmt, TDF_SLIM);
811     }
812
813   loop->nb_iterations = niters;
814 }
815
816
817 /* Given LOOP this function generates a new copy of it and puts it 
818    on E which is either the entry or exit of LOOP.  */
819
820 static struct loop *
821 slpeel_tree_duplicate_loop_to_edge_cfg (struct loop *loop, struct loops *loops, 
822                                         edge e)
823 {
824   struct loop *new_loop;
825   basic_block *new_bbs, *bbs;
826   bool at_exit;
827   bool was_imm_dom;
828   basic_block exit_dest; 
829   tree phi, phi_arg;
830
831   at_exit = (e == loop->single_exit); 
832   if (!at_exit && e != loop_preheader_edge (loop))
833     return NULL;
834
835   bbs = get_loop_body (loop);
836
837   /* Check whether duplication is possible.  */
838   if (!can_copy_bbs_p (bbs, loop->num_nodes))
839     {
840       free (bbs);
841       return NULL;
842     }
843
844   /* Generate new loop structure.  */
845   new_loop = duplicate_loop (loops, loop, loop->outer);
846   if (!new_loop)
847     {
848       free (bbs);
849       return NULL;
850     }
851
852   exit_dest = loop->single_exit->dest;
853   was_imm_dom = (get_immediate_dominator (CDI_DOMINATORS, 
854                                           exit_dest) == loop->header ? 
855                  true : false);
856
857   new_bbs = xmalloc (sizeof (basic_block) * loop->num_nodes);
858
859   copy_bbs (bbs, loop->num_nodes, new_bbs,
860             &loop->single_exit, 1, &new_loop->single_exit, NULL);
861
862   /* Duplicating phi args at exit bbs as coming 
863      also from exit of duplicated loop.  */
864   for (phi = phi_nodes (exit_dest); phi; phi = PHI_CHAIN (phi))
865     {
866       phi_arg = PHI_ARG_DEF_FROM_EDGE (phi, loop->single_exit);
867       if (phi_arg)
868         {
869           edge new_loop_exit_edge;
870
871           if (EDGE_SUCC (new_loop->header, 0)->dest == new_loop->latch)
872             new_loop_exit_edge = EDGE_SUCC (new_loop->header, 1);
873           else
874             new_loop_exit_edge = EDGE_SUCC (new_loop->header, 0);
875   
876           add_phi_arg (phi, phi_arg, new_loop_exit_edge);       
877         }
878     }    
879    
880   if (at_exit) /* Add the loop copy at exit.  */
881     {
882       redirect_edge_and_branch_force (e, new_loop->header);
883       set_immediate_dominator (CDI_DOMINATORS, new_loop->header, e->src);
884       if (was_imm_dom)
885         set_immediate_dominator (CDI_DOMINATORS, exit_dest, new_loop->header);
886     }
887   else /* Add the copy at entry.  */
888     {
889       edge new_exit_e;
890       edge entry_e = loop_preheader_edge (loop);
891       basic_block preheader = entry_e->src;
892            
893       if (!flow_bb_inside_loop_p (new_loop, 
894                                   EDGE_SUCC (new_loop->header, 0)->dest))
895         new_exit_e = EDGE_SUCC (new_loop->header, 0);
896       else
897         new_exit_e = EDGE_SUCC (new_loop->header, 1); 
898
899       redirect_edge_and_branch_force (new_exit_e, loop->header);
900       set_immediate_dominator (CDI_DOMINATORS, loop->header,
901                                new_exit_e->src);
902
903       /* We have to add phi args to the loop->header here as coming 
904          from new_exit_e edge.  */
905       for (phi = phi_nodes (loop->header); phi; phi = PHI_CHAIN (phi))
906         {
907           phi_arg = PHI_ARG_DEF_FROM_EDGE (phi, entry_e);
908           if (phi_arg)
909             add_phi_arg (phi, phi_arg, new_exit_e);     
910         }    
911
912       redirect_edge_and_branch_force (entry_e, new_loop->header);
913       set_immediate_dominator (CDI_DOMINATORS, new_loop->header, preheader);
914     }
915
916   free (new_bbs);
917   free (bbs);
918
919   return new_loop;
920 }
921
922
923 /* Given the condition statement COND, put it as the last statement
924    of GUARD_BB; EXIT_BB is the basic block to skip the loop;
925    Assumes that this is the single exit of the guarded loop.  
926    Returns the skip edge.  */
927
928 static edge
929 slpeel_add_loop_guard (basic_block guard_bb, tree cond, basic_block exit_bb,
930                         basic_block dom_bb)
931 {
932   block_stmt_iterator bsi;
933   edge new_e, enter_e;
934   tree cond_stmt, then_label, else_label;
935
936   enter_e = EDGE_SUCC (guard_bb, 0);
937   enter_e->flags &= ~EDGE_FALLTHRU;
938   enter_e->flags |= EDGE_FALSE_VALUE;
939   bsi = bsi_last (guard_bb);
940
941   then_label = build1 (GOTO_EXPR, void_type_node,
942                        tree_block_label (exit_bb));
943   else_label = build1 (GOTO_EXPR, void_type_node,
944                        tree_block_label (enter_e->dest));
945   cond_stmt = build3 (COND_EXPR, void_type_node, cond,
946                      then_label, else_label);
947   bsi_insert_after (&bsi, cond_stmt, BSI_NEW_STMT);
948   /* Add new edge to connect guard block to the merge/loop-exit block.  */
949   new_e = make_edge (guard_bb, exit_bb, EDGE_TRUE_VALUE);
950   set_immediate_dominator (CDI_DOMINATORS, exit_bb, dom_bb);
951   return new_e;
952 }
953
954
955 /* This function verifies that the following restrictions apply to LOOP:
956    (1) it is innermost
957    (2) it consists of exactly 2 basic blocks - header, and an empty latch.
958    (3) it is single entry, single exit
959    (4) its exit condition is the last stmt in the header
960    (5) E is the entry/exit edge of LOOP.
961  */
962
963 bool
964 slpeel_can_duplicate_loop_p (struct loop *loop, edge e)
965 {
966   edge exit_e = loop->single_exit;
967   edge entry_e = loop_preheader_edge (loop);
968   tree orig_cond = get_loop_exit_condition (loop);
969   block_stmt_iterator loop_exit_bsi = bsi_last (exit_e->src);
970
971   if (need_ssa_update_p ())
972     return false;
973
974   if (loop->inner
975       /* All loops have an outer scope; the only case loop->outer is NULL is for
976          the function itself.  */
977       || !loop->outer
978       || loop->num_nodes != 2
979       || !empty_block_p (loop->latch)
980       || !loop->single_exit
981       /* Verify that new loop exit condition can be trivially modified.  */
982       || (!orig_cond || orig_cond != bsi_stmt (loop_exit_bsi))
983       || (e != exit_e && e != entry_e))
984     return false;
985
986   return true;
987 }
988
989 #ifdef ENABLE_CHECKING
990 void
991 slpeel_verify_cfg_after_peeling (struct loop *first_loop,
992                                  struct loop *second_loop)
993 {
994   basic_block loop1_exit_bb = first_loop->single_exit->dest;
995   basic_block loop2_entry_bb = loop_preheader_edge (second_loop)->src;
996   basic_block loop1_entry_bb = loop_preheader_edge (first_loop)->src;
997
998   /* A guard that controls whether the second_loop is to be executed or skipped
999      is placed in first_loop->exit.  first_loopt->exit therefore has two
1000      successors - one is the preheader of second_loop, and the other is a bb
1001      after second_loop.
1002    */
1003   gcc_assert (EDGE_COUNT (loop1_exit_bb->succs) == 2);
1004    
1005   /* 1. Verify that one of the successors of first_loopt->exit is the preheader
1006         of second_loop.  */
1007    
1008   /* The preheader of new_loop is expected to have two predessors:
1009      first_loop->exit and the block that precedes first_loop.  */
1010
1011   gcc_assert (EDGE_COUNT (loop2_entry_bb->preds) == 2 
1012               && ((EDGE_PRED (loop2_entry_bb, 0)->src == loop1_exit_bb
1013                    && EDGE_PRED (loop2_entry_bb, 1)->src == loop1_entry_bb)
1014                || (EDGE_PRED (loop2_entry_bb, 1)->src ==  loop1_exit_bb
1015                    && EDGE_PRED (loop2_entry_bb, 0)->src == loop1_entry_bb)));
1016   
1017   /* Verify that the other successor of first_loopt->exit is after the
1018      second_loop.  */
1019   /* TODO */
1020 }
1021 #endif
1022
1023 /* Function slpeel_tree_peel_loop_to_edge.
1024
1025    Peel the first (last) iterations of LOOP into a new prolog (epilog) loop
1026    that is placed on the entry (exit) edge E of LOOP. After this transformation
1027    we have two loops one after the other - first-loop iterates FIRST_NITERS
1028    times, and second-loop iterates the remainder NITERS - FIRST_NITERS times.
1029
1030    Input:
1031    - LOOP: the loop to be peeled.
1032    - E: the exit or entry edge of LOOP.
1033         If it is the entry edge, we peel the first iterations of LOOP. In this
1034         case first-loop is LOOP, and second-loop is the newly created loop.
1035         If it is the exit edge, we peel the last iterations of LOOP. In this
1036         case, first-loop is the newly created loop, and second-loop is LOOP.
1037    - NITERS: the number of iterations that LOOP iterates.
1038    - FIRST_NITERS: the number of iterations that the first-loop should iterate.
1039    - UPDATE_FIRST_LOOP_COUNT:  specified whether this function is responsible
1040         for updating the loop bound of the first-loop to FIRST_NITERS.  If it
1041         is false, the caller of this function may want to take care of this
1042         (this can be useful if we don't want new stmts added to first-loop).
1043
1044    Output:
1045    The function returns a pointer to the new loop-copy, or NULL if it failed
1046    to perform the transformation.
1047
1048    The function generates two if-then-else guards: one before the first loop,
1049    and the other before the second loop:
1050    The first guard is:
1051      if (FIRST_NITERS == 0) then skip the first loop,
1052      and go directly to the second loop.
1053    The second guard is:
1054      if (FIRST_NITERS == NITERS) then skip the second loop.
1055
1056    FORNOW only simple loops are supported (see slpeel_can_duplicate_loop_p).
1057    FORNOW the resulting code will not be in loop-closed-ssa form.
1058 */
1059
1060 struct loop*
1061 slpeel_tree_peel_loop_to_edge (struct loop *loop, struct loops *loops, 
1062                                edge e, tree first_niters, 
1063                                tree niters, bool update_first_loop_count)
1064 {
1065   struct loop *new_loop = NULL, *first_loop, *second_loop;
1066   edge skip_e;
1067   tree pre_condition;
1068   bitmap definitions;
1069   basic_block bb_before_second_loop, bb_after_second_loop;
1070   basic_block bb_before_first_loop;
1071   basic_block bb_between_loops;
1072   basic_block new_exit_bb;
1073   edge exit_e = loop->single_exit;
1074   LOC loop_loc;
1075   
1076   if (!slpeel_can_duplicate_loop_p (loop, e))
1077     return NULL;
1078   
1079   /* We have to initialize cfg_hooks. Then, when calling
1080    cfg_hooks->split_edge, the function tree_split_edge 
1081    is actually called and, when calling cfg_hooks->duplicate_block,
1082    the function tree_duplicate_bb is called.  */
1083   tree_register_cfg_hooks ();
1084
1085
1086   /* 1. Generate a copy of LOOP and put it on E (E is the entry/exit of LOOP).
1087         Resulting CFG would be:
1088
1089         first_loop:
1090         do {
1091         } while ...
1092
1093         second_loop:
1094         do {
1095         } while ...
1096
1097         orig_exit_bb:
1098    */
1099   
1100   if (!(new_loop = slpeel_tree_duplicate_loop_to_edge_cfg (loop, loops, e)))
1101     {
1102       loop_loc = find_loop_location (loop);
1103       if (dump_file && (dump_flags & TDF_DETAILS))
1104         {
1105           if (loop_loc != UNKNOWN_LOC)
1106             fprintf (dump_file, "\n%s:%d: note: ",
1107                      LOC_FILE (loop_loc), LOC_LINE (loop_loc));
1108           fprintf (dump_file, "tree_duplicate_loop_to_edge_cfg failed.\n");
1109         }
1110       return NULL;
1111     }
1112   
1113   if (e == exit_e)
1114     {
1115       /* NEW_LOOP was placed after LOOP.  */
1116       first_loop = loop;
1117       second_loop = new_loop;
1118     }
1119   else
1120     {
1121       /* NEW_LOOP was placed before LOOP.  */
1122       first_loop = new_loop;
1123       second_loop = loop;
1124     }
1125
1126   definitions = ssa_names_to_replace ();
1127   slpeel_update_phis_for_duplicate_loop (loop, new_loop, e == exit_e);
1128   rename_variables_in_loop (new_loop);
1129
1130
1131   /* 2. Add the guard that controls whether the first loop is executed.
1132         Resulting CFG would be:
1133
1134         bb_before_first_loop:
1135         if (FIRST_NITERS == 0) GOTO bb_before_second_loop
1136                                GOTO first-loop
1137
1138         first_loop:
1139         do {
1140         } while ...
1141
1142         bb_before_second_loop:
1143
1144         second_loop:
1145         do {
1146         } while ...
1147
1148         orig_exit_bb:
1149    */
1150
1151   bb_before_first_loop = split_edge (loop_preheader_edge (first_loop));
1152   add_bb_to_loop (bb_before_first_loop, first_loop->outer);
1153   bb_before_second_loop = split_edge (first_loop->single_exit);
1154   add_bb_to_loop (bb_before_second_loop, first_loop->outer);
1155
1156   pre_condition =
1157     fold (build2 (LE_EXPR, boolean_type_node, first_niters, integer_zero_node));
1158   skip_e = slpeel_add_loop_guard (bb_before_first_loop, pre_condition,
1159                                   bb_before_second_loop, bb_before_first_loop);
1160   slpeel_update_phi_nodes_for_guard1 (skip_e, first_loop,
1161                                       first_loop == new_loop,
1162                                       &new_exit_bb, &definitions);
1163
1164
1165   /* 3. Add the guard that controls whether the second loop is executed.
1166         Resulting CFG would be:
1167
1168         bb_before_first_loop:
1169         if (FIRST_NITERS == 0) GOTO bb_before_second_loop (skip first loop)
1170                                GOTO first-loop
1171
1172         first_loop:
1173         do {
1174         } while ...
1175
1176         bb_between_loops:
1177         if (FIRST_NITERS == NITERS) GOTO bb_after_second_loop (skip second loop)
1178                                     GOTO bb_before_second_loop
1179
1180         bb_before_second_loop:
1181
1182         second_loop:
1183         do {
1184         } while ...
1185
1186         bb_after_second_loop:
1187
1188         orig_exit_bb:
1189    */
1190
1191   bb_between_loops = new_exit_bb;
1192   bb_after_second_loop = split_edge (second_loop->single_exit);
1193   add_bb_to_loop (bb_after_second_loop, second_loop->outer);
1194
1195   pre_condition = 
1196         fold (build2 (EQ_EXPR, boolean_type_node, first_niters, niters));
1197   skip_e = slpeel_add_loop_guard (bb_between_loops, pre_condition,
1198                                   bb_after_second_loop, bb_before_first_loop);
1199   slpeel_update_phi_nodes_for_guard2 (skip_e, second_loop,
1200                                      second_loop == new_loop, &new_exit_bb);
1201
1202   /* 4. Make first-loop iterate FIRST_NITERS times, if requested.
1203    */
1204   if (update_first_loop_count)
1205     slpeel_make_loop_iterate_ntimes (first_loop, first_niters);
1206
1207   BITMAP_FREE (definitions);
1208   delete_update_ssa ();
1209
1210   return new_loop;
1211 }
1212
1213 /* Function vect_get_loop_location.
1214
1215    Extract the location of the loop in the source code.
1216    If the loop is not well formed for vectorization, an estimated
1217    location is calculated.
1218    Return the loop location if succeed and NULL if not.  */
1219
1220 LOC
1221 find_loop_location (struct loop *loop)
1222 {
1223   tree node = NULL_TREE;
1224   basic_block bb;
1225   block_stmt_iterator si;
1226
1227   if (!loop)
1228     return UNKNOWN_LOC;
1229
1230   node = get_loop_exit_condition (loop);
1231
1232   if (node && EXPR_P (node) && EXPR_HAS_LOCATION (node)
1233       && EXPR_FILENAME (node) && EXPR_LINENO (node))
1234     return EXPR_LOC (node);
1235
1236   /* If we got here the loop is probably not "well formed",
1237      try to estimate the loop location */
1238
1239   if (!loop->header)
1240     return UNKNOWN_LOC;
1241
1242   bb = loop->header;
1243
1244   for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
1245     {
1246       node = bsi_stmt (si);
1247       if (node && EXPR_P (node) && EXPR_HAS_LOCATION (node))
1248         return EXPR_LOC (node);
1249     }
1250
1251   return UNKNOWN_LOC;
1252 }
1253
1254
1255 /*************************************************************************
1256   Vectorization Debug Information.
1257  *************************************************************************/
1258
1259 /* Function vect_set_verbosity_level.
1260
1261    Called from toplev.c upon detection of the
1262    -ftree-vectorizer-verbose=N option.  */
1263
1264 void
1265 vect_set_verbosity_level (const char *val)
1266 {
1267    unsigned int vl;
1268
1269    vl = atoi (val);
1270    if (vl < MAX_VERBOSITY_LEVEL)
1271      vect_verbosity_level = vl;
1272    else
1273      vect_verbosity_level = MAX_VERBOSITY_LEVEL - 1;
1274 }
1275
1276
1277 /* Function vect_set_dump_settings.
1278
1279    Fix the verbosity level of the vectorizer if the
1280    requested level was not set explicitly using the flag
1281    -ftree-vectorizer-verbose=N.
1282    Decide where to print the debugging information (dump_file/stderr).
1283    If the user defined the verbosity level, but there is no dump file,
1284    print to stderr, otherwise print to the dump file.  */
1285
1286 static void
1287 vect_set_dump_settings (void)
1288 {
1289   vect_dump = dump_file;
1290
1291   /* Check if the verbosity level was defined by the user:  */
1292   if (vect_verbosity_level != MAX_VERBOSITY_LEVEL)
1293     {
1294       /* If there is no dump file, print to stderr.  */
1295       if (!dump_file)
1296         vect_dump = stderr;
1297       return;
1298     }
1299
1300   /* User didn't specify verbosity level:  */
1301   if (dump_file && (dump_flags & TDF_DETAILS))
1302     vect_verbosity_level = REPORT_DETAILS;
1303   else if (dump_file && (dump_flags & TDF_STATS))
1304     vect_verbosity_level = REPORT_UNVECTORIZED_LOOPS;
1305   else
1306     vect_verbosity_level = REPORT_NONE;
1307
1308   gcc_assert (dump_file || vect_verbosity_level == REPORT_NONE);
1309 }
1310
1311
1312 /* Function debug_loop_details.
1313
1314    For vectorization debug dumps.  */
1315
1316 bool
1317 vect_print_dump_info (enum verbosity_levels vl, LOC loc)
1318 {
1319   if (vl > vect_verbosity_level)
1320     return false;
1321
1322   if (loc == UNKNOWN_LOC)
1323     fprintf (vect_dump, "\n%s:%d: note: ",
1324                  DECL_SOURCE_FILE (current_function_decl),
1325                  DECL_SOURCE_LINE (current_function_decl));
1326   else
1327     fprintf (vect_dump, "\n%s:%d: note: ", LOC_FILE (loc), LOC_LINE (loc));
1328
1329
1330   return true;
1331 }
1332
1333
1334 /*************************************************************************
1335   Vectorization Utilities.
1336  *************************************************************************/
1337
1338 /* Function new_stmt_vec_info.
1339
1340    Create and initialize a new stmt_vec_info struct for STMT.  */
1341
1342 stmt_vec_info
1343 new_stmt_vec_info (tree stmt, loop_vec_info loop_vinfo)
1344 {
1345   stmt_vec_info res;
1346   res = (stmt_vec_info) xcalloc (1, sizeof (struct _stmt_vec_info));
1347
1348   STMT_VINFO_TYPE (res) = undef_vec_info_type;
1349   STMT_VINFO_STMT (res) = stmt;
1350   STMT_VINFO_LOOP_VINFO (res) = loop_vinfo;
1351   STMT_VINFO_RELEVANT_P (res) = 0;
1352   STMT_VINFO_VECTYPE (res) = NULL;
1353   STMT_VINFO_VEC_STMT (res) = NULL;
1354   STMT_VINFO_DATA_REF (res) = NULL;
1355   STMT_VINFO_MEMTAG (res) = NULL;
1356   STMT_VINFO_PTR_INFO (res) = NULL;
1357   STMT_VINFO_SUBVARS (res) = NULL;
1358   STMT_VINFO_VECT_DR_BASE_ADDRESS (res) = NULL;
1359   STMT_VINFO_VECT_INIT_OFFSET (res) = NULL_TREE;
1360   STMT_VINFO_VECT_STEP (res) = NULL_TREE;
1361   STMT_VINFO_VECT_BASE_ALIGNED_P (res) = false;
1362   STMT_VINFO_VECT_MISALIGNMENT (res) = NULL_TREE;
1363
1364   return res;
1365 }
1366
1367
1368 /* Function new_loop_vec_info.
1369
1370    Create and initialize a new loop_vec_info struct for LOOP, as well as
1371    stmt_vec_info structs for all the stmts in LOOP.  */
1372
1373 loop_vec_info
1374 new_loop_vec_info (struct loop *loop)
1375 {
1376   loop_vec_info res;
1377   basic_block *bbs;
1378   block_stmt_iterator si;
1379   unsigned int i;
1380
1381   res = (loop_vec_info) xcalloc (1, sizeof (struct _loop_vec_info));
1382
1383   bbs = get_loop_body (loop);
1384
1385   /* Create stmt_info for all stmts in the loop.  */
1386   for (i = 0; i < loop->num_nodes; i++)
1387     {
1388       basic_block bb = bbs[i];
1389       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
1390         {
1391           tree stmt = bsi_stmt (si);
1392           stmt_ann_t ann;
1393
1394           ann = stmt_ann (stmt);
1395           set_stmt_info (ann, new_stmt_vec_info (stmt, res));
1396         }
1397     }
1398
1399   LOOP_VINFO_LOOP (res) = loop;
1400   LOOP_VINFO_BBS (res) = bbs;
1401   LOOP_VINFO_EXIT_COND (res) = NULL;
1402   LOOP_VINFO_NITERS (res) = NULL;
1403   LOOP_VINFO_VECTORIZABLE_P (res) = 0;
1404   LOOP_PEELING_FOR_ALIGNMENT (res) = 0;
1405   LOOP_VINFO_VECT_FACTOR (res) = 0;
1406   VARRAY_GENERIC_PTR_INIT (LOOP_VINFO_DATAREF_WRITES (res), 20,
1407                            "loop_write_datarefs");
1408   VARRAY_GENERIC_PTR_INIT (LOOP_VINFO_DATAREF_READS (res), 20,
1409                            "loop_read_datarefs");
1410   LOOP_VINFO_UNALIGNED_DR (res) = NULL;
1411   LOOP_VINFO_LOC (res) = UNKNOWN_LOC;
1412
1413   return res;
1414 }
1415
1416
1417 /* Function destroy_loop_vec_info.
1418  
1419    Free LOOP_VINFO struct, as well as all the stmt_vec_info structs of all the 
1420    stmts in the loop.  */
1421
1422 void
1423 destroy_loop_vec_info (loop_vec_info loop_vinfo)
1424 {
1425   struct loop *loop;
1426   basic_block *bbs;
1427   int nbbs;
1428   block_stmt_iterator si;
1429   int j;
1430
1431   if (!loop_vinfo)
1432     return;
1433
1434   loop = LOOP_VINFO_LOOP (loop_vinfo);
1435
1436   bbs = LOOP_VINFO_BBS (loop_vinfo);
1437   nbbs = loop->num_nodes;
1438
1439   for (j = 0; j < nbbs; j++)
1440     {
1441       basic_block bb = bbs[j];
1442       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
1443         {
1444           tree stmt = bsi_stmt (si);
1445           stmt_ann_t ann = stmt_ann (stmt);
1446           stmt_vec_info stmt_info = vinfo_for_stmt (stmt);
1447           free (stmt_info);
1448           set_stmt_info (ann, NULL);
1449         }
1450     }
1451
1452   free (LOOP_VINFO_BBS (loop_vinfo));
1453   varray_clear (LOOP_VINFO_DATAREF_WRITES (loop_vinfo));
1454   varray_clear (LOOP_VINFO_DATAREF_READS (loop_vinfo));
1455
1456   free (loop_vinfo);
1457 }
1458
1459
1460 /* Function vect_strip_conversions
1461
1462    Strip conversions that don't narrow the mode.  */
1463
1464 tree 
1465 vect_strip_conversion (tree expr)
1466 {
1467   tree to, ti, oprnd0;
1468   
1469   while (TREE_CODE (expr) == NOP_EXPR || TREE_CODE (expr) == CONVERT_EXPR)
1470     {
1471       to = TREE_TYPE (expr);
1472       oprnd0 = TREE_OPERAND (expr, 0);
1473       ti = TREE_TYPE (oprnd0);
1474  
1475       if (!INTEGRAL_TYPE_P (to) || !INTEGRAL_TYPE_P (ti))
1476         return NULL_TREE;
1477       if (GET_MODE_SIZE (TYPE_MODE (to)) < GET_MODE_SIZE (TYPE_MODE (ti)))
1478         return NULL_TREE;
1479       
1480       expr = oprnd0;
1481     }
1482   return expr; 
1483 }
1484
1485
1486 /* Function vect_force_dr_alignment_p.
1487
1488    Returns whether the alignment of a DECL can be forced to be aligned
1489    on ALIGNMENT bit boundary.  */
1490
1491 bool 
1492 vect_can_force_dr_alignment_p (tree decl, unsigned int alignment)
1493 {
1494   if (TREE_CODE (decl) != VAR_DECL)
1495     return false;
1496
1497   if (DECL_EXTERNAL (decl))
1498     return false;
1499
1500   if (TREE_ASM_WRITTEN (decl))
1501     return false;
1502
1503   if (TREE_STATIC (decl))
1504     return (alignment <= MAX_OFILE_ALIGNMENT);
1505   else
1506     /* This is not 100% correct.  The absolute correct stack alignment
1507        is STACK_BOUNDARY.  We're supposed to hope, but not assume, that
1508        PREFERRED_STACK_BOUNDARY is honored by all translation units.
1509        However, until someone implements forced stack alignment, SSE
1510        isn't really usable without this.  */  
1511     return (alignment <= PREFERRED_STACK_BOUNDARY); 
1512 }
1513
1514
1515 /* Function get_vectype_for_scalar_type.
1516
1517    Returns the vector type corresponding to SCALAR_TYPE as supported
1518    by the target.  */
1519
1520 tree
1521 get_vectype_for_scalar_type (tree scalar_type)
1522 {
1523   enum machine_mode inner_mode = TYPE_MODE (scalar_type);
1524   int nbytes = GET_MODE_SIZE (inner_mode);
1525   int nunits;
1526   tree vectype;
1527
1528   if (nbytes == 0)
1529     return NULL_TREE;
1530
1531   /* FORNOW: Only a single vector size per target (UNITS_PER_SIMD_WORD)
1532      is expected.  */
1533   nunits = UNITS_PER_SIMD_WORD / nbytes;
1534
1535   vectype = build_vector_type (scalar_type, nunits);
1536   if (vect_print_dump_info (REPORT_DETAILS, UNKNOWN_LOC))
1537     {
1538       fprintf (vect_dump, "get vectype with %d units of type ", nunits);
1539       print_generic_expr (vect_dump, scalar_type, TDF_SLIM);
1540     }
1541
1542   if (!vectype)
1543     return NULL_TREE;
1544
1545   if (vect_print_dump_info (REPORT_DETAILS, UNKNOWN_LOC))
1546     {
1547       fprintf (vect_dump, "vectype: ");
1548       print_generic_expr (vect_dump, vectype, TDF_SLIM);
1549     }
1550
1551   if (!VECTOR_MODE_P (TYPE_MODE (vectype)))
1552     {
1553       /* TODO: tree-complex.c sometimes can parallelize operations
1554          on generic vectors.  We can vectorize the loop in that case,
1555          but then we should re-run the lowering pass.  */
1556       if (vect_print_dump_info (REPORT_DETAILS, UNKNOWN_LOC))
1557         fprintf (vect_dump, "mode not supported by target.");
1558       return NULL_TREE;
1559     }
1560
1561   return vectype;
1562 }
1563
1564
1565 /* Function vect_supportable_dr_alignment
1566
1567    Return whether the data reference DR is supported with respect to its
1568    alignment.  */
1569
1570 enum dr_alignment_support
1571 vect_supportable_dr_alignment (struct data_reference *dr)
1572 {
1573   tree vectype = STMT_VINFO_VECTYPE (vinfo_for_stmt (DR_STMT (dr)));
1574   enum machine_mode mode = (int) TYPE_MODE (vectype);
1575
1576   if (aligned_access_p (dr))
1577     return dr_aligned;
1578
1579   /* Possibly unaligned access.  */
1580   
1581   if (DR_IS_READ (dr))
1582     {
1583       if (vec_realign_load_optab->handlers[mode].insn_code != CODE_FOR_nothing
1584           && (!targetm.vectorize.builtin_mask_for_load
1585               || targetm.vectorize.builtin_mask_for_load ()))
1586         return dr_unaligned_software_pipeline;
1587
1588       if (movmisalign_optab->handlers[mode].insn_code != CODE_FOR_nothing)
1589         /* Can't software pipeline the loads, but can at least do them.  */
1590         return dr_unaligned_supported;
1591     }
1592
1593   /* Unsupported.  */
1594   return dr_unaligned_unsupported;
1595 }
1596
1597
1598 /* Function vect_is_simple_use.
1599
1600    Input:
1601    LOOP - the loop that is being vectorized.
1602    OPERAND - operand of a stmt in LOOP.
1603    DEF - the defining stmt in case OPERAND is an SSA_NAME.
1604
1605    Returns whether a stmt with OPERAND can be vectorized.
1606    Supportable operands are constants, loop invariants, and operands that are
1607    defined by the current iteration of the loop. Unsupportable operands are 
1608    those that are defined by a previous iteration of the loop (as is the case
1609    in reduction/induction computations).  */
1610
1611 bool
1612 vect_is_simple_use (tree operand, loop_vec_info loop_vinfo, tree *def)
1613
1614   tree def_stmt;
1615   basic_block bb;
1616   struct loop *loop = LOOP_VINFO_LOOP (loop_vinfo);
1617
1618   if (def)
1619     *def = NULL_TREE;
1620
1621   if (TREE_CODE (operand) == INTEGER_CST || TREE_CODE (operand) == REAL_CST)
1622     return true;
1623
1624   if (TREE_CODE (operand) != SSA_NAME)
1625     return false;
1626
1627   def_stmt = SSA_NAME_DEF_STMT (operand);
1628   if (def_stmt == NULL_TREE )
1629     {
1630       if (vect_print_dump_info (REPORT_DETAILS, UNKNOWN_LOC))
1631         fprintf (vect_dump, "no def_stmt.");
1632       return false;
1633     }
1634
1635   /* empty stmt is expected only in case of a function argument.
1636      (Otherwise - we expect a phi_node or a modify_expr).  */
1637   if (IS_EMPTY_STMT (def_stmt))
1638     {
1639       tree arg = TREE_OPERAND (def_stmt, 0);
1640       if (TREE_CODE (arg) == INTEGER_CST || TREE_CODE (arg) == REAL_CST)
1641         return true;
1642       if (vect_print_dump_info (REPORT_DETAILS, UNKNOWN_LOC))
1643         {
1644           fprintf (vect_dump, "Unexpected empty stmt: ");
1645           print_generic_expr (vect_dump, def_stmt, TDF_SLIM);
1646         }
1647       return false;  
1648     }
1649
1650   /* phi_node inside the loop indicates an induction/reduction pattern.
1651      This is not supported yet.  */
1652   bb = bb_for_stmt (def_stmt);
1653   if (TREE_CODE (def_stmt) == PHI_NODE && flow_bb_inside_loop_p (loop, bb))
1654     {
1655       if (vect_print_dump_info (REPORT_DETAILS, UNKNOWN_LOC))
1656         fprintf (vect_dump, "reduction/induction - unsupported.");
1657       return false; /* FORNOW: not supported yet.  */
1658     }
1659
1660   /* Expecting a modify_expr or a phi_node.  */
1661   if (TREE_CODE (def_stmt) == MODIFY_EXPR
1662       || TREE_CODE (def_stmt) == PHI_NODE)
1663     {
1664       if (def)
1665         *def = def_stmt;        
1666       return true;
1667     }
1668
1669   return false;
1670 }
1671
1672
1673 /* Function vect_is_simple_iv_evolution.
1674
1675    FORNOW: A simple evolution of an induction variables in the loop is
1676    considered a polynomial evolution with constant step.  */
1677
1678 bool
1679 vect_is_simple_iv_evolution (unsigned loop_nb, tree access_fn, tree * init, 
1680                              tree * step)
1681 {
1682   tree init_expr;
1683   tree step_expr;
1684   
1685   tree evolution_part = evolution_part_in_loop_num (access_fn, loop_nb);
1686
1687   /* When there is no evolution in this loop, the evolution function
1688      is not "simple".  */  
1689   if (evolution_part == NULL_TREE)
1690     return false;
1691   
1692   /* When the evolution is a polynomial of degree >= 2
1693      the evolution function is not "simple".  */
1694   if (tree_is_chrec (evolution_part))
1695     return false;
1696   
1697   step_expr = evolution_part;
1698   init_expr = unshare_expr (initial_condition_in_loop_num (access_fn,
1699                                                            loop_nb));
1700
1701   if (vect_print_dump_info (REPORT_DETAILS, UNKNOWN_LOC))
1702     {
1703       fprintf (vect_dump, "step: ");
1704       print_generic_expr (vect_dump, step_expr, TDF_SLIM);
1705       fprintf (vect_dump, ",  init: ");
1706       print_generic_expr (vect_dump, init_expr, TDF_SLIM);
1707     }
1708
1709   *init = init_expr;
1710   *step = step_expr;
1711
1712   if (TREE_CODE (step_expr) != INTEGER_CST)
1713     {
1714       if (vect_print_dump_info (REPORT_DETAILS, UNKNOWN_LOC))
1715         fprintf (vect_dump, "step unknown.");
1716       return false;
1717     }
1718
1719   return true;
1720 }
1721
1722
1723 /* Function vectorize_loops.
1724    
1725    Entry Point to loop vectorization phase.  */
1726
1727 void
1728 vectorize_loops (struct loops *loops)
1729 {
1730   unsigned int i;
1731   unsigned int num_vectorized_loops = 0;
1732
1733   /* Fix the verbosity level if not defined explicitly by the user.  */
1734   vect_set_dump_settings ();
1735
1736   /* Does the target support SIMD?  */
1737   /* FORNOW: until more sophisticated machine modelling is in place.  */
1738   if (!UNITS_PER_SIMD_WORD)
1739     {
1740       if (vect_print_dump_info (REPORT_DETAILS, UNKNOWN_LOC))
1741         fprintf (vect_dump, "vectorizer: target vector size is not defined.");
1742       return;
1743     }
1744
1745   /*  ----------- Analyze loops. -----------  */
1746
1747   /* If some loop was duplicated, it gets bigger number 
1748      than all previously defined loops. This fact allows us to run 
1749      only over initial loops skipping newly generated ones.  */
1750   vect_loops_num = loops->num;
1751   for (i = 1; i < vect_loops_num; i++)
1752     {
1753       loop_vec_info loop_vinfo;
1754       struct loop *loop = loops->parray[i];
1755
1756       if (!loop)
1757         continue;
1758
1759       loop_vinfo = vect_analyze_loop (loop);
1760       loop->aux = loop_vinfo;
1761
1762       if (!loop_vinfo || !LOOP_VINFO_VECTORIZABLE_P (loop_vinfo))
1763         continue;
1764
1765       vect_transform_loop (loop_vinfo, loops); 
1766       num_vectorized_loops++;
1767     }
1768
1769   if (vect_print_dump_info (REPORT_VECTORIZED_LOOPS, UNKNOWN_LOC))
1770     fprintf (vect_dump, "vectorized %u loops in function.\n",
1771              num_vectorized_loops);
1772
1773   /*  ----------- Finalize. -----------  */
1774
1775   for (i = 1; i < vect_loops_num; i++)
1776     {
1777       struct loop *loop = loops->parray[i];
1778       loop_vec_info loop_vinfo;
1779
1780       if (!loop)
1781         continue;
1782       loop_vinfo = loop->aux;
1783       destroy_loop_vec_info (loop_vinfo);
1784       loop->aux = NULL;
1785     }
1786 }