OSDN Git Service

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