OSDN Git Service

2010-08-27 Jerry DeLisle <jvdelisle@gcc.gnu.org>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-loop-im.c
1 /* Loop invariant motion.
2    Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2010
3    Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT
13 ANY 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 COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "tm_p.h"
27 #include "basic-block.h"
28 #include "output.h"
29 #include "tree-pretty-print.h"
30 #include "gimple-pretty-print.h"
31 #include "tree-flow.h"
32 #include "tree-dump.h"
33 #include "timevar.h"
34 #include "cfgloop.h"
35 #include "domwalk.h"
36 #include "params.h"
37 #include "tree-pass.h"
38 #include "flags.h"
39 #include "hashtab.h"
40 #include "tree-affine.h"
41 #include "pointer-set.h"
42 #include "tree-ssa-propagate.h"
43
44 /* TODO:  Support for predicated code motion.  I.e.
45
46    while (1)
47      {
48        if (cond)
49          {
50            a = inv;
51            something;
52          }
53      }
54
55    Where COND and INV are is invariants, but evaluating INV may trap or be
56    invalid from some other reason if !COND.  This may be transformed to
57
58    if (cond)
59      a = inv;
60    while (1)
61      {
62        if (cond)
63          something;
64      }  */
65
66 /* A type for the list of statements that have to be moved in order to be able
67    to hoist an invariant computation.  */
68
69 struct depend
70 {
71   gimple stmt;
72   struct depend *next;
73 };
74
75 /* The auxiliary data kept for each statement.  */
76
77 struct lim_aux_data
78 {
79   struct loop *max_loop;        /* The outermost loop in that the statement
80                                    is invariant.  */
81
82   struct loop *tgt_loop;        /* The loop out of that we want to move the
83                                    invariant.  */
84
85   struct loop *always_executed_in;
86                                 /* The outermost loop for that we are sure
87                                    the statement is executed if the loop
88                                    is entered.  */
89
90   unsigned cost;                /* Cost of the computation performed by the
91                                    statement.  */
92
93   struct depend *depends;       /* List of statements that must be also hoisted
94                                    out of the loop when this statement is
95                                    hoisted; i.e. those that define the operands
96                                    of the statement and are inside of the
97                                    MAX_LOOP loop.  */
98 };
99
100 /* Maps statements to their lim_aux_data.  */
101
102 static struct pointer_map_t *lim_aux_data_map;
103
104 /* Description of a memory reference location.  */
105
106 typedef struct mem_ref_loc
107 {
108   tree *ref;                    /* The reference itself.  */
109   gimple stmt;                  /* The statement in that it occurs.  */
110 } *mem_ref_loc_p;
111
112 DEF_VEC_P(mem_ref_loc_p);
113 DEF_VEC_ALLOC_P(mem_ref_loc_p, heap);
114
115 /* The list of memory reference locations in a loop.  */
116
117 typedef struct mem_ref_locs
118 {
119   VEC (mem_ref_loc_p, heap) *locs;
120 } *mem_ref_locs_p;
121
122 DEF_VEC_P(mem_ref_locs_p);
123 DEF_VEC_ALLOC_P(mem_ref_locs_p, heap);
124
125 /* Description of a memory reference.  */
126
127 typedef struct mem_ref
128 {
129   tree mem;                     /* The memory itself.  */
130   unsigned id;                  /* ID assigned to the memory reference
131                                    (its index in memory_accesses.refs_list)  */
132   hashval_t hash;               /* Its hash value.  */
133   bitmap stored;                /* The set of loops in that this memory location
134                                    is stored to.  */
135   VEC (mem_ref_locs_p, heap) *accesses_in_loop;
136                                 /* The locations of the accesses.  Vector
137                                    indexed by the loop number.  */
138   bitmap vops;                  /* Vops corresponding to this memory
139                                    location.  */
140
141   /* The following sets are computed on demand.  We keep both set and
142      its complement, so that we know whether the information was
143      already computed or not.  */
144   bitmap indep_loop;            /* The set of loops in that the memory
145                                    reference is independent, meaning:
146                                    If it is stored in the loop, this store
147                                      is independent on all other loads and
148                                      stores.
149                                    If it is only loaded, then it is independent
150                                      on all stores in the loop.  */
151   bitmap dep_loop;              /* The complement of INDEP_LOOP.  */
152
153   bitmap indep_ref;             /* The set of memory references on that
154                                    this reference is independent.  */
155   bitmap dep_ref;               /* The complement of DEP_REF.  */
156 } *mem_ref_p;
157
158 DEF_VEC_P(mem_ref_p);
159 DEF_VEC_ALLOC_P(mem_ref_p, heap);
160
161 DEF_VEC_P(bitmap);
162 DEF_VEC_ALLOC_P(bitmap, heap);
163
164 DEF_VEC_P(htab_t);
165 DEF_VEC_ALLOC_P(htab_t, heap);
166
167 /* Description of memory accesses in loops.  */
168
169 static struct
170 {
171   /* The hash table of memory references accessed in loops.  */
172   htab_t refs;
173
174   /* The list of memory references.  */
175   VEC (mem_ref_p, heap) *refs_list;
176
177   /* The set of memory references accessed in each loop.  */
178   VEC (bitmap, heap) *refs_in_loop;
179
180   /* The set of memory references accessed in each loop, including
181      subloops.  */
182   VEC (bitmap, heap) *all_refs_in_loop;
183
184   /* The set of virtual operands clobbered in a given loop.  */
185   VEC (bitmap, heap) *clobbered_vops;
186
187   /* Map from the pair (loop, virtual operand) to the set of refs that
188      touch the virtual operand in the loop.  */
189   VEC (htab_t, heap) *vop_ref_map;
190
191   /* Cache for expanding memory addresses.  */
192   struct pointer_map_t *ttae_cache;
193 } memory_accesses;
194
195 static bool ref_indep_loop_p (struct loop *, mem_ref_p);
196
197 /* Minimum cost of an expensive expression.  */
198 #define LIM_EXPENSIVE ((unsigned) PARAM_VALUE (PARAM_LIM_EXPENSIVE))
199
200 /* The outermost loop for that execution of the header guarantees that the
201    block will be executed.  */
202 #define ALWAYS_EXECUTED_IN(BB) ((struct loop *) (BB)->aux)
203
204 static struct lim_aux_data *
205 init_lim_data (gimple stmt)
206 {
207   void **p = pointer_map_insert (lim_aux_data_map, stmt);
208
209   *p = XCNEW (struct lim_aux_data);
210   return (struct lim_aux_data *) *p;
211 }
212
213 static struct lim_aux_data *
214 get_lim_data (gimple stmt)
215 {
216   void **p = pointer_map_contains (lim_aux_data_map, stmt);
217   if (!p)
218     return NULL;
219
220   return (struct lim_aux_data *) *p;
221 }
222
223 /* Releases the memory occupied by DATA.  */
224
225 static void
226 free_lim_aux_data (struct lim_aux_data *data)
227 {
228   struct depend *dep, *next;
229
230   for (dep = data->depends; dep; dep = next)
231     {
232       next = dep->next;
233       free (dep);
234     }
235   free (data);
236 }
237
238 static void
239 clear_lim_data (gimple stmt)
240 {
241   void **p = pointer_map_contains (lim_aux_data_map, stmt);
242   if (!p)
243     return;
244
245   free_lim_aux_data ((struct lim_aux_data *) *p);
246   *p = NULL;
247 }
248
249 /* Calls CBCK for each index in memory reference ADDR_P.  There are two
250    kinds situations handled; in each of these cases, the memory reference
251    and DATA are passed to the callback:
252
253    Access to an array: ARRAY_{RANGE_}REF (base, index).  In this case we also
254    pass the pointer to the index to the callback.
255
256    Pointer dereference: INDIRECT_REF (addr).  In this case we also pass the
257    pointer to addr to the callback.
258
259    If the callback returns false, the whole search stops and false is returned.
260    Otherwise the function returns true after traversing through the whole
261    reference *ADDR_P.  */
262
263 bool
264 for_each_index (tree *addr_p, bool (*cbck) (tree, tree *, void *), void *data)
265 {
266   tree *nxt, *idx;
267
268   for (; ; addr_p = nxt)
269     {
270       switch (TREE_CODE (*addr_p))
271         {
272         case SSA_NAME:
273           return cbck (*addr_p, addr_p, data);
274
275         case MISALIGNED_INDIRECT_REF:
276         case MEM_REF:
277           nxt = &TREE_OPERAND (*addr_p, 0);
278           return cbck (*addr_p, nxt, data);
279
280         case BIT_FIELD_REF:
281         case VIEW_CONVERT_EXPR:
282         case REALPART_EXPR:
283         case IMAGPART_EXPR:
284           nxt = &TREE_OPERAND (*addr_p, 0);
285           break;
286
287         case COMPONENT_REF:
288           /* If the component has varying offset, it behaves like index
289              as well.  */
290           idx = &TREE_OPERAND (*addr_p, 2);
291           if (*idx
292               && !cbck (*addr_p, idx, data))
293             return false;
294
295           nxt = &TREE_OPERAND (*addr_p, 0);
296           break;
297
298         case ARRAY_REF:
299         case ARRAY_RANGE_REF:
300           nxt = &TREE_OPERAND (*addr_p, 0);
301           if (!cbck (*addr_p, &TREE_OPERAND (*addr_p, 1), data))
302             return false;
303           break;
304
305         case VAR_DECL:
306         case PARM_DECL:
307         case STRING_CST:
308         case RESULT_DECL:
309         case VECTOR_CST:
310         case COMPLEX_CST:
311         case INTEGER_CST:
312         case REAL_CST:
313         case FIXED_CST:
314         case CONSTRUCTOR:
315           return true;
316
317         case ADDR_EXPR:
318           gcc_assert (is_gimple_min_invariant (*addr_p));
319           return true;
320
321         case TARGET_MEM_REF:
322           idx = &TMR_BASE (*addr_p);
323           if (*idx
324               && !cbck (*addr_p, idx, data))
325             return false;
326           idx = &TMR_INDEX (*addr_p);
327           if (*idx
328               && !cbck (*addr_p, idx, data))
329             return false;
330           return true;
331
332         default:
333           gcc_unreachable ();
334         }
335     }
336 }
337
338 /* If it is possible to hoist the statement STMT unconditionally,
339    returns MOVE_POSSIBLE.
340    If it is possible to hoist the statement STMT, but we must avoid making
341    it executed if it would not be executed in the original program (e.g.
342    because it may trap), return MOVE_PRESERVE_EXECUTION.
343    Otherwise return MOVE_IMPOSSIBLE.  */
344
345 enum move_pos
346 movement_possibility (gimple stmt)
347 {
348   tree lhs;
349   enum move_pos ret = MOVE_POSSIBLE;
350
351   if (flag_unswitch_loops
352       && gimple_code (stmt) == GIMPLE_COND)
353     {
354       /* If we perform unswitching, force the operands of the invariant
355          condition to be moved out of the loop.  */
356       return MOVE_POSSIBLE;
357     }
358
359   if (gimple_code (stmt) == GIMPLE_PHI
360       && gimple_phi_num_args (stmt) <= 2
361       && is_gimple_reg (gimple_phi_result (stmt))
362       && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (gimple_phi_result (stmt)))
363     return MOVE_POSSIBLE;
364
365   if (gimple_get_lhs (stmt) == NULL_TREE)
366     return MOVE_IMPOSSIBLE;
367
368   if (gimple_vdef (stmt))
369     return MOVE_IMPOSSIBLE;
370
371   if (stmt_ends_bb_p (stmt)
372       || gimple_has_volatile_ops (stmt)
373       || gimple_has_side_effects (stmt)
374       || stmt_could_throw_p (stmt))
375     return MOVE_IMPOSSIBLE;
376
377   if (is_gimple_call (stmt))
378     {
379       /* While pure or const call is guaranteed to have no side effects, we
380          cannot move it arbitrarily.  Consider code like
381
382          char *s = something ();
383
384          while (1)
385            {
386              if (s)
387                t = strlen (s);
388              else
389                t = 0;
390            }
391
392          Here the strlen call cannot be moved out of the loop, even though
393          s is invariant.  In addition to possibly creating a call with
394          invalid arguments, moving out a function call that is not executed
395          may cause performance regressions in case the call is costly and
396          not executed at all.  */
397       ret = MOVE_PRESERVE_EXECUTION;
398       lhs = gimple_call_lhs (stmt);
399     }
400   else if (is_gimple_assign (stmt))
401     lhs = gimple_assign_lhs (stmt);
402   else
403     return MOVE_IMPOSSIBLE;
404
405   if (TREE_CODE (lhs) == SSA_NAME
406       && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
407     return MOVE_IMPOSSIBLE;
408
409   if (TREE_CODE (lhs) != SSA_NAME
410       || gimple_could_trap_p (stmt))
411     return MOVE_PRESERVE_EXECUTION;
412
413   return ret;
414 }
415
416 /* Suppose that operand DEF is used inside the LOOP.  Returns the outermost
417    loop to that we could move the expression using DEF if it did not have
418    other operands, i.e. the outermost loop enclosing LOOP in that the value
419    of DEF is invariant.  */
420
421 static struct loop *
422 outermost_invariant_loop (tree def, struct loop *loop)
423 {
424   gimple def_stmt;
425   basic_block def_bb;
426   struct loop *max_loop;
427   struct lim_aux_data *lim_data;
428
429   if (!def)
430     return superloop_at_depth (loop, 1);
431
432   if (TREE_CODE (def) != SSA_NAME)
433     {
434       gcc_assert (is_gimple_min_invariant (def));
435       return superloop_at_depth (loop, 1);
436     }
437
438   def_stmt = SSA_NAME_DEF_STMT (def);
439   def_bb = gimple_bb (def_stmt);
440   if (!def_bb)
441     return superloop_at_depth (loop, 1);
442
443   max_loop = find_common_loop (loop, def_bb->loop_father);
444
445   lim_data = get_lim_data (def_stmt);
446   if (lim_data != NULL && lim_data->max_loop != NULL)
447     max_loop = find_common_loop (max_loop,
448                                  loop_outer (lim_data->max_loop));
449   if (max_loop == loop)
450     return NULL;
451   max_loop = superloop_at_depth (loop, loop_depth (max_loop) + 1);
452
453   return max_loop;
454 }
455
456 /* DATA is a structure containing information associated with a statement
457    inside LOOP.  DEF is one of the operands of this statement.
458
459    Find the outermost loop enclosing LOOP in that value of DEF is invariant
460    and record this in DATA->max_loop field.  If DEF itself is defined inside
461    this loop as well (i.e. we need to hoist it out of the loop if we want
462    to hoist the statement represented by DATA), record the statement in that
463    DEF is defined to the DATA->depends list.  Additionally if ADD_COST is true,
464    add the cost of the computation of DEF to the DATA->cost.
465
466    If DEF is not invariant in LOOP, return false.  Otherwise return TRUE.  */
467
468 static bool
469 add_dependency (tree def, struct lim_aux_data *data, struct loop *loop,
470                 bool add_cost)
471 {
472   gimple def_stmt = SSA_NAME_DEF_STMT (def);
473   basic_block def_bb = gimple_bb (def_stmt);
474   struct loop *max_loop;
475   struct depend *dep;
476   struct lim_aux_data *def_data;
477
478   if (!def_bb)
479     return true;
480
481   max_loop = outermost_invariant_loop (def, loop);
482   if (!max_loop)
483     return false;
484
485   if (flow_loop_nested_p (data->max_loop, max_loop))
486     data->max_loop = max_loop;
487
488   def_data = get_lim_data (def_stmt);
489   if (!def_data)
490     return true;
491
492   if (add_cost
493       /* Only add the cost if the statement defining DEF is inside LOOP,
494          i.e. if it is likely that by moving the invariants dependent
495          on it, we will be able to avoid creating a new register for
496          it (since it will be only used in these dependent invariants).  */
497       && def_bb->loop_father == loop)
498     data->cost += def_data->cost;
499
500   dep = XNEW (struct depend);
501   dep->stmt = def_stmt;
502   dep->next = data->depends;
503   data->depends = dep;
504
505   return true;
506 }
507
508 /* Returns an estimate for a cost of statement STMT.  TODO -- the values here
509    are just ad-hoc constants.  The estimates should be based on target-specific
510    values.  */
511
512 static unsigned
513 stmt_cost (gimple stmt)
514 {
515   tree fndecl;
516   unsigned cost = 1;
517
518   /* Always try to create possibilities for unswitching.  */
519   if (gimple_code (stmt) == GIMPLE_COND
520       || gimple_code (stmt) == GIMPLE_PHI)
521     return LIM_EXPENSIVE;
522
523   /* Hoisting memory references out should almost surely be a win.  */
524   if (gimple_references_memory_p (stmt))
525     cost += 20;
526
527   if (is_gimple_call (stmt))
528     {
529       /* We should be hoisting calls if possible.  */
530
531       /* Unless the call is a builtin_constant_p; this always folds to a
532          constant, so moving it is useless.  */
533       fndecl = gimple_call_fndecl (stmt);
534       if (fndecl
535           && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
536           && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CONSTANT_P)
537         return 0;
538
539       return cost + 20;
540     }
541
542   if (gimple_code (stmt) != GIMPLE_ASSIGN)
543     return cost;
544
545   switch (gimple_assign_rhs_code (stmt))
546     {
547     case MULT_EXPR:
548     case TRUNC_DIV_EXPR:
549     case CEIL_DIV_EXPR:
550     case FLOOR_DIV_EXPR:
551     case ROUND_DIV_EXPR:
552     case EXACT_DIV_EXPR:
553     case CEIL_MOD_EXPR:
554     case FLOOR_MOD_EXPR:
555     case ROUND_MOD_EXPR:
556     case TRUNC_MOD_EXPR:
557     case RDIV_EXPR:
558       /* Division and multiplication are usually expensive.  */
559       cost += 20;
560       break;
561
562     case LSHIFT_EXPR:
563     case RSHIFT_EXPR:
564       cost += 20;
565       break;
566
567     default:
568       break;
569     }
570
571   return cost;
572 }
573
574 /* Finds the outermost loop between OUTER and LOOP in that the memory reference
575    REF is independent.  If REF is not independent in LOOP, NULL is returned
576    instead.  */
577
578 static struct loop *
579 outermost_indep_loop (struct loop *outer, struct loop *loop, mem_ref_p ref)
580 {
581   struct loop *aloop;
582
583   if (bitmap_bit_p (ref->stored, loop->num))
584     return NULL;
585
586   for (aloop = outer;
587        aloop != loop;
588        aloop = superloop_at_depth (loop, loop_depth (aloop) + 1))
589     if (!bitmap_bit_p (ref->stored, aloop->num)
590         && ref_indep_loop_p (aloop, ref))
591       return aloop;
592
593   if (ref_indep_loop_p (loop, ref))
594     return loop;
595   else
596     return NULL;
597 }
598
599 /* If there is a simple load or store to a memory reference in STMT, returns
600    the location of the memory reference, and sets IS_STORE according to whether
601    it is a store or load.  Otherwise, returns NULL.  */
602
603 static tree *
604 simple_mem_ref_in_stmt (gimple stmt, bool *is_store)
605 {
606   tree *lhs;
607   enum tree_code code;
608
609   /* Recognize MEM = (SSA_NAME | invariant) and SSA_NAME = MEM patterns.  */
610   if (gimple_code (stmt) != GIMPLE_ASSIGN)
611     return NULL;
612
613   code = gimple_assign_rhs_code (stmt);
614
615   lhs = gimple_assign_lhs_ptr (stmt);
616
617   if (TREE_CODE (*lhs) == SSA_NAME)
618     {
619       if (get_gimple_rhs_class (code) != GIMPLE_SINGLE_RHS
620           || !is_gimple_addressable (gimple_assign_rhs1 (stmt)))
621         return NULL;
622
623       *is_store = false;
624       return gimple_assign_rhs1_ptr (stmt);
625     }
626   else if (code == SSA_NAME
627            || (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS
628                && is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
629     {
630       *is_store = true;
631       return lhs;
632     }
633   else
634     return NULL;
635 }
636
637 /* Returns the memory reference contained in STMT.  */
638
639 static mem_ref_p
640 mem_ref_in_stmt (gimple stmt)
641 {
642   bool store;
643   tree *mem = simple_mem_ref_in_stmt (stmt, &store);
644   hashval_t hash;
645   mem_ref_p ref;
646
647   if (!mem)
648     return NULL;
649   gcc_assert (!store);
650
651   hash = iterative_hash_expr (*mem, 0);
652   ref = (mem_ref_p) htab_find_with_hash (memory_accesses.refs, *mem, hash);
653
654   gcc_assert (ref != NULL);
655   return ref;
656 }
657
658 /* From a controlling predicate in DOM determine the arguments from
659    the PHI node PHI that are chosen if the predicate evaluates to
660    true and false and store them to *TRUE_ARG_P and *FALSE_ARG_P if
661    they are non-NULL.  Returns true if the arguments can be determined,
662    else return false.  */
663
664 static bool
665 extract_true_false_args_from_phi (basic_block dom, gimple phi,
666                                   tree *true_arg_p, tree *false_arg_p)
667 {
668   basic_block bb = gimple_bb (phi);
669   edge true_edge, false_edge, tem;
670   tree arg0 = NULL_TREE, arg1 = NULL_TREE;
671
672   /* We have to verify that one edge into the PHI node is dominated
673      by the true edge of the predicate block and the other edge
674      dominated by the false edge.  This ensures that the PHI argument
675      we are going to take is completely determined by the path we
676      take from the predicate block.  */
677   extract_true_false_edges_from_block (dom, &true_edge, &false_edge);
678   tem = EDGE_PRED (bb, 0);
679   if (tem == true_edge
680       || tem->src == true_edge->dest
681       || dominated_by_p (CDI_DOMINATORS,
682                          tem->src, true_edge->dest))
683     arg0 = PHI_ARG_DEF (phi, tem->dest_idx);
684   else if (tem == false_edge
685            || tem->src == false_edge->dest
686            || dominated_by_p (CDI_DOMINATORS,
687                               tem->src, false_edge->dest))
688     arg1 = PHI_ARG_DEF (phi, tem->dest_idx);
689   else
690     return false;
691   tem = EDGE_PRED (bb, 1);
692   if (tem == true_edge
693       || tem->src == true_edge->dest
694       || dominated_by_p (CDI_DOMINATORS,
695                          tem->src, true_edge->dest))
696     arg0 = PHI_ARG_DEF (phi, tem->dest_idx);
697   else if (tem == false_edge
698            || tem->src == false_edge->dest
699            || dominated_by_p (CDI_DOMINATORS,
700                               tem->src, false_edge->dest))
701     arg1 = PHI_ARG_DEF (phi, tem->dest_idx);
702   else
703     return false;
704   if (!arg0 || !arg1)
705     return false;
706
707   if (true_arg_p)
708     *true_arg_p = arg0;
709   if (false_arg_p)
710     *false_arg_p = arg1;
711
712   return true;
713 }
714
715 /* Determine the outermost loop to that it is possible to hoist a statement
716    STMT and store it to LIM_DATA (STMT)->max_loop.  To do this we determine
717    the outermost loop in that the value computed by STMT is invariant.
718    If MUST_PRESERVE_EXEC is true, additionally choose such a loop that
719    we preserve the fact whether STMT is executed.  It also fills other related
720    information to LIM_DATA (STMT).
721
722    The function returns false if STMT cannot be hoisted outside of the loop it
723    is defined in, and true otherwise.  */
724
725 static bool
726 determine_max_movement (gimple stmt, bool must_preserve_exec)
727 {
728   basic_block bb = gimple_bb (stmt);
729   struct loop *loop = bb->loop_father;
730   struct loop *level;
731   struct lim_aux_data *lim_data = get_lim_data (stmt);
732   tree val;
733   ssa_op_iter iter;
734
735   if (must_preserve_exec)
736     level = ALWAYS_EXECUTED_IN (bb);
737   else
738     level = superloop_at_depth (loop, 1);
739   lim_data->max_loop = level;
740
741   if (gimple_code (stmt) == GIMPLE_PHI)
742     {
743       use_operand_p use_p;
744       unsigned min_cost = UINT_MAX;
745       unsigned total_cost = 0;
746       struct lim_aux_data *def_data;
747
748       /* We will end up promoting dependencies to be unconditionally
749          evaluated.  For this reason the PHI cost (and thus the
750          cost we remove from the loop by doing the invariant motion)
751          is that of the cheapest PHI argument dependency chain.  */
752       FOR_EACH_PHI_ARG (use_p, stmt, iter, SSA_OP_USE)
753         {
754           val = USE_FROM_PTR (use_p);
755           if (TREE_CODE (val) != SSA_NAME)
756             continue;
757           if (!add_dependency (val, lim_data, loop, false))
758             return false;
759           def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
760           if (def_data)
761             {
762               min_cost = MIN (min_cost, def_data->cost);
763               total_cost += def_data->cost;
764             }
765         }
766
767       lim_data->cost += min_cost;
768
769       if (gimple_phi_num_args (stmt) > 1)
770         {
771           basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
772           gimple cond;
773           if (gsi_end_p (gsi_last_bb (dom)))
774             return false;
775           cond = gsi_stmt (gsi_last_bb (dom));
776           if (gimple_code (cond) != GIMPLE_COND)
777             return false;
778           /* Verify that this is an extended form of a diamond and
779              the PHI arguments are completely controlled by the
780              predicate in DOM.  */
781           if (!extract_true_false_args_from_phi (dom, stmt, NULL, NULL))
782             return false;
783
784           /* Fold in dependencies and cost of the condition.  */
785           FOR_EACH_SSA_TREE_OPERAND (val, cond, iter, SSA_OP_USE)
786             {
787               if (!add_dependency (val, lim_data, loop, false))
788                 return false;
789               def_data = get_lim_data (SSA_NAME_DEF_STMT (val));
790               if (def_data)
791                 total_cost += def_data->cost;
792             }
793
794           /* We want to avoid unconditionally executing very expensive
795              operations.  As costs for our dependencies cannot be
796              negative just claim we are not invariand for this case.
797              We also are not sure whether the control-flow inside the
798              loop will vanish.  */
799           if (total_cost - min_cost >= 2 * LIM_EXPENSIVE
800               && !(min_cost != 0
801                    && total_cost / min_cost <= 2))
802             return false;
803
804           /* Assume that the control-flow in the loop will vanish.
805              ???  We should verify this and not artificially increase
806              the cost if that is not the case.  */
807           lim_data->cost += stmt_cost (stmt);
808         }
809
810       return true;
811     }
812   else
813     FOR_EACH_SSA_TREE_OPERAND (val, stmt, iter, SSA_OP_USE)
814       if (!add_dependency (val, lim_data, loop, true))
815         return false;
816
817   if (gimple_vuse (stmt))
818     {
819       mem_ref_p ref = mem_ref_in_stmt (stmt);
820
821       if (ref)
822         {
823           lim_data->max_loop
824                   = outermost_indep_loop (lim_data->max_loop, loop, ref);
825           if (!lim_data->max_loop)
826             return false;
827         }
828       else
829         {
830           if ((val = gimple_vuse (stmt)) != NULL_TREE)
831             {
832               if (!add_dependency (val, lim_data, loop, false))
833                 return false;
834             }
835         }
836     }
837
838   lim_data->cost += stmt_cost (stmt);
839
840   return true;
841 }
842
843 /* Suppose that some statement in ORIG_LOOP is hoisted to the loop LEVEL,
844    and that one of the operands of this statement is computed by STMT.
845    Ensure that STMT (together with all the statements that define its
846    operands) is hoisted at least out of the loop LEVEL.  */
847
848 static void
849 set_level (gimple stmt, struct loop *orig_loop, struct loop *level)
850 {
851   struct loop *stmt_loop = gimple_bb (stmt)->loop_father;
852   struct depend *dep;
853   struct lim_aux_data *lim_data;
854
855   stmt_loop = find_common_loop (orig_loop, stmt_loop);
856   lim_data = get_lim_data (stmt);
857   if (lim_data != NULL && lim_data->tgt_loop != NULL)
858     stmt_loop = find_common_loop (stmt_loop,
859                                   loop_outer (lim_data->tgt_loop));
860   if (flow_loop_nested_p (stmt_loop, level))
861     return;
862
863   gcc_assert (level == lim_data->max_loop
864               || flow_loop_nested_p (lim_data->max_loop, level));
865
866   lim_data->tgt_loop = level;
867   for (dep = lim_data->depends; dep; dep = dep->next)
868     set_level (dep->stmt, orig_loop, level);
869 }
870
871 /* Determines an outermost loop from that we want to hoist the statement STMT.
872    For now we chose the outermost possible loop.  TODO -- use profiling
873    information to set it more sanely.  */
874
875 static void
876 set_profitable_level (gimple stmt)
877 {
878   set_level (stmt, gimple_bb (stmt)->loop_father, get_lim_data (stmt)->max_loop);
879 }
880
881 /* Returns true if STMT is a call that has side effects.  */
882
883 static bool
884 nonpure_call_p (gimple stmt)
885 {
886   if (gimple_code (stmt) != GIMPLE_CALL)
887     return false;
888
889   return gimple_has_side_effects (stmt);
890 }
891
892 /* Rewrite a/b to a*(1/b).  Return the invariant stmt to process.  */
893
894 static gimple
895 rewrite_reciprocal (gimple_stmt_iterator *bsi)
896 {
897   gimple stmt, stmt1, stmt2;
898   tree var, name, lhs, type;
899   tree real_one;
900   gimple_stmt_iterator gsi;
901
902   stmt = gsi_stmt (*bsi);
903   lhs = gimple_assign_lhs (stmt);
904   type = TREE_TYPE (lhs);
905
906   var = create_tmp_var (type, "reciptmp");
907   add_referenced_var (var);
908   DECL_GIMPLE_REG_P (var) = 1;
909
910   /* For vectors, create a VECTOR_CST full of 1's.  */
911   if (TREE_CODE (type) == VECTOR_TYPE)
912     {
913       int i, len;
914       tree list = NULL_TREE;
915       real_one = build_real (TREE_TYPE (type), dconst1);
916       len = TYPE_VECTOR_SUBPARTS (type);
917       for (i = 0; i < len; i++)
918         list = tree_cons (NULL, real_one, list);
919       real_one = build_vector (type, list);
920     }
921   else
922     real_one = build_real (type, dconst1);
923
924   stmt1 = gimple_build_assign_with_ops (RDIV_EXPR,
925                 var, real_one, gimple_assign_rhs2 (stmt));
926   name = make_ssa_name (var, stmt1);
927   gimple_assign_set_lhs (stmt1, name);
928
929   stmt2 = gimple_build_assign_with_ops (MULT_EXPR, lhs, name,
930                                         gimple_assign_rhs1 (stmt));
931
932   /* Replace division stmt with reciprocal and multiply stmts.
933      The multiply stmt is not invariant, so update iterator
934      and avoid rescanning.  */
935   gsi = *bsi;
936   gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
937   gsi_replace (&gsi, stmt2, true);
938
939   /* Continue processing with invariant reciprocal statement.  */
940   return stmt1;
941 }
942
943 /* Check if the pattern at *BSI is a bittest of the form
944    (A >> B) & 1 != 0 and in this case rewrite it to A & (1 << B) != 0.  */
945
946 static gimple
947 rewrite_bittest (gimple_stmt_iterator *bsi)
948 {
949   gimple stmt, use_stmt, stmt1, stmt2;
950   tree lhs, var, name, t, a, b;
951   use_operand_p use;
952
953   stmt = gsi_stmt (*bsi);
954   lhs = gimple_assign_lhs (stmt);
955
956   /* Verify that the single use of lhs is a comparison against zero.  */
957   if (TREE_CODE (lhs) != SSA_NAME
958       || !single_imm_use (lhs, &use, &use_stmt)
959       || gimple_code (use_stmt) != GIMPLE_COND)
960     return stmt;
961   if (gimple_cond_lhs (use_stmt) != lhs
962       || (gimple_cond_code (use_stmt) != NE_EXPR
963           && gimple_cond_code (use_stmt) != EQ_EXPR)
964       || !integer_zerop (gimple_cond_rhs (use_stmt)))
965     return stmt;
966
967   /* Get at the operands of the shift.  The rhs is TMP1 & 1.  */
968   stmt1 = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (stmt));
969   if (gimple_code (stmt1) != GIMPLE_ASSIGN)
970     return stmt;
971
972   /* There is a conversion in between possibly inserted by fold.  */
973   if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt1)))
974     {
975       t = gimple_assign_rhs1 (stmt1);
976       if (TREE_CODE (t) != SSA_NAME
977           || !has_single_use (t))
978         return stmt;
979       stmt1 = SSA_NAME_DEF_STMT (t);
980       if (gimple_code (stmt1) != GIMPLE_ASSIGN)
981         return stmt;
982     }
983
984   /* Verify that B is loop invariant but A is not.  Verify that with
985      all the stmt walking we are still in the same loop.  */
986   if (gimple_assign_rhs_code (stmt1) != RSHIFT_EXPR
987       || loop_containing_stmt (stmt1) != loop_containing_stmt (stmt))
988     return stmt;
989
990   a = gimple_assign_rhs1 (stmt1);
991   b = gimple_assign_rhs2 (stmt1);
992
993   if (outermost_invariant_loop (b, loop_containing_stmt (stmt1)) != NULL
994       && outermost_invariant_loop (a, loop_containing_stmt (stmt1)) == NULL)
995     {
996       gimple_stmt_iterator rsi;
997
998       /* 1 << B */
999       var = create_tmp_var (TREE_TYPE (a), "shifttmp");
1000       add_referenced_var (var);
1001       t = fold_build2 (LSHIFT_EXPR, TREE_TYPE (a),
1002                        build_int_cst (TREE_TYPE (a), 1), b);
1003       stmt1 = gimple_build_assign (var, t);
1004       name = make_ssa_name (var, stmt1);
1005       gimple_assign_set_lhs (stmt1, name);
1006
1007       /* A & (1 << B) */
1008       t = fold_build2 (BIT_AND_EXPR, TREE_TYPE (a), a, name);
1009       stmt2 = gimple_build_assign (var, t);
1010       name = make_ssa_name (var, stmt2);
1011       gimple_assign_set_lhs (stmt2, name);
1012
1013       /* Replace the SSA_NAME we compare against zero.  Adjust
1014          the type of zero accordingly.  */
1015       SET_USE (use, name);
1016       gimple_cond_set_rhs (use_stmt, build_int_cst_type (TREE_TYPE (name), 0));
1017
1018       /* Don't use gsi_replace here, none of the new assignments sets
1019          the variable originally set in stmt.  Move bsi to stmt1, and
1020          then remove the original stmt, so that we get a chance to
1021          retain debug info for it.  */
1022       rsi = *bsi;
1023       gsi_insert_before (bsi, stmt1, GSI_NEW_STMT);
1024       gsi_insert_before (&rsi, stmt2, GSI_SAME_STMT);
1025       gsi_remove (&rsi, true);
1026
1027       return stmt1;
1028     }
1029
1030   return stmt;
1031 }
1032
1033
1034 /* Determine the outermost loops in that statements in basic block BB are
1035    invariant, and record them to the LIM_DATA associated with the statements.
1036    Callback for walk_dominator_tree.  */
1037
1038 static void
1039 determine_invariantness_stmt (struct dom_walk_data *dw_data ATTRIBUTE_UNUSED,
1040                               basic_block bb)
1041 {
1042   enum move_pos pos;
1043   gimple_stmt_iterator bsi;
1044   gimple stmt;
1045   bool maybe_never = ALWAYS_EXECUTED_IN (bb) == NULL;
1046   struct loop *outermost = ALWAYS_EXECUTED_IN (bb);
1047   struct lim_aux_data *lim_data;
1048
1049   if (!loop_outer (bb->loop_father))
1050     return;
1051
1052   if (dump_file && (dump_flags & TDF_DETAILS))
1053     fprintf (dump_file, "Basic block %d (loop %d -- depth %d):\n\n",
1054              bb->index, bb->loop_father->num, loop_depth (bb->loop_father));
1055
1056   /* Look at PHI nodes, but only if there is at most two.
1057      ???  We could relax this further by post-processing the inserted
1058      code and transforming adjacent cond-exprs with the same predicate
1059      to control flow again.  */
1060   bsi = gsi_start_phis (bb);
1061   if (!gsi_end_p (bsi)
1062       && ((gsi_next (&bsi), gsi_end_p (bsi))
1063           || (gsi_next (&bsi), gsi_end_p (bsi))))
1064     for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1065       {
1066         stmt = gsi_stmt (bsi);
1067
1068         pos = movement_possibility (stmt);
1069         if (pos == MOVE_IMPOSSIBLE)
1070           continue;
1071
1072         lim_data = init_lim_data (stmt);
1073         lim_data->always_executed_in = outermost;
1074
1075         if (!determine_max_movement (stmt, false))
1076           {
1077             lim_data->max_loop = NULL;
1078             continue;
1079           }
1080
1081         if (dump_file && (dump_flags & TDF_DETAILS))
1082           {
1083             print_gimple_stmt (dump_file, stmt, 2, 0);
1084             fprintf (dump_file, "  invariant up to level %d, cost %d.\n\n",
1085                      loop_depth (lim_data->max_loop),
1086                      lim_data->cost);
1087           }
1088
1089         if (lim_data->cost >= LIM_EXPENSIVE)
1090           set_profitable_level (stmt);
1091       }
1092
1093   for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1094     {
1095       stmt = gsi_stmt (bsi);
1096
1097       pos = movement_possibility (stmt);
1098       if (pos == MOVE_IMPOSSIBLE)
1099         {
1100           if (nonpure_call_p (stmt))
1101             {
1102               maybe_never = true;
1103               outermost = NULL;
1104             }
1105           /* Make sure to note always_executed_in for stores to make
1106              store-motion work.  */
1107           else if (stmt_makes_single_store (stmt))
1108             {
1109               struct lim_aux_data *lim_data = init_lim_data (stmt);
1110               lim_data->always_executed_in = outermost;
1111             }
1112           continue;
1113         }
1114
1115       if (is_gimple_assign (stmt)
1116           && (get_gimple_rhs_class (gimple_assign_rhs_code (stmt))
1117               == GIMPLE_BINARY_RHS))
1118         {
1119           tree op0 = gimple_assign_rhs1 (stmt);
1120           tree op1 = gimple_assign_rhs2 (stmt);
1121           struct loop *ol1 = outermost_invariant_loop (op1,
1122                                         loop_containing_stmt (stmt));
1123
1124           /* If divisor is invariant, convert a/b to a*(1/b), allowing reciprocal
1125              to be hoisted out of loop, saving expensive divide.  */
1126           if (pos == MOVE_POSSIBLE
1127               && gimple_assign_rhs_code (stmt) == RDIV_EXPR
1128               && flag_unsafe_math_optimizations
1129               && !flag_trapping_math
1130               && ol1 != NULL
1131               && outermost_invariant_loop (op0, ol1) == NULL)
1132             stmt = rewrite_reciprocal (&bsi);
1133
1134           /* If the shift count is invariant, convert (A >> B) & 1 to
1135              A & (1 << B) allowing the bit mask to be hoisted out of the loop
1136              saving an expensive shift.  */
1137           if (pos == MOVE_POSSIBLE
1138               && gimple_assign_rhs_code (stmt) == BIT_AND_EXPR
1139               && integer_onep (op1)
1140               && TREE_CODE (op0) == SSA_NAME
1141               && has_single_use (op0))
1142             stmt = rewrite_bittest (&bsi);
1143         }
1144
1145       lim_data = init_lim_data (stmt);
1146       lim_data->always_executed_in = outermost;
1147
1148       if (maybe_never && pos == MOVE_PRESERVE_EXECUTION)
1149         continue;
1150
1151       if (!determine_max_movement (stmt, pos == MOVE_PRESERVE_EXECUTION))
1152         {
1153           lim_data->max_loop = NULL;
1154           continue;
1155         }
1156
1157       if (dump_file && (dump_flags & TDF_DETAILS))
1158         {
1159           print_gimple_stmt (dump_file, stmt, 2, 0);
1160           fprintf (dump_file, "  invariant up to level %d, cost %d.\n\n",
1161                    loop_depth (lim_data->max_loop),
1162                    lim_data->cost);
1163         }
1164
1165       if (lim_data->cost >= LIM_EXPENSIVE)
1166         set_profitable_level (stmt);
1167     }
1168 }
1169
1170 /* For each statement determines the outermost loop in that it is invariant,
1171    statements on whose motion it depends and the cost of the computation.
1172    This information is stored to the LIM_DATA structure associated with
1173    each statement.  */
1174
1175 static void
1176 determine_invariantness (void)
1177 {
1178   struct dom_walk_data walk_data;
1179
1180   memset (&walk_data, 0, sizeof (struct dom_walk_data));
1181   walk_data.dom_direction = CDI_DOMINATORS;
1182   walk_data.before_dom_children = determine_invariantness_stmt;
1183
1184   init_walk_dominator_tree (&walk_data);
1185   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1186   fini_walk_dominator_tree (&walk_data);
1187 }
1188
1189 /* Hoist the statements in basic block BB out of the loops prescribed by
1190    data stored in LIM_DATA structures associated with each statement.  Callback
1191    for walk_dominator_tree.  */
1192
1193 static void
1194 move_computations_stmt (struct dom_walk_data *dw_data,
1195                         basic_block bb)
1196 {
1197   struct loop *level;
1198   gimple_stmt_iterator bsi;
1199   gimple stmt;
1200   unsigned cost = 0;
1201   struct lim_aux_data *lim_data;
1202
1203   if (!loop_outer (bb->loop_father))
1204     return;
1205
1206   for (bsi = gsi_start_phis (bb); !gsi_end_p (bsi); )
1207     {
1208       gimple new_stmt;
1209       stmt = gsi_stmt (bsi);
1210
1211       lim_data = get_lim_data (stmt);
1212       if (lim_data == NULL)
1213         {
1214           gsi_next (&bsi);
1215           continue;
1216         }
1217
1218       cost = lim_data->cost;
1219       level = lim_data->tgt_loop;
1220       clear_lim_data (stmt);
1221
1222       if (!level)
1223         {
1224           gsi_next (&bsi);
1225           continue;
1226         }
1227
1228       if (dump_file && (dump_flags & TDF_DETAILS))
1229         {
1230           fprintf (dump_file, "Moving PHI node\n");
1231           print_gimple_stmt (dump_file, stmt, 0, 0);
1232           fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1233                    cost, level->num);
1234         }
1235
1236       if (gimple_phi_num_args (stmt) == 1)
1237         {
1238           tree arg = PHI_ARG_DEF (stmt, 0);
1239           new_stmt = gimple_build_assign_with_ops (TREE_CODE (arg),
1240                                                    gimple_phi_result (stmt),
1241                                                    arg, NULL_TREE);
1242           SSA_NAME_DEF_STMT (gimple_phi_result (stmt)) = new_stmt;
1243         }
1244       else
1245         {
1246           basic_block dom = get_immediate_dominator (CDI_DOMINATORS, bb);
1247           gimple cond = gsi_stmt (gsi_last_bb (dom));
1248           tree arg0 = NULL_TREE, arg1 = NULL_TREE, t;
1249           /* Get the PHI arguments corresponding to the true and false
1250              edges of COND.  */
1251           extract_true_false_args_from_phi (dom, stmt, &arg0, &arg1);
1252           gcc_assert (arg0 && arg1);
1253           t = build2 (gimple_cond_code (cond), boolean_type_node,
1254                       gimple_cond_lhs (cond), gimple_cond_rhs (cond));
1255           t = build3 (COND_EXPR, TREE_TYPE (gimple_phi_result (stmt)),
1256                       t, arg0, arg1);
1257           new_stmt = gimple_build_assign_with_ops (COND_EXPR,
1258                                                    gimple_phi_result (stmt),
1259                                                    t, NULL_TREE);
1260           SSA_NAME_DEF_STMT (gimple_phi_result (stmt)) = new_stmt;
1261           *((unsigned int *)(dw_data->global_data)) |= TODO_cleanup_cfg;
1262         }
1263       gsi_insert_on_edge (loop_preheader_edge (level), new_stmt);
1264       remove_phi_node (&bsi, false);
1265     }
1266
1267   for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); )
1268     {
1269       stmt = gsi_stmt (bsi);
1270
1271       lim_data = get_lim_data (stmt);
1272       if (lim_data == NULL)
1273         {
1274           gsi_next (&bsi);
1275           continue;
1276         }
1277
1278       cost = lim_data->cost;
1279       level = lim_data->tgt_loop;
1280       clear_lim_data (stmt);
1281
1282       if (!level)
1283         {
1284           gsi_next (&bsi);
1285           continue;
1286         }
1287
1288       /* We do not really want to move conditionals out of the loop; we just
1289          placed it here to force its operands to be moved if necessary.  */
1290       if (gimple_code (stmt) == GIMPLE_COND)
1291         continue;
1292
1293       if (dump_file && (dump_flags & TDF_DETAILS))
1294         {
1295           fprintf (dump_file, "Moving statement\n");
1296           print_gimple_stmt (dump_file, stmt, 0, 0);
1297           fprintf (dump_file, "(cost %u) out of loop %d.\n\n",
1298                    cost, level->num);
1299         }
1300
1301       mark_virtual_ops_for_renaming (stmt);
1302       gsi_insert_on_edge (loop_preheader_edge (level), stmt);
1303       gsi_remove (&bsi, false);
1304     }
1305 }
1306
1307 /* Hoist the statements out of the loops prescribed by data stored in
1308    LIM_DATA structures associated with each statement.*/
1309
1310 static unsigned int
1311 move_computations (void)
1312 {
1313   struct dom_walk_data walk_data;
1314   unsigned int todo = 0;
1315
1316   memset (&walk_data, 0, sizeof (struct dom_walk_data));
1317   walk_data.global_data = &todo;
1318   walk_data.dom_direction = CDI_DOMINATORS;
1319   walk_data.before_dom_children = move_computations_stmt;
1320
1321   init_walk_dominator_tree (&walk_data);
1322   walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
1323   fini_walk_dominator_tree (&walk_data);
1324
1325   gsi_commit_edge_inserts ();
1326   if (need_ssa_update_p (cfun))
1327     rewrite_into_loop_closed_ssa (NULL, TODO_update_ssa);
1328
1329   return todo;
1330 }
1331
1332 /* Checks whether the statement defining variable *INDEX can be hoisted
1333    out of the loop passed in DATA.  Callback for for_each_index.  */
1334
1335 static bool
1336 may_move_till (tree ref, tree *index, void *data)
1337 {
1338   struct loop *loop = (struct loop *) data, *max_loop;
1339
1340   /* If REF is an array reference, check also that the step and the lower
1341      bound is invariant in LOOP.  */
1342   if (TREE_CODE (ref) == ARRAY_REF)
1343     {
1344       tree step = TREE_OPERAND (ref, 3);
1345       tree lbound = TREE_OPERAND (ref, 2);
1346
1347       max_loop = outermost_invariant_loop (step, loop);
1348       if (!max_loop)
1349         return false;
1350
1351       max_loop = outermost_invariant_loop (lbound, loop);
1352       if (!max_loop)
1353         return false;
1354     }
1355
1356   max_loop = outermost_invariant_loop (*index, loop);
1357   if (!max_loop)
1358     return false;
1359
1360   return true;
1361 }
1362
1363 /* If OP is SSA NAME, force the statement that defines it to be
1364    moved out of the LOOP.  ORIG_LOOP is the loop in that EXPR is used.  */
1365
1366 static void
1367 force_move_till_op (tree op, struct loop *orig_loop, struct loop *loop)
1368 {
1369   gimple stmt;
1370
1371   if (!op
1372       || is_gimple_min_invariant (op))
1373     return;
1374
1375   gcc_assert (TREE_CODE (op) == SSA_NAME);
1376
1377   stmt = SSA_NAME_DEF_STMT (op);
1378   if (gimple_nop_p (stmt))
1379     return;
1380
1381   set_level (stmt, orig_loop, loop);
1382 }
1383
1384 /* Forces statement defining invariants in REF (and *INDEX) to be moved out of
1385    the LOOP.  The reference REF is used in the loop ORIG_LOOP.  Callback for
1386    for_each_index.  */
1387
1388 struct fmt_data
1389 {
1390   struct loop *loop;
1391   struct loop *orig_loop;
1392 };
1393
1394 static bool
1395 force_move_till (tree ref, tree *index, void *data)
1396 {
1397   struct fmt_data *fmt_data = (struct fmt_data *) data;
1398
1399   if (TREE_CODE (ref) == ARRAY_REF)
1400     {
1401       tree step = TREE_OPERAND (ref, 3);
1402       tree lbound = TREE_OPERAND (ref, 2);
1403
1404       force_move_till_op (step, fmt_data->orig_loop, fmt_data->loop);
1405       force_move_till_op (lbound, fmt_data->orig_loop, fmt_data->loop);
1406     }
1407
1408   force_move_till_op (*index, fmt_data->orig_loop, fmt_data->loop);
1409
1410   return true;
1411 }
1412
1413 /* A hash function for struct mem_ref object OBJ.  */
1414
1415 static hashval_t
1416 memref_hash (const void *obj)
1417 {
1418   const struct mem_ref *const mem = (const struct mem_ref *) obj;
1419
1420   return mem->hash;
1421 }
1422
1423 /* An equality function for struct mem_ref object OBJ1 with
1424    memory reference OBJ2.  */
1425
1426 static int
1427 memref_eq (const void *obj1, const void *obj2)
1428 {
1429   const struct mem_ref *const mem1 = (const struct mem_ref *) obj1;
1430
1431   return operand_equal_p (mem1->mem, (const_tree) obj2, 0);
1432 }
1433
1434 /* Releases list of memory reference locations ACCS.  */
1435
1436 static void
1437 free_mem_ref_locs (mem_ref_locs_p accs)
1438 {
1439   unsigned i;
1440   mem_ref_loc_p loc;
1441
1442   if (!accs)
1443     return;
1444
1445   FOR_EACH_VEC_ELT (mem_ref_loc_p, accs->locs, i, loc)
1446     free (loc);
1447   VEC_free (mem_ref_loc_p, heap, accs->locs);
1448   free (accs);
1449 }
1450
1451 /* A function to free the mem_ref object OBJ.  */
1452
1453 static void
1454 memref_free (void *obj)
1455 {
1456   struct mem_ref *const mem = (struct mem_ref *) obj;
1457   unsigned i;
1458   mem_ref_locs_p accs;
1459
1460   BITMAP_FREE (mem->stored);
1461   BITMAP_FREE (mem->indep_loop);
1462   BITMAP_FREE (mem->dep_loop);
1463   BITMAP_FREE (mem->indep_ref);
1464   BITMAP_FREE (mem->dep_ref);
1465
1466   FOR_EACH_VEC_ELT (mem_ref_locs_p, mem->accesses_in_loop, i, accs)
1467     free_mem_ref_locs (accs);
1468   VEC_free (mem_ref_locs_p, heap, mem->accesses_in_loop);
1469
1470   BITMAP_FREE (mem->vops);
1471   free (mem);
1472 }
1473
1474 /* Allocates and returns a memory reference description for MEM whose hash
1475    value is HASH and id is ID.  */
1476
1477 static mem_ref_p
1478 mem_ref_alloc (tree mem, unsigned hash, unsigned id)
1479 {
1480   mem_ref_p ref = XNEW (struct mem_ref);
1481   ref->mem = mem;
1482   ref->id = id;
1483   ref->hash = hash;
1484   ref->stored = BITMAP_ALLOC (NULL);
1485   ref->indep_loop = BITMAP_ALLOC (NULL);
1486   ref->dep_loop = BITMAP_ALLOC (NULL);
1487   ref->indep_ref = BITMAP_ALLOC (NULL);
1488   ref->dep_ref = BITMAP_ALLOC (NULL);
1489   ref->accesses_in_loop = NULL;
1490   ref->vops = BITMAP_ALLOC (NULL);
1491
1492   return ref;
1493 }
1494
1495 /* Allocates and returns the new list of locations.  */
1496
1497 static mem_ref_locs_p
1498 mem_ref_locs_alloc (void)
1499 {
1500   mem_ref_locs_p accs = XNEW (struct mem_ref_locs);
1501   accs->locs = NULL;
1502   return accs;
1503 }
1504
1505 /* Records memory reference location *LOC in LOOP to the memory reference
1506    description REF.  The reference occurs in statement STMT.  */
1507
1508 static void
1509 record_mem_ref_loc (mem_ref_p ref, struct loop *loop, gimple stmt, tree *loc)
1510 {
1511   mem_ref_loc_p aref = XNEW (struct mem_ref_loc);
1512   mem_ref_locs_p accs;
1513   bitmap ril = VEC_index (bitmap, memory_accesses.refs_in_loop, loop->num);
1514
1515   if (VEC_length (mem_ref_locs_p, ref->accesses_in_loop)
1516       <= (unsigned) loop->num)
1517     VEC_safe_grow_cleared (mem_ref_locs_p, heap, ref->accesses_in_loop,
1518                            loop->num + 1);
1519   accs = VEC_index (mem_ref_locs_p, ref->accesses_in_loop, loop->num);
1520   if (!accs)
1521     {
1522       accs = mem_ref_locs_alloc ();
1523       VEC_replace (mem_ref_locs_p, ref->accesses_in_loop, loop->num, accs);
1524     }
1525
1526   aref->stmt = stmt;
1527   aref->ref = loc;
1528
1529   VEC_safe_push (mem_ref_loc_p, heap, accs->locs, aref);
1530   bitmap_set_bit (ril, ref->id);
1531 }
1532
1533 /* Marks reference REF as stored in LOOP.  */
1534
1535 static void
1536 mark_ref_stored (mem_ref_p ref, struct loop *loop)
1537 {
1538   for (;
1539        loop != current_loops->tree_root
1540        && !bitmap_bit_p (ref->stored, loop->num);
1541        loop = loop_outer (loop))
1542     bitmap_set_bit (ref->stored, loop->num);
1543 }
1544
1545 /* Gathers memory references in statement STMT in LOOP, storing the
1546    information about them in the memory_accesses structure.  Marks
1547    the vops accessed through unrecognized statements there as
1548    well.  */
1549
1550 static void
1551 gather_mem_refs_stmt (struct loop *loop, gimple stmt)
1552 {
1553   tree *mem = NULL;
1554   hashval_t hash;
1555   PTR *slot;
1556   mem_ref_p ref;
1557   tree vname;
1558   bool is_stored;
1559   bitmap clvops;
1560   unsigned id;
1561
1562   if (!gimple_vuse (stmt))
1563     return;
1564
1565   mem = simple_mem_ref_in_stmt (stmt, &is_stored);
1566   if (!mem)
1567     goto fail;
1568
1569   hash = iterative_hash_expr (*mem, 0);
1570   slot = htab_find_slot_with_hash (memory_accesses.refs, *mem, hash, INSERT);
1571
1572   if (*slot)
1573     {
1574       ref = (mem_ref_p) *slot;
1575       id = ref->id;
1576     }
1577   else
1578     {
1579       id = VEC_length (mem_ref_p, memory_accesses.refs_list);
1580       ref = mem_ref_alloc (*mem, hash, id);
1581       VEC_safe_push (mem_ref_p, heap, memory_accesses.refs_list, ref);
1582       *slot = ref;
1583
1584       if (dump_file && (dump_flags & TDF_DETAILS))
1585         {
1586           fprintf (dump_file, "Memory reference %u: ", id);
1587           print_generic_expr (dump_file, ref->mem, TDF_SLIM);
1588           fprintf (dump_file, "\n");
1589         }
1590     }
1591   if (is_stored)
1592     mark_ref_stored (ref, loop);
1593
1594   if ((vname = gimple_vuse (stmt)) != NULL_TREE)
1595     bitmap_set_bit (ref->vops, DECL_UID (SSA_NAME_VAR (vname)));
1596   record_mem_ref_loc (ref, loop, stmt, mem);
1597   return;
1598
1599 fail:
1600   clvops = VEC_index (bitmap, memory_accesses.clobbered_vops, loop->num);
1601   if ((vname = gimple_vuse (stmt)) != NULL_TREE)
1602     bitmap_set_bit (clvops, DECL_UID (SSA_NAME_VAR (vname)));
1603 }
1604
1605 /* Gathers memory references in loops.  */
1606
1607 static void
1608 gather_mem_refs_in_loops (void)
1609 {
1610   gimple_stmt_iterator bsi;
1611   basic_block bb;
1612   struct loop *loop;
1613   loop_iterator li;
1614   bitmap clvo, clvi;
1615   bitmap lrefs, alrefs, alrefso;
1616
1617   FOR_EACH_BB (bb)
1618     {
1619       loop = bb->loop_father;
1620       if (loop == current_loops->tree_root)
1621         continue;
1622
1623       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
1624         gather_mem_refs_stmt (loop, gsi_stmt (bsi));
1625     }
1626
1627   /* Propagate the information about clobbered vops and accessed memory
1628      references up the loop hierarchy.  */
1629   FOR_EACH_LOOP (li, loop, LI_FROM_INNERMOST)
1630     {
1631       lrefs = VEC_index (bitmap, memory_accesses.refs_in_loop, loop->num);
1632       alrefs = VEC_index (bitmap, memory_accesses.all_refs_in_loop, loop->num);
1633       bitmap_ior_into (alrefs, lrefs);
1634
1635       if (loop_outer (loop) == current_loops->tree_root)
1636         continue;
1637
1638       clvi = VEC_index (bitmap, memory_accesses.clobbered_vops, loop->num);
1639       clvo = VEC_index (bitmap, memory_accesses.clobbered_vops,
1640                         loop_outer (loop)->num);
1641       bitmap_ior_into (clvo, clvi);
1642
1643       alrefso = VEC_index (bitmap, memory_accesses.all_refs_in_loop,
1644                            loop_outer (loop)->num);
1645       bitmap_ior_into (alrefso, alrefs);
1646     }
1647 }
1648
1649 /* Element of the hash table that maps vops to memory references.  */
1650
1651 struct vop_to_refs_elt
1652 {
1653   /* DECL_UID of the vop.  */
1654   unsigned uid;
1655
1656   /* List of the all references.  */
1657   bitmap refs_all;
1658
1659   /* List of stored references.  */
1660   bitmap refs_stored;
1661 };
1662
1663 /* A hash function for struct vop_to_refs_elt object OBJ.  */
1664
1665 static hashval_t
1666 vtoe_hash (const void *obj)
1667 {
1668   const struct vop_to_refs_elt *const vtoe =
1669     (const struct vop_to_refs_elt *) obj;
1670
1671   return vtoe->uid;
1672 }
1673
1674 /* An equality function for struct vop_to_refs_elt object OBJ1 with
1675    uid of a vop OBJ2.  */
1676
1677 static int
1678 vtoe_eq (const void *obj1, const void *obj2)
1679 {
1680   const struct vop_to_refs_elt *const vtoe =
1681     (const struct vop_to_refs_elt *) obj1;
1682   const unsigned *const uid = (const unsigned *) obj2;
1683
1684   return vtoe->uid == *uid;
1685 }
1686
1687 /* A function to free the struct vop_to_refs_elt object.  */
1688
1689 static void
1690 vtoe_free (void *obj)
1691 {
1692   struct vop_to_refs_elt *const vtoe =
1693     (struct vop_to_refs_elt *) obj;
1694
1695   BITMAP_FREE (vtoe->refs_all);
1696   BITMAP_FREE (vtoe->refs_stored);
1697   free (vtoe);
1698 }
1699
1700 /* Records REF to hashtable VOP_TO_REFS for the index VOP.  STORED is true
1701    if the reference REF is stored.  */
1702
1703 static void
1704 record_vop_access (htab_t vop_to_refs, unsigned vop, unsigned ref, bool stored)
1705 {
1706   void **slot = htab_find_slot_with_hash (vop_to_refs, &vop, vop, INSERT);
1707   struct vop_to_refs_elt *vtoe;
1708
1709   if (!*slot)
1710     {
1711       vtoe = XNEW (struct vop_to_refs_elt);
1712       vtoe->uid = vop;
1713       vtoe->refs_all = BITMAP_ALLOC (NULL);
1714       vtoe->refs_stored = BITMAP_ALLOC (NULL);
1715       *slot = vtoe;
1716     }
1717   else
1718     vtoe = (struct vop_to_refs_elt *) *slot;
1719
1720   bitmap_set_bit (vtoe->refs_all, ref);
1721   if (stored)
1722     bitmap_set_bit (vtoe->refs_stored, ref);
1723 }
1724
1725 /* Returns the set of references that access VOP according to the table
1726    VOP_TO_REFS.  */
1727
1728 static bitmap
1729 get_vop_accesses (htab_t vop_to_refs, unsigned vop)
1730 {
1731   struct vop_to_refs_elt *const vtoe =
1732     (struct vop_to_refs_elt *) htab_find_with_hash (vop_to_refs, &vop, vop);
1733   return vtoe->refs_all;
1734 }
1735
1736 /* Returns the set of stores that access VOP according to the table
1737    VOP_TO_REFS.  */
1738
1739 static bitmap
1740 get_vop_stores (htab_t vop_to_refs, unsigned vop)
1741 {
1742   struct vop_to_refs_elt *const vtoe =
1743     (struct vop_to_refs_elt *) htab_find_with_hash (vop_to_refs, &vop, vop);
1744   return vtoe->refs_stored;
1745 }
1746
1747 /* Adds REF to mapping from virtual operands to references in LOOP.  */
1748
1749 static void
1750 add_vop_ref_mapping (struct loop *loop, mem_ref_p ref)
1751 {
1752   htab_t map = VEC_index (htab_t, memory_accesses.vop_ref_map, loop->num);
1753   bool stored = bitmap_bit_p (ref->stored, loop->num);
1754   bitmap clobbers = VEC_index (bitmap, memory_accesses.clobbered_vops,
1755                                loop->num);
1756   bitmap_iterator bi;
1757   unsigned vop;
1758
1759   EXECUTE_IF_AND_COMPL_IN_BITMAP (ref->vops, clobbers, 0, vop, bi)
1760     {
1761       record_vop_access (map, vop, ref->id, stored);
1762     }
1763 }
1764
1765 /* Create a mapping from virtual operands to references that touch them
1766    in LOOP.  */
1767
1768 static void
1769 create_vop_ref_mapping_loop (struct loop *loop)
1770 {
1771   bitmap refs = VEC_index (bitmap, memory_accesses.refs_in_loop, loop->num);
1772   struct loop *sloop;
1773   bitmap_iterator bi;
1774   unsigned i;
1775   mem_ref_p ref;
1776
1777   EXECUTE_IF_SET_IN_BITMAP (refs, 0, i, bi)
1778     {
1779       ref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
1780       for (sloop = loop; sloop != current_loops->tree_root; sloop = loop_outer (sloop))
1781         add_vop_ref_mapping (sloop, ref);
1782     }
1783 }
1784
1785 /* For each non-clobbered virtual operand and each loop, record the memory
1786    references in this loop that touch the operand.  */
1787
1788 static void
1789 create_vop_ref_mapping (void)
1790 {
1791   loop_iterator li;
1792   struct loop *loop;
1793
1794   FOR_EACH_LOOP (li, loop, 0)
1795     {
1796       create_vop_ref_mapping_loop (loop);
1797     }
1798 }
1799
1800 /* Gathers information about memory accesses in the loops.  */
1801
1802 static void
1803 analyze_memory_references (void)
1804 {
1805   unsigned i;
1806   bitmap empty;
1807   htab_t hempty;
1808
1809   memory_accesses.refs
1810           = htab_create (100, memref_hash, memref_eq, memref_free);
1811   memory_accesses.refs_list = NULL;
1812   memory_accesses.refs_in_loop = VEC_alloc (bitmap, heap,
1813                                             number_of_loops ());
1814   memory_accesses.all_refs_in_loop = VEC_alloc (bitmap, heap,
1815                                                 number_of_loops ());
1816   memory_accesses.clobbered_vops = VEC_alloc (bitmap, heap,
1817                                               number_of_loops ());
1818   memory_accesses.vop_ref_map = VEC_alloc (htab_t, heap,
1819                                            number_of_loops ());
1820
1821   for (i = 0; i < number_of_loops (); i++)
1822     {
1823       empty = BITMAP_ALLOC (NULL);
1824       VEC_quick_push (bitmap, memory_accesses.refs_in_loop, empty);
1825       empty = BITMAP_ALLOC (NULL);
1826       VEC_quick_push (bitmap, memory_accesses.all_refs_in_loop, empty);
1827       empty = BITMAP_ALLOC (NULL);
1828       VEC_quick_push (bitmap, memory_accesses.clobbered_vops, empty);
1829       hempty = htab_create (10, vtoe_hash, vtoe_eq, vtoe_free);
1830       VEC_quick_push (htab_t, memory_accesses.vop_ref_map, hempty);
1831     }
1832
1833   memory_accesses.ttae_cache = NULL;
1834
1835   gather_mem_refs_in_loops ();
1836   create_vop_ref_mapping ();
1837 }
1838
1839 /* Returns true if a region of size SIZE1 at position 0 and a region of
1840    size SIZE2 at position DIFF cannot overlap.  */
1841
1842 static bool
1843 cannot_overlap_p (aff_tree *diff, double_int size1, double_int size2)
1844 {
1845   double_int d, bound;
1846
1847   /* Unless the difference is a constant, we fail.  */
1848   if (diff->n != 0)
1849     return false;
1850
1851   d = diff->offset;
1852   if (double_int_negative_p (d))
1853     {
1854       /* The second object is before the first one, we succeed if the last
1855          element of the second object is before the start of the first one.  */
1856       bound = double_int_add (d, double_int_add (size2, double_int_minus_one));
1857       return double_int_negative_p (bound);
1858     }
1859   else
1860     {
1861       /* We succeed if the second object starts after the first one ends.  */
1862       return double_int_scmp (size1, d) <= 0;
1863     }
1864 }
1865
1866 /* Returns true if MEM1 and MEM2 may alias.  TTAE_CACHE is used as a cache in
1867    tree_to_aff_combination_expand.  */
1868
1869 static bool
1870 mem_refs_may_alias_p (tree mem1, tree mem2, struct pointer_map_t **ttae_cache)
1871 {
1872   /* Perform BASE + OFFSET analysis -- if MEM1 and MEM2 are based on the same
1873      object and their offset differ in such a way that the locations cannot
1874      overlap, then they cannot alias.  */
1875   double_int size1, size2;
1876   aff_tree off1, off2;
1877
1878   /* Perform basic offset and type-based disambiguation.  */
1879   if (!refs_may_alias_p (mem1, mem2))
1880     return false;
1881
1882   /* The expansion of addresses may be a bit expensive, thus we only do
1883      the check at -O2 and higher optimization levels.  */
1884   if (optimize < 2)
1885     return true;
1886
1887   get_inner_reference_aff (mem1, &off1, &size1);
1888   get_inner_reference_aff (mem2, &off2, &size2);
1889   aff_combination_expand (&off1, ttae_cache);
1890   aff_combination_expand (&off2, ttae_cache);
1891   aff_combination_scale (&off1, double_int_minus_one);
1892   aff_combination_add (&off2, &off1);
1893
1894   if (cannot_overlap_p (&off2, size1, size2))
1895     return false;
1896
1897   return true;
1898 }
1899
1900 /* Rewrites location LOC by TMP_VAR.  */
1901
1902 static void
1903 rewrite_mem_ref_loc (mem_ref_loc_p loc, tree tmp_var)
1904 {
1905   mark_virtual_ops_for_renaming (loc->stmt);
1906   *loc->ref = tmp_var;
1907   update_stmt (loc->stmt);
1908 }
1909
1910 /* Adds all locations of REF in LOOP and its subloops to LOCS.  */
1911
1912 static void
1913 get_all_locs_in_loop (struct loop *loop, mem_ref_p ref,
1914                       VEC (mem_ref_loc_p, heap) **locs)
1915 {
1916   mem_ref_locs_p accs;
1917   unsigned i;
1918   mem_ref_loc_p loc;
1919   bitmap refs = VEC_index (bitmap, memory_accesses.all_refs_in_loop,
1920                            loop->num);
1921   struct loop *subloop;
1922
1923   if (!bitmap_bit_p (refs, ref->id))
1924     return;
1925
1926   if (VEC_length (mem_ref_locs_p, ref->accesses_in_loop)
1927       > (unsigned) loop->num)
1928     {
1929       accs = VEC_index (mem_ref_locs_p, ref->accesses_in_loop, loop->num);
1930       if (accs)
1931         {
1932           FOR_EACH_VEC_ELT (mem_ref_loc_p, accs->locs, i, loc)
1933             VEC_safe_push (mem_ref_loc_p, heap, *locs, loc);
1934         }
1935     }
1936
1937   for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
1938     get_all_locs_in_loop (subloop, ref, locs);
1939 }
1940
1941 /* Rewrites all references to REF in LOOP by variable TMP_VAR.  */
1942
1943 static void
1944 rewrite_mem_refs (struct loop *loop, mem_ref_p ref, tree tmp_var)
1945 {
1946   unsigned i;
1947   mem_ref_loc_p loc;
1948   VEC (mem_ref_loc_p, heap) *locs = NULL;
1949
1950   get_all_locs_in_loop (loop, ref, &locs);
1951   FOR_EACH_VEC_ELT (mem_ref_loc_p, locs, i, loc)
1952     rewrite_mem_ref_loc (loc, tmp_var);
1953   VEC_free (mem_ref_loc_p, heap, locs);
1954 }
1955
1956 /* The name and the length of the currently generated variable
1957    for lsm.  */
1958 #define MAX_LSM_NAME_LENGTH 40
1959 static char lsm_tmp_name[MAX_LSM_NAME_LENGTH + 1];
1960 static int lsm_tmp_name_length;
1961
1962 /* Adds S to lsm_tmp_name.  */
1963
1964 static void
1965 lsm_tmp_name_add (const char *s)
1966 {
1967   int l = strlen (s) + lsm_tmp_name_length;
1968   if (l > MAX_LSM_NAME_LENGTH)
1969     return;
1970
1971   strcpy (lsm_tmp_name + lsm_tmp_name_length, s);
1972   lsm_tmp_name_length = l;
1973 }
1974
1975 /* Stores the name for temporary variable that replaces REF to
1976    lsm_tmp_name.  */
1977
1978 static void
1979 gen_lsm_tmp_name (tree ref)
1980 {
1981   const char *name;
1982
1983   switch (TREE_CODE (ref))
1984     {
1985     case MISALIGNED_INDIRECT_REF:
1986     case MEM_REF:
1987       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1988       lsm_tmp_name_add ("_");
1989       break;
1990
1991     case ADDR_EXPR:
1992       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1993       break;
1994
1995     case BIT_FIELD_REF:
1996     case VIEW_CONVERT_EXPR:
1997     case ARRAY_RANGE_REF:
1998       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
1999       break;
2000
2001     case REALPART_EXPR:
2002       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
2003       lsm_tmp_name_add ("_RE");
2004       break;
2005
2006     case IMAGPART_EXPR:
2007       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
2008       lsm_tmp_name_add ("_IM");
2009       break;
2010
2011     case COMPONENT_REF:
2012       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
2013       lsm_tmp_name_add ("_");
2014       name = get_name (TREE_OPERAND (ref, 1));
2015       if (!name)
2016         name = "F";
2017       lsm_tmp_name_add (name);
2018       break;
2019
2020     case ARRAY_REF:
2021       gen_lsm_tmp_name (TREE_OPERAND (ref, 0));
2022       lsm_tmp_name_add ("_I");
2023       break;
2024
2025     case SSA_NAME:
2026       ref = SSA_NAME_VAR (ref);
2027       /* Fallthru.  */
2028
2029     case VAR_DECL:
2030     case PARM_DECL:
2031       name = get_name (ref);
2032       if (!name)
2033         name = "D";
2034       lsm_tmp_name_add (name);
2035       break;
2036
2037     case STRING_CST:
2038       lsm_tmp_name_add ("S");
2039       break;
2040
2041     case RESULT_DECL:
2042       lsm_tmp_name_add ("R");
2043       break;
2044
2045     case INTEGER_CST:
2046       /* Nothing.  */
2047       break;
2048
2049     default:
2050       gcc_unreachable ();
2051     }
2052 }
2053
2054 /* Determines name for temporary variable that replaces REF.
2055    The name is accumulated into the lsm_tmp_name variable.
2056    N is added to the name of the temporary.  */
2057
2058 char *
2059 get_lsm_tmp_name (tree ref, unsigned n)
2060 {
2061   char ns[2];
2062
2063   lsm_tmp_name_length = 0;
2064   gen_lsm_tmp_name (ref);
2065   lsm_tmp_name_add ("_lsm");
2066   if (n < 10)
2067     {
2068       ns[0] = '0' + n;
2069       ns[1] = 0;
2070       lsm_tmp_name_add (ns);
2071     }
2072   return lsm_tmp_name;
2073 }
2074
2075 /* Executes store motion of memory reference REF from LOOP.
2076    Exits from the LOOP are stored in EXITS.  The initialization of the
2077    temporary variable is put to the preheader of the loop, and assignments
2078    to the reference from the temporary variable are emitted to exits.  */
2079
2080 static void
2081 execute_sm (struct loop *loop, VEC (edge, heap) *exits, mem_ref_p ref)
2082 {
2083   tree tmp_var;
2084   unsigned i;
2085   gimple load, store;
2086   struct fmt_data fmt_data;
2087   edge ex;
2088   struct lim_aux_data *lim_data;
2089
2090   if (dump_file && (dump_flags & TDF_DETAILS))
2091     {
2092       fprintf (dump_file, "Executing store motion of ");
2093       print_generic_expr (dump_file, ref->mem, 0);
2094       fprintf (dump_file, " from loop %d\n", loop->num);
2095     }
2096
2097   tmp_var = make_rename_temp (TREE_TYPE (ref->mem),
2098                               get_lsm_tmp_name (ref->mem, ~0));
2099
2100   fmt_data.loop = loop;
2101   fmt_data.orig_loop = loop;
2102   for_each_index (&ref->mem, force_move_till, &fmt_data);
2103
2104   rewrite_mem_refs (loop, ref, tmp_var);
2105
2106   /* Emit the load & stores.  */
2107   load = gimple_build_assign (tmp_var, unshare_expr (ref->mem));
2108   lim_data = init_lim_data (load);
2109   lim_data->max_loop = loop;
2110   lim_data->tgt_loop = loop;
2111
2112   /* Put this into the latch, so that we are sure it will be processed after
2113      all dependencies.  */
2114   gsi_insert_on_edge (loop_latch_edge (loop), load);
2115
2116   FOR_EACH_VEC_ELT (edge, exits, i, ex)
2117     {
2118       store = gimple_build_assign (unshare_expr (ref->mem), tmp_var);
2119       gsi_insert_on_edge (ex, store);
2120     }
2121 }
2122
2123 /* Hoists memory references MEM_REFS out of LOOP.  EXITS is the list of exit
2124    edges of the LOOP.  */
2125
2126 static void
2127 hoist_memory_references (struct loop *loop, bitmap mem_refs,
2128                          VEC (edge, heap) *exits)
2129 {
2130   mem_ref_p ref;
2131   unsigned  i;
2132   bitmap_iterator bi;
2133
2134   EXECUTE_IF_SET_IN_BITMAP (mem_refs, 0, i, bi)
2135     {
2136       ref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
2137       execute_sm (loop, exits, ref);
2138     }
2139 }
2140
2141 /* Returns true if REF is always accessed in LOOP.  If STORED_P is true
2142    make sure REF is always stored to in LOOP.  */
2143
2144 static bool
2145 ref_always_accessed_p (struct loop *loop, mem_ref_p ref, bool stored_p)
2146 {
2147   VEC (mem_ref_loc_p, heap) *locs = NULL;
2148   unsigned i;
2149   mem_ref_loc_p loc;
2150   bool ret = false;
2151   struct loop *must_exec;
2152   tree base;
2153
2154   base = get_base_address (ref->mem);
2155   if (INDIRECT_REF_P (base)
2156       || TREE_CODE (base) == MEM_REF)
2157     base = TREE_OPERAND (base, 0);
2158
2159   get_all_locs_in_loop (loop, ref, &locs);
2160   FOR_EACH_VEC_ELT (mem_ref_loc_p, locs, i, loc)
2161     {
2162       if (!get_lim_data (loc->stmt))
2163         continue;
2164
2165       /* If we require an always executed store make sure the statement
2166          stores to the reference.  */
2167       if (stored_p)
2168         {
2169           tree lhs;
2170           if (!gimple_get_lhs (loc->stmt))
2171             continue;
2172           lhs = get_base_address (gimple_get_lhs (loc->stmt));
2173           if (!lhs)
2174             continue;
2175           if (INDIRECT_REF_P (lhs)
2176               || TREE_CODE (lhs) == MEM_REF)
2177             lhs = TREE_OPERAND (lhs, 0);
2178           if (lhs != base)
2179             continue;
2180         }
2181
2182       must_exec = get_lim_data (loc->stmt)->always_executed_in;
2183       if (!must_exec)
2184         continue;
2185
2186       if (must_exec == loop
2187           || flow_loop_nested_p (must_exec, loop))
2188         {
2189           ret = true;
2190           break;
2191         }
2192     }
2193   VEC_free (mem_ref_loc_p, heap, locs);
2194
2195   return ret;
2196 }
2197
2198 /* Returns true if REF1 and REF2 are independent.  */
2199
2200 static bool
2201 refs_independent_p (mem_ref_p ref1, mem_ref_p ref2)
2202 {
2203   if (ref1 == ref2
2204       || bitmap_bit_p (ref1->indep_ref, ref2->id))
2205     return true;
2206   if (bitmap_bit_p (ref1->dep_ref, ref2->id))
2207     return false;
2208
2209   if (dump_file && (dump_flags & TDF_DETAILS))
2210     fprintf (dump_file, "Querying dependency of refs %u and %u: ",
2211              ref1->id, ref2->id);
2212
2213   if (mem_refs_may_alias_p (ref1->mem, ref2->mem,
2214                             &memory_accesses.ttae_cache))
2215     {
2216       bitmap_set_bit (ref1->dep_ref, ref2->id);
2217       bitmap_set_bit (ref2->dep_ref, ref1->id);
2218       if (dump_file && (dump_flags & TDF_DETAILS))
2219         fprintf (dump_file, "dependent.\n");
2220       return false;
2221     }
2222   else
2223     {
2224       bitmap_set_bit (ref1->indep_ref, ref2->id);
2225       bitmap_set_bit (ref2->indep_ref, ref1->id);
2226       if (dump_file && (dump_flags & TDF_DETAILS))
2227         fprintf (dump_file, "independent.\n");
2228       return true;
2229     }
2230 }
2231
2232 /* Records the information whether REF is independent in LOOP (according
2233    to INDEP).  */
2234
2235 static void
2236 record_indep_loop (struct loop *loop, mem_ref_p ref, bool indep)
2237 {
2238   if (indep)
2239     bitmap_set_bit (ref->indep_loop, loop->num);
2240   else
2241     bitmap_set_bit (ref->dep_loop, loop->num);
2242 }
2243
2244 /* Returns true if REF is independent on all other memory references in
2245    LOOP.  */
2246
2247 static bool
2248 ref_indep_loop_p_1 (struct loop *loop, mem_ref_p ref)
2249 {
2250   bitmap clobbers, refs_to_check, refs;
2251   unsigned i;
2252   bitmap_iterator bi;
2253   bool ret = true, stored = bitmap_bit_p (ref->stored, loop->num);
2254   htab_t map;
2255   mem_ref_p aref;
2256
2257   /* If the reference is clobbered, it is not independent.  */
2258   clobbers = VEC_index (bitmap, memory_accesses.clobbered_vops, loop->num);
2259   if (bitmap_intersect_p (ref->vops, clobbers))
2260     return false;
2261
2262   refs_to_check = BITMAP_ALLOC (NULL);
2263
2264   map = VEC_index (htab_t, memory_accesses.vop_ref_map, loop->num);
2265   EXECUTE_IF_AND_COMPL_IN_BITMAP (ref->vops, clobbers, 0, i, bi)
2266     {
2267       if (stored)
2268         refs = get_vop_accesses (map, i);
2269       else
2270         refs = get_vop_stores (map, i);
2271
2272       bitmap_ior_into (refs_to_check, refs);
2273     }
2274
2275   EXECUTE_IF_SET_IN_BITMAP (refs_to_check, 0, i, bi)
2276     {
2277       aref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
2278       if (!refs_independent_p (ref, aref))
2279         {
2280           ret = false;
2281           record_indep_loop (loop, aref, false);
2282           break;
2283         }
2284     }
2285
2286   BITMAP_FREE (refs_to_check);
2287   return ret;
2288 }
2289
2290 /* Returns true if REF is independent on all other memory references in
2291    LOOP.  Wrapper over ref_indep_loop_p_1, caching its results.  */
2292
2293 static bool
2294 ref_indep_loop_p (struct loop *loop, mem_ref_p ref)
2295 {
2296   bool ret;
2297
2298   if (bitmap_bit_p (ref->indep_loop, loop->num))
2299     return true;
2300   if (bitmap_bit_p (ref->dep_loop, loop->num))
2301     return false;
2302
2303   ret = ref_indep_loop_p_1 (loop, ref);
2304
2305   if (dump_file && (dump_flags & TDF_DETAILS))
2306     fprintf (dump_file, "Querying dependencies of ref %u in loop %d: %s\n",
2307              ref->id, loop->num, ret ? "independent" : "dependent");
2308
2309   record_indep_loop (loop, ref, ret);
2310
2311   return ret;
2312 }
2313
2314 /* Returns true if we can perform store motion of REF from LOOP.  */
2315
2316 static bool
2317 can_sm_ref_p (struct loop *loop, mem_ref_p ref)
2318 {
2319   tree base;
2320
2321   /* Unless the reference is stored in the loop, there is nothing to do.  */
2322   if (!bitmap_bit_p (ref->stored, loop->num))
2323     return false;
2324
2325   /* It should be movable.  */
2326   if (!is_gimple_reg_type (TREE_TYPE (ref->mem))
2327       || TREE_THIS_VOLATILE (ref->mem)
2328       || !for_each_index (&ref->mem, may_move_till, loop))
2329     return false;
2330
2331   /* If it can trap, it must be always executed in LOOP.
2332      Readonly memory locations may trap when storing to them, but
2333      tree_could_trap_p is a predicate for rvalues, so check that
2334      explicitly.  */
2335   base = get_base_address (ref->mem);
2336   if ((tree_could_trap_p (ref->mem)
2337        || (DECL_P (base) && TREE_READONLY (base)))
2338       && !ref_always_accessed_p (loop, ref, true))
2339     return false;
2340
2341   /* And it must be independent on all other memory references
2342      in LOOP.  */
2343   if (!ref_indep_loop_p (loop, ref))
2344     return false;
2345
2346   return true;
2347 }
2348
2349 /* Marks the references in LOOP for that store motion should be performed
2350    in REFS_TO_SM.  SM_EXECUTED is the set of references for that store
2351    motion was performed in one of the outer loops.  */
2352
2353 static void
2354 find_refs_for_sm (struct loop *loop, bitmap sm_executed, bitmap refs_to_sm)
2355 {
2356   bitmap refs = VEC_index (bitmap, memory_accesses.all_refs_in_loop,
2357                            loop->num);
2358   unsigned i;
2359   bitmap_iterator bi;
2360   mem_ref_p ref;
2361
2362   EXECUTE_IF_AND_COMPL_IN_BITMAP (refs, sm_executed, 0, i, bi)
2363     {
2364       ref = VEC_index (mem_ref_p, memory_accesses.refs_list, i);
2365       if (can_sm_ref_p (loop, ref))
2366         bitmap_set_bit (refs_to_sm, i);
2367     }
2368 }
2369
2370 /* Checks whether LOOP (with exits stored in EXITS array) is suitable
2371    for a store motion optimization (i.e. whether we can insert statement
2372    on its exits).  */
2373
2374 static bool
2375 loop_suitable_for_sm (struct loop *loop ATTRIBUTE_UNUSED,
2376                       VEC (edge, heap) *exits)
2377 {
2378   unsigned i;
2379   edge ex;
2380
2381   FOR_EACH_VEC_ELT (edge, exits, i, ex)
2382     if (ex->flags & EDGE_ABNORMAL)
2383       return false;
2384
2385   return true;
2386 }
2387
2388 /* Try to perform store motion for all memory references modified inside
2389    LOOP.  SM_EXECUTED is the bitmap of the memory references for that
2390    store motion was executed in one of the outer loops.  */
2391
2392 static void
2393 store_motion_loop (struct loop *loop, bitmap sm_executed)
2394 {
2395   VEC (edge, heap) *exits = get_loop_exit_edges (loop);
2396   struct loop *subloop;
2397   bitmap sm_in_loop = BITMAP_ALLOC (NULL);
2398
2399   if (loop_suitable_for_sm (loop, exits))
2400     {
2401       find_refs_for_sm (loop, sm_executed, sm_in_loop);
2402       hoist_memory_references (loop, sm_in_loop, exits);
2403     }
2404   VEC_free (edge, heap, exits);
2405
2406   bitmap_ior_into (sm_executed, sm_in_loop);
2407   for (subloop = loop->inner; subloop != NULL; subloop = subloop->next)
2408     store_motion_loop (subloop, sm_executed);
2409   bitmap_and_compl_into (sm_executed, sm_in_loop);
2410   BITMAP_FREE (sm_in_loop);
2411 }
2412
2413 /* Try to perform store motion for all memory references modified inside
2414    loops.  */
2415
2416 static void
2417 store_motion (void)
2418 {
2419   struct loop *loop;
2420   bitmap sm_executed = BITMAP_ALLOC (NULL);
2421
2422   for (loop = current_loops->tree_root->inner; loop != NULL; loop = loop->next)
2423     store_motion_loop (loop, sm_executed);
2424
2425   BITMAP_FREE (sm_executed);
2426   gsi_commit_edge_inserts ();
2427 }
2428
2429 /* Fills ALWAYS_EXECUTED_IN information for basic blocks of LOOP, i.e.
2430    for each such basic block bb records the outermost loop for that execution
2431    of its header implies execution of bb.  CONTAINS_CALL is the bitmap of
2432    blocks that contain a nonpure call.  */
2433
2434 static void
2435 fill_always_executed_in (struct loop *loop, sbitmap contains_call)
2436 {
2437   basic_block bb = NULL, *bbs, last = NULL;
2438   unsigned i;
2439   edge e;
2440   struct loop *inn_loop = loop;
2441
2442   if (!loop->header->aux)
2443     {
2444       bbs = get_loop_body_in_dom_order (loop);
2445
2446       for (i = 0; i < loop->num_nodes; i++)
2447         {
2448           edge_iterator ei;
2449           bb = bbs[i];
2450
2451           if (dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2452             last = bb;
2453
2454           if (TEST_BIT (contains_call, bb->index))
2455             break;
2456
2457           FOR_EACH_EDGE (e, ei, bb->succs)
2458             if (!flow_bb_inside_loop_p (loop, e->dest))
2459               break;
2460           if (e)
2461             break;
2462
2463           /* A loop might be infinite (TODO use simple loop analysis
2464              to disprove this if possible).  */
2465           if (bb->flags & BB_IRREDUCIBLE_LOOP)
2466             break;
2467
2468           if (!flow_bb_inside_loop_p (inn_loop, bb))
2469             break;
2470
2471           if (bb->loop_father->header == bb)
2472             {
2473               if (!dominated_by_p (CDI_DOMINATORS, loop->latch, bb))
2474                 break;
2475
2476               /* In a loop that is always entered we may proceed anyway.
2477                  But record that we entered it and stop once we leave it.  */
2478               inn_loop = bb->loop_father;
2479             }
2480         }
2481
2482       while (1)
2483         {
2484           last->aux = loop;
2485           if (last == loop->header)
2486             break;
2487           last = get_immediate_dominator (CDI_DOMINATORS, last);
2488         }
2489
2490       free (bbs);
2491     }
2492
2493   for (loop = loop->inner; loop; loop = loop->next)
2494     fill_always_executed_in (loop, contains_call);
2495 }
2496
2497 /* Compute the global information needed by the loop invariant motion pass.  */
2498
2499 static void
2500 tree_ssa_lim_initialize (void)
2501 {
2502   sbitmap contains_call = sbitmap_alloc (last_basic_block);
2503   gimple_stmt_iterator bsi;
2504   struct loop *loop;
2505   basic_block bb;
2506
2507   sbitmap_zero (contains_call);
2508   FOR_EACH_BB (bb)
2509     {
2510       for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
2511         {
2512           if (nonpure_call_p (gsi_stmt (bsi)))
2513             break;
2514         }
2515
2516       if (!gsi_end_p (bsi))
2517         SET_BIT (contains_call, bb->index);
2518     }
2519
2520   for (loop = current_loops->tree_root->inner; loop; loop = loop->next)
2521     fill_always_executed_in (loop, contains_call);
2522
2523   sbitmap_free (contains_call);
2524
2525   lim_aux_data_map = pointer_map_create ();
2526 }
2527
2528 /* Cleans up after the invariant motion pass.  */
2529
2530 static void
2531 tree_ssa_lim_finalize (void)
2532 {
2533   basic_block bb;
2534   unsigned i;
2535   bitmap b;
2536   htab_t h;
2537
2538   FOR_EACH_BB (bb)
2539     {
2540       bb->aux = NULL;
2541     }
2542
2543   pointer_map_destroy (lim_aux_data_map);
2544
2545   VEC_free (mem_ref_p, heap, memory_accesses.refs_list);
2546   htab_delete (memory_accesses.refs);
2547
2548   FOR_EACH_VEC_ELT (bitmap, memory_accesses.refs_in_loop, i, b)
2549     BITMAP_FREE (b);
2550   VEC_free (bitmap, heap, memory_accesses.refs_in_loop);
2551
2552   FOR_EACH_VEC_ELT (bitmap, memory_accesses.all_refs_in_loop, i, b)
2553     BITMAP_FREE (b);
2554   VEC_free (bitmap, heap, memory_accesses.all_refs_in_loop);
2555
2556   FOR_EACH_VEC_ELT (bitmap, memory_accesses.clobbered_vops, i, b)
2557     BITMAP_FREE (b);
2558   VEC_free (bitmap, heap, memory_accesses.clobbered_vops);
2559
2560   FOR_EACH_VEC_ELT (htab_t, memory_accesses.vop_ref_map, i, h)
2561     htab_delete (h);
2562   VEC_free (htab_t, heap, memory_accesses.vop_ref_map);
2563
2564   if (memory_accesses.ttae_cache)
2565     pointer_map_destroy (memory_accesses.ttae_cache);
2566 }
2567
2568 /* Moves invariants from loops.  Only "expensive" invariants are moved out --
2569    i.e. those that are likely to be win regardless of the register pressure.  */
2570
2571 unsigned int
2572 tree_ssa_lim (void)
2573 {
2574   unsigned int todo;
2575
2576   tree_ssa_lim_initialize ();
2577
2578   /* Gathers information about memory accesses in the loops.  */
2579   analyze_memory_references ();
2580
2581   /* For each statement determine the outermost loop in that it is
2582      invariant and cost for computing the invariant.  */
2583   determine_invariantness ();
2584
2585   /* Execute store motion.  Force the necessary invariants to be moved
2586      out of the loops as well.  */
2587   store_motion ();
2588
2589   /* Move the expressions that are expensive enough.  */
2590   todo = move_computations ();
2591
2592   tree_ssa_lim_finalize ();
2593
2594   return todo;
2595 }